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: 354704 $")
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 "asterisk/message.h"
00268 #include "sip/include/sip.h"
00269 #include "sip/include/globals.h"
00270 #include "sip/include/config_parser.h"
00271 #include "sip/include/reqresp_parser.h"
00272 #include "sip/include/sip_utils.h"
00273 #include "sip/include/srtp.h"
00274 #include "sip/include/sdp_crypto.h"
00275 #include "asterisk/ccss.h"
00276 #include "asterisk/xml.h"
00277 #include "sip/include/dialog.h"
00278 #include "sip/include/dialplan_functions.h"
00279 #include "sip/include/security_events.h"
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
00559
00560
00561
00562 static int min_expiry = DEFAULT_MIN_EXPIRY;
00563 static int max_expiry = DEFAULT_MAX_EXPIRY;
00564 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00565 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00566
00567 static int unauth_sessions = 0;
00568 static int authlimit = DEFAULT_AUTHLIMIT;
00569 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00570
00571
00572
00573 static struct ast_jb_conf default_jbconf =
00574 {
00575 .flags = 0,
00576 .max_size = 200,
00577 .resync_threshold = 1000,
00578 .impl = "fixed",
00579 .target_extra = 40,
00580 };
00581 static struct ast_jb_conf global_jbconf;
00582
00583 static const char config[] = "sip.conf";
00584 static const char notify_config[] = "sip_notify.conf";
00585
00586
00587
00588 static const struct invstate2stringtable {
00589 const enum invitestates state;
00590 const char *desc;
00591 } invitestate2string[] = {
00592 {INV_NONE, "None" },
00593 {INV_CALLING, "Calling (Trying)"},
00594 {INV_PROCEEDING, "Proceeding "},
00595 {INV_EARLY_MEDIA, "Early media"},
00596 {INV_COMPLETED, "Completed (done)"},
00597 {INV_CONFIRMED, "Confirmed (up)"},
00598 {INV_TERMINATED, "Done"},
00599 {INV_CANCELLED, "Cancelled"}
00600 };
00601
00602
00603
00604
00605
00606
00607 static const struct cfsubscription_types {
00608 enum subscriptiontype type;
00609 const char * const event;
00610 const char * const mediatype;
00611 const char * const text;
00612 } subscription_types[] = {
00613 { NONE, "-", "unknown", "unknown" },
00614
00615 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00616 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00617 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00618 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00619 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00620 };
00621
00622
00623
00624
00625
00626
00627 static const struct cfsip_methods {
00628 enum sipmethod id;
00629 int need_rtp;
00630 char * const text;
00631 enum can_create_dialog can_create;
00632 } sip_methods[] = {
00633 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
00634 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00635 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00636 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00637 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00638 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00639 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00640 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00641 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00642 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00643 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00644 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00645 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00646 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00647 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00648 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
00649 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00650 };
00651
00652
00653
00654
00655
00656
00657
00658
00659 static const struct sip_reasons {
00660 enum AST_REDIRECTING_REASON code;
00661 char * const text;
00662 } sip_reason_table[] = {
00663 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00664 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00665 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00666 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00667 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00668 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00669 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00670 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00671 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00672 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00673 { AST_REDIRECTING_REASON_AWAY, "away" },
00674 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00675 };
00676
00677
00678
00679
00680
00681
00682
00683 static char default_language[MAX_LANGUAGE];
00684 static char default_callerid[AST_MAX_EXTENSION];
00685 static char default_mwi_from[80];
00686 static char default_fromdomain[AST_MAX_EXTENSION];
00687 static int default_fromdomainport;
00688 static char default_notifymime[AST_MAX_EXTENSION];
00689 static char default_vmexten[AST_MAX_EXTENSION];
00690 static int default_qualify;
00691 static char default_mohinterpret[MAX_MUSICCLASS];
00692 static char default_mohsuggest[MAX_MUSICCLASS];
00693
00694 static char default_parkinglot[AST_MAX_CONTEXT];
00695 static char default_engine[256];
00696 static int default_maxcallbitrate;
00697 static struct ast_codec_pref default_prefs;
00698 static char default_zone[MAX_TONEZONE_COUNTRY];
00699 static unsigned int default_transports;
00700 static unsigned int default_primary_transport;
00701
00702
00703 static struct sip_settings sip_cfg;
00704
00705
00706
00707 #define SIP_PEDANTIC_DECODE(str) \
00708 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00709 ast_uri_decode(str, ast_uri_sip_user); \
00710 } \
00711
00712 static unsigned int chan_idx;
00713 static int global_match_auth_username;
00714
00715 static int global_relaxdtmf;
00716 static int global_prematuremediafilter;
00717 static int global_rtptimeout;
00718 static int global_rtpholdtimeout;
00719 static int global_rtpkeepalive;
00720 static int global_reg_timeout;
00721 static int global_regattempts_max;
00722 static int global_shrinkcallerid;
00723 static int global_callcounter;
00724
00725
00726 static unsigned int global_tos_sip;
00727 static unsigned int global_tos_audio;
00728 static unsigned int global_tos_video;
00729 static unsigned int global_tos_text;
00730 static unsigned int global_cos_sip;
00731 static unsigned int global_cos_audio;
00732 static unsigned int global_cos_video;
00733 static unsigned int global_cos_text;
00734 static unsigned int recordhistory;
00735 static unsigned int dumphistory;
00736 static char global_useragent[AST_MAX_EXTENSION];
00737 static char global_sdpsession[AST_MAX_EXTENSION];
00738 static char global_sdpowner[AST_MAX_EXTENSION];
00739 static int global_authfailureevents;
00740 static int global_t1;
00741 static int global_t1min;
00742 static int global_timer_b;
00743 static unsigned int global_autoframing;
00744 static int global_qualifyfreq;
00745 static int global_qualify_gap;
00746 static int global_qualify_peers;
00747
00748 static enum st_mode global_st_mode;
00749 static enum st_refresher global_st_refresher;
00750 static int global_min_se;
00751 static int global_max_se;
00752
00753 static int global_store_sip_cause;
00754
00755 static int global_dynamic_exclude_static = 0;
00756
00757
00758
00759
00760
00761
00762
00763
00764 static int can_parse_xml;
00765
00766
00767
00768
00769 static int speerobjs = 0;
00770 static int rpeerobjs = 0;
00771 static int apeerobjs = 0;
00772 static int regobjs = 0;
00773
00774
00775 static struct ast_flags global_flags[3] = {{0}};
00776 static int global_t38_maxdatagram;
00777
00778 static struct ast_event_sub *network_change_event_subscription;
00779 static int network_change_event_sched_id = -1;
00780
00781 static char used_context[AST_MAX_CONTEXT];
00782
00783 AST_MUTEX_DEFINE_STATIC(netlock);
00784
00785
00786
00787 AST_MUTEX_DEFINE_STATIC(monlock);
00788
00789 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00790
00791
00792
00793 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00794
00795 static int sip_reloading = FALSE;
00796 static enum channelreloadreason sip_reloadreason;
00797
00798 struct ast_sched_context *sched;
00799 static struct io_context *io;
00800 static int *sipsock_read_id;
00801 struct sip_pkt;
00802 static AST_LIST_HEAD_STATIC(domain_list, domain);
00803
00804 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00805
00806 static enum sip_debug_e sipdebug;
00807
00808
00809
00810
00811
00812 static int sipdebug_text;
00813
00814 static const struct _map_x_s referstatusstrings[] = {
00815 { REFER_IDLE, "<none>" },
00816 { REFER_SENT, "Request sent" },
00817 { REFER_RECEIVED, "Request received" },
00818 { REFER_CONFIRMED, "Confirmed" },
00819 { REFER_ACCEPTED, "Accepted" },
00820 { REFER_RINGING, "Target ringing" },
00821 { REFER_200OK, "Done" },
00822 { REFER_FAILED, "Failed" },
00823 { REFER_NOAUTH, "Failed - auth failure" },
00824 { -1, NULL}
00825 };
00826
00827
00828 #ifdef LOW_MEMORY
00829 static const int HASH_PEER_SIZE = 17;
00830 static const int HASH_DIALOG_SIZE = 17;
00831 #else
00832 static const int HASH_PEER_SIZE = 563;
00833 static const int HASH_DIALOG_SIZE = 563;
00834 #endif
00835
00836 static const struct {
00837 enum ast_cc_service_type service;
00838 const char *service_string;
00839 } sip_cc_service_map [] = {
00840 [AST_CC_NONE] = { AST_CC_NONE, "" },
00841 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00842 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00843 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00844 };
00845
00846 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00847 {
00848 enum ast_cc_service_type service;
00849 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00850 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00851 return service;
00852 }
00853 }
00854 return AST_CC_NONE;
00855 }
00856
00857 static const struct {
00858 enum sip_cc_notify_state state;
00859 const char *state_string;
00860 } sip_cc_notify_state_map [] = {
00861 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00862 [CC_READY] = {CC_READY, "cc-state: ready"},
00863 };
00864
00865 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00866
00867 static int sip_epa_register(const struct epa_static_data *static_data)
00868 {
00869 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00870
00871 if (!backend) {
00872 return -1;
00873 }
00874
00875 backend->static_data = static_data;
00876
00877 AST_LIST_LOCK(&epa_static_data_list);
00878 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00879 AST_LIST_UNLOCK(&epa_static_data_list);
00880 return 0;
00881 }
00882
00883 static void sip_epa_unregister_all(void)
00884 {
00885 struct epa_backend *backend;
00886
00887 AST_LIST_LOCK(&epa_static_data_list);
00888 while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00889 ast_free(backend);
00890 }
00891 AST_LIST_UNLOCK(&epa_static_data_list);
00892 }
00893
00894 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00895
00896 static void cc_epa_destructor(void *data)
00897 {
00898 struct sip_epa_entry *epa_entry = data;
00899 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00900 ast_free(cc_entry);
00901 }
00902
00903 static const struct epa_static_data cc_epa_static_data = {
00904 .event = CALL_COMPLETION,
00905 .name = "call-completion",
00906 .handle_error = cc_handle_publish_error,
00907 .destructor = cc_epa_destructor,
00908 };
00909
00910 static const struct epa_static_data *find_static_data(const char * const event_package)
00911 {
00912 const struct epa_backend *backend = NULL;
00913
00914 AST_LIST_LOCK(&epa_static_data_list);
00915 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00916 if (!strcmp(backend->static_data->name, event_package)) {
00917 break;
00918 }
00919 }
00920 AST_LIST_UNLOCK(&epa_static_data_list);
00921 return backend ? backend->static_data : NULL;
00922 }
00923
00924 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00925 {
00926 struct sip_epa_entry *epa_entry;
00927 const struct epa_static_data *static_data;
00928
00929 if (!(static_data = find_static_data(event_package))) {
00930 return NULL;
00931 }
00932
00933 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00934 return NULL;
00935 }
00936
00937 epa_entry->static_data = static_data;
00938 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00939 return epa_entry;
00940 }
00941
00942
00943
00944
00945 static int esc_etag_counter;
00946 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00947
00948 #ifdef HAVE_LIBXML2
00949 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);
00950
00951 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00952 .initial_handler = cc_esc_publish_handler,
00953 .modify_handler = cc_esc_publish_handler,
00954 };
00955 #endif
00956
00957
00958
00959
00960
00961
00962
00963
00964
00965
00966
00967
00968
00969 static struct event_state_compositor {
00970 enum subscriptiontype event;
00971 const char * name;
00972 const struct sip_esc_publish_callbacks *callbacks;
00973 struct ao2_container *compositor;
00974 } event_state_compositors [] = {
00975 #ifdef HAVE_LIBXML2
00976 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00977 #endif
00978 };
00979
00980 static const int ESC_MAX_BUCKETS = 37;
00981
00982 static void esc_entry_destructor(void *obj)
00983 {
00984 struct sip_esc_entry *esc_entry = obj;
00985 if (esc_entry->sched_id > -1) {
00986 AST_SCHED_DEL(sched, esc_entry->sched_id);
00987 }
00988 }
00989
00990 static int esc_hash_fn(const void *obj, const int flags)
00991 {
00992 const struct sip_esc_entry *entry = obj;
00993 return ast_str_hash(entry->entity_tag);
00994 }
00995
00996 static int esc_cmp_fn(void *obj, void *arg, int flags)
00997 {
00998 struct sip_esc_entry *entry1 = obj;
00999 struct sip_esc_entry *entry2 = arg;
01000
01001 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
01002 }
01003
01004 static struct event_state_compositor *get_esc(const char * const event_package) {
01005 int i;
01006 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01007 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01008 return &event_state_compositors[i];
01009 }
01010 }
01011 return NULL;
01012 }
01013
01014 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01015 struct sip_esc_entry *entry;
01016 struct sip_esc_entry finder;
01017
01018 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01019
01020 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01021
01022 return entry;
01023 }
01024
01025 static int publish_expire(const void *data)
01026 {
01027 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01028 struct event_state_compositor *esc = get_esc(esc_entry->event);
01029
01030 ast_assert(esc != NULL);
01031
01032 ao2_unlink(esc->compositor, esc_entry);
01033 ao2_ref(esc_entry, -1);
01034 return 0;
01035 }
01036
01037 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01038 {
01039 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01040 struct event_state_compositor *esc = get_esc(esc_entry->event);
01041
01042 ast_assert(esc != NULL);
01043 if (is_linked) {
01044 ao2_unlink(esc->compositor, esc_entry);
01045 }
01046 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01047 ao2_link(esc->compositor, esc_entry);
01048 }
01049
01050 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01051 {
01052 struct sip_esc_entry *esc_entry;
01053 int expires_ms;
01054
01055 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01056 return NULL;
01057 }
01058
01059 esc_entry->event = esc->name;
01060
01061 expires_ms = expires * 1000;
01062
01063 ao2_ref(esc_entry, +1);
01064 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01065
01066
01067 create_new_sip_etag(esc_entry, 0);
01068
01069 return esc_entry;
01070 }
01071
01072 static int initialize_escs(void)
01073 {
01074 int i, res = 0;
01075 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01076 if (!((event_state_compositors[i].compositor) =
01077 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01078 res = -1;
01079 }
01080 }
01081 return res;
01082 }
01083
01084 static void destroy_escs(void)
01085 {
01086 int i;
01087 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01088 ao2_ref(event_state_compositors[i].compositor, -1);
01089 }
01090 }
01091
01092
01093
01094
01095
01096
01097
01098 struct ao2_container *dialogs_needdestroy;
01099
01100
01101
01102
01103
01104
01105
01106 struct ao2_container *dialogs_rtpcheck;
01107
01108
01109
01110
01111
01112
01113
01114
01115
01116
01117 static struct ao2_container *dialogs;
01118 #define sip_pvt_lock(x) ao2_lock(x)
01119 #define sip_pvt_trylock(x) ao2_trylock(x)
01120 #define sip_pvt_unlock(x) ao2_unlock(x)
01121
01122
01123 static struct ao2_container *threadt;
01124
01125
01126 static struct ao2_container *peers;
01127 static struct ao2_container *peers_by_ip;
01128
01129
01130 static struct ast_register_list {
01131 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01132 int recheck;
01133 } regl;
01134
01135
01136 static struct ast_subscription_mwi_list {
01137 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01138 } submwil;
01139 static int temp_pvt_init(void *);
01140 static void temp_pvt_cleanup(void *);
01141
01142
01143 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01144
01145
01146 static struct sip_auth_container *authl = NULL;
01147
01148 AST_MUTEX_DEFINE_STATIC(authl_lock);
01149
01150
01151
01152
01153
01154
01155
01156
01157
01158
01159
01160
01161
01162
01163
01164
01165
01166 static int sipsock = -1;
01167
01168 struct ast_sockaddr bindaddr;
01169
01170
01171
01172
01173
01174
01175
01176 static struct ast_sockaddr internip;
01177
01178
01179
01180
01181
01182
01183
01184
01185
01186
01187
01188
01189
01190
01191
01192
01193 static struct ast_sockaddr externaddr;
01194 static struct ast_sockaddr media_address;
01195
01196 static char externhost[MAXHOSTNAMELEN];
01197 static time_t externexpire;
01198 static int externrefresh = 10;
01199 static uint16_t externtcpport;
01200 static uint16_t externtlsport;
01201
01202
01203
01204
01205
01206
01207
01208 static struct ast_ha *localaddr;
01209
01210 static int ourport_tcp;
01211 static int ourport_tls;
01212 static struct ast_sockaddr debugaddr;
01213
01214 static struct ast_config *notify_types = NULL;
01215
01216
01217
01218 #define UNLINK(element, head, prev) do { \
01219 if (prev) \
01220 (prev)->next = (element)->next; \
01221 else \
01222 (head) = (element)->next; \
01223 } while (0)
01224
01225
01226
01227
01228
01229
01230 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
01231 static int sip_devicestate(const char *data);
01232 static int sip_sendtext(struct ast_channel *ast, const char *text);
01233 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
01234 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01235 static int sip_hangup(struct ast_channel *ast);
01236 static int sip_answer(struct ast_channel *ast);
01237 static struct ast_frame *sip_read(struct ast_channel *ast);
01238 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01239 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01240 static int sip_transfer(struct ast_channel *ast, const char *dest);
01241 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01242 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01243 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01244 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01245 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01246 static const char *sip_get_callid(struct ast_channel *chan);
01247
01248 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01249 static int sip_standard_port(enum sip_transport type, int port);
01250 static int sip_prepare_socket(struct sip_pvt *p);
01251 static int get_address_family_filter(const struct ast_sockaddr *addr);
01252
01253
01254 static int sipsock_read(int *id, int fd, short events, void *ignore);
01255 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01256 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01257 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01258 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01259 static int retrans_pkt(const void *data);
01260 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);
01261 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01262 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01263 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01264 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);
01265 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01266 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);
01267 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01268 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01269 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01270 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01271 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01272 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01273 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01274 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01275 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01276 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01277 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01278 static int transmit_message(struct sip_pvt *p, int init, int auth);
01279 static int transmit_refer(struct sip_pvt *p, const char *dest);
01280 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01281 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01282 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01283 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01284 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01285 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01286 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01287 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01288 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01289 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01290
01291
01292 static int __sip_autodestruct(const void *data);
01293 static void *registry_unref(struct sip_registry *reg, char *tag);
01294 static int update_call_counter(struct sip_pvt *fup, int event);
01295 static int auto_congest(const void *arg);
01296 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01297 static void free_old_route(struct sip_route *route);
01298 static void list_route(struct sip_route *route);
01299 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01300 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01301 struct sip_request *req, const char *uri);
01302 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01303 static void check_pendings(struct sip_pvt *p);
01304 static void *sip_park_thread(void *stuff);
01305 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);
01306
01307 static void *sip_pickup_thread(void *stuff);
01308 static int sip_pickup(struct ast_channel *chan);
01309
01310 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01311 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01312
01313
01314 static void try_suggested_sip_codec(struct sip_pvt *p);
01315 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01316 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01317 static int find_sdp(struct sip_request *req);
01318 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01319 static int process_sdp_o(const char *o, struct sip_pvt *p);
01320 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01321 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01322 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01323 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01324 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);
01325 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01326 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
01327 struct ast_str **m_buf, struct ast_str **a_buf,
01328 int debug, int *min_packet_size);
01329 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01330 struct ast_str **m_buf, struct ast_str **a_buf,
01331 int debug);
01332 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01333 static void do_setnat(struct sip_pvt *p);
01334 static void stop_media_flows(struct sip_pvt *p);
01335
01336
01337 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01338 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01339 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01340 const char *secret, const char *md5secret, int sipmethod,
01341 const char *uri, enum xmittype reliable, int ignore);
01342 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01343 int sipmethod, const char *uri, enum xmittype reliable,
01344 struct ast_sockaddr *addr, struct sip_peer **authpeer);
01345 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01346
01347
01348 static int check_sip_domain(const char *domain, char *context, size_t len);
01349 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01350 static void clear_sip_domains(void);
01351
01352
01353 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01354 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01355
01356
01357 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01358 static int reload_config(enum channelreloadreason reason);
01359 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01360 static int expire_register(const void *data);
01361 static void *do_monitor(void *data);
01362 static int restart_monitor(void);
01363 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01364 static struct ast_variable *copy_vars(struct ast_variable *src);
01365 static int dialog_find_multiple(void *obj, void *arg, int flags);
01366 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01367
01368 static int sip_refer_allocate(struct sip_pvt *p);
01369 static int sip_notify_allocate(struct sip_pvt *p);
01370 static void ast_quiet_chan(struct ast_channel *chan);
01371 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01372 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01373
01374
01375 static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data);
01376 static int sip_poke_noanswer(const void *data);
01377 static int sip_poke_peer(struct sip_peer *peer, int force);
01378 static void sip_poke_all_peers(void);
01379 static void sip_peer_hold(struct sip_pvt *p, int hold);
01380 static void mwi_event_cb(const struct ast_event *, void *);
01381 static void network_change_event_cb(const struct ast_event *, void *);
01382
01383
01384 static const char *sip_nat_mode(const struct sip_pvt *p);
01385 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01386 static char *transfermode2str(enum transfermodes mode) attribute_const;
01387 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01388 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01389 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01390 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01391 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01392 static void print_group(int fd, ast_group_t group, int crlf);
01393 static const char *dtmfmode2str(int mode) attribute_const;
01394 static int str2dtmfmode(const char *str) attribute_unused;
01395 static const char *insecure2str(int mode) attribute_const;
01396 static const char *allowoverlap2str(int mode) attribute_const;
01397 static void cleanup_stale_contexts(char *new, char *old);
01398 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01399 static const char *domain_mode_to_text(const enum domain_mode mode);
01400 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01401 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01402 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01403 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01404 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01405 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01406 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01407 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01408 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01409 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01410 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01411 static char *complete_sip_peer(const char *word, int state, int flags2);
01412 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01413 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01414 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01415 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01416 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01417 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01418 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01419 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01420 static char *sip_do_debug_ip(int fd, const char *arg);
01421 static char *sip_do_debug_peer(int fd, const char *arg);
01422 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01423 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01424 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01425 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01426 static int sip_addheader(struct ast_channel *chan, const char *data);
01427 static int sip_do_reload(enum channelreloadreason reason);
01428 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01429 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01430 const char *name, int flag, int family);
01431 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01432 const char *name, int flag);
01433
01434
01435
01436
01437
01438 static void sip_dump_history(struct sip_pvt *dialog);
01439 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01440 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01441 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01442 static void sip_dump_history(struct sip_pvt *dialog);
01443
01444
01445 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01446 static int update_call_counter(struct sip_pvt *fup, int event);
01447 static void sip_destroy_peer(struct sip_peer *peer);
01448 static void sip_destroy_peer_fn(void *peer);
01449 static void set_peer_defaults(struct sip_peer *peer);
01450 static struct sip_peer *temp_peer(const char *name);
01451 static void register_peer_exten(struct sip_peer *peer, int onoff);
01452 static int sip_poke_peer_s(const void *data);
01453 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01454 static void reg_source_db(struct sip_peer *peer);
01455 static void destroy_association(struct sip_peer *peer);
01456 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01457 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01458 static void set_socket_transport(struct sip_socket *socket, int transport);
01459 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
01460
01461
01462 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);
01463 static void update_peer(struct sip_peer *p, int expire);
01464 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01465 static const char *get_name_from_variable(const struct ast_variable *var);
01466 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
01467 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01468
01469
01470 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01471 static void sip_registry_destroy(struct sip_registry *reg);
01472 static int sip_register(const char *value, int lineno);
01473 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01474 static int sip_reregister(const void *data);
01475 static int __sip_do_register(struct sip_registry *r);
01476 static int sip_reg_timeout(const void *data);
01477 static void sip_send_all_registers(void);
01478 static int sip_reinvite_retry(const void *data);
01479
01480
01481 static void append_date(struct sip_request *req);
01482 static int determine_firstline_parts(struct sip_request *req);
01483 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01484 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01485 static int find_sip_method(const char *msg);
01486 static unsigned int parse_allowed_methods(struct sip_request *req);
01487 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01488 static int parse_request(struct sip_request *req);
01489 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01490 static int method_match(enum sipmethod id, const char *name);
01491 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01492 static const char *find_alias(const char *name, const char *_default);
01493 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01494 static void lws2sws(struct ast_str *msgbuf);
01495 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01496 static char *remove_uri_parameters(char *uri);
01497 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01498 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01499 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01500 static int set_address_from_contact(struct sip_pvt *pvt);
01501 static void check_via(struct sip_pvt *p, struct sip_request *req);
01502 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01503 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01504 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01505 static int get_msg_text(char *buf, int len, struct sip_request *req);
01506 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01507 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01508 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01509 static int get_domain(const char *str, char *domain, int len);
01510 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01511
01512
01513 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
01514 static void *sip_tcp_worker_fn(void *);
01515
01516
01517 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01518 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01519 static void deinit_req(struct sip_request *req);
01520 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01521 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01522 static int init_resp(struct sip_request *resp, const char *msg);
01523 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01524 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01525 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01526 static void build_via(struct sip_pvt *p);
01527 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01528 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address);
01529 static char *generate_random_string(char *buf, size_t size);
01530 static void build_callid_pvt(struct sip_pvt *pvt);
01531 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01532 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01533 static void make_our_tag(char *tagbuf, size_t len);
01534 static int add_header(struct sip_request *req, const char *var, const char *value);
01535 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01536 static int add_content(struct sip_request *req, const char *line);
01537 static int finalize_content(struct sip_request *req);
01538 static void destroy_msg_headers(struct sip_pvt *pvt);
01539 static int add_text(struct sip_request *req, struct sip_pvt *p);
01540 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01541 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01542 static int add_vidupdate(struct sip_request *req);
01543 static void add_route(struct sip_request *req, struct sip_route *route);
01544 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01545 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01546 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01547 static void set_destination(struct sip_pvt *p, char *uri);
01548 static void append_date(struct sip_request *req);
01549 static void build_contact(struct sip_pvt *p);
01550
01551
01552 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01553 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01554 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);
01555 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01556 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01557 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01558 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01559 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01560 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01561 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01562 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01563 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01564 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01565 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01566
01567
01568 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01569 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01570 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01571 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01572 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01573 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01574 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01575
01576
01577 static int setup_srtp(struct sip_srtp **srtp);
01578 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01579
01580
01581 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01582 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01583 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01584 static void change_t38_state(struct sip_pvt *p, int state);
01585
01586
01587 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01588 static int proc_session_timer(const void *vp);
01589 static void stop_session_timer(struct sip_pvt *p);
01590 static void start_session_timer(struct sip_pvt *p);
01591 static void restart_session_timer(struct sip_pvt *p);
01592 static const char *strefresher2str(enum st_refresher r);
01593 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
01594 static int parse_minse(const char *p_hdrval, int *const p_interval);
01595 static int st_get_se(struct sip_pvt *, int max);
01596 static enum st_refresher st_get_refresher(struct sip_pvt *);
01597 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01598 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01599
01600
01601 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
01602
01603
01604 static int sip_subscribe_mwi(const char *value, int lineno);
01605 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01606 static void sip_send_all_mwi_subscriptions(void);
01607 static int sip_subscribe_mwi_do(const void *data);
01608 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01609
01610
01611 struct ast_channel_tech sip_tech = {
01612 .type = "SIP",
01613 .description = "Session Initiation Protocol (SIP)",
01614 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01615 .requester = sip_request_call,
01616 .devicestate = sip_devicestate,
01617 .call = sip_call,
01618 .send_html = sip_sendhtml,
01619 .hangup = sip_hangup,
01620 .answer = sip_answer,
01621 .read = sip_read,
01622 .write = sip_write,
01623 .write_video = sip_write,
01624 .write_text = sip_write,
01625 .indicate = sip_indicate,
01626 .transfer = sip_transfer,
01627 .fixup = sip_fixup,
01628 .send_digit_begin = sip_senddigit_begin,
01629 .send_digit_end = sip_senddigit_end,
01630 .bridge = ast_rtp_instance_bridge,
01631 .early_bridge = ast_rtp_instance_early_bridge,
01632 .send_text = sip_sendtext,
01633 .func_channel_read = sip_acf_channel_read,
01634 .setoption = sip_setoption,
01635 .queryoption = sip_queryoption,
01636 .get_pvt_uniqueid = sip_get_callid,
01637 };
01638
01639
01640
01641
01642
01643
01644
01645 struct ast_channel_tech sip_tech_info;
01646
01647
01648 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01649 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01650 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01651 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01652 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01653 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01654 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01655 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01656
01657 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01658 .type = "SIP",
01659 .init = sip_cc_agent_init,
01660 .start_offer_timer = sip_cc_agent_start_offer_timer,
01661 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01662 .respond = sip_cc_agent_respond,
01663 .status_request = sip_cc_agent_status_request,
01664 .start_monitoring = sip_cc_agent_start_monitoring,
01665 .callee_available = sip_cc_agent_recall,
01666 .destructor = sip_cc_agent_destructor,
01667 };
01668
01669 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01670 {
01671 struct ast_cc_agent *agent = obj;
01672 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01673 const char *uri = arg;
01674
01675 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01676 }
01677
01678 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01679 {
01680 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01681 return agent;
01682 }
01683
01684 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01685 {
01686 struct ast_cc_agent *agent = obj;
01687 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01688 const char *uri = arg;
01689
01690 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01691 }
01692
01693 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01694 {
01695 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01696 return agent;
01697 }
01698
01699 static int find_by_callid_helper(void *obj, void *arg, int flags)
01700 {
01701 struct ast_cc_agent *agent = obj;
01702 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01703 struct sip_pvt *call_pvt = arg;
01704
01705 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01706 }
01707
01708 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01709 {
01710 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01711 return agent;
01712 }
01713
01714 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01715 {
01716 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01717 struct sip_pvt *call_pvt = chan->tech_pvt;
01718
01719 if (!agent_pvt) {
01720 return -1;
01721 }
01722
01723 ast_assert(!strcmp(chan->tech->type, "SIP"));
01724
01725 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01726 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01727 agent_pvt->offer_timer_id = -1;
01728 agent->private_data = agent_pvt;
01729 sip_pvt_lock(call_pvt);
01730 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01731 sip_pvt_unlock(call_pvt);
01732 return 0;
01733 }
01734
01735 static int sip_offer_timer_expire(const void *data)
01736 {
01737 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01738 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01739
01740 agent_pvt->offer_timer_id = -1;
01741
01742 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01743 }
01744
01745 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01746 {
01747 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01748 int when;
01749
01750 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01751 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01752 return 0;
01753 }
01754
01755 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01756 {
01757 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01758
01759 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01760 return 0;
01761 }
01762
01763 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01764 {
01765 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01766
01767 sip_pvt_lock(agent_pvt->subscribe_pvt);
01768 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01769 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01770
01771
01772
01773
01774
01775
01776
01777
01778
01779
01780
01781
01782 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01783 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01784 } else {
01785 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01786 }
01787 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01788 agent_pvt->is_available = TRUE;
01789 }
01790
01791 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01792 {
01793 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01794 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01795 return ast_cc_agent_status_response(agent->core_id, state);
01796 }
01797
01798 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01799 {
01800
01801
01802
01803
01804 return 0;
01805 }
01806
01807 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01808 {
01809 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01810
01811
01812
01813
01814 if (!agent_pvt->is_available) {
01815 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01816 agent->device_name);
01817 }
01818
01819
01820
01821 sip_pvt_lock(agent_pvt->subscribe_pvt);
01822 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01823 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01824 return 0;
01825 }
01826
01827 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01828 {
01829 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01830
01831 if (!agent_pvt) {
01832
01833 return;
01834 }
01835
01836 sip_cc_agent_stop_offer_timer(agent);
01837 if (agent_pvt->subscribe_pvt) {
01838 sip_pvt_lock(agent_pvt->subscribe_pvt);
01839 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01840
01841
01842
01843 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01844 }
01845 sip_pvt_unlock(agent_pvt->subscribe_pvt);
01846 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01847 }
01848 ast_free(agent_pvt);
01849 }
01850
01851 struct ao2_container *sip_monitor_instances;
01852
01853 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01854 {
01855 const struct sip_monitor_instance *monitor_instance = obj;
01856 return monitor_instance->core_id;
01857 }
01858
01859 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01860 {
01861 struct sip_monitor_instance *monitor_instance1 = obj;
01862 struct sip_monitor_instance *monitor_instance2 = arg;
01863
01864 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01865 }
01866
01867 static void sip_monitor_instance_destructor(void *data)
01868 {
01869 struct sip_monitor_instance *monitor_instance = data;
01870 if (monitor_instance->subscription_pvt) {
01871 sip_pvt_lock(monitor_instance->subscription_pvt);
01872 monitor_instance->subscription_pvt->expiry = 0;
01873 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01874 sip_pvt_unlock(monitor_instance->subscription_pvt);
01875 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01876 }
01877 if (monitor_instance->suspension_entry) {
01878 monitor_instance->suspension_entry->body[0] = '\0';
01879 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01880 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01881 }
01882 ast_string_field_free_memory(monitor_instance);
01883 }
01884
01885 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)
01886 {
01887 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01888
01889 if (!monitor_instance) {
01890 return NULL;
01891 }
01892
01893 if (ast_string_field_init(monitor_instance, 256)) {
01894 ao2_ref(monitor_instance, -1);
01895 return NULL;
01896 }
01897
01898 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01899 ast_string_field_set(monitor_instance, peername, peername);
01900 ast_string_field_set(monitor_instance, device_name, device_name);
01901 monitor_instance->core_id = core_id;
01902 ao2_link(sip_monitor_instances, monitor_instance);
01903 return monitor_instance;
01904 }
01905
01906 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01907 {
01908 struct sip_monitor_instance *monitor_instance = obj;
01909 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01910 }
01911
01912 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01913 {
01914 struct sip_monitor_instance *monitor_instance = obj;
01915 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01916 }
01917
01918 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01919 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01920 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01921 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01922 static void sip_cc_monitor_destructor(void *private_data);
01923
01924 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01925 .type = "SIP",
01926 .request_cc = sip_cc_monitor_request_cc,
01927 .suspend = sip_cc_monitor_suspend,
01928 .unsuspend = sip_cc_monitor_unsuspend,
01929 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01930 .destructor = sip_cc_monitor_destructor,
01931 };
01932
01933 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01934 {
01935 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01936 enum ast_cc_service_type service = monitor->service_offered;
01937 int when;
01938
01939 if (!monitor_instance) {
01940 return -1;
01941 }
01942
01943 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01944 return -1;
01945 }
01946
01947 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01948 ast_get_ccnr_available_timer(monitor->interface->config_params);
01949
01950 sip_pvt_lock(monitor_instance->subscription_pvt);
01951 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01952 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
01953 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01954 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01955 monitor_instance->subscription_pvt->expiry = when;
01956
01957 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01958 sip_pvt_unlock(monitor_instance->subscription_pvt);
01959
01960 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01961 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01962 return 0;
01963 }
01964
01965 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01966 {
01967 struct ast_str *body = ast_str_alloca(size);
01968 char tuple_id[32];
01969
01970 generate_random_string(tuple_id, sizeof(tuple_id));
01971
01972
01973
01974
01975 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01976
01977
01978
01979
01980
01981
01982 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01983 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01984 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01985 ast_str_append(&body, 0, "</tuple>\n");
01986 ast_str_append(&body, 0, "</presence>\n");
01987 ast_copy_string(pidf_body, ast_str_buffer(body), size);
01988 return 0;
01989 }
01990
01991 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01992 {
01993 struct sip_monitor_instance *monitor_instance = monitor->private_data;
01994 enum sip_publish_type publish_type;
01995 struct cc_epa_entry *cc_entry;
01996
01997 if (!monitor_instance) {
01998 return -1;
01999 }
02000
02001 if (!monitor_instance->suspension_entry) {
02002
02003 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02004 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02005 ao2_ref(monitor_instance, -1);
02006 return -1;
02007 }
02008 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02009 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02010 ao2_ref(monitor_instance, -1);
02011 return -1;
02012 }
02013 cc_entry->core_id = monitor->core_id;
02014 monitor_instance->suspension_entry->instance_data = cc_entry;
02015 publish_type = SIP_PUBLISH_INITIAL;
02016 } else {
02017 publish_type = SIP_PUBLISH_MODIFY;
02018 cc_entry = monitor_instance->suspension_entry->instance_data;
02019 }
02020
02021 cc_entry->current_state = CC_CLOSED;
02022
02023 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02024
02025
02026
02027
02028
02029
02030
02031
02032
02033
02034
02035
02036 return 0;
02037 }
02038 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02039 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02040 }
02041
02042 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02043 {
02044 struct sip_monitor_instance *monitor_instance = monitor->private_data;
02045 struct cc_epa_entry *cc_entry;
02046
02047 if (!monitor_instance) {
02048 return -1;
02049 }
02050
02051 ast_assert(monitor_instance->suspension_entry != NULL);
02052
02053 cc_entry = monitor_instance->suspension_entry->instance_data;
02054 cc_entry->current_state = CC_OPEN;
02055 if (ast_strlen_zero(monitor_instance->notify_uri)) {
02056
02057
02058
02059
02060 return 0;
02061 }
02062 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02063 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02064 }
02065
02066 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02067 {
02068 if (*sched_id != -1) {
02069 AST_SCHED_DEL(sched, *sched_id);
02070 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02071 }
02072 return 0;
02073 }
02074
02075 static void sip_cc_monitor_destructor(void *private_data)
02076 {
02077 struct sip_monitor_instance *monitor_instance = private_data;
02078 ao2_unlink(sip_monitor_instances, monitor_instance);
02079 ast_module_unref(ast_module_info->self);
02080 }
02081
02082 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02083 {
02084 char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
02085 char *uri;
02086 char *purpose;
02087 char *service_str;
02088 static const char cc_purpose[] = "purpose=call-completion";
02089 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02090
02091 if (ast_strlen_zero(call_info)) {
02092
02093 return -1;
02094 }
02095
02096 uri = strsep(&call_info, ";");
02097
02098 while ((purpose = strsep(&call_info, ";"))) {
02099 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02100 break;
02101 }
02102 }
02103 if (!purpose) {
02104
02105 return -1;
02106 }
02107
02108
02109 while ((service_str = strsep(&call_info, ";"))) {
02110 if (!strncmp(service_str, "m=", 2)) {
02111 break;
02112 }
02113 }
02114 if (!service_str) {
02115
02116
02117
02118 service_str = "BS";
02119 } else {
02120
02121
02122
02123 strsep(&service_str, "=");
02124 }
02125
02126 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02127
02128 return -1;
02129 }
02130
02131 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02132
02133 return 0;
02134 }
02135
02136
02137
02138
02139
02140
02141
02142
02143
02144
02145
02146
02147
02148
02149
02150
02151
02152
02153 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02154 {
02155 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02156 int core_id;
02157 char interface_name[AST_CHANNEL_NAME];
02158
02159 if (monitor_policy == AST_CC_MONITOR_NEVER) {
02160
02161 return;
02162 }
02163
02164 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02165
02166 return;
02167 }
02168
02169 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02170
02171 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02172 char subscribe_uri[SIPBUFSIZE];
02173 char device_name[AST_CHANNEL_NAME];
02174 enum ast_cc_service_type offered_service;
02175 struct sip_monitor_instance *monitor_instance;
02176 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02177
02178
02179
02180
02181 goto generic;
02182 }
02183 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02184 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02185
02186 goto generic;
02187 }
02188
02189
02190
02191
02192 ast_module_ref(ast_module_info->self);
02193 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02194 ao2_ref(monitor_instance, -1);
02195 return;
02196 }
02197
02198 generic:
02199 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02200 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02201 }
02202 }
02203
02204
02205 static struct ast_tls_config sip_tls_cfg;
02206
02207
02208 static struct ast_tls_config default_tls_cfg;
02209
02210
02211 static struct ast_tcptls_session_args sip_tcp_desc = {
02212 .accept_fd = -1,
02213 .master = AST_PTHREADT_NULL,
02214 .tls_cfg = NULL,
02215 .poll_timeout = -1,
02216 .name = "SIP TCP server",
02217 .accept_fn = ast_tcptls_server_root,
02218 .worker_fn = sip_tcp_worker_fn,
02219 };
02220
02221
02222 static struct ast_tcptls_session_args sip_tls_desc = {
02223 .accept_fd = -1,
02224 .master = AST_PTHREADT_NULL,
02225 .tls_cfg = &sip_tls_cfg,
02226 .poll_timeout = -1,
02227 .name = "SIP TLS server",
02228 .accept_fn = ast_tcptls_server_root,
02229 .worker_fn = sip_tcp_worker_fn,
02230 };
02231
02232
02233
02234 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02235
02236 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02237 {
02238 if (p)
02239 #ifdef REF_DEBUG
02240 __ao2_ref_debug(p, 1, tag, file, line, func);
02241 #else
02242 ao2_ref(p, 1);
02243 #endif
02244 else
02245 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02246 return p;
02247 }
02248
02249 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02250 {
02251 if (p)
02252 #ifdef REF_DEBUG
02253 __ao2_ref_debug(p, -1, tag, file, line, func);
02254 #else
02255 ao2_ref(p, -1);
02256 #endif
02257 return NULL;
02258 }
02259
02260
02261
02262
02263 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02264 {
02265 const struct _map_x_s *cur;
02266
02267 for (cur = table; cur->s; cur++) {
02268 if (cur->x == x) {
02269 return cur->s;
02270 }
02271 }
02272 return errorstring;
02273 }
02274
02275
02276
02277
02278 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02279 {
02280 const struct _map_x_s *cur;
02281
02282 for (cur = table; cur->s; cur++) {
02283 if (!strcasecmp(cur->s, s)) {
02284 return cur->x;
02285 }
02286 }
02287 return errorvalue;
02288 }
02289
02290 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02291 {
02292 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02293 int i;
02294
02295 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02296 if (!strcasecmp(text, sip_reason_table[i].text)) {
02297 ast = sip_reason_table[i].code;
02298 break;
02299 }
02300 }
02301
02302 return ast;
02303 }
02304
02305 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02306 {
02307 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02308 return sip_reason_table[code].text;
02309 }
02310
02311 return "unknown";
02312 }
02313
02314
02315
02316
02317
02318
02319
02320
02321 #define check_request_transport(peer, tmpl) ({ \
02322 int ret = 0; \
02323 if (peer->socket.type == tmpl->socket.type) \
02324 ; \
02325 else if (!(peer->transports & tmpl->socket.type)) {\
02326 ast_log(LOG_ERROR, \
02327 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02328 sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02329 ); \
02330 ret = 1; \
02331 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02332 ast_log(LOG_WARNING, \
02333 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02334 peer->name, sip_get_transport(tmpl->socket.type) \
02335 ); \
02336 } else { \
02337 ast_debug(1, \
02338 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02339 peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
02340 ); \
02341 }\
02342 (ret); \
02343 })
02344
02345
02346
02347
02348 static struct ast_variable *copy_vars(struct ast_variable *src)
02349 {
02350 struct ast_variable *res = NULL, *tmp, *v = NULL;
02351
02352 for (v = src ; v ; v = v->next) {
02353 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02354 tmp->next = res;
02355 res = tmp;
02356 }
02357 }
02358 return res;
02359 }
02360
02361 static void tcptls_packet_destructor(void *obj)
02362 {
02363 struct tcptls_packet *packet = obj;
02364
02365 ast_free(packet->data);
02366 }
02367
02368 static void sip_tcptls_client_args_destructor(void *obj)
02369 {
02370 struct ast_tcptls_session_args *args = obj;
02371 if (args->tls_cfg) {
02372 ast_free(args->tls_cfg->certfile);
02373 ast_free(args->tls_cfg->pvtfile);
02374 ast_free(args->tls_cfg->cipher);
02375 ast_free(args->tls_cfg->cafile);
02376 ast_free(args->tls_cfg->capath);
02377 }
02378 ast_free(args->tls_cfg);
02379 ast_free((char *) args->name);
02380 }
02381
02382 static void sip_threadinfo_destructor(void *obj)
02383 {
02384 struct sip_threadinfo *th = obj;
02385 struct tcptls_packet *packet;
02386
02387 if (th->alert_pipe[1] > -1) {
02388 close(th->alert_pipe[0]);
02389 }
02390 if (th->alert_pipe[1] > -1) {
02391 close(th->alert_pipe[1]);
02392 }
02393 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02394
02395 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02396 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02397 }
02398
02399 if (th->tcptls_session) {
02400 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02401 }
02402 }
02403
02404
02405 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02406 {
02407 struct sip_threadinfo *th;
02408
02409 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02410 return NULL;
02411 }
02412
02413 th->alert_pipe[0] = th->alert_pipe[1] = -1;
02414
02415 if (pipe(th->alert_pipe) == -1) {
02416 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02417 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02418 return NULL;
02419 }
02420 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02421 th->tcptls_session = tcptls_session;
02422 th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02423 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02424 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02425 return th;
02426 }
02427
02428
02429 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02430 {
02431 int res = len;
02432 struct sip_threadinfo *th = NULL;
02433 struct tcptls_packet *packet = NULL;
02434 struct sip_threadinfo tmp = {
02435 .tcptls_session = tcptls_session,
02436 };
02437 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02438
02439 if (!tcptls_session) {
02440 return XMIT_ERROR;
02441 }
02442
02443 ast_mutex_lock(&tcptls_session->lock);
02444
02445 if ((tcptls_session->fd == -1) ||
02446 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02447 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02448 !(packet->data = ast_str_create(len))) {
02449 goto tcptls_write_setup_error;
02450 }
02451
02452
02453 ast_str_set(&packet->data, 0, "%s", (char *) buf);
02454 packet->len = len;
02455
02456
02457
02458
02459 ao2_lock(th);
02460 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02461 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02462 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02463 packet = NULL;
02464 res = XMIT_ERROR;
02465 } else {
02466 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02467 }
02468 ao2_unlock(th);
02469
02470 ast_mutex_unlock(&tcptls_session->lock);
02471 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02472 return res;
02473
02474 tcptls_write_setup_error:
02475 if (th) {
02476 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02477 }
02478 if (packet) {
02479 ao2_t_ref(packet, -1, "could not allocate packet's data");
02480 }
02481 ast_mutex_unlock(&tcptls_session->lock);
02482
02483 return XMIT_ERROR;
02484 }
02485
02486
02487 static void *sip_tcp_worker_fn(void *data)
02488 {
02489 struct ast_tcptls_session_instance *tcptls_session = data;
02490
02491 return _sip_tcp_helper_thread(NULL, tcptls_session);
02492 }
02493
02494
02495
02496
02497
02498
02499
02500
02501 static int sip_check_authtimeout(time_t start)
02502 {
02503 int timeout;
02504 time_t now;
02505 if(time(&now) == -1) {
02506 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02507 return -1;
02508 }
02509
02510 timeout = (authtimeout - (now - start)) * 1000;
02511 if (timeout < 0) {
02512
02513 return 0;
02514 }
02515
02516 return timeout;
02517 }
02518
02519
02520
02521
02522 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02523 {
02524 int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02525 time_t start;
02526 struct sip_request req = { 0, } , reqcpy = { 0, };
02527 struct sip_threadinfo *me = NULL;
02528 char buf[1024] = "";
02529 struct pollfd fds[2] = { { 0 }, { 0 }, };
02530 struct ast_tcptls_session_args *ca = NULL;
02531
02532
02533
02534
02535
02536
02537
02538
02539
02540
02541
02542
02543 if (!tcptls_session->client) {
02544 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02545
02546 goto cleanup;
02547 }
02548
02549 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02550 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02551 goto cleanup;
02552 }
02553
02554 flags |= O_NONBLOCK;
02555 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02556 ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02557 goto cleanup;
02558 }
02559
02560 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02561 goto cleanup;
02562 }
02563 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02564 } else {
02565 struct sip_threadinfo tmp = {
02566 .tcptls_session = tcptls_session,
02567 };
02568
02569 if ((!(ca = tcptls_session->parent)) ||
02570 (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02571 (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02572 goto cleanup;
02573 }
02574 }
02575
02576 flags = 1;
02577 if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02578 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02579 goto cleanup;
02580 }
02581
02582 me->threadid = pthread_self();
02583 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02584
02585
02586 fds[0].fd = tcptls_session->fd;
02587 fds[1].fd = me->alert_pipe[0];
02588 fds[0].events = fds[1].events = POLLIN | POLLPRI;
02589
02590 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02591 goto cleanup;
02592 }
02593 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02594 goto cleanup;
02595 }
02596
02597 if(time(&start) == -1) {
02598 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02599 goto cleanup;
02600 }
02601
02602 for (;;) {
02603 struct ast_str *str_save;
02604
02605 if (!tcptls_session->client && req.authenticated && !authenticated) {
02606 authenticated = 1;
02607 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02608 }
02609
02610
02611 if (!tcptls_session->client && !authenticated ) {
02612 if ((timeout = sip_check_authtimeout(start)) < 0) {
02613 goto cleanup;
02614 }
02615
02616 if (timeout == 0) {
02617 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02618 goto cleanup;
02619 }
02620 } else {
02621 timeout = -1;
02622 }
02623
02624 res = ast_poll(fds, 2, timeout);
02625 if (res < 0) {
02626 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02627 goto cleanup;
02628 } else if (res == 0) {
02629
02630 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02631 goto cleanup;
02632 }
02633
02634
02635
02636 if (fds[0].revents) {
02637 after_poll = 1;
02638
02639 fds[0].revents = 0;
02640
02641
02642 str_save = req.data;
02643 memset(&req, 0, sizeof(req));
02644 req.data = str_save;
02645 ast_str_reset(req.data);
02646
02647 str_save = reqcpy.data;
02648 memset(&reqcpy, 0, sizeof(reqcpy));
02649 reqcpy.data = str_save;
02650 ast_str_reset(reqcpy.data);
02651
02652 memset(buf, 0, sizeof(buf));
02653
02654 if (tcptls_session->ssl) {
02655 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02656 req.socket.port = htons(ourport_tls);
02657 } else {
02658 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02659 req.socket.port = htons(ourport_tcp);
02660 }
02661 req.socket.fd = tcptls_session->fd;
02662
02663
02664 while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
02665 if (!tcptls_session->client && !authenticated ) {
02666 if ((timeout = sip_check_authtimeout(start)) < 0) {
02667 goto cleanup;
02668 }
02669
02670 if (timeout == 0) {
02671 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02672 goto cleanup;
02673 }
02674 } else {
02675 timeout = -1;
02676 }
02677
02678
02679
02680
02681 if (!tcptls_session->ssl || need_poll) {
02682 need_poll = 0;
02683 after_poll = 1;
02684 res = ast_wait_for_input(tcptls_session->fd, timeout);
02685 if (res < 0) {
02686 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02687 goto cleanup;
02688 } else if (res == 0) {
02689
02690 ast_debug(2, "SIP TCP server timed out\n");
02691 goto cleanup;
02692 }
02693 }
02694
02695 ast_mutex_lock(&tcptls_session->lock);
02696 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02697 ast_mutex_unlock(&tcptls_session->lock);
02698 if (after_poll) {
02699 goto cleanup;
02700 } else {
02701 need_poll = 1;
02702 continue;
02703 }
02704 }
02705 ast_mutex_unlock(&tcptls_session->lock);
02706 after_poll = 0;
02707 if (me->stop) {
02708 goto cleanup;
02709 }
02710 ast_str_append(&req.data, 0, "%s", buf);
02711 }
02712 copy_request(&reqcpy, &req);
02713 parse_request(&reqcpy);
02714
02715 if (sscanf(sip_get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02716 while (cl > 0) {
02717 size_t bytes_read;
02718 if (!tcptls_session->client && !authenticated ) {
02719 if ((timeout = sip_check_authtimeout(start)) < 0) {
02720 goto cleanup;
02721 }
02722
02723 if (timeout == 0) {
02724 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02725 goto cleanup;
02726 }
02727 } else {
02728 timeout = -1;
02729 }
02730
02731 if (!tcptls_session->ssl || need_poll) {
02732 need_poll = 0;
02733 after_poll = 1;
02734 res = ast_wait_for_input(tcptls_session->fd, timeout);
02735 if (res < 0) {
02736 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02737 goto cleanup;
02738 } else if (res == 0) {
02739
02740 ast_debug(2, "SIP TCP server timed out\n");
02741 goto cleanup;
02742 }
02743 }
02744
02745 ast_mutex_lock(&tcptls_session->lock);
02746 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02747 ast_mutex_unlock(&tcptls_session->lock);
02748 if (after_poll) {
02749 goto cleanup;
02750 } else {
02751 need_poll = 1;
02752 continue;
02753 }
02754 }
02755 buf[bytes_read] = '\0';
02756 ast_mutex_unlock(&tcptls_session->lock);
02757 after_poll = 0;
02758 if (me->stop) {
02759 goto cleanup;
02760 }
02761 cl -= strlen(buf);
02762 ast_str_append(&req.data, 0, "%s", buf);
02763 }
02764 }
02765
02766
02767
02768 req.socket.tcptls_session = tcptls_session;
02769 handle_request_do(&req, &tcptls_session->remote_address);
02770 }
02771
02772 if (fds[1].revents) {
02773 enum sip_tcptls_alert alert;
02774 struct tcptls_packet *packet;
02775
02776 fds[1].revents = 0;
02777
02778 if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02779 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02780 continue;
02781 }
02782
02783 switch (alert) {
02784 case TCPTLS_ALERT_STOP:
02785 goto cleanup;
02786 case TCPTLS_ALERT_DATA:
02787 ao2_lock(me);
02788 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02789 ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02790 }
02791 ao2_unlock(me);
02792
02793 if (packet) {
02794 if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02795 ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02796 }
02797 ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02798 }
02799 break;
02800 default:
02801 ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02802 }
02803 }
02804 }
02805
02806 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02807
02808 cleanup:
02809 if (tcptls_session && !tcptls_session->client && !authenticated) {
02810 ast_atomic_fetchadd_int(&unauth_sessions, -1);
02811 }
02812
02813 if (me) {
02814 ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02815 ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02816 }
02817 deinit_req(&reqcpy);
02818 deinit_req(&req);
02819
02820
02821 if (ca) {
02822 ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02823 }
02824
02825 if (tcptls_session) {
02826 ast_mutex_lock(&tcptls_session->lock);
02827 ast_tcptls_close_session_file(tcptls_session);
02828 tcptls_session->parent = NULL;
02829 ast_mutex_unlock(&tcptls_session->lock);
02830
02831 ao2_ref(tcptls_session, -1);
02832 tcptls_session = NULL;
02833 }
02834 return NULL;
02835 }
02836
02837 #ifdef REF_DEBUG
02838 #define sip_ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02839 #define sip_unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02840 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02841 {
02842 if (peer)
02843 __ao2_ref_debug(peer, 1, tag, file, line, func);
02844 else
02845 ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02846 return peer;
02847 }
02848
02849 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02850 {
02851 if (peer)
02852 __ao2_ref_debug(peer, -1, tag, file, line, func);
02853 return NULL;
02854 }
02855 #else
02856
02857
02858
02859
02860
02861 void *sip_unref_peer(struct sip_peer *peer, char *tag)
02862 {
02863 ao2_t_ref(peer, -1, tag);
02864 return NULL;
02865 }
02866
02867 struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
02868 {
02869 ao2_t_ref(peer, 1, tag);
02870 return peer;
02871 }
02872 #endif
02873
02874 static void peer_sched_cleanup(struct sip_peer *peer)
02875 {
02876 if (peer->pokeexpire != -1) {
02877 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02878 sip_unref_peer(peer, "removing poke peer ref"));
02879 }
02880 if (peer->expire != -1) {
02881 AST_SCHED_DEL_UNREF(sched, peer->expire,
02882 sip_unref_peer(peer, "remove register expire ref"));
02883 }
02884 }
02885
02886 typedef enum {
02887 SIP_PEERS_MARKED,
02888 SIP_PEERS_ALL,
02889 } peer_unlink_flag_t;
02890
02891
02892
02893 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
02894 {
02895 struct sip_peer *peer = peerobj;
02896 peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
02897
02898 if (which == SIP_PEERS_ALL || peer->the_mark) {
02899 peer_sched_cleanup(peer);
02900 if (peer->dnsmgr) {
02901 ast_dnsmgr_release(peer->dnsmgr);
02902 peer->dnsmgr = NULL;
02903 sip_unref_peer(peer, "Release peer from dnsmgr");
02904 }
02905 return CMP_MATCH;
02906 }
02907 return 0;
02908 }
02909
02910 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
02911 {
02912 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02913 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02914 ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02915 match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02916 }
02917
02918
02919 static void unlink_marked_peers_from_tables(void)
02920 {
02921 unlink_peers_from_tables(SIP_PEERS_MARKED);
02922 }
02923
02924 static void unlink_all_peers_from_tables(void)
02925 {
02926 unlink_peers_from_tables(SIP_PEERS_ALL);
02927 }
02928
02929
02930 static void unlink_peer_from_tables(struct sip_peer *peer)
02931 {
02932 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02933 if (!ast_sockaddr_isnull(&peer->addr)) {
02934 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02935 }
02936 }
02937
02938
02939
02940
02941
02942
02943
02944
02945
02946
02947
02948
02949 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02950 {
02951 struct sip_proxy *old_obproxy = pvt->outboundproxy;
02952
02953
02954
02955 if (proxy && proxy != &sip_cfg.outboundproxy) {
02956 ao2_ref(proxy, +1);
02957 }
02958 pvt->outboundproxy = proxy;
02959 if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02960 ao2_ref(old_obproxy, -1);
02961 }
02962 }
02963
02964
02965
02966
02967
02968
02969
02970
02971 void dialog_unlink_all(struct sip_pvt *dialog)
02972 {
02973 struct sip_pkt *cp;
02974 struct ast_channel *owner;
02975
02976 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02977
02978 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02979 ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
02980 ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
02981
02982
02983 owner = sip_pvt_lock_full(dialog);
02984 if (owner) {
02985 ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
02986 owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02987 ast_channel_unlock(owner);
02988 ast_channel_unref(owner);
02989 dialog->owner = NULL;
02990 }
02991 sip_pvt_unlock(dialog);
02992
02993 if (dialog->registry) {
02994 if (dialog->registry->call == dialog) {
02995 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02996 }
02997 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02998 }
02999 if (dialog->stateid != -1) {
03000 ast_extension_state_del(dialog->stateid, cb_extensionstate);
03001 dialog->stateid = -1;
03002 }
03003
03004 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03005 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03006 }
03007 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03008 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03009 }
03010
03011
03012 while((cp = dialog->packets)) {
03013 dialog->packets = dialog->packets->next;
03014 AST_SCHED_DEL(sched, cp->retransid);
03015 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03016 if (cp->data) {
03017 ast_free(cp->data);
03018 }
03019 ast_free(cp);
03020 }
03021
03022 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"));
03023
03024 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"));
03025
03026 if (dialog->autokillid > -1) {
03027 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"));
03028 }
03029
03030 if (dialog->request_queue_sched_id > -1) {
03031 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"));
03032 }
03033
03034 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"));
03035
03036 if (dialog->t38id > -1) {
03037 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"));
03038 }
03039
03040 if (dialog->stimer) {
03041 stop_session_timer(dialog);
03042 }
03043
03044 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03045 }
03046
03047 void *registry_unref(struct sip_registry *reg, char *tag)
03048 {
03049 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03050 ASTOBJ_UNREF(reg, sip_registry_destroy);
03051 return NULL;
03052 }
03053
03054
03055 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03056 {
03057 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03058 return ASTOBJ_REF(reg);
03059 }
03060
03061
03062 static struct ast_udptl_protocol sip_udptl = {
03063 type: "SIP",
03064 get_udptl_info: sip_get_udptl_peer,
03065 set_udptl_peer: sip_set_udptl_peer,
03066 };
03067
03068 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03069 __attribute__((format(printf, 2, 3)));
03070
03071
03072
03073 static const char *referstatus2str(enum referstatus rstatus)
03074 {
03075 return map_x_s(referstatusstrings, rstatus, "");
03076 }
03077
03078 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03079 {
03080 if (pvt->final_destruction_scheduled) {
03081 return;
03082 }
03083 append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03084 if (!pvt->needdestroy) {
03085 pvt->needdestroy = 1;
03086 ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
03087 }
03088 }
03089
03090
03091
03092
03093 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03094 {
03095 if (p->initreq.headers) {
03096 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03097 } else {
03098 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03099 }
03100
03101 copy_request(&p->initreq, req);
03102 parse_request(&p->initreq);
03103 if (req->debug) {
03104 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03105 }
03106 }
03107
03108
03109 static void sip_alreadygone(struct sip_pvt *dialog)
03110 {
03111 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03112 dialog->alreadygone = 1;
03113 }
03114
03115
03116 static int proxy_update(struct sip_proxy *proxy)
03117 {
03118
03119
03120 if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03121
03122
03123 proxy->ip.ss.ss_family = get_address_family_filter(&bindaddr);
03124 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03125 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03126 return FALSE;
03127 }
03128
03129 }
03130
03131 ast_sockaddr_set_port(&proxy->ip, proxy->port);
03132
03133 proxy->last_dnsupdate = time(NULL);
03134 return TRUE;
03135 }
03136
03137
03138
03139
03140
03141 unsigned int port_str2int(const char *pt, unsigned int standard)
03142 {
03143 int port = standard;
03144 if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03145 port = standard;
03146 }
03147
03148 return port;
03149 }
03150
03151
03152 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03153 {
03154 if (peer && peer->outboundproxy) {
03155 if (sipdebug) {
03156 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03157 }
03158 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03159 return peer->outboundproxy;
03160 }
03161 if (sip_cfg.outboundproxy.name[0]) {
03162 if (sipdebug) {
03163 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03164 }
03165 append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03166 return &sip_cfg.outboundproxy;
03167 }
03168 if (sipdebug) {
03169 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03170 }
03171 return NULL;
03172 }
03173
03174
03175
03176
03177
03178
03179
03180 static int method_match(enum sipmethod id, const char *name)
03181 {
03182 int len = strlen(sip_methods[id].text);
03183 int l_name = name ? strlen(name) : 0;
03184
03185 return (l_name >= len && name[len] < 33 &&
03186 !strncasecmp(sip_methods[id].text, name, len));
03187 }
03188
03189
03190 static int find_sip_method(const char *msg)
03191 {
03192 int i, res = 0;
03193
03194 if (ast_strlen_zero(msg)) {
03195 return 0;
03196 }
03197 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03198 if (method_match(i, msg)) {
03199 res = sip_methods[i].id;
03200 }
03201 }
03202 return res;
03203 }
03204
03205
03206 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03207 {
03208
03209 if (!sipdebug) {
03210 return 0;
03211 }
03212
03213
03214 if (ast_sockaddr_isnull(&debugaddr)) {
03215 return 1;
03216 }
03217
03218
03219
03220
03221 if (ast_sockaddr_port(&debugaddr)) {
03222 return !ast_sockaddr_cmp(&debugaddr, addr);
03223 } else {
03224 return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03225 }
03226 }
03227
03228
03229 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03230 {
03231 if (p->outboundproxy) {
03232 return &p->outboundproxy->ip;
03233 }
03234
03235 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;
03236 }
03237
03238
03239 static const char *sip_nat_mode(const struct sip_pvt *p)
03240 {
03241 return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03242 }
03243
03244
03245 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03246 {
03247 if (!sipdebug) {
03248 return 0;
03249 }
03250 return sip_debug_test_addr(sip_real_dst(p));
03251 }
03252
03253
03254 static int get_transport_str2enum(const char *transport)
03255 {
03256 int res = 0;
03257
03258 if (ast_strlen_zero(transport)) {
03259 return res;
03260 }
03261
03262 if (!strcasecmp(transport, "udp")) {
03263 res |= SIP_TRANSPORT_UDP;
03264 }
03265 if (!strcasecmp(transport, "tcp")) {
03266 res |= SIP_TRANSPORT_TCP;
03267 }
03268 if (!strcasecmp(transport, "tls")) {
03269 res |= SIP_TRANSPORT_TLS;
03270 }
03271
03272 return res;
03273 }
03274
03275
03276 static inline const char *get_transport_list(unsigned int transports) {
03277 switch (transports) {
03278 case SIP_TRANSPORT_UDP:
03279 return "UDP";
03280 case SIP_TRANSPORT_TCP:
03281 return "TCP";
03282 case SIP_TRANSPORT_TLS:
03283 return "TLS";
03284 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03285 return "TCP,UDP";
03286 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03287 return "TLS,UDP";
03288 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03289 return "TLS,TCP";
03290 default:
03291 return transports ?
03292 "TLS,TCP,UDP" : "UNKNOWN";
03293 }
03294 }
03295
03296
03297 const char *sip_get_transport(enum sip_transport t)
03298 {
03299 switch (t) {
03300 case SIP_TRANSPORT_UDP:
03301 return "UDP";
03302 case SIP_TRANSPORT_TCP:
03303 return "TCP";
03304 case SIP_TRANSPORT_TLS:
03305 return "TLS";
03306 }
03307
03308 return "UNKNOWN";
03309 }
03310
03311
03312 static inline const char *get_srv_protocol(enum sip_transport t)
03313 {
03314 switch (t) {
03315 case SIP_TRANSPORT_UDP:
03316 return "udp";
03317 case SIP_TRANSPORT_TLS:
03318 case SIP_TRANSPORT_TCP:
03319 return "tcp";
03320 }
03321
03322 return "udp";
03323 }
03324
03325
03326 static inline const char *get_srv_service(enum sip_transport t)
03327 {
03328 switch (t) {
03329 case SIP_TRANSPORT_TCP:
03330 case SIP_TRANSPORT_UDP:
03331 return "sip";
03332 case SIP_TRANSPORT_TLS:
03333 return "sips";
03334 }
03335 return "sip";
03336 }
03337
03338
03339
03340
03341
03342
03343
03344 static inline const char *get_transport_pvt(struct sip_pvt *p)
03345 {
03346 if (p->outboundproxy && p->outboundproxy->transport) {
03347 set_socket_transport(&p->socket, p->outboundproxy->transport);
03348 }
03349
03350 return sip_get_transport(p->socket.type);
03351 }
03352
03353
03354
03355
03356
03357
03358
03359
03360
03361
03362
03363
03364 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03365 {
03366 int res = 0;
03367 const struct ast_sockaddr *dst = sip_real_dst(p);
03368
03369 ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03370
03371 if (sip_prepare_socket(p) < 0) {
03372 return XMIT_ERROR;
03373 }
03374
03375 if (p->socket.type == SIP_TRANSPORT_UDP) {
03376 res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
03377 } else if (p->socket.tcptls_session) {
03378 res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
03379 } else {
03380 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03381 return XMIT_ERROR;
03382 }
03383
03384 if (res == -1) {
03385 switch (errno) {
03386 case EBADF:
03387 case EHOSTUNREACH:
03388 case ENETDOWN:
03389 case ENETUNREACH:
03390 case ECONNREFUSED:
03391 res = XMIT_ERROR;
03392 }
03393 }
03394 if (res != ast_str_strlen(data)) {
03395 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));
03396 }
03397
03398 return res;
03399 }
03400
03401
03402 static void build_via(struct sip_pvt *p)
03403 {
03404
03405 const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03406
03407
03408 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03409 get_transport_pvt(p),
03410 ast_sockaddr_stringify_remote(&p->ourip),
03411 (int) p->branch, rport);
03412 }
03413
03414
03415
03416
03417
03418
03419
03420
03421 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03422 {
03423 struct ast_sockaddr theirs;
03424
03425
03426
03427
03428
03429
03430
03431
03432
03433
03434
03435
03436
03437 int want_remap = 0;
03438
03439 ast_sockaddr_copy(us, &internip);
03440
03441 ast_ouraddrfor(them, us);
03442 ast_sockaddr_copy(&theirs, them);
03443
03444 if (ast_sockaddr_is_ipv6(&theirs)) {
03445 if (localaddr && !ast_sockaddr_isnull(&externaddr)) {
03446 ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03447 "but we're using IPv6, which doesn't need it. Please "
03448 "remove \"localnet\" and/or \"externaddr\" settings.\n");
03449 }
03450 } else {
03451 want_remap = localaddr &&
03452 !ast_sockaddr_isnull(&externaddr) &&
03453 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03454 }
03455
03456 if (want_remap &&
03457 (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03458
03459 if (externexpire && time(NULL) >= externexpire) {
03460 if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03461 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03462 }
03463 externexpire = time(NULL) + externrefresh;
03464 }
03465 if (!ast_sockaddr_isnull(&externaddr)) {
03466 ast_sockaddr_copy(us, &externaddr);
03467 switch (p->socket.type) {
03468 case SIP_TRANSPORT_TCP:
03469 if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03470
03471 externtcpport = ast_sockaddr_port(&externaddr);
03472 }
03473 ast_sockaddr_set_port(us, externtcpport);
03474 break;
03475 case SIP_TRANSPORT_TLS:
03476 ast_sockaddr_set_port(us, externtlsport);
03477 break;
03478 case SIP_TRANSPORT_UDP:
03479 if (!ast_sockaddr_port(&externaddr)) {
03480 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03481 }
03482 break;
03483 default:
03484 break;
03485 }
03486 }
03487 ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03488 ast_sockaddr_stringify(them));
03489 } else if (p) {
03490
03491 switch (p->socket.type) {
03492 case SIP_TRANSPORT_TCP:
03493 if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03494 ast_sockaddr_copy(us,
03495 &sip_tcp_desc.local_address);
03496 } else {
03497 ast_sockaddr_set_port(us,
03498 ast_sockaddr_port(&sip_tcp_desc.local_address));
03499 }
03500 break;
03501 case SIP_TRANSPORT_TLS:
03502 if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03503 ast_sockaddr_copy(us,
03504 &sip_tls_desc.local_address);
03505 } else {
03506 ast_sockaddr_set_port(us,
03507 ast_sockaddr_port(&sip_tls_desc.local_address));
03508 }
03509 break;
03510 case SIP_TRANSPORT_UDP:
03511
03512 default:
03513 if (!ast_sockaddr_is_any(&bindaddr)) {
03514 ast_sockaddr_copy(us, &bindaddr);
03515 }
03516 if (!ast_sockaddr_port(us)) {
03517 ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03518 }
03519 }
03520 } else if (!ast_sockaddr_is_any(&bindaddr)) {
03521 ast_sockaddr_copy(us, &bindaddr);
03522 }
03523 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
03524 }
03525
03526
03527 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03528 {
03529 char buf[80], *c = buf;
03530 struct sip_history *hist;
03531 int l;
03532
03533 vsnprintf(buf, sizeof(buf), fmt, ap);
03534 strsep(&c, "\r\n");
03535 l = strlen(buf) + 1;
03536 if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03537 return;
03538 }
03539 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03540 ast_free(hist);
03541 return;
03542 }
03543 memcpy(hist->event, buf, l);
03544 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03545 struct sip_history *oldest;
03546 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03547 p->history_entries--;
03548 ast_free(oldest);
03549 }
03550 AST_LIST_INSERT_TAIL(p->history, hist, list);
03551 p->history_entries++;
03552 }
03553
03554
03555 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03556 {
03557 va_list ap;
03558
03559 if (!p) {
03560 return;
03561 }
03562
03563 if (!p->do_history && !recordhistory && !dumphistory) {
03564 return;
03565 }
03566
03567 va_start(ap, fmt);
03568 append_history_va(p, fmt, ap);
03569 va_end(ap);
03570
03571 return;
03572 }
03573
03574
03575 static int retrans_pkt(const void *data)
03576 {
03577 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03578 int reschedule = DEFAULT_RETRANS;
03579 int xmitres = 0;
03580
03581 int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03582
03583
03584
03585
03586 if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03587 pkt->retrans_stop = 1;
03588 }
03589
03590
03591 sip_pvt_lock(pkt->owner);
03592
03593 if (!pkt->retrans_stop) {
03594 pkt->retrans++;
03595 if (!pkt->timer_t1) {
03596 if (sipdebug) {
03597 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03598 pkt->retransid,
03599 sip_methods[pkt->method].text,
03600 pkt->method);
03601 }
03602 } else {
03603 int siptimer_a;
03604
03605 if (sipdebug) {
03606 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03607 pkt->retransid,
03608 pkt->retrans,
03609 sip_methods[pkt->method].text,
03610 pkt->method);
03611 }
03612 if (!pkt->timer_a) {
03613 pkt->timer_a = 2 ;
03614 } else {
03615 pkt->timer_a = 2 * pkt->timer_a;
03616 }
03617
03618
03619 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03620 if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03621 siptimer_a = 4000;
03622 }
03623
03624
03625 reschedule = siptimer_a;
03626 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03627 pkt->retrans + 1,
03628 siptimer_a,
03629 pkt->timer_t1,
03630 pkt->retransid);
03631 }
03632
03633 if (sip_debug_test_pvt(pkt->owner)) {
03634 const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03635 ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03636 pkt->retrans, sip_nat_mode(pkt->owner),
03637 ast_sockaddr_stringify(dst),
03638 pkt->data->str);
03639 }
03640
03641 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03642 xmitres = __sip_xmit(pkt->owner, pkt->data);
03643
03644
03645
03646
03647
03648
03649 if (xmitres != XMIT_ERROR) {
03650 if (reschedule >= diff) {
03651 pkt->retrans_stop = 1;
03652 reschedule = diff;
03653 }
03654 sip_pvt_unlock(pkt->owner);
03655 return reschedule;
03656 }
03657 }
03658
03659
03660
03661
03662 pkt->retransid = -1;
03663
03664 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03665 if (pkt->is_fatal || sipdebug) {
03666 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"
03667 "Packet timed out after %dms with no response\n",
03668 pkt->owner->callid,
03669 pkt->seqno,
03670 pkt->is_fatal ? "Critical" : "Non-critical",
03671 pkt->is_resp ? "Response" : "Request",
03672 (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03673 }
03674 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03675 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);
03676 }
03677
03678 if (xmitres == XMIT_ERROR) {
03679 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03680 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03681 } else {
03682 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03683 }
03684
03685 if (pkt->is_fatal) {
03686 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03687 sip_pvt_unlock(pkt->owner);
03688 usleep(1);
03689 sip_pvt_lock(pkt->owner);
03690 }
03691 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03692 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03693 }
03694 if (pkt->owner->owner) {
03695 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);
03696
03697 if (pkt->is_resp &&
03698 (pkt->response_code >= 200) &&
03699 (pkt->response_code < 300) &&
03700 pkt->owner->pendinginvite &&
03701 ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03702
03703
03704
03705
03706
03707
03708
03709 pkt->owner->invitestate = INV_TERMINATED;
03710 pkt->owner->pendinginvite = 0;
03711 } else {
03712
03713 sip_alreadygone(pkt->owner);
03714 }
03715 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03716 ast_channel_unlock(pkt->owner->owner);
03717 } else {
03718
03719
03720
03721 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03722 pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03723 sip_alreadygone(pkt->owner);
03724 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03725 }
03726 }
03727 }
03728
03729 if (pkt->method == SIP_BYE) {
03730
03731 sip_alreadygone(pkt->owner);
03732 if (pkt->owner->owner) {
03733 ast_channel_unlock(pkt->owner->owner);
03734 }
03735 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03736 pvt_set_needdestroy(pkt->owner, "no response to BYE");
03737 }
03738
03739
03740 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03741 if (cur == pkt) {
03742 UNLINK(cur, pkt->owner->packets, prev);
03743 sip_pvt_unlock(pkt->owner);
03744 if (pkt->owner) {
03745 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03746 }
03747 if (pkt->data) {
03748 ast_free(pkt->data);
03749 }
03750 pkt->data = NULL;
03751 ast_free(pkt);
03752 return 0;
03753 }
03754 }
03755
03756 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03757 sip_pvt_unlock(pkt->owner);
03758 return 0;
03759 }
03760
03761
03762
03763
03764
03765
03766 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03767 {
03768 struct sip_pkt *pkt = NULL;
03769 int siptimer_a = DEFAULT_RETRANS;
03770 int xmitres = 0;
03771 int respid;
03772
03773 if (sipmethod == SIP_INVITE) {
03774
03775 p->pendinginvite = seqno;
03776 }
03777
03778
03779
03780
03781 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03782 xmitres = __sip_xmit(p, data);
03783 if (xmitres == XMIT_ERROR) {
03784 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03785 return AST_FAILURE;
03786 } else {
03787 return AST_SUCCESS;
03788 }
03789 }
03790
03791 if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03792 return AST_FAILURE;
03793 }
03794
03795 if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03796 ast_free(pkt);
03797 return AST_FAILURE;
03798 }
03799 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03800
03801 pkt->method = sipmethod;
03802 pkt->seqno = seqno;
03803 pkt->is_resp = resp;
03804 pkt->is_fatal = fatal;
03805 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03806 pkt->next = p->packets;
03807 p->packets = pkt;
03808 if (resp) {
03809
03810 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03811 pkt->response_code = respid;
03812 }
03813 }
03814 pkt->timer_t1 = p->timer_t1;
03815 pkt->retransid = -1;
03816 if (pkt->timer_t1) {
03817 siptimer_a = pkt->timer_t1;
03818 }
03819
03820 pkt->time_sent = ast_tvnow();
03821 pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1);
03822
03823
03824 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03825 if (sipdebug) {
03826 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03827 }
03828
03829 xmitres = __sip_xmit(pkt->owner, pkt->data);
03830
03831 if (xmitres == XMIT_ERROR) {
03832 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03833 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03834 AST_SCHED_DEL(sched, pkt->retransid);
03835 p->packets = pkt->next;
03836 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03837 ast_free(pkt->data);
03838 ast_free(pkt);
03839 return AST_FAILURE;
03840 } else {
03841
03842
03843
03844
03845 if (monitor_thread != AST_PTHREADT_NULL) {
03846 pthread_kill(monitor_thread, SIGURG);
03847 }
03848 return AST_SUCCESS;
03849 }
03850 }
03851
03852
03853
03854
03855
03856
03857 static int __sip_autodestruct(const void *data)
03858 {
03859 struct sip_pvt *p = (struct sip_pvt *)data;
03860 struct ast_channel *owner;
03861
03862
03863 if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03864 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03865 p->subscribed = NONE;
03866 append_history(p, "Subscribestatus", "timeout");
03867 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03868 return 10000;
03869 }
03870
03871
03872 if (p->packets) {
03873 if (!p->needdestroy) {
03874 char method_str[31];
03875 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03876 append_history(p, "ReliableXmit", "timeout");
03877 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03878 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03879 pvt_set_needdestroy(p, "autodestruct");
03880 }
03881 }
03882 return 10000;
03883 } else {
03884
03885 __sip_pretend_ack(p);
03886 }
03887 }
03888
03889
03890 p->autokillid = -1;
03891
03892
03893
03894
03895
03896 owner = sip_pvt_lock_full(p);
03897 if (owner) {
03898 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03899 ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
03900 ast_channel_unlock(owner);
03901 ast_channel_unref(owner);
03902 } else if (p->refer && !p->alreadygone) {
03903 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03904 stop_media_flows(p);
03905 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03906 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03907 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03908 } else {
03909 append_history(p, "AutoDestroy", "%s", p->callid);
03910 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03911 sip_pvt_unlock(p);
03912 dialog_unlink_all(p);
03913 sip_pvt_lock(p);
03914
03915
03916
03917 }
03918
03919 sip_pvt_unlock(p);
03920
03921 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03922
03923 return 0;
03924 }
03925
03926
03927
03928
03929 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03930 {
03931 if (p->final_destruction_scheduled) {
03932 return;
03933 }
03934
03935 sip_scheddestroy(p, ms);
03936 if (p->autokillid != -1) {
03937 p->final_destruction_scheduled = 1;
03938 }
03939 }
03940
03941
03942 void sip_scheddestroy(struct sip_pvt *p, int ms)
03943 {
03944 if (p->final_destruction_scheduled) {
03945 return;
03946 }
03947
03948 if (ms < 0) {
03949 if (p->timer_t1 == 0) {
03950 p->timer_t1 = global_t1;
03951 }
03952 if (p->timer_b == 0) {
03953 p->timer_b = global_timer_b;
03954 }
03955 ms = p->timer_t1 * 64;
03956 }
03957 if (sip_debug_test_pvt(p)) {
03958 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03959 }
03960 if (sip_cancel_destroy(p)) {
03961 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03962 }
03963
03964 if (p->do_history) {
03965 append_history(p, "SchedDestroy", "%d ms", ms);
03966 }
03967 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03968
03969 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
03970 stop_session_timer(p);
03971 }
03972 }
03973
03974
03975
03976
03977
03978 int sip_cancel_destroy(struct sip_pvt *p)
03979 {
03980 if (p->final_destruction_scheduled) {
03981 return 0;
03982 }
03983
03984 if (p->autokillid > -1) {
03985 append_history(p, "CancelDestroy", "");
03986 AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
03987 }
03988 return 0;
03989 }
03990
03991
03992
03993 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
03994 {
03995 struct sip_pkt *cur, *prev = NULL;
03996 const char *msg = "Not Found";
03997 int res = FALSE;
03998
03999
04000
04001
04002
04003
04004 if (p->outboundproxy && !p->outboundproxy->force){
04005 ref_proxy(p, NULL);
04006 }
04007
04008 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04009 if (cur->seqno != seqno || cur->is_resp != resp) {
04010 continue;
04011 }
04012 if (cur->is_resp || cur->method == sipmethod) {
04013 res = TRUE;
04014 msg = "Found";
04015 if (!resp && (seqno == p->pendinginvite)) {
04016 ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04017 p->pendinginvite = 0;
04018 }
04019 if (cur->retransid > -1) {
04020 if (sipdebug)
04021 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04022 }
04023
04024
04025
04026
04027
04028
04029
04030
04031
04032
04033
04034
04035
04036
04037
04038
04039 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04040 sip_pvt_unlock(p);
04041 usleep(1);
04042 sip_pvt_lock(p);
04043 }
04044 UNLINK(cur, p->packets, prev);
04045 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04046 if (cur->data) {
04047 ast_free(cur->data);
04048 }
04049 ast_free(cur);
04050 break;
04051 }
04052 }
04053 ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04054 p->callid, resp ? "Response" : "Request", seqno, msg);
04055 return res;
04056 }
04057
04058
04059
04060 void __sip_pretend_ack(struct sip_pvt *p)
04061 {
04062 struct sip_pkt *cur = NULL;
04063
04064 while (p->packets) {
04065 int method;
04066 if (cur == p->packets) {
04067 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04068 return;
04069 }
04070 cur = p->packets;
04071 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04072 __sip_ack(p, cur->seqno, cur->is_resp, method);
04073 }
04074 }
04075
04076
04077 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04078 {
04079 struct sip_pkt *cur;
04080 int res = FALSE;
04081
04082 for (cur = p->packets; cur; cur = cur->next) {
04083 if (cur->seqno == seqno && cur->is_resp == resp &&
04084 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04085
04086 if (cur->retransid > -1) {
04087 if (sipdebug)
04088 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04089 }
04090 AST_SCHED_DEL(sched, cur->retransid);
04091 res = TRUE;
04092 break;
04093 }
04094 }
04095 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");
04096 return res;
04097 }
04098
04099
04100
04101 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04102 {
04103 copy_request(dst, src);
04104 parse_request(dst);
04105 }
04106
04107
04108 static void add_blank(struct sip_request *req)
04109 {
04110 if (!req->lines) {
04111
04112 ast_str_append(&req->data, 0, "\r\n");
04113 }
04114 }
04115
04116 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04117 {
04118 const char *msg = NULL;
04119 struct ast_channel *chan;
04120 int res = 0;
04121
04122 chan = sip_pvt_lock_full(pvt);
04123
04124 if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04125 msg = "183 Session Progress";
04126 }
04127
04128 if (pvt->invitestate < INV_COMPLETED) {
04129 if (with_sdp) {
04130 transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04131 } else {
04132 transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04133 }
04134 res = PROVIS_KEEPALIVE_TIMEOUT;
04135 }
04136
04137 if (chan) {
04138 ast_channel_unlock(chan);
04139 chan = ast_channel_unref(chan);
04140 }
04141
04142 if (!res) {
04143 pvt->provisional_keepalive_sched_id = -1;
04144 }
04145
04146 sip_pvt_unlock(pvt);
04147
04148 #if 0
04149
04150
04151
04152
04153
04154
04155
04156
04157 if (!res) {
04158 dialog_unref(pvt, "dialog ref for provisional keepalive");
04159 }
04160 #endif
04161
04162 return res;
04163 }
04164
04165 static int send_provisional_keepalive(const void *data)
04166 {
04167 struct sip_pvt *pvt = (struct sip_pvt *) data;
04168
04169 return send_provisional_keepalive_full(pvt, 0);
04170 }
04171
04172 static int send_provisional_keepalive_with_sdp(const void *data)
04173 {
04174 struct sip_pvt *pvt = (void *) data;
04175
04176 return send_provisional_keepalive_full(pvt, 1);
04177 }
04178
04179 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04180 {
04181 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"));
04182
04183 pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04184 with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04185 }
04186
04187
04188 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04189 {
04190 int res;
04191
04192 finalize_content(req);
04193 add_blank(req);
04194 if (sip_debug_test_pvt(p)) {
04195 const struct ast_sockaddr *dst = sip_real_dst(p);
04196
04197 ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04198 reliable ? "Reliably " : "", sip_nat_mode(p),
04199 ast_sockaddr_stringify(dst),
04200 req->data->str);
04201 }
04202 if (p->do_history) {
04203 struct sip_request tmp = { .rlPart1 = 0, };
04204 parse_copy(&tmp, req);
04205 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"),
04206 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04207 deinit_req(&tmp);
04208 }
04209
04210
04211 if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04212 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"));
04213 }
04214
04215 res = (reliable) ?
04216 __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04217 __sip_xmit(p, req->data);
04218 deinit_req(req);
04219 if (res > 0) {
04220 return 0;
04221 }
04222 return res;
04223 }
04224
04225
04226
04227
04228
04229
04230 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04231 {
04232 int res;
04233
04234
04235
04236
04237 if (p->outboundproxy) {
04238 p->sa = p->outboundproxy->ip;
04239 }
04240
04241 finalize_content(req);
04242 add_blank(req);
04243 if (sip_debug_test_pvt(p)) {
04244 if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04245 ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04246 } else {
04247 ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04248 }
04249 }
04250 if (p->do_history) {
04251 struct sip_request tmp = { .rlPart1 = 0, };
04252 parse_copy(&tmp, req);
04253 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04254 deinit_req(&tmp);
04255 }
04256 res = (reliable) ?
04257 __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04258 __sip_xmit(p, req->data);
04259 deinit_req(req);
04260 return res;
04261 }
04262
04263 static void enable_dsp_detect(struct sip_pvt *p)
04264 {
04265 int features = 0;
04266
04267 if (p->dsp) {
04268 return;
04269 }
04270
04271 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04272 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04273 if (p->rtp) {
04274 ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04275 }
04276 features |= DSP_FEATURE_DIGIT_DETECT;
04277 }
04278
04279 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04280 features |= DSP_FEATURE_FAX_DETECT;
04281 }
04282
04283 if (!features) {
04284 return;
04285 }
04286
04287 if (!(p->dsp = ast_dsp_new())) {
04288 return;
04289 }
04290
04291 ast_dsp_set_features(p->dsp, features);
04292 if (global_relaxdtmf) {
04293 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04294 }
04295 }
04296
04297 static void disable_dsp_detect(struct sip_pvt *p)
04298 {
04299 if (p->dsp) {
04300 ast_dsp_free(p->dsp);
04301 p->dsp = NULL;
04302 }
04303 }
04304
04305
04306 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04307 {
04308 int res = -1;
04309 struct sip_pvt *p = chan->tech_pvt;
04310
04311 if (!p) {
04312 ast_log(LOG_ERROR, "Attempt to Ref a null pointer. sip private structure is gone!\n");
04313 return -1;
04314 }
04315
04316 sip_pvt_lock(p);
04317
04318 switch (option) {
04319 case AST_OPTION_FORMAT_READ:
04320 if (p->rtp) {
04321 res = ast_rtp_instance_set_read_format(p->rtp, (struct ast_format *) data);
04322 }
04323 break;
04324 case AST_OPTION_FORMAT_WRITE:
04325 if (p->rtp) {
04326 res = ast_rtp_instance_set_write_format(p->rtp, (struct ast_format *) data);
04327 }
04328 break;
04329 case AST_OPTION_MAKE_COMPATIBLE:
04330 if (p->rtp) {
04331 res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04332 }
04333 break;
04334 case AST_OPTION_DIGIT_DETECT:
04335 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04336 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04337 char *cp = (char *) data;
04338
04339 ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
04340 if (*cp) {
04341 enable_dsp_detect(p);
04342 } else {
04343 disable_dsp_detect(p);
04344 }
04345 res = 0;
04346 }
04347 break;
04348 case AST_OPTION_SECURE_SIGNALING:
04349 p->req_secure_signaling = *(unsigned int *) data;
04350 res = 0;
04351 break;
04352 case AST_OPTION_SECURE_MEDIA:
04353 ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04354 res = 0;
04355 break;
04356 default:
04357 break;
04358 }
04359
04360 sip_pvt_unlock(p);
04361
04362 return res;
04363 }
04364
04365
04366 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04367 {
04368 int res = -1;
04369 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04370 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04371 char *cp;
04372
04373 sip_pvt_lock(p);
04374
04375 switch (option) {
04376 case AST_OPTION_T38_STATE:
04377
04378 if (*datalen != sizeof(enum ast_t38_state)) {
04379 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04380 break;
04381 }
04382
04383
04384 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04385 switch (p->t38.state) {
04386 case T38_LOCAL_REINVITE:
04387 case T38_PEER_REINVITE:
04388 state = T38_STATE_NEGOTIATING;
04389 break;
04390 case T38_ENABLED:
04391 state = T38_STATE_NEGOTIATED;
04392 break;
04393 case T38_REJECTED:
04394 state = T38_STATE_REJECTED;
04395 break;
04396 default:
04397 state = T38_STATE_UNKNOWN;
04398 }
04399 }
04400
04401 *((enum ast_t38_state *) data) = state;
04402 res = 0;
04403
04404 break;
04405 case AST_OPTION_DIGIT_DETECT:
04406 cp = (char *) data;
04407 *cp = p->dsp ? 1 : 0;
04408 ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
04409 break;
04410 case AST_OPTION_SECURE_SIGNALING:
04411 *((unsigned int *) data) = p->req_secure_signaling;
04412 res = 0;
04413 break;
04414 case AST_OPTION_SECURE_MEDIA:
04415 *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04416 res = 0;
04417 break;
04418 case AST_OPTION_DEVICE_NAME:
04419 if (p && p->outgoing_call) {
04420 cp = (char *) data;
04421 ast_copy_string(cp, p->dialstring, *datalen);
04422 res = 0;
04423 }
04424
04425
04426
04427 break;
04428 default:
04429 break;
04430 }
04431
04432 sip_pvt_unlock(p);
04433
04434 return res;
04435 }
04436
04437
04438
04439
04440
04441 const char *find_closing_quote(const char *start, const char *lim)
04442 {
04443 char last_char = '\0';
04444 const char *s;
04445 for (s = start; *s && s != lim; last_char = *s++) {
04446 if (*s == '"' && last_char != '\\')
04447 break;
04448 }
04449 return s;
04450 }
04451
04452
04453 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04454 {
04455 struct sip_pvt *p = chan->tech_pvt;
04456
04457 if (subclass != AST_HTML_URL)
04458 return -1;
04459
04460 ast_string_field_build(p, url, "<%s>;mode=active", data);
04461
04462 if (sip_debug_test_pvt(p))
04463 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04464
04465 switch (chan->_state) {
04466 case AST_STATE_RING:
04467 transmit_response(p, "100 Trying", &p->initreq);
04468 break;
04469 case AST_STATE_RINGING:
04470 transmit_response(p, "180 Ringing", &p->initreq);
04471 break;
04472 case AST_STATE_UP:
04473 if (!p->pendinginvite) {
04474 transmit_reinvite_with_sdp(p, FALSE, FALSE);
04475 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04476 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04477 }
04478 break;
04479 default:
04480 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04481 }
04482
04483 return 0;
04484 }
04485
04486
04487 static const char *sip_get_callid(struct ast_channel *chan)
04488 {
04489 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04490 }
04491
04492
04493
04494
04495
04496
04497 static int sip_sendtext(struct ast_channel *ast, const char *text)
04498 {
04499 struct sip_pvt *dialog = ast->tech_pvt;
04500 int debug;
04501
04502 if (!dialog) {
04503 return -1;
04504 }
04505
04506
04507 if (!text) {
04508 return 0;
04509 }
04510 if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04511 ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04512 return(0);
04513 }
04514
04515 debug = sip_debug_test_pvt(dialog);
04516 if (debug) {
04517 ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
04518 }
04519
04520
04521 sip_pvt_lock(dialog);
04522 destroy_msg_headers(dialog);
04523 ast_string_field_set(dialog, msg_body, text);
04524 transmit_message(dialog, 0, 0);
04525 sip_pvt_unlock(dialog);
04526 return 0;
04527 }
04528
04529
04530
04531
04532
04533
04534 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)
04535 {
04536 char port[10];
04537 char ipaddr[INET6_ADDRSTRLEN];
04538 char regseconds[20];
04539 char *tablename = NULL;
04540 char str_lastms[20];
04541
04542 const char *sysname = ast_config_AST_SYSTEM_NAME;
04543 char *syslabel = NULL;
04544
04545 time_t nowtime = time(NULL) + expirey;
04546 const char *fc = fullcontact ? "fullcontact" : NULL;
04547
04548 int realtimeregs = ast_check_realtime("sipregs");
04549
04550 tablename = realtimeregs ? "sipregs" : "sippeers";
04551
04552 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04553 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
04554 ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04555 ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04556
04557 if (ast_strlen_zero(sysname))
04558 sysname = NULL;
04559 else if (sip_cfg.rtsave_sysname)
04560 syslabel = "regserver";
04561
04562
04563
04564
04565
04566
04567
04568 if (fc) {
04569 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04570 "port", port, "regseconds", regseconds,
04571 deprecated_username ? "username" : "defaultuser", defaultuser,
04572 "useragent", useragent, "lastms", str_lastms,
04573 fc, fullcontact, syslabel, sysname, SENTINEL);
04574 } else {
04575 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04576 "port", port, "regseconds", regseconds,
04577 "useragent", useragent, "lastms", str_lastms,
04578 deprecated_username ? "username" : "defaultuser", defaultuser,
04579 syslabel, sysname, SENTINEL);
04580 }
04581 }
04582
04583
04584 static void register_peer_exten(struct sip_peer *peer, int onoff)
04585 {
04586 char multi[256];
04587 char *stringp, *ext, *context;
04588 struct pbx_find_info q = { .stacklen = 0 };
04589
04590
04591
04592
04593
04594 if (ast_strlen_zero(sip_cfg.regcontext))
04595 return;
04596
04597 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04598 stringp = multi;
04599 while ((ext = strsep(&stringp, "&"))) {
04600 if ((context = strchr(ext, '@'))) {
04601 *context++ = '\0';
04602 if (!ast_context_find(context)) {
04603 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04604 continue;
04605 }
04606 } else {
04607 context = sip_cfg.regcontext;
04608 }
04609 if (onoff) {
04610 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04611 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04612 ast_strdup(peer->name), ast_free_ptr, "SIP");
04613 }
04614 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04615 ast_context_remove_extension(context, ext, 1, NULL);
04616 }
04617 }
04618 }
04619
04620
04621 static void destroy_mailbox(struct sip_mailbox *mailbox)
04622 {
04623 if (mailbox->event_sub)
04624 ast_event_unsubscribe(mailbox->event_sub);
04625 ast_free(mailbox);
04626 }
04627
04628
04629 static void clear_peer_mailboxes(struct sip_peer *peer)
04630 {
04631 struct sip_mailbox *mailbox;
04632
04633 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04634 destroy_mailbox(mailbox);
04635 }
04636
04637 static void sip_destroy_peer_fn(void *peer)
04638 {
04639 sip_destroy_peer(peer);
04640 }
04641
04642
04643 static void sip_destroy_peer(struct sip_peer *peer)
04644 {
04645 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04646
04647
04648
04649
04650
04651
04652 clear_peer_mailboxes(peer);
04653
04654 if (peer->outboundproxy) {
04655 ao2_ref(peer->outboundproxy, -1);
04656 peer->outboundproxy = NULL;
04657 }
04658
04659
04660 if (peer->call) {
04661 dialog_unlink_all(peer->call);
04662 peer->call = dialog_unref(peer->call, "peer->call is being unset");
04663 }
04664
04665 if (peer->mwipvt) {
04666 dialog_unlink_all(peer->mwipvt);
04667 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04668 }
04669
04670 if (peer->chanvars) {
04671 ast_variables_destroy(peer->chanvars);
04672 peer->chanvars = NULL;
04673 }
04674
04675 register_peer_exten(peer, FALSE);
04676 ast_free_ha(peer->ha);
04677 ast_free_ha(peer->directmediaha);
04678 if (peer->selfdestruct)
04679 ast_atomic_fetchadd_int(&apeerobjs, -1);
04680 else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04681 ast_atomic_fetchadd_int(&rpeerobjs, -1);
04682 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04683 } else
04684 ast_atomic_fetchadd_int(&speerobjs, -1);
04685 if (peer->auth) {
04686 ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04687 peer->auth = NULL;
04688 }
04689
04690 if (peer->socket.tcptls_session) {
04691 ao2_ref(peer->socket.tcptls_session, -1);
04692 peer->socket.tcptls_session = NULL;
04693 }
04694
04695 ast_cc_config_params_destroy(peer->cc_params);
04696
04697 ast_string_field_free_memory(peer);
04698
04699 peer->caps = ast_format_cap_destroy(peer->caps);
04700 }
04701
04702
04703 static void update_peer(struct sip_peer *p, int expire)
04704 {
04705 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04706 if (sip_cfg.peer_rtupdate &&
04707 (p->is_realtime || rtcachefriends)) {
04708 realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04709 }
04710 }
04711
04712 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04713 {
04714 struct ast_variable *var = NULL;
04715 struct ast_flags flags = {0};
04716 char *cat = NULL;
04717 const char *insecure;
04718 while ((cat = ast_category_browse(cfg, cat))) {
04719 insecure = ast_variable_retrieve(cfg, cat, "insecure");
04720 set_insecure_flags(&flags, insecure, -1);
04721 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04722 var = ast_category_root(cfg, cat);
04723 break;
04724 }
04725 }
04726 return var;
04727 }
04728
04729 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04730 {
04731 struct ast_config *peerlist;
04732 struct ast_variable *var = NULL;
04733 if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04734 if ((var = get_insecure_variable_from_config(peerlist))) {
04735
04736
04737 var = ast_variables_dup(var);
04738 }
04739 ast_config_destroy(peerlist);
04740 }
04741 return var;
04742 }
04743
04744
04745
04746
04747
04748
04749 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04750 {
04751 struct ast_variable *varregs = NULL;
04752 struct ast_config *regs, *peers;
04753 char *regscat;
04754 const char *regname;
04755
04756 if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04757 return NULL;
04758 }
04759
04760
04761 if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04762 ast_config_destroy(regs);
04763 return NULL;
04764 }
04765
04766
04767
04768 regscat = NULL;
04769 while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04770 char *peerscat;
04771 const char *peername;
04772
04773 peerscat = NULL;
04774 while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04775 if (!strcasecmp(regname, peername)) {
04776
04777
04778 const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04779 struct ast_flags flags = {0};
04780 set_insecure_flags(&flags, insecure, -1);
04781 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04782
04783 if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04784 if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04785 ast_variables_destroy(varregs);
04786 varregs = NULL;
04787 }
04788 }
04789 goto done;
04790 }
04791 }
04792 }
04793 }
04794
04795 done:
04796 ast_config_destroy(regs);
04797 ast_config_destroy(peers);
04798 return varregs;
04799 }
04800
04801 static const char *get_name_from_variable(const struct ast_variable *var)
04802 {
04803
04804
04805
04806
04807
04808
04809
04810
04811 const struct ast_variable *tmp;
04812 for (tmp = var; tmp; tmp = tmp->next) {
04813 if (!strcasecmp(tmp->name, "name")) {
04814 if (!ast_strlen_zero(tmp->value)) {
04815 return tmp->value;
04816 }
04817 break;
04818 }
04819 }
04820 return NULL;
04821 }
04822
04823
04824
04825 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)
04826 {
04827
04828 if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
04829 ;
04830
04831 } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
04832 ;
04833
04834 } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04835
04836
04837
04838
04839
04840
04841 if (addr) {
04842 struct ast_variable *tmp;
04843 for (tmp = *var; tmp; tmp = tmp->next) {
04844 if (!strcasecmp(tmp->name, "host")) {
04845 struct ast_sockaddr *addrs = NULL;
04846
04847 if (ast_sockaddr_resolve(&addrs,
04848 tmp->value,
04849 PARSE_PORT_FORBID,
04850 get_address_family_filter(&bindaddr)) <= 0 ||
04851 ast_sockaddr_cmp(&addrs[0], addr)) {
04852
04853 ast_variables_destroy(*var);
04854 *var = NULL;
04855 }
04856 ast_free(addrs);
04857 break;
04858 }
04859 }
04860 }
04861 }
04862
04863
04864 if (*var) {
04865 if (varregs) {
04866 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04867 }
04868 return 1;
04869 }
04870 return 0;
04871 }
04872
04873
04874
04875
04876
04877
04878
04879 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
04880 struct ast_variable *var = NULL;
04881 const char *old_name = *name;
04882 *name = get_name_from_variable(*varregs);
04883 if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04884 if (!*name) {
04885 ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
04886 }
04887 ast_variables_destroy(*varregs);
04888 *varregs = NULL;
04889 *name = old_name;
04890 }
04891 return var;
04892 }
04893
04894
04895
04896
04897 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, const char *callbackexten, struct ast_variable **var, struct ast_variable **varregs)
04898 {
04899 char portstring[6];
04900 ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04901
04902
04903 *name = NULL;
04904
04905
04906 if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
04907 ;
04908
04909 } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
04910 ;
04911
04912 } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
04913 (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
04914 ;
04915
04916 } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
04917 ;
04918
04919 } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
04920 ;
04921
04922
04923
04924
04925 } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
04926 ;
04927
04928 } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
04929 ;
04930 }
04931
04932
04933 if (!*var) {
04934 return 0;
04935 }
04936
04937
04938
04939
04940 if (!*name && !(*name = get_name_from_variable(*var))) {
04941 ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
04942 ast_variables_destroy(*var);
04943 *var = NULL;
04944 if (varregs && *varregs) {
04945 ast_variables_destroy(*varregs);
04946 *varregs = NULL;
04947 }
04948 return 0;
04949 }
04950
04951
04952
04953
04954 if (varregs && !*varregs) {
04955 *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04956 }
04957 return 1;
04958 }
04959
04960 static int register_realtime_peers_with_callbackextens(void)
04961 {
04962 struct ast_config *cfg;
04963 char *cat = NULL;
04964
04965 if (!(ast_check_realtime("sippeers"))) {
04966 return 0;
04967 }
04968
04969
04970 if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
04971 return -1;
04972 }
04973
04974 while ((cat = ast_category_browse(cfg, cat))) {
04975 struct sip_peer *peer;
04976 struct ast_variable *var = ast_category_root(cfg, cat);
04977
04978 if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
04979 continue;
04980 }
04981 ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
04982
04983 peer->is_realtime = 1;
04984 sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
04985 }
04986
04987 ast_config_destroy(cfg);
04988
04989 return 0;
04990 }
04991
04992
04993
04994
04995
04996
04997
04998
04999
05000
05001 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
05002 {
05003 struct sip_peer *peer = NULL;
05004 struct ast_variable *var = NULL;
05005 struct ast_variable *varregs = NULL;
05006 char ipaddr[INET6_ADDRSTRLEN];
05007 int realtimeregs = ast_check_realtime("sipregs");
05008
05009 if (addr) {
05010 ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05011 } else {
05012 ipaddr[0] = '\0';
05013 }
05014
05015 if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05016 ;
05017 } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
05018 ;
05019 } else {
05020 return NULL;
05021 }
05022
05023
05024
05025 if (which_objects == FINDUSERS) {
05026 struct ast_variable *tmp;
05027 for (tmp = var; tmp; tmp = tmp->next) {
05028 if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05029 goto cleanup;
05030 }
05031 }
05032 }
05033
05034
05035 peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05036 if (!peer) {
05037 goto cleanup;
05038 }
05039
05040 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05041
05042 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05043
05044 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05045 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05046 AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05047 sip_unref_peer(_data, "remove registration ref"),
05048 sip_unref_peer(peer, "remove registration ref"),
05049 sip_ref_peer(peer, "add registration ref"));
05050 }
05051 ao2_t_link(peers, peer, "link peer into peers table");
05052 if (!ast_sockaddr_isnull(&peer->addr)) {
05053 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05054 }
05055 }
05056 peer->is_realtime = 1;
05057
05058 cleanup:
05059 ast_variables_destroy(var);
05060 ast_variables_destroy(varregs);
05061 return peer;
05062 }
05063
05064
05065 static int find_by_name(void *obj, void *arg, void *data, int flags)
05066 {
05067 struct sip_peer *search = obj, *match = arg;
05068 int *which_objects = data;
05069
05070
05071 if (strcmp(search->name, match->name)) {
05072 return 0;
05073 }
05074
05075 switch (*which_objects) {
05076 case FINDUSERS:
05077 if (!(search->type & SIP_TYPE_USER)) {
05078 return 0;
05079 }
05080 break;
05081 case FINDPEERS:
05082 if (!(search->type & SIP_TYPE_PEER)) {
05083 return 0;
05084 }
05085 break;
05086 case FINDALLDEVICES:
05087 break;
05088 }
05089
05090 return CMP_MATCH | CMP_STOP;
05091 }
05092
05093 static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
05094 {
05095 struct sip_peer *p = NULL;
05096 struct sip_peer tmp_peer;
05097
05098 if (peer) {
05099 ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05100 p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05101 } else if (addr) {
05102 ast_sockaddr_copy(&tmp_peer.addr, addr);
05103 tmp_peer.flags[0].flags = 0;
05104 tmp_peer.transports = transport;
05105 p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
05106 if (!p) {
05107 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05108 p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table 2");
05109 if (p) {
05110 return p;
05111 }
05112 }
05113 }
05114
05115 if (!p && (realtime || devstate_only)) {
05116
05117
05118 p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
05119 if (p) {
05120 switch (which_objects) {
05121 case FINDUSERS:
05122 if (!(p->type & SIP_TYPE_USER)) {
05123 sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05124 return NULL;
05125 }
05126 break;
05127 case FINDPEERS:
05128 if (!(p->type & SIP_TYPE_PEER)) {
05129 sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05130 return NULL;
05131 }
05132 break;
05133 case FINDALLDEVICES:
05134 break;
05135 }
05136 }
05137 }
05138
05139 return p;
05140 }
05141
05142
05143
05144
05145
05146
05147
05148
05149
05150
05151
05152
05153
05154
05155 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05156 {
05157 return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
05158 }
05159
05160 static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
05161 {
05162 return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
05163 }
05164
05165
05166 static void do_setnat(struct sip_pvt *p)
05167 {
05168 const char *mode;
05169 int natflags;
05170
05171 natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05172 mode = natflags ? "On" : "Off";
05173
05174 if (p->rtp) {
05175 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05176 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05177 }
05178 if (p->vrtp) {
05179 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05180 ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05181 }
05182 if (p->udptl) {
05183 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05184 ast_udptl_setnat(p->udptl, natflags);
05185 }
05186 if (p->trtp) {
05187 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05188 ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05189 }
05190 }
05191
05192
05193 static void change_t38_state(struct sip_pvt *p, int state)
05194 {
05195 int old = p->t38.state;
05196 struct ast_channel *chan = p->owner;
05197 struct ast_control_t38_parameters parameters = { .request_response = 0 };
05198
05199
05200 if (old == state)
05201 return;
05202
05203 p->t38.state = state;
05204 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
05205
05206
05207 if (!chan)
05208 return;
05209
05210
05211 switch (state) {
05212 case T38_PEER_REINVITE:
05213 parameters = p->t38.their_parms;
05214 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05215 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05216 ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05217 break;
05218 case T38_ENABLED:
05219 parameters = p->t38.their_parms;
05220 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05221 parameters.request_response = AST_T38_NEGOTIATED;
05222 ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05223 break;
05224 case T38_REJECTED:
05225 case T38_DISABLED:
05226 if (old == T38_ENABLED) {
05227 parameters.request_response = AST_T38_TERMINATED;
05228 } else if (old == T38_LOCAL_REINVITE) {
05229 parameters.request_response = AST_T38_REFUSED;
05230 }
05231 break;
05232 case T38_LOCAL_REINVITE:
05233
05234 break;
05235 }
05236
05237
05238 if (parameters.request_response)
05239 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
05240 }
05241
05242
05243 static void set_t38_capabilities(struct sip_pvt *p)
05244 {
05245 if (p->udptl) {
05246 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05247 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05248 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05249 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05250 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05251 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05252 }
05253 }
05254 }
05255
05256 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05257 {
05258 if (to_sock->tcptls_session) {
05259 ao2_ref(to_sock->tcptls_session, -1);
05260 to_sock->tcptls_session = NULL;
05261 }
05262
05263 if (from_sock->tcptls_session) {
05264 ao2_ref(from_sock->tcptls_session, +1);
05265 }
05266
05267 *to_sock = *from_sock;
05268 }
05269
05270
05271
05272
05273 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05274 {
05275 struct ast_sockaddr bindaddr_tmp;
05276
05277 if (!sip_methods[dialog->method].need_rtp) {
05278 return 0;
05279 }
05280
05281 ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05282 if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05283 return -1;
05284 }
05285
05286 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05287 (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
05288 if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05289 return -1;
05290 }
05291 ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05292 ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05293 ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05294
05295 ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05296 }
05297
05298 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05299 if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05300 return -1;
05301 }
05302
05303 ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05304
05305 ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05306 }
05307
05308 ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05309 ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05310 ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05311
05312 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05313 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05314 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05315
05316 ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05317
05318 do_setnat(dialog);
05319
05320 return 0;
05321 }
05322
05323
05324
05325
05326
05327
05328
05329
05330 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05331 {
05332 struct sip_auth_container *credentials;
05333
05334
05335
05336
05337 if (dialog->socket.type && check_request_transport(peer, dialog))
05338 return -1;
05339 copy_socket_data(&dialog->socket, &peer->socket);
05340
05341 if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05342 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
05343 dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05344 dialog->recv = dialog->sa;
05345 } else
05346 return -1;
05347
05348
05349 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05350 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05351 ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05352 ast_format_cap_copy(dialog->caps, peer->caps);
05353 dialog->prefs = peer->prefs;
05354 dialog->amaflags = peer->amaflags;
05355
05356 ast_string_field_set(dialog, engine, peer->engine);
05357
05358 dialog->rtptimeout = peer->rtptimeout;
05359 dialog->rtpholdtimeout = peer->rtpholdtimeout;
05360 dialog->rtpkeepalive = peer->rtpkeepalive;
05361 if (dialog_initialize_rtp(dialog)) {
05362 return -1;
05363 }
05364
05365 if (dialog->rtp) {
05366 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05367 ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05368
05369 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05370 dialog->autoframing = peer->autoframing;
05371 }
05372
05373
05374 ast_string_field_set(dialog, peername, peer->name);
05375 ast_string_field_set(dialog, authname, peer->username);
05376 ast_string_field_set(dialog, username, peer->username);
05377 ast_string_field_set(dialog, peersecret, peer->secret);
05378 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05379 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05380 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05381 ast_string_field_set(dialog, tohost, peer->tohost);
05382 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05383 ast_string_field_set(dialog, accountcode, peer->accountcode);
05384 ast_string_field_set(dialog, context, peer->context);
05385 ast_string_field_set(dialog, cid_num, peer->cid_num);
05386 ast_string_field_set(dialog, cid_name, peer->cid_name);
05387 ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05388 ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05389 if (!ast_strlen_zero(peer->parkinglot)) {
05390 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05391 }
05392 ast_string_field_set(dialog, engine, peer->engine);
05393 ref_proxy(dialog, obproxy_get(dialog, peer));
05394 dialog->callgroup = peer->callgroup;
05395 dialog->pickupgroup = peer->pickupgroup;
05396 ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
05397 dialog->allowtransfer = peer->allowtransfer;
05398 dialog->jointnoncodeccapability = dialog->noncodeccapability;
05399
05400
05401 ao2_lock(peer);
05402 credentials = peer->auth;
05403 if (credentials) {
05404 ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05405 }
05406 ao2_unlock(peer);
05407 ao2_lock(dialog);
05408 if (dialog->peerauth) {
05409 ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05410 }
05411 dialog->peerauth = credentials;
05412 ao2_unlock(dialog);
05413
05414 dialog->maxcallbitrate = peer->maxcallbitrate;
05415 dialog->disallowed_methods = peer->disallowed_methods;
05416 ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05417 if (ast_strlen_zero(dialog->tohost))
05418 ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05419 if (!ast_strlen_zero(peer->fromdomain)) {
05420 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05421 if (!dialog->initreq.headers) {
05422 char *new_callid;
05423 char *tmpcall = ast_strdupa(dialog->callid);
05424
05425 new_callid = strchr(tmpcall, '@');
05426 if (new_callid) {
05427 int callid_size;
05428
05429 *new_callid = '\0';
05430
05431
05432 callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05433 new_callid = alloca(callid_size);
05434 snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05435 change_callid_pvt(dialog, new_callid);
05436 }
05437 }
05438 }
05439 if (!ast_strlen_zero(peer->fromuser))
05440 ast_string_field_set(dialog, fromuser, peer->fromuser);
05441 if (!ast_strlen_zero(peer->language))
05442 ast_string_field_set(dialog, language, peer->language);
05443
05444
05445
05446
05447 if (peer->maxms && peer->lastms)
05448 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05449 else
05450 dialog->timer_t1 = peer->timer_t1;
05451
05452
05453
05454 if (peer->timer_b)
05455 dialog->timer_b = peer->timer_b;
05456 else
05457 dialog->timer_b = 64 * dialog->timer_t1;
05458
05459 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05460 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05461 dialog->noncodeccapability |= AST_RTP_DTMF;
05462 else
05463 dialog->noncodeccapability &= ~AST_RTP_DTMF;
05464 dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05465 if (peer->call_limit)
05466 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05467 if (!dialog->portinuri)
05468 dialog->portinuri = peer->portinuri;
05469 dialog->chanvars = copy_vars(peer->chanvars);
05470 if (peer->fromdomainport)
05471 dialog->fromdomainport = peer->fromdomainport;
05472
05473 return 0;
05474 }
05475
05476
05477 static inline int default_sip_port(enum sip_transport type)
05478 {
05479 return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05480 }
05481
05482
05483
05484
05485 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog, struct ast_sockaddr *remote_address)
05486 {
05487 struct sip_peer *peer;
05488 char *peername, *peername2, *hostn;
05489 char host[MAXHOSTNAMELEN];
05490 char service[MAXHOSTNAMELEN];
05491 int srv_ret = 0;
05492 int tportno;
05493
05494 AST_DECLARE_APP_ARGS(hostport,
05495 AST_APP_ARG(host);
05496 AST_APP_ARG(port);
05497 );
05498
05499 peername = ast_strdupa(opeer);
05500 peername2 = ast_strdupa(opeer);
05501 AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05502
05503 if (hostport.port)
05504 dialog->portinuri = 1;
05505
05506 dialog->timer_t1 = global_t1;
05507 dialog->timer_b = global_timer_b;
05508 peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05509
05510 if (peer) {
05511 int res;
05512 if (newdialog) {
05513 set_socket_transport(&dialog->socket, 0);
05514 }
05515 res = create_addr_from_peer(dialog, peer);
05516 if (!ast_sockaddr_isnull(remote_address)) {
05517 ast_sockaddr_copy(&dialog->sa, remote_address);
05518 }
05519 dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05520 sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
05521 return res;
05522 } else if (ast_check_digits(peername)) {
05523
05524
05525
05526 ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05527 return -1;
05528 } else {
05529 dialog->rtptimeout = global_rtptimeout;
05530 dialog->rtpholdtimeout = global_rtpholdtimeout;
05531 dialog->rtpkeepalive = global_rtpkeepalive;
05532 if (dialog_initialize_rtp(dialog)) {
05533 return -1;
05534 }
05535 }
05536
05537 ast_string_field_set(dialog, tohost, hostport.host);
05538 dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05539
05540
05541 ref_proxy(dialog, obproxy_get(dialog, NULL));
05542
05543 if (addr) {
05544
05545 ast_sockaddr_copy(&dialog->sa, addr);
05546 } else {
05547
05548
05549
05550
05551
05552
05553 hostn = peername;
05554
05555
05556
05557 if (!hostport.port && sip_cfg.srvlookup) {
05558 snprintf(service, sizeof(service), "_%s._%s.%s",
05559 get_srv_service(dialog->socket.type),
05560 get_srv_protocol(dialog->socket.type), peername);
05561 if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05562 service)) > 0) {
05563 hostn = host;
05564 }
05565 }
05566
05567 if (ast_sockaddr_resolve_first(&dialog->sa, hostn, 0)) {
05568 ast_log(LOG_WARNING, "No such host: %s\n", peername);
05569 return -1;
05570 }
05571
05572 if (srv_ret > 0) {
05573 ast_sockaddr_set_port(&dialog->sa, tportno);
05574 }
05575 }
05576
05577 if (!dialog->socket.type)
05578 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05579 if (!dialog->socket.port) {
05580 dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05581 }
05582
05583 if (!ast_sockaddr_port(&dialog->sa)) {
05584 ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05585 }
05586 ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05587 return 0;
05588 }
05589
05590
05591
05592
05593 static int auto_congest(const void *arg)
05594 {
05595 struct sip_pvt *p = (struct sip_pvt *)arg;
05596
05597 sip_pvt_lock(p);
05598 p->initid = -1;
05599 if (p->owner) {
05600
05601 if (!ast_channel_trylock(p->owner)) {
05602 append_history(p, "Cong", "Auto-congesting (timer)");
05603 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05604 ast_channel_unlock(p->owner);
05605 }
05606
05607
05608 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05609 }
05610 sip_pvt_unlock(p);
05611 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05612 return 0;
05613 }
05614
05615
05616
05617
05618 static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
05619 {
05620 int res;
05621 struct sip_pvt *p = ast->tech_pvt;
05622 struct varshead *headp;
05623 struct ast_var_t *current;
05624 const char *referer = NULL;
05625 int cc_core_id;
05626 char uri[SIPBUFSIZE] = "";
05627
05628 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05629 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
05630 return -1;
05631 }
05632
05633 if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05634 char device_name[AST_CHANNEL_NAME];
05635 struct ast_cc_monitor *recall_monitor;
05636 struct sip_monitor_instance *monitor_instance;
05637 ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05638 if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05639 monitor_instance = recall_monitor->private_data;
05640 ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05641 ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05642 }
05643 }
05644
05645
05646 headp=&ast->varshead;
05647 AST_LIST_TRAVERSE(headp, current, entries) {
05648
05649 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05650 p->options->vxml_url = ast_var_value(current);
05651 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05652 p->options->uri_options = ast_var_value(current);
05653 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05654
05655 p->options->addsipheaders = 1;
05656 } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05657 ast_string_field_set(p, fromdomain, ast_var_value(current));
05658 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05659
05660 p->options->transfer = 1;
05661 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05662
05663 referer = ast_var_value(current);
05664 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05665
05666 p->options->replaces = ast_var_value(current);
05667 } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05668 if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
05669 ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.");
05670 }
05671 }
05672 }
05673
05674
05675 if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05676 ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05677 ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05678 return -1;
05679 }
05680
05681 if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05682 if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05683 ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05684 ast_clear_flag(&p->flags[0], SIP_REINVITE);
05685 }
05686
05687 if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05688 ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05689 return -1;
05690 }
05691
05692 if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05693 ast_log(LOG_WARNING, "SRTP video setup failed\n");
05694 return -1;
05695 }
05696
05697 if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05698 ast_log(LOG_WARNING, "SRTP text setup failed\n");
05699 return -1;
05700 }
05701 }
05702
05703 res = 0;
05704 ast_set_flag(&p->flags[0], SIP_OUTGOING);
05705
05706
05707
05708
05709 ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05710
05711 if (p->options->transfer) {
05712 char buf[SIPBUFSIZE/2];
05713
05714 if (referer) {
05715 if (sipdebug)
05716 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05717 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05718 } else
05719 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05720 ast_string_field_set(p, cid_name, buf);
05721 }
05722 ast_debug(1, "Outgoing Call for %s\n", p->username);
05723
05724 res = update_call_counter(p, INC_CALL_RINGING);
05725
05726 if (res == -1) {
05727 ast->hangupcause = AST_CAUSE_USER_BUSY;
05728 return res;
05729 }
05730 p->callingpres = ast_party_id_presentation(&ast->caller.id);
05731 ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
05732 p->jointnoncodeccapability = p->noncodeccapability;
05733
05734
05735 if (!(ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO))) {
05736 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05737 res = -1;
05738 } else {
05739 int xmitres;
05740 struct ast_party_connected_line connected;
05741 struct ast_set_party_connected_line update_connected;
05742
05743 sip_pvt_lock(p);
05744
05745
05746 memset(&update_connected, 0, sizeof(update_connected));
05747 ast_party_connected_line_init(&connected);
05748 if (!ast_strlen_zero(p->cid_num)
05749 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05750 update_connected.id.number = 1;
05751 connected.id.number.valid = 1;
05752 connected.id.number.str = (char *) p->cid_num;
05753 connected.id.number.presentation = p->callingpres;
05754 }
05755 if (!ast_strlen_zero(p->cid_name)
05756 || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05757 update_connected.id.name = 1;
05758 connected.id.name.valid = 1;
05759 connected.id.name.str = (char *) p->cid_name;
05760 connected.id.name.presentation = p->callingpres;
05761 }
05762 if (update_connected.id.number || update_connected.id.name) {
05763 connected.id.tag = (char *) p->cid_tag;
05764 connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05765 ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05766 }
05767
05768 xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05769 sip_pvt_unlock(p);
05770 if (xmitres == XMIT_ERROR)
05771 return -1;
05772 p->invitestate = INV_CALLING;
05773
05774
05775 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05776 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05777 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05778 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05779 }
05780 return res;
05781 }
05782
05783
05784
05785 static void sip_registry_destroy(struct sip_registry *reg)
05786 {
05787
05788 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05789
05790 if (reg->call) {
05791
05792
05793 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05794 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05795 dialog_unlink_all(reg->call);
05796 reg->call = dialog_unref(reg->call, "unref reg->call");
05797
05798 }
05799 AST_SCHED_DEL(sched, reg->expire);
05800 AST_SCHED_DEL(sched, reg->timeout);
05801
05802 ast_string_field_free_memory(reg);
05803 ast_atomic_fetchadd_int(®objs, -1);
05804 ast_free(reg);
05805 }
05806
05807
05808 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05809 {
05810 if (mwi->call) {
05811 mwi->call->mwi = NULL;
05812 sip_destroy(mwi->call);
05813 }
05814
05815 AST_SCHED_DEL(sched, mwi->resub);
05816 ast_string_field_free_memory(mwi);
05817 ast_free(mwi);
05818 }
05819
05820
05821 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05822 {
05823 struct sip_request *req;
05824
05825
05826 if (p->stimer) {
05827 p->stimer->quit_flag = 1;
05828 stop_session_timer(p);
05829 ast_free(p->stimer);
05830 p->stimer = NULL;
05831 }
05832
05833 if (sip_debug_test_pvt(p))
05834 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05835
05836 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05837 update_call_counter(p, DEC_CALL_LIMIT);
05838 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05839 }
05840
05841
05842 if (p->owner) {
05843 if (lockowner)
05844 ast_channel_lock(p->owner);
05845 ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
05846 p->owner->tech_pvt = NULL;
05847
05848 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05849 if (lockowner)
05850 ast_channel_unlock(p->owner);
05851
05852 usleep(1);
05853 }
05854
05855
05856 if (p->relatedpeer && p->relatedpeer->mwipvt)
05857 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05858 if (p->relatedpeer && p->relatedpeer->call == p)
05859 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05860
05861 if (p->relatedpeer)
05862 p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05863
05864 if (p->registry) {
05865 if (p->registry->call == p)
05866 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05867 p->registry = registry_unref(p->registry, "delete p->registry");
05868 }
05869
05870 if (p->mwi) {
05871 p->mwi->call = NULL;
05872 }
05873
05874 if (dumphistory)
05875 sip_dump_history(p);
05876
05877 if (p->options)
05878 ast_free(p->options);
05879
05880 if (p->notify) {
05881 ast_variables_destroy(p->notify->headers);
05882 ast_free(p->notify->content);
05883 ast_free(p->notify);
05884 }
05885 if (p->rtp) {
05886 ast_rtp_instance_destroy(p->rtp);
05887 }
05888 if (p->vrtp) {
05889 ast_rtp_instance_destroy(p->vrtp);
05890 }
05891 if (p->trtp) {
05892 ast_rtp_instance_destroy(p->trtp);
05893 }
05894 if (p->udptl)
05895 ast_udptl_destroy(p->udptl);
05896 if (p->refer)
05897 ast_free(p->refer);
05898 if (p->route) {
05899 free_old_route(p->route);
05900 p->route = NULL;
05901 }
05902 deinit_req(&p->initreq);
05903
05904
05905 if (p->history) {
05906 struct sip_history *hist;
05907 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05908 ast_free(hist);
05909 p->history_entries--;
05910 }
05911 ast_free(p->history);
05912 p->history = NULL;
05913 }
05914
05915 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05916 ast_free(req);
05917 }
05918
05919 if (p->chanvars) {
05920 ast_variables_destroy(p->chanvars);
05921 p->chanvars = NULL;
05922 }
05923
05924 destroy_msg_headers(p);
05925
05926 if (p->srtp) {
05927 sip_srtp_destroy(p->srtp);
05928 p->srtp = NULL;
05929 }
05930
05931 if (p->vsrtp) {
05932 sip_srtp_destroy(p->vsrtp);
05933 p->vsrtp = NULL;
05934 }
05935
05936 if (p->tsrtp) {
05937 sip_srtp_destroy(p->tsrtp);
05938 p->tsrtp = NULL;
05939 }
05940
05941 if (p->directmediaha) {
05942 ast_free_ha(p->directmediaha);
05943 p->directmediaha = NULL;
05944 }
05945
05946 ast_string_field_free_memory(p);
05947
05948 ast_cc_config_params_destroy(p->cc_params);
05949
05950 if (p->epa_entry) {
05951 ao2_ref(p->epa_entry, -1);
05952 p->epa_entry = NULL;
05953 }
05954
05955 if (p->socket.tcptls_session) {
05956 ao2_ref(p->socket.tcptls_session, -1);
05957 p->socket.tcptls_session = NULL;
05958 }
05959
05960 if (p->peerauth) {
05961 ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
05962 p->peerauth = NULL;
05963 }
05964
05965 p->caps = ast_format_cap_destroy(p->caps);
05966 p->jointcaps = ast_format_cap_destroy(p->jointcaps);
05967 p->peercaps = ast_format_cap_destroy(p->peercaps);
05968 p->redircaps = ast_format_cap_destroy(p->redircaps);
05969 p->prefcaps = ast_format_cap_destroy(p->prefcaps);
05970 }
05971
05972
05973
05974
05975
05976
05977
05978
05979
05980
05981
05982
05983
05984
05985
05986 static int update_call_counter(struct sip_pvt *fup, int event)
05987 {
05988 char name[256];
05989 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05990 int outgoing = fup->outgoing_call;
05991 struct sip_peer *p = NULL;
05992
05993 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05994
05995
05996
05997
05998 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05999 return 0;
06000
06001 ast_copy_string(name, fup->username, sizeof(name));
06002
06003
06004 if (fup->relatedpeer) {
06005 p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06006 inuse = &p->inUse;
06007 call_limit = &p->call_limit;
06008 inringing = &p->inRinging;
06009 ast_copy_string(name, fup->peername, sizeof(name));
06010 }
06011 if (!p) {
06012 ast_debug(2, "%s is not a local device, no call limit\n", name);
06013 return 0;
06014 }
06015
06016 switch(event) {
06017
06018 case DEC_CALL_LIMIT:
06019
06020 if (inuse) {
06021 sip_pvt_lock(fup);
06022 ao2_lock(p);
06023 if (*inuse > 0) {
06024 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06025 (*inuse)--;
06026 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06027 }
06028 } else {
06029 *inuse = 0;
06030 }
06031 ao2_unlock(p);
06032 sip_pvt_unlock(fup);
06033 }
06034
06035
06036 if (inringing) {
06037 sip_pvt_lock(fup);
06038 ao2_lock(p);
06039 if (*inringing > 0) {
06040 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06041 (*inringing)--;
06042 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06043 }
06044 } else {
06045 *inringing = 0;
06046 }
06047 ao2_unlock(p);
06048 sip_pvt_unlock(fup);
06049 }
06050
06051
06052 sip_pvt_lock(fup);
06053 ao2_lock(p);
06054 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06055 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06056 ao2_unlock(p);
06057 sip_pvt_unlock(fup);
06058 sip_peer_hold(fup, FALSE);
06059 } else {
06060 ao2_unlock(p);
06061 sip_pvt_unlock(fup);
06062 }
06063 if (sipdebug)
06064 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06065 break;
06066
06067 case INC_CALL_RINGING:
06068 case INC_CALL_LIMIT:
06069
06070 if (*call_limit > 0 ) {
06071 if (*inuse >= *call_limit) {
06072 ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06073 sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06074 return -1;
06075 }
06076 }
06077 if (inringing && (event == INC_CALL_RINGING)) {
06078 sip_pvt_lock(fup);
06079 ao2_lock(p);
06080 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06081 (*inringing)++;
06082 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06083 }
06084 ao2_unlock(p);
06085 sip_pvt_unlock(fup);
06086 }
06087 if (inuse) {
06088 sip_pvt_lock(fup);
06089 ao2_lock(p);
06090 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06091 (*inuse)++;
06092 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06093 }
06094 ao2_unlock(p);
06095 sip_pvt_unlock(fup);
06096 }
06097 if (sipdebug) {
06098 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06099 }
06100 break;
06101
06102 case DEC_CALL_RINGING:
06103 if (inringing) {
06104 sip_pvt_lock(fup);
06105 ao2_lock(p);
06106 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06107 if (*inringing > 0) {
06108 (*inringing)--;
06109 }
06110 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06111 }
06112 ao2_unlock(p);
06113 sip_pvt_unlock(fup);
06114 }
06115 break;
06116
06117 default:
06118 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06119 }
06120
06121 if (p) {
06122 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06123 sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
06124 }
06125 return 0;
06126 }
06127
06128
06129 static void sip_destroy_fn(void *p)
06130 {
06131 sip_destroy(p);
06132 }
06133
06134
06135
06136
06137
06138
06139 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06140 {
06141 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06142 __sip_destroy(p, TRUE, TRUE);
06143 return NULL;
06144 }
06145
06146
06147 int hangup_sip2cause(int cause)
06148 {
06149
06150
06151 switch(cause) {
06152 case 401:
06153 return AST_CAUSE_CALL_REJECTED;
06154 case 403:
06155 return AST_CAUSE_CALL_REJECTED;
06156 case 404:
06157 return AST_CAUSE_UNALLOCATED;
06158 case 405:
06159 return AST_CAUSE_INTERWORKING;
06160 case 407:
06161 return AST_CAUSE_CALL_REJECTED;
06162 case 408:
06163 return AST_CAUSE_NO_USER_RESPONSE;
06164 case 409:
06165 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06166 case 410:
06167 return AST_CAUSE_NUMBER_CHANGED;
06168 case 411:
06169 return AST_CAUSE_INTERWORKING;
06170 case 413:
06171 return AST_CAUSE_INTERWORKING;
06172 case 414:
06173 return AST_CAUSE_INTERWORKING;
06174 case 415:
06175 return AST_CAUSE_INTERWORKING;
06176 case 420:
06177 return AST_CAUSE_NO_ROUTE_DESTINATION;
06178 case 480:
06179 return AST_CAUSE_NO_ANSWER;
06180 case 481:
06181 return AST_CAUSE_INTERWORKING;
06182 case 482:
06183 return AST_CAUSE_INTERWORKING;
06184 case 483:
06185 return AST_CAUSE_NO_ANSWER;
06186 case 484:
06187 return AST_CAUSE_INVALID_NUMBER_FORMAT;
06188 case 485:
06189 return AST_CAUSE_UNALLOCATED;
06190 case 486:
06191 return AST_CAUSE_BUSY;
06192 case 487:
06193 return AST_CAUSE_INTERWORKING;
06194 case 488:
06195 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06196 case 491:
06197 return AST_CAUSE_INTERWORKING;
06198 case 493:
06199 return AST_CAUSE_INTERWORKING;
06200 case 500:
06201 return AST_CAUSE_FAILURE;
06202 case 501:
06203 return AST_CAUSE_FACILITY_REJECTED;
06204 case 502:
06205 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06206 case 503:
06207 return AST_CAUSE_CONGESTION;
06208 case 504:
06209 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06210 case 505:
06211 return AST_CAUSE_INTERWORKING;
06212 case 600:
06213 return AST_CAUSE_USER_BUSY;
06214 case 603:
06215 return AST_CAUSE_CALL_REJECTED;
06216 case 604:
06217 return AST_CAUSE_UNALLOCATED;
06218 case 606:
06219 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06220 default:
06221 if (cause < 500 && cause >= 400) {
06222
06223 return AST_CAUSE_INTERWORKING;
06224 } else if (cause < 600 && cause >= 500) {
06225
06226 return AST_CAUSE_CONGESTION;
06227 } else if (cause < 700 && cause >= 600) {
06228
06229 return AST_CAUSE_INTERWORKING;
06230 }
06231 return AST_CAUSE_NORMAL;
06232 }
06233
06234 return 0;
06235 }
06236
06237
06238
06239
06240
06241
06242
06243
06244
06245
06246
06247
06248
06249
06250
06251
06252
06253
06254
06255
06256
06257
06258
06259
06260
06261
06262
06263
06264
06265
06266
06267
06268
06269 const char *hangup_cause2sip(int cause)
06270 {
06271 switch (cause) {
06272 case AST_CAUSE_UNALLOCATED:
06273 case AST_CAUSE_NO_ROUTE_DESTINATION:
06274 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
06275 return "404 Not Found";
06276 case AST_CAUSE_CONGESTION:
06277 case AST_CAUSE_SWITCH_CONGESTION:
06278 return "503 Service Unavailable";
06279 case AST_CAUSE_NO_USER_RESPONSE:
06280 return "408 Request Timeout";
06281 case AST_CAUSE_NO_ANSWER:
06282 case AST_CAUSE_UNREGISTERED:
06283 return "480 Temporarily unavailable";
06284 case AST_CAUSE_CALL_REJECTED:
06285 return "403 Forbidden";
06286 case AST_CAUSE_NUMBER_CHANGED:
06287 return "410 Gone";
06288 case AST_CAUSE_NORMAL_UNSPECIFIED:
06289 return "480 Temporarily unavailable";
06290 case AST_CAUSE_INVALID_NUMBER_FORMAT:
06291 return "484 Address incomplete";
06292 case AST_CAUSE_USER_BUSY:
06293 return "486 Busy here";
06294 case AST_CAUSE_FAILURE:
06295 return "500 Server internal failure";
06296 case AST_CAUSE_FACILITY_REJECTED:
06297 return "501 Not Implemented";
06298 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06299 return "503 Service Unavailable";
06300
06301 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06302 return "502 Bad Gateway";
06303 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
06304 return "488 Not Acceptable Here";
06305 case AST_CAUSE_INTERWORKING:
06306 return "500 Network error";
06307
06308 case AST_CAUSE_NOTDEFINED:
06309 default:
06310 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06311 return NULL;
06312 }
06313
06314
06315 return 0;
06316 }
06317
06318
06319
06320 static int sip_hangup(struct ast_channel *ast)
06321 {
06322 struct sip_pvt *p = ast->tech_pvt;
06323 int needcancel = FALSE;
06324 int needdestroy = 0;
06325 struct ast_channel *oldowner = ast;
06326
06327 if (!p) {
06328 ast_debug(1, "Asked to hangup channel that was not connected\n");
06329 return 0;
06330 }
06331 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06332 ast_debug(1, "This call was answered elsewhere");
06333 if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06334 ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06335 }
06336 append_history(p, "Cancel", "Call answered elsewhere");
06337 p->answered_elsewhere = TRUE;
06338 }
06339
06340
06341 if (p->owner)
06342 p->hangupcause = p->owner->hangupcause;
06343
06344 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06345 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06346 if (sipdebug)
06347 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06348 update_call_counter(p, DEC_CALL_LIMIT);
06349 }
06350 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06351 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06352 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
06353 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06354 sip_pvt_lock(p);
06355 p->owner = NULL;
06356 sip_pvt_unlock(p);
06357 ast_module_unref(ast_module_info->self);
06358 return 0;
06359 }
06360
06361 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06362 if (p->refer)
06363 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast_channel_name(ast), p->callid);
06364 else
06365 ast_debug(1, "Hanging up zombie call. Be scared.\n");
06366 } else
06367 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
06368
06369 sip_pvt_lock(p);
06370 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06371 if (sipdebug)
06372 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06373 update_call_counter(p, DEC_CALL_LIMIT);
06374 }
06375
06376
06377 if (p->owner != ast) {
06378 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
06379 sip_pvt_unlock(p);
06380 return 0;
06381 }
06382
06383
06384 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06385 needcancel = TRUE;
06386 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06387 }
06388
06389 stop_media_flows(p);
06390
06391 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06392
06393
06394 disable_dsp_detect(p);
06395
06396 p->owner = NULL;
06397 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06398
06399 ast_module_unref(ast_module_info->self);
06400
06401
06402
06403
06404
06405
06406 if (p->alreadygone)
06407 needdestroy = 1;
06408 else if (p->invitestate != INV_CALLING)
06409 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06410
06411
06412 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06413 if (needcancel) {
06414 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06415
06416 if (p->invitestate == INV_CALLING) {
06417
06418 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06419
06420 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06421 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06422 } else {
06423 struct sip_pkt *cur;
06424
06425 for (cur = p->packets; cur; cur = cur->next) {
06426 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06427 }
06428 p->invitestate = INV_CANCELLED;
06429
06430 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06431
06432
06433 needdestroy = 0;
06434 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06435 }
06436 } else {
06437 const char *res;
06438 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"));
06439 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06440 transmit_response_reliable(p, res, &p->initreq);
06441 else
06442 transmit_response_reliable(p, "603 Declined", &p->initreq);
06443 p->invitestate = INV_TERMINATED;
06444 }
06445 } else {
06446 if (p->stimer->st_active == TRUE) {
06447 stop_session_timer(p);
06448 }
06449
06450 if (!p->pendinginvite) {
06451 struct ast_channel *bridge = ast_bridged_channel(oldowner);
06452 char quality_buf[AST_MAX_USER_FIELD], *quality;
06453
06454
06455
06456
06457 while (bridge && ast_channel_trylock(bridge)) {
06458 sip_pvt_unlock(p);
06459 do {
06460 CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06461 } while (sip_pvt_trylock(p));
06462 bridge = ast_bridged_channel(oldowner);
06463 }
06464
06465 if (p->rtp) {
06466 ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06467 }
06468
06469 if (bridge) {
06470 struct sip_pvt *q = bridge->tech_pvt;
06471
06472 if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06473 ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06474 }
06475 ast_channel_unlock(bridge);
06476 }
06477
06478 if (p->do_history || oldowner) {
06479 if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06480 if (p->do_history) {
06481 append_history(p, "RTCPaudio", "Quality:%s", quality);
06482 }
06483 if (oldowner) {
06484 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06485 }
06486 }
06487 if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06488 if (p->do_history) {
06489 append_history(p, "RTCPvideo", "Quality:%s", quality);
06490 }
06491 if (oldowner) {
06492 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06493 }
06494 }
06495 if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06496 if (p->do_history) {
06497 append_history(p, "RTCPtext", "Quality:%s", quality);
06498 }
06499 if (oldowner) {
06500 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06501 }
06502 }
06503 }
06504
06505
06506 if (oldowner->_state == AST_STATE_UP) {
06507 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06508 }
06509
06510 } else {
06511
06512
06513 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06514 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
06515 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"));
06516 if (sip_cancel_destroy(p))
06517 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
06518 }
06519 }
06520 }
06521 if (needdestroy) {
06522 pvt_set_needdestroy(p, "hangup");
06523 }
06524 sip_pvt_unlock(p);
06525 return 0;
06526 }
06527
06528
06529 static void try_suggested_sip_codec(struct sip_pvt *p)
06530 {
06531 struct ast_format fmt;
06532 const char *codec;
06533
06534 ast_format_clear(&fmt);
06535
06536 if (p->outgoing_call) {
06537 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06538 } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06539 codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06540 }
06541
06542 if (!codec)
06543 return;
06544
06545 ast_getformatbyname(codec, &fmt);
06546 if (fmt.id) {
06547 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06548 if (ast_format_cap_iscompatible(p->jointcaps, &fmt)) {
06549 ast_format_cap_set(p->jointcaps, &fmt);
06550 ast_format_cap_set(p->caps, &fmt);
06551 } else
06552 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06553 } else
06554 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06555 return;
06556 }
06557
06558
06559
06560 static int sip_answer(struct ast_channel *ast)
06561 {
06562 int res = 0;
06563 struct sip_pvt *p = ast->tech_pvt;
06564
06565 sip_pvt_lock(p);
06566 if (ast->_state != AST_STATE_UP) {
06567 try_suggested_sip_codec(p);
06568
06569 ast_setstate(ast, AST_STATE_UP);
06570 ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
06571 ast_rtp_instance_update_source(p->rtp);
06572 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06573 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06574 }
06575 sip_pvt_unlock(p);
06576 return res;
06577 }
06578
06579
06580 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06581 {
06582 struct sip_pvt *p = ast->tech_pvt;
06583 int res = 0;
06584
06585 switch (frame->frametype) {
06586 case AST_FRAME_VOICE:
06587 if (!(ast_format_cap_iscompatible(ast->nativeformats, &frame->subclass.format))) {
06588 char s1[512];
06589 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06590 ast_getformatname(&frame->subclass.format),
06591 ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats),
06592 ast_getformatname(&ast->readformat),
06593 ast_getformatname(&ast->writeformat));
06594 return 0;
06595 }
06596 if (p) {
06597 sip_pvt_lock(p);
06598 if (p->t38.state == T38_ENABLED) {
06599
06600 sip_pvt_unlock(p);
06601 break;
06602 } else if (p->rtp) {
06603
06604 if ((ast->_state != AST_STATE_UP) &&
06605 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06606 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06607 ast_rtp_instance_update_source(p->rtp);
06608 if (!global_prematuremediafilter) {
06609 p->invitestate = INV_EARLY_MEDIA;
06610 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06611 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06612 }
06613 }
06614 p->lastrtptx = time(NULL);
06615 res = ast_rtp_instance_write(p->rtp, frame);
06616 }
06617 sip_pvt_unlock(p);
06618 }
06619 break;
06620 case AST_FRAME_VIDEO:
06621 if (p) {
06622 sip_pvt_lock(p);
06623 if (p->vrtp) {
06624
06625 if ((ast->_state != AST_STATE_UP) &&
06626 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06627 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06628 p->invitestate = INV_EARLY_MEDIA;
06629 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06630 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06631 }
06632 p->lastrtptx = time(NULL);
06633 res = ast_rtp_instance_write(p->vrtp, frame);
06634 }
06635 sip_pvt_unlock(p);
06636 }
06637 break;
06638 case AST_FRAME_TEXT:
06639 if (p) {
06640 sip_pvt_lock(p);
06641 if (p->red) {
06642 ast_rtp_red_buffer(p->trtp, frame);
06643 } else {
06644 if (p->trtp) {
06645
06646 if ((ast->_state != AST_STATE_UP) &&
06647 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06648 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06649 p->invitestate = INV_EARLY_MEDIA;
06650 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06651 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06652 }
06653 p->lastrtptx = time(NULL);
06654 res = ast_rtp_instance_write(p->trtp, frame);
06655 }
06656 }
06657 sip_pvt_unlock(p);
06658 }
06659 break;
06660 case AST_FRAME_IMAGE:
06661 return 0;
06662 break;
06663 case AST_FRAME_MODEM:
06664 if (p) {
06665 sip_pvt_lock(p);
06666
06667
06668
06669
06670 if ((ast->_state == AST_STATE_UP) &&
06671 p->udptl &&
06672 (p->t38.state == T38_ENABLED)) {
06673 res = ast_udptl_write(p->udptl, frame);
06674 }
06675 sip_pvt_unlock(p);
06676 }
06677 break;
06678 default:
06679 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06680 return 0;
06681 }
06682
06683 return res;
06684 }
06685
06686
06687
06688 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06689 {
06690 int ret = -1;
06691 struct sip_pvt *p;
06692
06693 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06694 ast_debug(1, "New channel is zombie\n");
06695 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06696 ast_debug(1, "Old channel is zombie\n");
06697
06698 if (!newchan || !newchan->tech_pvt) {
06699 if (!newchan)
06700 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
06701 else
06702 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
06703 return -1;
06704 }
06705 p = newchan->tech_pvt;
06706
06707 sip_pvt_lock(p);
06708 append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
06709 append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
06710 if (p->owner != oldchan)
06711 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06712 else {
06713 p->owner = newchan;
06714
06715
06716
06717
06718
06719
06720 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06721 ret = 0;
06722 }
06723 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, ast_channel_name(p->owner), ast_channel_name(oldchan));
06724
06725 sip_pvt_unlock(p);
06726 return ret;
06727 }
06728
06729 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06730 {
06731 struct sip_pvt *p = ast->tech_pvt;
06732 int res = 0;
06733
06734 sip_pvt_lock(p);
06735 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06736 case SIP_DTMF_INBAND:
06737 res = -1;
06738 break;
06739 case SIP_DTMF_RFC2833:
06740 if (p->rtp)
06741 ast_rtp_instance_dtmf_begin(p->rtp, digit);
06742 break;
06743 default:
06744 break;
06745 }
06746 sip_pvt_unlock(p);
06747
06748 return res;
06749 }
06750
06751
06752
06753 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06754 {
06755 struct sip_pvt *p = ast->tech_pvt;
06756 int res = 0;
06757
06758 sip_pvt_lock(p);
06759 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06760 case SIP_DTMF_INFO:
06761 case SIP_DTMF_SHORTINFO:
06762 transmit_info_with_digit(p, digit, duration);
06763 break;
06764 case SIP_DTMF_RFC2833:
06765 if (p->rtp)
06766 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06767 break;
06768 case SIP_DTMF_INBAND:
06769 res = -1;
06770 break;
06771 }
06772 sip_pvt_unlock(p);
06773
06774 return res;
06775 }
06776
06777
06778 static int sip_transfer(struct ast_channel *ast, const char *dest)
06779 {
06780 struct sip_pvt *p = ast->tech_pvt;
06781 int res;
06782
06783 if (dest == NULL)
06784 dest = "";
06785 sip_pvt_lock(p);
06786 if (ast->_state == AST_STATE_RING)
06787 res = sip_sipredirect(p, dest);
06788 else
06789 res = transmit_refer(p, dest);
06790 sip_pvt_unlock(p);
06791 return res;
06792 }
06793
06794
06795 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06796 {
06797 int res = 0;
06798
06799 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06800 return -1;
06801 }
06802 switch (parameters->request_response) {
06803 case AST_T38_NEGOTIATED:
06804 case AST_T38_REQUEST_NEGOTIATE:
06805
06806 if (!parameters->max_ifp) {
06807 if (p->t38.state == T38_PEER_REINVITE) {
06808 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"));
06809 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06810 }
06811 change_t38_state(p, T38_REJECTED);
06812 break;
06813 } else if (p->t38.state == T38_PEER_REINVITE) {
06814 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"));
06815 p->t38.our_parms = *parameters;
06816
06817
06818
06819 if (!p->t38.their_parms.fill_bit_removal) {
06820 p->t38.our_parms.fill_bit_removal = FALSE;
06821 }
06822 if (!p->t38.their_parms.transcoding_mmr) {
06823 p->t38.our_parms.transcoding_mmr = FALSE;
06824 }
06825 if (!p->t38.their_parms.transcoding_jbig) {
06826 p->t38.our_parms.transcoding_jbig = FALSE;
06827 }
06828 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06829 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06830 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06831 change_t38_state(p, T38_ENABLED);
06832 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06833 } else if (p->t38.state != T38_ENABLED) {
06834 p->t38.our_parms = *parameters;
06835 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06836 change_t38_state(p, T38_LOCAL_REINVITE);
06837 if (!p->pendinginvite) {
06838 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06839 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06840 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06841 }
06842 }
06843 break;
06844 case AST_T38_TERMINATED:
06845 case AST_T38_REFUSED:
06846 case AST_T38_REQUEST_TERMINATE:
06847 if (p->t38.state == T38_PEER_REINVITE) {
06848 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"));
06849 change_t38_state(p, T38_REJECTED);
06850 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06851 } else if (p->t38.state == T38_ENABLED)
06852 transmit_reinvite_with_sdp(p, FALSE, FALSE);
06853 break;
06854 case AST_T38_REQUEST_PARMS: {
06855 struct ast_control_t38_parameters parameters = p->t38.their_parms;
06856
06857 if (p->t38.state == T38_PEER_REINVITE) {
06858 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"));
06859 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06860 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06861 ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
06862
06863
06864
06865
06866 res = AST_T38_REQUEST_PARMS;
06867 }
06868 break;
06869 }
06870 default:
06871 res = -1;
06872 break;
06873 }
06874
06875 return res;
06876 }
06877
06878
06879
06880
06881
06882
06883
06884
06885
06886
06887 static int initialize_udptl(struct sip_pvt *p)
06888 {
06889 int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
06890
06891 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06892 return 1;
06893 }
06894
06895
06896 if (p->udptl) {
06897 return 0;
06898 }
06899
06900
06901 if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
06902 if (p->owner) {
06903 ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
06904 }
06905
06906 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06907 p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
06908 set_t38_capabilities(p);
06909
06910 ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
06911 ast_udptl_setnat(p->udptl, natflags);
06912 } else {
06913 ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
06914 ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
06915 return 1;
06916 }
06917
06918 return 0;
06919 }
06920
06921
06922
06923
06924
06925
06926 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06927 {
06928 struct sip_pvt *p = ast->tech_pvt;
06929 int res = 0;
06930
06931 sip_pvt_lock(p);
06932 switch(condition) {
06933 case AST_CONTROL_RINGING:
06934 if (ast->_state == AST_STATE_RING) {
06935 p->invitestate = INV_EARLY_MEDIA;
06936 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06937 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
06938
06939 transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06940 ast_set_flag(&p->flags[0], SIP_RINGING);
06941 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06942 break;
06943 } else {
06944
06945 }
06946 }
06947 res = -1;
06948 break;
06949 case AST_CONTROL_BUSY:
06950 if (ast->_state != AST_STATE_UP) {
06951 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06952 p->invitestate = INV_COMPLETED;
06953 sip_alreadygone(p);
06954 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06955 break;
06956 }
06957 res = -1;
06958 break;
06959 case AST_CONTROL_CONGESTION:
06960 if (ast->_state != AST_STATE_UP) {
06961 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06962 p->invitestate = INV_COMPLETED;
06963 sip_alreadygone(p);
06964 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06965 break;
06966 }
06967 res = -1;
06968 break;
06969 case AST_CONTROL_INCOMPLETE:
06970 if (ast->_state != AST_STATE_UP) {
06971 switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
06972 case SIP_PAGE2_ALLOWOVERLAP_YES:
06973 transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
06974 p->invitestate = INV_COMPLETED;
06975 sip_alreadygone(p);
06976 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06977 break;
06978 case SIP_PAGE2_ALLOWOVERLAP_DTMF:
06979
06980 break;
06981 default:
06982
06983 transmit_response_reliable(p, "404 Not Found", &p->initreq);
06984 p->invitestate = INV_COMPLETED;
06985 sip_alreadygone(p);
06986 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06987 break;
06988 }
06989 }
06990 break;
06991 case AST_CONTROL_PROCEEDING:
06992 if ((ast->_state != AST_STATE_UP) &&
06993 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06994 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06995 transmit_response(p, "100 Trying", &p->initreq);
06996 p->invitestate = INV_PROCEEDING;
06997 break;
06998 }
06999 res = -1;
07000 break;
07001 case AST_CONTROL_PROGRESS:
07002 if ((ast->_state != AST_STATE_UP) &&
07003 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07004 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07005 p->invitestate = INV_EARLY_MEDIA;
07006 transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07007 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07008 break;
07009 }
07010 res = -1;
07011 break;
07012 case AST_CONTROL_HOLD:
07013 ast_rtp_instance_update_source(p->rtp);
07014 ast_moh_start(ast, data, p->mohinterpret);
07015 break;
07016 case AST_CONTROL_UNHOLD:
07017 ast_rtp_instance_update_source(p->rtp);
07018 ast_moh_stop(ast);
07019 break;
07020 case AST_CONTROL_VIDUPDATE:
07021 if (p->vrtp && !p->novideo) {
07022 transmit_info_with_vidupdate(p);
07023
07024 } else
07025 res = -1;
07026 break;
07027 case AST_CONTROL_T38_PARAMETERS:
07028 res = -1;
07029 if (datalen != sizeof(struct ast_control_t38_parameters)) {
07030 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);
07031 } else {
07032 const struct ast_control_t38_parameters *parameters = data;
07033 if (!initialize_udptl(p)) {
07034 res = interpret_t38_parameters(p, parameters);
07035 }
07036 }
07037 break;
07038 case AST_CONTROL_SRCUPDATE:
07039 ast_rtp_instance_update_source(p->rtp);
07040 break;
07041 case AST_CONTROL_SRCCHANGE:
07042 ast_rtp_instance_change_source(p->rtp);
07043 break;
07044 case AST_CONTROL_CONNECTED_LINE:
07045 update_connectedline(p, data, datalen);
07046 break;
07047 case AST_CONTROL_REDIRECTING:
07048 update_redirecting(p, data, datalen);
07049 break;
07050 case AST_CONTROL_AOC:
07051 {
07052 struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07053 if (!decoded) {
07054 ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07055 res = -1;
07056 break;
07057 }
07058 switch (ast_aoc_get_msg_type(decoded)) {
07059 case AST_AOC_REQUEST:
07060 if (ast_aoc_get_termination_request(decoded)) {
07061
07062
07063
07064
07065
07066
07067
07068 ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", ast_channel_name(p->owner));
07069 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07070 }
07071 break;
07072 case AST_AOC_D:
07073 case AST_AOC_E:
07074 if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07075 transmit_info_with_aoc(p, decoded);
07076 }
07077 break;
07078 case AST_AOC_S:
07079 default:
07080 break;
07081 }
07082 ast_aoc_destroy_decoded(decoded);
07083 }
07084 break;
07085 case AST_CONTROL_UPDATE_RTP_PEER:
07086 break;
07087 case -1:
07088 res = -1;
07089 break;
07090 default:
07091 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07092 res = -1;
07093 break;
07094 }
07095 sip_pvt_unlock(p);
07096 return res;
07097 }
07098
07099
07100
07101
07102
07103
07104
07105
07106
07107
07108
07109
07110 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07111 {
07112 struct ast_channel *tmp;
07113 struct ast_variable *v = NULL;
07114 struct ast_format fmt;
07115 struct ast_format_cap *what = NULL;
07116 int needvideo = 0;
07117 int needtext = 0;
07118 char buf[SIPBUFSIZE];
07119 char *exten;
07120
07121 {
07122 const char *my_name;
07123
07124 if (title) {
07125 my_name = title;
07126 } else {
07127 my_name = ast_strdupa(i->fromdomain);
07128 }
07129
07130 sip_pvt_unlock(i);
07131
07132 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));
07133 }
07134 if (!tmp) {
07135 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07136 sip_pvt_lock(i);
07137 return NULL;
07138 }
07139 ast_channel_lock(tmp);
07140 sip_pvt_lock(i);
07141 ast_channel_cc_params_init(tmp, i->cc_params);
07142 tmp->caller.id.tag = ast_strdup(i->cid_tag);
07143
07144 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;
07145
07146
07147
07148 if (!(ast_format_cap_is_empty(i->jointcaps))) {
07149 what = i->jointcaps;
07150 } else if (!(ast_format_cap_is_empty(i->caps))) {
07151 what = i->caps;
07152 } else {
07153 what = sip_cfg.caps;
07154 }
07155
07156
07157 ast_format_cap_copy(tmp->nativeformats, what);
07158
07159 ast_codec_choose(&i->prefs, tmp->nativeformats, 1, &fmt);
07160 ast_format_cap_remove_bytype(tmp->nativeformats, AST_FORMAT_TYPE_AUDIO);
07161 ast_format_cap_add(tmp->nativeformats, &fmt);
07162
07163 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07164 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcaps));
07165 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->caps));
07166 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname(&fmt));
07167 if (!ast_format_cap_is_empty(i->prefcaps)) {
07168 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcaps));
07169 }
07170
07171
07172
07173
07174
07175 if (i->vrtp) {
07176 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07177 needvideo = 1;
07178 else if (!ast_format_cap_is_empty(i->prefcaps))
07179 needvideo = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_VIDEO);
07180 else
07181 needvideo = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_VIDEO);
07182 }
07183
07184 if (i->trtp) {
07185 if (!ast_format_cap_is_empty(i->prefcaps))
07186 needtext = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_TEXT);
07187 else
07188 needtext = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_TEXT);
07189 }
07190
07191 if (needvideo) {
07192 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07193 } else {
07194 ast_debug(3, "This channel will not be able to handle video.\n");
07195 }
07196
07197 enable_dsp_detect(i);
07198
07199 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07200 (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07201 if (i->rtp) {
07202 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07203 }
07204 } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07205 if (i->rtp) {
07206 ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07207 }
07208 }
07209
07210
07211
07212
07213 if (i->rtp) {
07214 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07215 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07216 }
07217 if (needvideo && i->vrtp) {
07218 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07219 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07220 }
07221 if (needtext && i->trtp) {
07222 ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07223 }
07224 if (i->udptl) {
07225 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07226 }
07227
07228 if (state == AST_STATE_RING) {
07229 tmp->rings = 1;
07230 }
07231 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07232
07233 ast_format_copy(&tmp->writeformat, &fmt);
07234 ast_format_copy(&tmp->rawwriteformat, &fmt);
07235 ast_rtp_instance_set_write_format(i->rtp, &fmt);
07236
07237 ast_format_copy(&tmp->readformat, &fmt);
07238 ast_format_copy(&tmp->rawreadformat, &fmt);
07239 ast_rtp_instance_set_read_format(i->rtp, &fmt);
07240
07241 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07242
07243 tmp->callgroup = i->callgroup;
07244 tmp->pickupgroup = i->pickupgroup;
07245 tmp->caller.id.name.presentation = i->callingpres;
07246 tmp->caller.id.number.presentation = i->callingpres;
07247 if (!ast_strlen_zero(i->parkinglot)) {
07248 ast_channel_parkinglot_set(tmp, i->parkinglot);
07249 }
07250 if (!ast_strlen_zero(i->accountcode)) {
07251 ast_channel_accountcode_set(tmp, i->accountcode);
07252 }
07253 if (i->amaflags) {
07254 tmp->amaflags = i->amaflags;
07255 }
07256 if (!ast_strlen_zero(i->language)) {
07257 ast_channel_language_set(tmp, i->language);
07258 }
07259 if (!ast_strlen_zero(i->zone)) {
07260 if (!(tmp->zone = ast_get_indication_zone(i->zone))) {
07261 ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
07262 }
07263 }
07264 i->owner = tmp;
07265 ast_module_ref(ast_module_info->self);
07266 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07267
07268
07269
07270
07271 exten = ast_strdupa(i->exten);
07272 sip_pvt_unlock(i);
07273 ast_channel_unlock(tmp);
07274 if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07275 ast_uri_decode(exten, ast_uri_sip_user);
07276 }
07277 ast_channel_lock(tmp);
07278 sip_pvt_lock(i);
07279 ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07280
07281
07282
07283 if (!ast_strlen_zero(i->cid_num)) {
07284 tmp->caller.ani.number.valid = 1;
07285 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07286 }
07287 if (!ast_strlen_zero(i->rdnis)) {
07288 tmp->redirecting.from.number.valid = 1;
07289 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07290 }
07291
07292 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07293 tmp->dialed.number.str = ast_strdup(i->exten);
07294 }
07295
07296 tmp->priority = 1;
07297 if (!ast_strlen_zero(i->uri)) {
07298 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07299 }
07300 if (!ast_strlen_zero(i->domain)) {
07301 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07302 }
07303 if (!ast_strlen_zero(i->callid)) {
07304 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07305 }
07306 if (i->rtp) {
07307 ast_jb_configure(tmp, &global_jbconf);
07308 }
07309
07310
07311 for (v = i->chanvars ; v ; v = v->next) {
07312 char valuebuf[1024];
07313 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07314 }
07315
07316 if (i->do_history) {
07317 append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
07318 }
07319
07320
07321 if (sip_cfg.callevents) {
07322 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07323 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07324 ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
07325 }
07326
07327 return tmp;
07328 }
07329
07330
07331 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07332 {
07333 if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter) {
07334 return ast_skip_blanks(line + nameLen + 1);
07335 }
07336
07337 return "";
07338 }
07339
07340
07341
07342
07343
07344 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07345 {
07346 int len = strlen(name);
07347
07348 while (*start < (req->sdp_start + req->sdp_count)) {
07349 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07350 if (r[0] != '\0')
07351 return r;
07352 }
07353
07354
07355 (*start)++;
07356
07357 return "";
07358 }
07359
07360
07361
07362
07363
07364
07365 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07366 {
07367 char type = '\0';
07368 const char *line = NULL;
07369
07370 if (stop > (req->sdp_start + req->sdp_count)) {
07371 stop = req->sdp_start + req->sdp_count;
07372 }
07373
07374 while (*start < stop) {
07375 line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07376 if (line[1] == '=') {
07377 type = line[0];
07378 *value = ast_skip_blanks(line + 2);
07379 break;
07380 }
07381 }
07382
07383 return type;
07384 }
07385
07386
07387 static char *get_body(struct sip_request *req, char *name, char delimiter)
07388 {
07389 int x;
07390 int len = strlen(name);
07391 char *r;
07392
07393 for (x = 0; x < req->lines; x++) {
07394 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07395 if (r[0] != '\0') {
07396 return r;
07397 }
07398 }
07399
07400 return "";
07401 }
07402
07403
07404 struct cfalias {
07405 const char *fullname;
07406 const char *shortname;
07407 };
07408 static const struct cfalias aliases[] = {
07409 { "Content-Type", "c" },
07410 { "Content-Encoding", "e" },
07411 { "From", "f" },
07412 { "Call-ID", "i" },
07413 { "Contact", "m" },
07414 { "Content-Length", "l" },
07415 { "Subject", "s" },
07416 { "To", "t" },
07417 { "Supported", "k" },
07418 { "Refer-To", "r" },
07419 { "Referred-By", "b" },
07420 { "Allow-Events", "u" },
07421 { "Event", "o" },
07422 { "Via", "v" },
07423 { "Accept-Contact", "a" },
07424 { "Reject-Contact", "j" },
07425 { "Request-Disposition", "d" },
07426 { "Session-Expires", "x" },
07427 { "Identity", "y" },
07428 { "Identity-Info", "n" },
07429 };
07430
07431
07432 static const char *find_alias(const char *name, const char *_default)
07433 {
07434 int x;
07435
07436 for (x = 0; x < ARRAY_LEN(aliases); x++) {
07437 if (!strcasecmp(aliases[x].fullname, name))
07438 return aliases[x].shortname;
07439 }
07440
07441 return _default;
07442 }
07443
07444
07445 static const char *find_full_alias(const char *name, const char *_default)
07446 {
07447 int x;
07448
07449 if (strlen(name) == 1) {
07450
07451 for (x = 0; x < ARRAY_LEN(aliases); ++x) {
07452 if (!strcasecmp(aliases[x].shortname, name))
07453 return aliases[x].fullname;
07454 }
07455 }
07456
07457 return _default;
07458 }
07459
07460 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07461 {
07462
07463
07464
07465
07466
07467
07468
07469
07470
07471 const char *sname = find_alias(name, NULL);
07472 int x, len = strlen(name), slen = (sname ? 1 : 0);
07473 for (x = *start; x < req->headers; x++) {
07474 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07475 int smatch = 0, match = !strncasecmp(header, name, len);
07476 if (slen) {
07477 smatch = !strncasecmp(header, sname, slen);
07478 }
07479 if (match || smatch) {
07480
07481 const char *r = header + (match ? len : slen );
07482 if (sip_cfg.pedanticsipchecking) {
07483 r = ast_skip_blanks(r);
07484 }
07485
07486 if (*r == ':') {
07487 *start = x+1;
07488 return ast_skip_blanks(r+1);
07489 }
07490 }
07491 }
07492
07493
07494 return "";
07495 }
07496
07497
07498
07499
07500 const char *sip_get_header(const struct sip_request *req, const char *name)
07501 {
07502 int start = 0;
07503 return __get_header(req, name, &start);
07504 }
07505
07506
07507 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07508 {
07509
07510 struct ast_frame *f;
07511
07512 if (!p->rtp) {
07513
07514 return &ast_null_frame;
07515 }
07516
07517 switch(ast->fdno) {
07518 case 0:
07519 f = ast_rtp_instance_read(p->rtp, 0);
07520 break;
07521 case 1:
07522 f = ast_rtp_instance_read(p->rtp, 1);
07523 break;
07524 case 2:
07525 f = ast_rtp_instance_read(p->vrtp, 0);
07526 break;
07527 case 3:
07528 f = ast_rtp_instance_read(p->vrtp, 1);
07529 break;
07530 case 4:
07531 f = ast_rtp_instance_read(p->trtp, 0);
07532 if (sipdebug_text) {
07533 struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
07534 int i;
07535 unsigned char* arr = f->data.ptr;
07536 do {
07537 if (!out) {
07538 break;
07539 }
07540 for (i = 0; i < f->datalen; i++) {
07541 ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07542 }
07543 ast_str_append(&out, 0, " -> ");
07544 for (i = 0; i < f->datalen; i++) {
07545 ast_str_append(&out, 0, "%02X ", arr[i]);
07546 }
07547 ast_verb(0, "%s\n", ast_str_buffer(out));
07548 ast_free(out);
07549 } while (0);
07550 }
07551 break;
07552 case 5:
07553 f = ast_udptl_read(p->udptl);
07554 break;
07555 default:
07556 f = &ast_null_frame;
07557 }
07558
07559 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07560 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07561 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07562 return &ast_null_frame;
07563 }
07564
07565
07566 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
07567 return f;
07568 }
07569
07570 if (f && !ast_format_cap_iscompatible(p->owner->nativeformats, &f->subclass.format)) {
07571 if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
07572 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07573 ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));
07574 return &ast_null_frame;
07575 }
07576 ast_debug(1, "Oooh, format changed to %s\n",
07577 ast_getformatname(&f->subclass.format));
07578 ast_format_cap_remove_bytype(p->owner->nativeformats, AST_FORMAT_TYPE_AUDIO);
07579 ast_format_cap_add(p->owner->nativeformats, &f->subclass.format);
07580 ast_set_read_format(p->owner, &p->owner->readformat);
07581 ast_set_write_format(p->owner, &p->owner->writeformat);
07582 }
07583
07584 if (f && p->dsp) {
07585 f = ast_dsp_process(p->owner, p->dsp, f);
07586 if (f && f->frametype == AST_FRAME_DTMF) {
07587 if (f->subclass.integer == 'f') {
07588 ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
07589 *faxdetect = 1;
07590
07591 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07592 ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07593 } else {
07594 ast_dsp_free(p->dsp);
07595 p->dsp = NULL;
07596 }
07597 } else {
07598 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07599 }
07600 }
07601 }
07602
07603 return f;
07604 }
07605
07606
07607 static struct ast_frame *sip_read(struct ast_channel *ast)
07608 {
07609 struct ast_frame *fr;
07610 struct sip_pvt *p = ast->tech_pvt;
07611 int faxdetected = FALSE;
07612
07613 sip_pvt_lock(p);
07614 fr = sip_rtp_read(ast, p, &faxdetected);
07615 p->lastrtprx = time(NULL);
07616
07617
07618 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07619 if (strcmp(ast->exten, "fax")) {
07620 const char *target_context = S_OR(ast->macrocontext, ast->context);
07621
07622
07623
07624
07625
07626 sip_pvt_unlock(p);
07627 ast_channel_unlock(ast);
07628 if (ast_exists_extension(ast, target_context, "fax", 1,
07629 S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07630 ast_channel_lock(ast);
07631 sip_pvt_lock(p);
07632 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
07633 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07634 if (ast_async_goto(ast, target_context, "fax", 1)) {
07635 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
07636 }
07637 fr = &ast_null_frame;
07638 } else {
07639 ast_channel_lock(ast);
07640 sip_pvt_lock(p);
07641 ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07642 }
07643 }
07644 }
07645
07646
07647 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07648 fr = &ast_null_frame;
07649 }
07650
07651 sip_pvt_unlock(p);
07652
07653 return fr;
07654 }
07655
07656
07657
07658 static char *generate_random_string(char *buf, size_t size)
07659 {
07660 long val[4];
07661 int x;
07662
07663 for (x=0; x<4; x++)
07664 val[x] = ast_random();
07665 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07666
07667 return buf;
07668 }
07669
07670 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07671 {
07672 struct ast_str *uri = ast_str_alloca(size);
07673 ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07674
07675
07676
07677 ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07678 ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07679 ast_copy_string(buf, ast_str_buffer(uri), size);
07680 return buf;
07681 }
07682
07683
07684
07685
07686
07687
07688
07689
07690 static void build_callid_pvt(struct sip_pvt *pvt)
07691 {
07692 char buf[33];
07693 const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07694
07695 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07696 }
07697
07698
07699 #define CONTAINER_UNLINK(container, obj, tag) \
07700 ({ \
07701 int found = 0; \
07702 typeof((obj)) __removed_obj; \
07703 __removed_obj = ao2_t_callback((container), \
07704 OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag)); \
07705 if (__removed_obj) { \
07706 ao2_ref(__removed_obj, -1); \
07707 found = 1; \
07708 } \
07709 found; \
07710 })
07711
07712
07713
07714
07715
07716
07717
07718
07719
07720
07721 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07722 {
07723 int in_dialog_container;
07724 int in_rtp_container;
07725
07726 ao2_lock(dialogs);
07727 ao2_lock(dialogs_rtpcheck);
07728 in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07729 "About to change the callid -- remove the old name");
07730 in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
07731 "About to change the callid -- remove the old name");
07732 if (callid) {
07733 ast_string_field_set(pvt, callid, callid);
07734 } else {
07735 build_callid_pvt(pvt);
07736 }
07737 if (in_dialog_container) {
07738 ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07739 }
07740 if (in_rtp_container) {
07741 ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
07742 }
07743 ao2_unlock(dialogs_rtpcheck);
07744 ao2_unlock(dialogs);
07745 }
07746
07747
07748 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07749 {
07750 char buf[33];
07751
07752 const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07753
07754 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07755 }
07756
07757
07758 static void make_our_tag(char *tagbuf, size_t len)
07759 {
07760 snprintf(tagbuf, len, "as%08lx", ast_random());
07761 }
07762
07763
07764 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07765 {
07766 struct sip_st_dlg *stp;
07767
07768 if (p->stimer) {
07769 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07770 return p->stimer;
07771 }
07772
07773 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07774 return NULL;
07775
07776 p->stimer = stp;
07777
07778 stp->st_schedid = -1;
07779
07780 return p->stimer;
07781 }
07782
07783
07784
07785
07786
07787 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07788 int useglobal_nat, const int intended_method, struct sip_request *req)
07789 {
07790 struct sip_pvt *p;
07791
07792 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07793 return NULL;
07794
07795 if (ast_string_field_init(p, 512)) {
07796 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07797 return NULL;
07798 }
07799
07800 if (!(p->cc_params = ast_cc_config_params_init())) {
07801 ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07802 return NULL;
07803 }
07804 p->caps = ast_format_cap_alloc_nolock();
07805 p->jointcaps = ast_format_cap_alloc_nolock();
07806 p->peercaps = ast_format_cap_alloc_nolock();
07807 p->redircaps = ast_format_cap_alloc_nolock();
07808 p->prefcaps = ast_format_cap_alloc_nolock();
07809
07810 if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps) {
07811 p->caps = ast_format_cap_destroy(p->caps);
07812 p->jointcaps = ast_format_cap_destroy(p->jointcaps);
07813 p->peercaps = ast_format_cap_destroy(p->peercaps);
07814 p->redircaps = ast_format_cap_destroy(p->redircaps);
07815 p->prefcaps = ast_format_cap_destroy(p->prefcaps);
07816 ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
07817 return NULL;
07818 }
07819
07820
07821
07822
07823 if (req) {
07824 struct sip_via *via;
07825 const char *cseq = sip_get_header(req, "Cseq");
07826 uint32_t seqno;
07827
07828
07829 via = parse_via(sip_get_header(req, "Via"));
07830 if (via) {
07831
07832
07833 if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
07834 ast_string_field_set(p, initviabranch, via->branch);
07835 ast_string_field_set(p, initviasentby, via->sent_by);
07836 }
07837 free_via(via);
07838 }
07839
07840
07841
07842 if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07843 p->init_icseq = seqno;
07844 }
07845
07846 set_socket_transport(&p->socket, req->socket.type);
07847 } else {
07848 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07849 }
07850
07851 p->socket.fd = -1;
07852 p->method = intended_method;
07853 p->initid = -1;
07854 p->waitid = -1;
07855 p->autokillid = -1;
07856 p->request_queue_sched_id = -1;
07857 p->provisional_keepalive_sched_id = -1;
07858 p->t38id = -1;
07859 p->subscribed = NONE;
07860 p->stateid = -1;
07861 p->sessionversion_remote = -1;
07862 p->session_modify = TRUE;
07863 p->stimer = NULL;
07864 p->prefs = default_prefs;
07865 ast_copy_string(p->zone, default_zone, sizeof(p->zone));
07866 p->maxforwards = sip_cfg.default_max_forwards;
07867
07868 if (intended_method != SIP_OPTIONS) {
07869 p->timer_t1 = global_t1;
07870 p->timer_b = global_timer_b;
07871 }
07872
07873 if (!addr) {
07874 p->ourip = internip;
07875 } else {
07876 ast_sockaddr_copy(&p->sa, addr);
07877 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07878 }
07879
07880
07881 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07882 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07883 ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07884
07885 p->do_history = recordhistory;
07886
07887 p->branch = ast_random();
07888 make_our_tag(p->tag, sizeof(p->tag));
07889 p->ocseq = INITIAL_CSEQ;
07890 p->allowed_methods = UINT_MAX;
07891
07892 if (sip_methods[intended_method].need_rtp) {
07893 p->maxcallbitrate = default_maxcallbitrate;
07894 p->autoframing = global_autoframing;
07895 }
07896
07897 if (useglobal_nat && addr) {
07898
07899 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07900 ast_sockaddr_copy(&p->recv, addr);
07901
07902 do_setnat(p);
07903 }
07904
07905 if (p->method != SIP_REGISTER) {
07906 ast_string_field_set(p, fromdomain, default_fromdomain);
07907 p->fromdomainport = default_fromdomainport;
07908 }
07909 build_via(p);
07910 if (!callid)
07911 build_callid_pvt(p);
07912 else
07913 ast_string_field_set(p, callid, callid);
07914
07915 ast_string_field_set(p, mohinterpret, default_mohinterpret);
07916 ast_string_field_set(p, mohsuggest, default_mohsuggest);
07917 ast_format_cap_copy(p->caps, sip_cfg.caps);
07918 p->allowtransfer = sip_cfg.allowtransfer;
07919 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07920 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07921 p->noncodeccapability |= AST_RTP_DTMF;
07922 }
07923 ast_string_field_set(p, context, sip_cfg.default_context);
07924 ast_string_field_set(p, parkinglot, default_parkinglot);
07925 ast_string_field_set(p, engine, default_engine);
07926
07927 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07928
07929
07930
07931 ao2_t_link(dialogs, p, "link pvt into dialogs table");
07932
07933 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");
07934 return p;
07935 }
07936
07937
07938
07939
07940
07941
07942
07943
07944
07945
07946
07947
07948
07949
07950
07951
07952 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07953 {
07954 struct sip_via *via = parse_via(sip_get_header(req, "Via"));
07955
07956 if (!via) {
07957 ast_log(LOG_ERROR, "error processing via header\n");
07958 return -1;
07959 }
07960
07961 if (via->maddr) {
07962 if (ast_sockaddr_resolve_first(&p->sa, via->maddr, PARSE_PORT_FORBID)) {
07963 ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07964 ast_log(LOG_ERROR, "error processing via header\n");
07965 free_via(via);
07966 return -1;
07967 }
07968
07969 if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
07970 setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07971 }
07972 }
07973
07974 ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
07975
07976 free_via(via);
07977 return 0;
07978 }
07979
07980
07981 struct match_req_args {
07982 int method;
07983 const char *callid;
07984 const char *totag;
07985 const char *fromtag;
07986 uint32_t seqno;
07987
07988
07989 int respid;
07990
07991
07992 const char *ruri;
07993 const char *viabranch;
07994 const char *viasentby;
07995
07996
07997 int authentication_present;
07998 };
07999
08000 enum match_req_res {
08001 SIP_REQ_MATCH,
08002 SIP_REQ_NOT_MATCH,
08003 SIP_REQ_LOOP_DETECTED,
08004 SIP_REQ_FORKED,
08005 };
08006
08007
08008
08009
08010
08011
08012 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08013 {
08014 const char *init_ruri = NULL;
08015 if (sip_pvt_ptr->initreq.headers) {
08016 init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
08017 }
08018
08019
08020
08021
08022 if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08023
08024 return SIP_REQ_NOT_MATCH;
08025 }
08026 if (arg->method == SIP_RESPONSE) {
08027
08028 if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08029
08030 return SIP_REQ_NOT_MATCH;
08031 }
08032
08033
08034
08035 if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08036 if (ast_strlen_zero(arg->totag)) {
08037
08038 return SIP_REQ_NOT_MATCH;
08039 }
08040
08041 if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08042
08043 char invite_branch[32] = { 0, };
08044 if (sip_pvt_ptr->invite_branch) {
08045 snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (int) sip_pvt_ptr->invite_branch);
08046 }
08047
08048
08049
08050
08051
08052
08053
08054
08055
08056
08057
08058
08059 if ((arg->respid == 200) &&
08060 !ast_strlen_zero(invite_branch) &&
08061 !ast_strlen_zero(arg->viabranch) &&
08062 !strcmp(invite_branch, arg->viabranch)) {
08063 return SIP_REQ_FORKED;
08064 }
08065
08066
08067 return SIP_REQ_NOT_MATCH;
08068 }
08069 }
08070 } else {
08071
08072
08073
08074 if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08075
08076 return SIP_REQ_NOT_MATCH;
08077 }
08078
08079 if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08080
08081 return SIP_REQ_NOT_MATCH;
08082 }
08083 }
08084
08085
08086
08087
08088
08089
08090
08091
08092
08093
08094
08095
08096
08097
08098
08099
08100
08101 if ((arg->method != SIP_RESPONSE) &&
08102 ast_strlen_zero(arg->totag) &&
08103 (sip_pvt_ptr->init_icseq == arg->seqno) &&
08104 !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&
08105 init_ruri) {
08106
08107
08108 if (ast_strlen_zero(arg->viabranch) ||
08109 strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08110 ast_strlen_zero(arg->viasentby) ||
08111 strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08112
08113
08114
08115 if ((sip_pvt_ptr->method != arg->method)) {
08116 return SIP_REQ_NOT_MATCH;
08117 }
08118
08119
08120
08121 if (sip_uri_cmp(init_ruri, arg->ruri)) {
08122
08123 return SIP_REQ_NOT_MATCH;
08124 }
08125
08126
08127
08128
08129
08130
08131
08132
08133
08134
08135
08136
08137
08138
08139
08140
08141
08142
08143
08144 return SIP_REQ_LOOP_DETECTED;
08145 }
08146 }
08147
08148
08149
08150
08151
08152
08153 if ((arg->method != SIP_RESPONSE) &&
08154 ast_strlen_zero(arg->totag) &&
08155 arg->authentication_present &&
08156 sip_uri_cmp(init_ruri, arg->ruri)) {
08157
08158
08159 return SIP_REQ_NOT_MATCH;
08160 }
08161
08162 return SIP_REQ_MATCH;
08163 }
08164
08165
08166
08167
08168 static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
08169 {
08170 struct sip_pvt *p;
08171
08172 if (!(p = sip_alloc(original->callid, addr, 1, SIP_INVITE, req))) {
08173 return;
08174 }
08175 p->invitestate = INV_TERMINATED;
08176 p->ocseq = original->ocseq;
08177 p->branch = original->branch;
08178
08179 memcpy(&p->flags, &original->flags, sizeof(p->flags));
08180 copy_request(&p->initreq, &original->initreq);
08181 ast_string_field_set(p, theirtag, new_theirtag);
08182 ast_copy_string(p->tag, original->tag, sizeof(p->tag));
08183 ast_string_field_set(p, uri, original->uri);
08184 ast_string_field_set(p, our_contact, original->our_contact);
08185 ast_string_field_set(p, fullcontact, original->fullcontact);
08186 parse_ok_contact(p, req);
08187 build_route(p, req, 1);
08188
08189 transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
08190 transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
08191
08192 pvt_set_needdestroy(p, "forked request");
08193 dialog_unref(p, "setup forked invite termination");
08194 }
08195
08196
08197
08198
08199
08200
08201
08202
08203
08204
08205
08206
08207
08208
08209
08210
08211
08212
08213 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08214 {
08215 struct ast_channel *chan;
08216
08217
08218
08219
08220 for (;;) {
08221
08222 sip_pvt_lock(pvt);
08223 chan = pvt->owner;
08224 if (chan) {
08225
08226
08227
08228 ast_channel_ref(chan);
08229 } else {
08230
08231 return NULL;
08232 }
08233
08234
08235
08236
08237 sip_pvt_unlock(pvt);
08238
08239
08240 ast_channel_lock(chan);
08241 sip_pvt_lock(pvt);
08242
08243 if (pvt->owner == chan) {
08244
08245 break;
08246 }
08247
08248
08249
08250
08251
08252
08253 ast_channel_unlock(chan);
08254 ast_channel_unref(chan);
08255 sip_pvt_unlock(pvt);
08256 }
08257
08258
08259 return pvt->owner;
08260 }
08261
08262
08263
08264
08265
08266
08267 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08268 {
08269 char totag[128];
08270 char fromtag[128];
08271 const char *callid = sip_get_header(req, "Call-ID");
08272 const char *from = sip_get_header(req, "From");
08273 const char *to = sip_get_header(req, "To");
08274 const char *cseq = sip_get_header(req, "Cseq");
08275 struct sip_pvt *sip_pvt_ptr;
08276 uint32_t seqno;
08277
08278
08279 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08280 ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08281 (sscanf(cseq, "%30u", &seqno) != 1)) {
08282
08283
08284 if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08285 transmit_response_using_temp(callid, addr, 1, intended_method,
08286 req, "400 Bad Request");
08287 }
08288 return NULL;
08289 }
08290
08291 if (sip_cfg.pedanticsipchecking) {
08292
08293
08294
08295
08296
08297
08298 if (gettag(req, "To", totag, sizeof(totag)))
08299 req->has_to_tag = 1;
08300 gettag(req, "From", fromtag, sizeof(fromtag));
08301
08302 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);
08303
08304
08305 if (ast_strlen_zero(fromtag)) {
08306 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08307 return NULL;
08308 }
08309
08310 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08311 if (req->method != SIP_ACK) {
08312 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08313 }
08314 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08315 return NULL;
08316 }
08317 }
08318
08319 if (!sip_cfg.pedanticsipchecking) {
08320 struct sip_pvt tmp_dialog = {
08321 .callid = callid,
08322 };
08323 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08324 if (sip_pvt_ptr) {
08325
08326 return sip_pvt_ptr;
08327 }
08328 } else {
08329 struct sip_pvt tmp_dialog = {
08330 .callid = callid,
08331 };
08332
08333
08334 struct sip_pvt *fork_pvt = NULL;
08335 struct match_req_args args = { 0, };
08336 int found;
08337 struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08338 OBJ_POINTER | OBJ_MULTIPLE,
08339 dialog_find_multiple,
08340 &tmp_dialog,
08341 "pedantic ao2_find in dialogs");
08342 struct sip_via *via = NULL;
08343
08344 args.method = req->method;
08345 args.callid = NULL;
08346 args.totag = totag;
08347 args.fromtag = fromtag;
08348 args.seqno = seqno;
08349
08350 args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08351 via = parse_via(sip_get_header(req, "Via"));
08352 if (via) {
08353 args.viasentby = via->sent_by;
08354 args.viabranch = via->branch;
08355 }
08356
08357 if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
08358 !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
08359 args.authentication_present = 1;
08360 }
08361
08362 if (req->method == SIP_RESPONSE) {
08363 const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
08364 int respid;
08365 if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
08366 args.respid = respid;
08367 }
08368 }
08369
08370
08371 while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08372 found = match_req_to_dialog(sip_pvt_ptr, &args);
08373
08374 switch (found) {
08375 case SIP_REQ_MATCH:
08376 ao2_iterator_destroy(iterator);
08377 dialog_unref(fork_pvt, "unref fork_pvt");
08378 free_via(via);
08379 return sip_pvt_ptr;
08380 case SIP_REQ_LOOP_DETECTED:
08381
08382
08383 transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08384 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08385 ao2_iterator_destroy(iterator);
08386 dialog_unref(fork_pvt, "unref fork_pvt");
08387 free_via(via);
08388 return NULL;
08389 case SIP_REQ_FORKED:
08390 dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
08391 fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
08392
08393 case SIP_REQ_NOT_MATCH:
08394 default:
08395 dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08396 }
08397 }
08398 if (iterator) {
08399 ao2_iterator_destroy(iterator);
08400 }
08401
08402
08403 if (fork_pvt) {
08404
08405
08406 if (fork_pvt->method == SIP_INVITE) {
08407 forked_invite_init(req, args.totag, fork_pvt, addr);
08408 dialog_unref(fork_pvt, "throwing way old forked pvt");
08409 free_via(via);
08410 return NULL;
08411 }
08412 fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
08413 }
08414
08415 free_via(via);
08416 }
08417
08418
08419 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08420 struct sip_pvt *p = NULL;
08421
08422 if (intended_method == SIP_REFER) {
08423
08424 transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08425
08426
08427 } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req))) {
08428
08429
08430
08431
08432
08433
08434
08435
08436 transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08437 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08438 }
08439 return p;
08440 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08441
08442 transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08443 ast_debug(2, "Got a request with unsupported SIP method.\n");
08444 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08445
08446 transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08447 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08448 }
08449
08450
08451 if (intended_method == SIP_RESPONSE)
08452 ast_debug(2, "That's odd... Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08453
08454 return NULL;
08455 }
08456
08457
08458 static int sip_register(const char *value, int lineno)
08459 {
08460 struct sip_registry *reg, *tmp;
08461
08462 if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08463 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08464 return -1;
08465 }
08466
08467 ASTOBJ_INIT(reg);
08468
08469 ast_copy_string(reg->name, value, sizeof(reg->name));
08470 if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08471 registry_unref(reg, "failure to parse, unref the reg pointer");
08472 return -1;
08473 }
08474
08475
08476 if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08477 reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08478 }
08479
08480
08481 if ((tmp = ASTOBJ_CONTAINER_FIND(®l, reg->name))) {
08482 registry_unref(tmp, "throw away found registry");
08483 } else {
08484 ast_atomic_fetchadd_int(®objs, 1);
08485 ASTOBJ_CONTAINER_LINK(®l, reg);
08486 }
08487
08488
08489 registry_unref(reg, "unref the reg pointer");
08490
08491 return 0;
08492 }
08493
08494
08495 static int sip_subscribe_mwi(const char *value, int lineno)
08496 {
08497 struct sip_subscription_mwi *mwi;
08498 int portnum = 0;
08499 enum sip_transport transport = SIP_TRANSPORT_UDP;
08500 char buf[256] = "";
08501 char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL, *at = NULL;
08502
08503 if (!value) {
08504 return -1;
08505 }
08506
08507 ast_copy_string(buf, value, sizeof(buf));
08508
08509 if (!(at = strstr(buf, "@"))) {
08510 return -1;
08511 }
08512
08513 if ((hostname = strrchr(buf, '@'))) {
08514 *hostname++ = '\0';
08515 username = buf;
08516 }
08517
08518 if ((secret = strchr(username, ':'))) {
08519 *secret++ = '\0';
08520 if ((authuser = strchr(secret, ':'))) {
08521 *authuser++ = '\0';
08522 }
08523 }
08524
08525 if ((mailbox = strchr(hostname, '/'))) {
08526 *mailbox++ = '\0';
08527 }
08528
08529 if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08530 ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08531 return -1;
08532 }
08533
08534 if ((porta = strchr(hostname, ':'))) {
08535 *porta++ = '\0';
08536 if (!(portnum = atoi(porta))) {
08537 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08538 return -1;
08539 }
08540 }
08541
08542 if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08543 return -1;
08544 }
08545
08546 ASTOBJ_INIT(mwi);
08547 ast_string_field_set(mwi, username, username);
08548 if (secret) {
08549 ast_string_field_set(mwi, secret, secret);
08550 }
08551 if (authuser) {
08552 ast_string_field_set(mwi, authuser, authuser);
08553 }
08554 ast_string_field_set(mwi, hostname, hostname);
08555 ast_string_field_set(mwi, mailbox, mailbox);
08556 mwi->resub = -1;
08557 mwi->portno = portnum;
08558 mwi->transport = transport;
08559
08560 ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08561 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08562
08563 return 0;
08564 }
08565
08566 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08567 {
08568 (*allowed_methods) |= (1 << method);
08569 }
08570
08571 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08572 {
08573 (*allowed_methods) &= ~(1 << method);
08574 }
08575
08576
08577 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08578 {
08579 return ((*allowed_methods) >> method) & 1;
08580 }
08581
08582 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08583 {
08584 char *method;
08585 for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08586 int id = find_sip_method(ast_skip_blanks(method));
08587 if (id == SIP_UNKNOWN) {
08588 continue;
08589 }
08590 mark_method_allowed(methods, id);
08591 }
08592 }
08593
08594
08595
08596
08597
08598
08599
08600
08601
08602
08603
08604
08605
08606
08607
08608
08609 static unsigned int parse_allowed_methods(struct sip_request *req)
08610 {
08611 char *allow = ast_strdupa(sip_get_header(req, "Allow"));
08612 unsigned int allowed_methods = SIP_UNKNOWN;
08613
08614 if (ast_strlen_zero(allow)) {
08615
08616
08617
08618
08619 char *contact = ast_strdupa(sip_get_header(req, "Contact"));
08620 char *methods = strstr(contact, ";methods=");
08621
08622 if (ast_strlen_zero(methods)) {
08623
08624
08625
08626
08627
08628
08629
08630
08631
08632
08633
08634 return UINT_MAX;
08635 }
08636 allow = ast_strip_quoted(methods + 9, "\"", "\"");
08637 }
08638 mark_parsed_methods(&allowed_methods, allow);
08639 return allowed_methods;
08640 }
08641
08642
08643
08644
08645
08646
08647
08648
08649
08650
08651 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08652 {
08653 pvt->allowed_methods = parse_allowed_methods(req);
08654
08655 if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08656 mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08657 }
08658 pvt->allowed_methods &= ~(pvt->disallowed_methods);
08659
08660 return pvt->allowed_methods;
08661 }
08662
08663
08664
08665 static void lws2sws(struct ast_str *data)
08666 {
08667 char *msgbuf = data->str;
08668 int len = ast_str_strlen(data);
08669 int h = 0, t = 0;
08670 int lws = 0;
08671
08672 for (; h < len;) {
08673
08674 if (msgbuf[h] == '\r') {
08675 h++;
08676 continue;
08677 }
08678
08679 if (msgbuf[h] == '\n') {
08680
08681 if (h + 1 == len)
08682 break;
08683
08684 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08685
08686 h++;
08687 continue;
08688 }
08689
08690 msgbuf[t++] = msgbuf[h++];
08691 lws = 0;
08692 continue;
08693 }
08694 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08695 if (lws) {
08696 h++;
08697 continue;
08698 }
08699 msgbuf[t++] = msgbuf[h++];
08700 lws = 1;
08701 continue;
08702 }
08703 msgbuf[t++] = msgbuf[h++];
08704 if (lws)
08705 lws = 0;
08706 }
08707 msgbuf[t] = '\0';
08708 data->used = t;
08709 }
08710
08711
08712
08713
08714 static int parse_request(struct sip_request *req)
08715 {
08716 char *c = req->data->str;
08717 ptrdiff_t *dst = req->header;
08718 int i = 0, lim = SIP_MAX_HEADERS - 1;
08719 unsigned int skipping_headers = 0;
08720 ptrdiff_t current_header_offset = 0;
08721 char *previous_header = "";
08722
08723 req->header[0] = 0;
08724 req->headers = -1;
08725 for (; *c; c++) {
08726 if (*c == '\r') {
08727 *c = '\0';
08728 } else if (*c == '\n') {
08729 *c = '\0';
08730 current_header_offset = (c + 1) - req->data->str;
08731 previous_header = req->data->str + dst[i];
08732 if (skipping_headers) {
08733
08734
08735
08736 if (ast_strlen_zero(previous_header)) {
08737 skipping_headers = 0;
08738 }
08739 dst[i] = current_header_offset;
08740 continue;
08741 }
08742 if (sipdebug) {
08743 ast_debug(4, "%7s %2d [%3d]: %s\n",
08744 req->headers < 0 ? "Header" : "Body",
08745 i, (int) strlen(previous_header), previous_header);
08746 }
08747 if (ast_strlen_zero(previous_header) && req->headers < 0) {
08748 req->headers = i;
08749 dst = req->line;
08750 i = 0;
08751 lim = SIP_MAX_LINES - 1;
08752 } else {
08753 if (i++ == lim) {
08754
08755
08756
08757 if (req->headers != -1) {
08758 break;
08759 } else {
08760 req->headers = i;
08761 dst = req->line;
08762 i = 0;
08763 lim = SIP_MAX_LINES - 1;
08764 skipping_headers = 1;
08765 }
08766 }
08767 }
08768 dst[i] = current_header_offset;
08769 }
08770 }
08771
08772
08773
08774
08775
08776
08777 previous_header = req->data->str + dst[i];
08778 if ((i < lim) && !ast_strlen_zero(previous_header)) {
08779 if (sipdebug) {
08780 ast_debug(4, "%7s %2d [%3d]: %s\n",
08781 req->headers < 0 ? "Header" : "Body",
08782 i, (int) strlen(previous_header), previous_header );
08783 }
08784 i++;
08785 }
08786
08787
08788 if (req->headers >= 0) {
08789 req->lines = i;
08790 } else {
08791 req->headers = i;
08792 req->lines = 0;
08793
08794 req->line[0] = ast_str_strlen(req->data);
08795 }
08796
08797 if (*c) {
08798 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08799 }
08800
08801
08802 return determine_firstline_parts(req);
08803 }
08804
08805
08806
08807
08808
08809
08810
08811
08812
08813 static int find_sdp(struct sip_request *req)
08814 {
08815 const char *content_type;
08816 const char *content_length;
08817 const char *search;
08818 char *boundary;
08819 unsigned int x;
08820 int boundaryisquoted = FALSE;
08821 int found_application_sdp = FALSE;
08822 int found_end_of_headers = FALSE;
08823
08824 content_length = sip_get_header(req, "Content-Length");
08825
08826 if (!ast_strlen_zero(content_length)) {
08827 if (sscanf(content_length, "%30u", &x) != 1) {
08828 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08829 return 0;
08830 }
08831
08832
08833
08834 if (x == 0)
08835 return 0;
08836 }
08837
08838 content_type = sip_get_header(req, "Content-Type");
08839
08840
08841 if (!strncasecmp(content_type, "application/sdp", 15)) {
08842 req->sdp_start = 0;
08843 req->sdp_count = req->lines;
08844 return req->lines ? 1 : 0;
08845 }
08846
08847
08848 if (strncasecmp(content_type, "multipart/mixed", 15))
08849 return 0;
08850
08851
08852 if ((search = strcasestr(content_type, ";boundary=")))
08853 search += 10;
08854 else if ((search = strcasestr(content_type, "; boundary=")))
08855 search += 11;
08856 else
08857 return 0;
08858
08859 if (ast_strlen_zero(search))
08860 return 0;
08861
08862
08863 if (*search == '\"') {
08864 search++;
08865 boundaryisquoted = TRUE;
08866 }
08867
08868
08869
08870 boundary = ast_strdupa(search - 2);
08871 boundary[0] = boundary[1] = '-';
08872
08873 if (boundaryisquoted)
08874 boundary[strlen(boundary) - 1] = '\0';
08875
08876
08877
08878
08879 for (x = 0; x < (req->lines); x++) {
08880 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08881 if (!strncasecmp(line, boundary, strlen(boundary))){
08882 if (found_application_sdp && found_end_of_headers) {
08883 req->sdp_count = (x - 1) - req->sdp_start;
08884 return 1;
08885 }
08886 found_application_sdp = FALSE;
08887 }
08888 if (!strcasecmp(line, "Content-Type: application/sdp"))
08889 found_application_sdp = TRUE;
08890
08891 if (ast_strlen_zero(line)) {
08892 if (found_application_sdp && !found_end_of_headers){
08893 req->sdp_start = x;
08894 found_end_of_headers = TRUE;
08895 }
08896 }
08897 }
08898 if (found_application_sdp && found_end_of_headers) {
08899 req->sdp_count = x - req->sdp_start;
08900 return TRUE;
08901 }
08902 return FALSE;
08903 }
08904
08905
08906 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08907 {
08908 if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08909 sip_peer_hold(dialog, holdstate);
08910 if (sip_cfg.callevents)
08911 manager_event(EVENT_FLAG_CALL, "Hold",
08912 "Status: %s\r\n"
08913 "Channel: %s\r\n"
08914 "Uniqueid: %s\r\n",
08915 holdstate ? "On" : "Off",
08916 ast_channel_name(dialog->owner),
08917 ast_channel_uniqueid(dialog->owner));
08918 append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08919 if (!holdstate) {
08920 ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08921 return;
08922 }
08923
08924
08925 if (sendonly == 1)
08926 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08927 else if (sendonly == 2)
08928 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08929 else
08930 ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08931 return;
08932 }
08933
08934
08935 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08936 {
08937 const char *m;
08938 const char *c;
08939 int miterator = req->sdp_start;
08940 int citerator = req->sdp_start;
08941 int x = 0;
08942 int numberofports;
08943 int len;
08944 int af;
08945 char proto[4], host[258] = "";
08946
08947 c = get_sdp_iterate(&citerator, req, "c");
08948 if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08949 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08950
08951 }
08952
08953 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08954 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08955 (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08956 (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08957 (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08958
08959
08960
08961
08962 c = get_sdp_iterate(&citerator, req, "c");
08963 if (!ast_strlen_zero(c)) {
08964 sscanf(c, "IN %3s %256s", proto, host);
08965 }
08966 break;
08967 }
08968 }
08969
08970 if (!strcmp("IP4", proto)) {
08971 af = AF_INET;
08972 } else if (!strcmp("IP6", proto)) {
08973 af = AF_INET6;
08974 } else {
08975 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08976 return -1;
08977 }
08978
08979 if (ast_strlen_zero(host) || x == 0) {
08980 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08981 return -1;
08982 }
08983
08984 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08985 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08986 return -1;
08987 }
08988
08989 return 0;
08990 }
08991
08992
08993
08994
08995
08996
08997
08998 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
08999 {
09000 return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09001 }
09002
09003
09004
09005
09006
09007
09008 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09009 {
09010 int res = 0;
09011
09012
09013 int start = req->sdp_start;
09014 int next = start;
09015 int iterator = start;
09016
09017
09018 char type = '\0';
09019 const char *value = NULL;
09020 const char *m = NULL;
09021 const char *nextm = NULL;
09022 int len = -1;
09023
09024
09025 struct ast_sockaddr sessionsa;
09026 struct ast_sockaddr audiosa;
09027 struct ast_sockaddr videosa;
09028 struct ast_sockaddr textsa;
09029 struct ast_sockaddr imagesa;
09030 struct ast_sockaddr *sa = NULL;
09031 struct ast_sockaddr *vsa = NULL;
09032 struct ast_sockaddr *tsa = NULL;
09033 struct ast_sockaddr *isa = NULL;
09034 int portno = -1;
09035 int vportno = -1;
09036 int tportno = -1;
09037 int udptlportno = -1;
09038
09039
09040 struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
09041 struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
09042 struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
09043
09044 int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09045
09046 struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
09047 struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock();
09048 struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
09049 int newnoncodeccapability;
09050
09051 const char *codecs;
09052 int codec;
09053
09054
09055 int secure_audio = FALSE;
09056 int secure_video = FALSE;
09057
09058
09059 int sendonly = -1;
09060 int vsendonly = -1;
09061 int numberofports;
09062 int numberofmediastreams = 0;
09063 int last_rtpmap_codec = 0;
09064 int red_data_pt[10];
09065 int red_num_gen = 0;
09066 char red_fmtp[100] = "empty";
09067 int debug = sip_debug_test_pvt(p);
09068
09069
09070 char buf[SIPBUFSIZE];
09071 struct ast_format tmp_fmt;
09072
09073
09074
09075 if (!p->rtp) {
09076 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09077 res = -1;
09078 goto process_sdp_cleanup;
09079 }
09080 if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
09081 res = -1;
09082 goto process_sdp_cleanup;
09083 }
09084
09085
09086 ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
09087 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09088 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09089
09090
09091 p->lastrtprx = p->lastrtptx = time(NULL);
09092
09093 memset(p->offered_media, 0, sizeof(p->offered_media));
09094
09095 if (p->vrtp) {
09096 ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09097 }
09098
09099 if (p->trtp) {
09100 ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09101 }
09102
09103
09104 nextm = get_sdp_iterate(&next, req, "m");
09105 if (ast_strlen_zero(nextm)) {
09106 ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09107 res = -1;
09108 goto process_sdp_cleanup;
09109 }
09110
09111
09112 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09113 int processed = FALSE;
09114 switch (type) {
09115 case 'o':
09116
09117
09118
09119 if (!process_sdp_o(value, p)) {
09120 res = (p->session_modify == FALSE) ? 0 : -1;
09121 goto process_sdp_cleanup;
09122 }
09123 break;
09124 case 'c':
09125 if (process_sdp_c(value, &sessionsa)) {
09126 processed = TRUE;
09127 sa = &sessionsa;
09128 vsa = sa;
09129 tsa = sa;
09130 isa = sa;
09131 }
09132 break;
09133 case 'a':
09134 if (process_sdp_a_sendonly(value, &sendonly)) {
09135 processed = TRUE;
09136 vsendonly = sendonly;
09137 }
09138 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09139 processed = TRUE;
09140 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09141 processed = TRUE;
09142 else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09143 processed = TRUE;
09144 else if (process_sdp_a_image(value, p))
09145 processed = TRUE;
09146 break;
09147 }
09148
09149 ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
09150 }
09151
09152
09153 p->novideo = TRUE;
09154 p->notext = TRUE;
09155
09156
09157 while (!ast_strlen_zero(nextm)) {
09158 int audio = FALSE;
09159 int video = FALSE;
09160 int image = FALSE;
09161 int text = FALSE;
09162 char protocol[5] = {0,};
09163 int x;
09164
09165 numberofports = 1;
09166 len = -1;
09167 start = next;
09168 m = nextm;
09169 iterator = next;
09170 nextm = get_sdp_iterate(&next, req, "m");
09171
09172
09173 if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09174 (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09175 if (x == 0) {
09176 ast_log(LOG_WARNING, "ignoring 'audio' media offer because port number is zero");
09177 continue;
09178 }
09179 if (!strcmp(protocol, "SAVP")) {
09180 secure_audio = 1;
09181 } else if (strcmp(protocol, "AVP")) {
09182 ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
09183 continue;
09184 }
09185 if (p->offered_media[SDP_AUDIO].order_offered) {
09186 ast_log(LOG_WARNING, "Multiple audio streams are not supported\n");
09187 res = -3;
09188 goto process_sdp_cleanup;
09189 }
09190 audio = TRUE;
09191 p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09192 portno = x;
09193
09194
09195 codecs = m + len;
09196 ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09197 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09198 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09199 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09200 res = -1;
09201 goto process_sdp_cleanup;
09202 }
09203 if (debug)
09204 ast_verbose("Found RTP audio format %d\n", codec);
09205
09206 ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09207 }
09208
09209 } else if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09210 (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09211 if (x == 0) {
09212 ast_log(LOG_WARNING, "ignoring 'video' media offer because port number is zero");
09213 continue;
09214 }
09215 if (!strcmp(protocol, "SAVP")) {
09216 secure_video = 1;
09217 } else if (strcmp(protocol, "AVP")) {
09218 ast_log(LOG_WARNING, "unknown SDP media protocol in offer: %s\n", protocol);
09219 continue;
09220 }
09221 if (p->offered_media[SDP_VIDEO].order_offered) {
09222 ast_log(LOG_WARNING, "Multiple video streams are not supported\n");
09223 res = -3;
09224 goto process_sdp_cleanup;
09225 }
09226 video = TRUE;
09227 p->novideo = FALSE;
09228 p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09229 vportno = x;
09230
09231
09232 codecs = m + len;
09233 ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09234 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09235 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09236 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09237 res = -1;
09238 goto process_sdp_cleanup;
09239 }
09240 if (debug)
09241 ast_verbose("Found RTP video format %d\n", codec);
09242 ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09243 }
09244
09245 } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09246 (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09247 if (x == 0) {
09248 ast_log(LOG_WARNING, "ignoring 'text' media offer because port number is zero");
09249 continue;
09250 }
09251 if (p->offered_media[SDP_TEXT].order_offered) {
09252 ast_log(LOG_WARNING, "Multiple text streams are not supported\n");
09253 res = -3;
09254 goto process_sdp_cleanup;
09255 }
09256 text = TRUE;
09257 p->notext = FALSE;
09258 p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09259 tportno = x;
09260
09261
09262 codecs = m + len;
09263 ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09264 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09265 if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09266 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
09267 res = -1;
09268 goto process_sdp_cleanup;
09269 }
09270 if (debug)
09271 ast_verbose("Found RTP text format %d\n", codec);
09272 ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09273 }
09274
09275 } else if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09276 (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09277 if (x == 0) {
09278 ast_log(LOG_WARNING, "ignoring 'image' media offer because port number is zero");
09279 continue;
09280 }
09281 if (initialize_udptl(p)) {
09282 continue;
09283 }
09284
09285 if (p->offered_media[SDP_IMAGE].order_offered) {
09286 ast_log(LOG_WARNING, "Multiple T.38 streams are not supported\n");
09287 res = -3;
09288 goto process_sdp_cleanup;
09289 }
09290 image = TRUE;
09291 if (debug)
09292 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09293 p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09294 udptlportno = x;
09295
09296 if (p->t38.state != T38_ENABLED) {
09297 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09298
09299
09300
09301 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09302 }
09303 } else {
09304 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
09305 continue;
09306 }
09307
09308
09309 if (numberofports > 1)
09310 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
09311
09312
09313 while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09314 int processed = FALSE;
09315
09316 switch (type) {
09317 case 'c':
09318 if (audio) {
09319 if (process_sdp_c(value, &audiosa)) {
09320 processed = TRUE;
09321 sa = &audiosa;
09322 }
09323 } else if (video) {
09324 if (process_sdp_c(value, &videosa)) {
09325 processed = TRUE;
09326 vsa = &videosa;
09327 }
09328 } else if (text) {
09329 if (process_sdp_c(value, &textsa)) {
09330 processed = TRUE;
09331 tsa = &textsa;
09332 }
09333 } else if (image) {
09334 if (process_sdp_c(value, &imagesa)) {
09335 processed = TRUE;
09336 isa = &imagesa;
09337 }
09338 }
09339 break;
09340 case 'a':
09341
09342 if (audio) {
09343 if (process_sdp_a_sendonly(value, &sendonly))
09344 processed = TRUE;
09345 else if (process_crypto(p, p->rtp, &p->srtp, value))
09346 processed = TRUE;
09347 else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09348 processed = TRUE;
09349 }
09350
09351 else if (video) {
09352 if (process_sdp_a_sendonly(value, &vsendonly))
09353 processed = TRUE;
09354 else if (process_crypto(p, p->vrtp, &p->vsrtp, value))
09355 processed = TRUE;
09356 else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09357 processed = TRUE;
09358 }
09359
09360 else if (text) {
09361 if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09362 processed = TRUE;
09363 else if (process_crypto(p, p->trtp, &p->tsrtp, value))
09364 processed = TRUE;
09365 }
09366
09367 else if (image) {
09368 if (process_sdp_a_image(value, p))
09369 processed = TRUE;
09370 }
09371 break;
09372 }
09373
09374 ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09375 (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
09376 type, value,
09377 (processed == TRUE)? "OK." : "UNSUPPORTED.");
09378 }
09379 }
09380
09381
09382
09383 if (!sa && !vsa && !tsa && !isa) {
09384 ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09385 res = -1;
09386 goto process_sdp_cleanup;
09387 }
09388
09389 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1) {
09390
09391
09392 ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09393 res = -2;
09394 goto process_sdp_cleanup;
09395 }
09396
09397 if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09398 ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09399 res = -4;
09400 goto process_sdp_cleanup;
09401 }
09402
09403 if (!secure_audio && p->srtp) {
09404 ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09405 res = -4;
09406 goto process_sdp_cleanup;
09407 }
09408
09409 if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09410 ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09411 res = -4;
09412 goto process_sdp_cleanup;
09413 }
09414
09415 if (!p->novideo && !secure_video && p->vsrtp) {
09416 ast_log(LOG_WARNING, "We are requesting SRTP, but they responded without it!\n");
09417 res = -4;
09418 goto process_sdp_cleanup;
09419 }
09420
09421 if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09422 ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09423 res = -4;
09424 goto process_sdp_cleanup;
09425 }
09426
09427 if (udptlportno == -1) {
09428 change_t38_state(p, T38_DISABLED);
09429 }
09430
09431
09432 ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
09433 ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
09434 ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
09435
09436 ast_format_cap_append(newpeercapability, peercapability);
09437 ast_format_cap_append(newpeercapability, vpeercapability);
09438 ast_format_cap_append(newpeercapability, tpeercapability);
09439
09440 ast_format_cap_joint_copy(p->caps, newpeercapability, newjointcapability);
09441 if (ast_format_cap_is_empty(newjointcapability) && udptlportno == -1) {
09442 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09443
09444 res = -1;
09445 goto process_sdp_cleanup;
09446 }
09447
09448 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09449
09450 if (debug) {
09451
09452 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09453
09454 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09455 ast_getformatname_multiple(s1, SIPBUFSIZE, p->caps),
09456 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09457 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09458 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09459 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09460 }
09461 if (debug) {
09462 struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09463 struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09464 struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09465
09466 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09467 ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
09468 ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
09469 ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
09470 }
09471
09472 if (portno != -1 || vportno != -1 || tportno != -1) {
09473
09474
09475 ast_format_cap_copy(p->jointcaps, newjointcapability);
09476 ast_format_cap_copy(p->peercaps, newpeercapability);
09477 p->jointnoncodeccapability = newnoncodeccapability;
09478
09479
09480 if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09481 ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
09482 ast_format_cap_set(p->jointcaps, &tmp_fmt);
09483 }
09484 }
09485
09486
09487 if (p->rtp) {
09488 if (portno > 0) {
09489 ast_sockaddr_set_port(sa, portno);
09490 ast_rtp_instance_set_remote_address(p->rtp, sa);
09491 if (debug) {
09492 ast_verbose("Peer audio RTP is at port %s\n",
09493 ast_sockaddr_stringify(sa));
09494 }
09495
09496 ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09497
09498
09499 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09500
09501 if (p->owner) {
09502 ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09503 }
09504
09505 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09506 ast_clear_flag(&p->flags[0], SIP_DTMF);
09507 if (newnoncodeccapability & AST_RTP_DTMF) {
09508
09509 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09510
09511 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09512 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09513 } else {
09514 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09515 }
09516 }
09517 } else if (udptlportno > 0) {
09518 if (debug)
09519 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09520
09521 if (p->owner) {
09522 ast_channel_set_fd(p->owner, 1, -1);
09523 }
09524
09525 ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09526 } else {
09527 ast_rtp_instance_stop(p->rtp);
09528 if (debug)
09529 ast_verbose("Peer doesn't provide audio\n");
09530 }
09531 }
09532
09533
09534 if (p->vrtp) {
09535 if (vportno > 0) {
09536 ast_sockaddr_set_port(vsa, vportno);
09537 ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09538 if (debug) {
09539 ast_verbose("Peer video RTP is at port %s\n",
09540 ast_sockaddr_stringify(vsa));
09541 }
09542 ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09543 } else {
09544 ast_rtp_instance_stop(p->vrtp);
09545 if (debug)
09546 ast_verbose("Peer doesn't provide video\n");
09547 }
09548 }
09549
09550
09551 if (p->trtp) {
09552 if (tportno > 0) {
09553 ast_sockaddr_set_port(tsa, tportno);
09554 ast_rtp_instance_set_remote_address(p->trtp, tsa);
09555 if (debug) {
09556 ast_verbose("Peer T.140 RTP is at port %s\n",
09557 ast_sockaddr_stringify(tsa));
09558 }
09559 if (ast_format_cap_iscompatible(p->jointcaps, ast_format_set(&tmp_fmt, AST_FORMAT_T140RED, 0))) {
09560 p->red = 1;
09561 ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09562 } else {
09563 p->red = 0;
09564 }
09565 ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09566 } else {
09567 ast_rtp_instance_stop(p->trtp);
09568 if (debug)
09569 ast_verbose("Peer doesn't provide T.140\n");
09570 }
09571 }
09572
09573 if (p->udptl) {
09574 if (udptlportno > 0) {
09575 if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09576 ast_rtp_instance_get_remote_address(p->rtp, isa);
09577 if (!ast_sockaddr_isnull(isa) && debug) {
09578 ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09579 }
09580 }
09581 ast_sockaddr_set_port(isa, udptlportno);
09582 ast_udptl_set_peer(p->udptl, isa);
09583 if (debug)
09584 ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09585
09586
09587 if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09588
09589 ast_udptl_set_far_max_datagram(p->udptl, 0);
09590 }
09591
09592
09593 if ((t38action == SDP_T38_ACCEPT) &&
09594 (p->t38.state == T38_LOCAL_REINVITE)) {
09595 change_t38_state(p, T38_ENABLED);
09596 } else if ((t38action == SDP_T38_INITIATE) &&
09597 p->owner && p->lastinvite) {
09598 change_t38_state(p, T38_PEER_REINVITE);
09599
09600 if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09601 ast_channel_lock(p->owner);
09602 if (strcmp(p->owner->exten, "fax")) {
09603 const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09604 ast_channel_unlock(p->owner);
09605 if (ast_exists_extension(p->owner, target_context, "fax", 1,
09606 S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09607 ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
09608 pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09609 if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09610 ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
09611 }
09612 } else {
09613 ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09614 }
09615 } else {
09616 ast_channel_unlock(p->owner);
09617 }
09618 }
09619 }
09620 } else {
09621 change_t38_state(p, T38_DISABLED);
09622 ast_udptl_stop(p->udptl);
09623 if (debug)
09624 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09625 }
09626 }
09627
09628 if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
09629 ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09630 res = 0;
09631 goto process_sdp_cleanup;
09632 }
09633
09634
09635 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcaps));
09636
09637 if (!p->owner) {
09638 res = 0;
09639 goto process_sdp_cleanup;
09640 }
09641
09642 ast_debug(4, "We have an owner, now see if we need to change this call\n");
09643 if (ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO)) {
09644 if (debug) {
09645 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09646 ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
09647 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcaps),
09648 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09649 }
09650
09651 ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
09652
09653 ast_format_cap_set(p->owner->nativeformats, &tmp_fmt);
09654 ast_format_cap_joint_append(p->caps, vpeercapability, p->owner->nativeformats);
09655 ast_format_cap_joint_append(p->caps, tpeercapability, p->owner->nativeformats);
09656
09657 ast_set_read_format(p->owner, &p->owner->readformat);
09658 ast_set_write_format(p->owner, &p->owner->writeformat);
09659 }
09660
09661 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)) {
09662 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09663
09664 ast_queue_frame(p->owner, &ast_null_frame);
09665 change_hold_state(p, req, FALSE, sendonly);
09666 } 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)) {
09667 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09668 S_OR(p->mohsuggest, NULL),
09669 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09670 if (sendonly)
09671 ast_rtp_instance_stop(p->rtp);
09672
09673
09674 ast_queue_frame(p->owner, &ast_null_frame);
09675 change_hold_state(p, req, TRUE, sendonly);
09676 }
09677
09678 process_sdp_cleanup:
09679 ast_format_cap_destroy(peercapability);
09680 ast_format_cap_destroy(vpeercapability);
09681 ast_format_cap_destroy(tpeercapability);
09682 ast_format_cap_destroy(newjointcapability);
09683 ast_format_cap_destroy(newpeercapability);
09684 return res;
09685 }
09686
09687 static int process_sdp_o(const char *o, struct sip_pvt *p)
09688 {
09689 char *o_copy;
09690 char *token;
09691 int64_t rua_version;
09692
09693
09694
09695
09696
09697
09698
09699
09700
09701
09702 p->session_modify = TRUE;
09703
09704 if (ast_strlen_zero(o)) {
09705 ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09706 return FALSE;
09707 }
09708
09709 o_copy = ast_strdupa(o);
09710 token = strsep(&o_copy, " ");
09711 if (!o_copy) {
09712 ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09713 return FALSE;
09714 }
09715 token = strsep(&o_copy, " ");
09716 if (!o_copy) {
09717 ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09718 return FALSE;
09719 }
09720 token = strsep(&o_copy, " ");
09721 if (!o_copy) {
09722 ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09723 return FALSE;
09724 }
09725 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09726 ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09727 return FALSE;
09728 }
09729
09730
09731
09732
09733
09734
09735
09736
09737
09738
09739
09740
09741
09742
09743
09744
09745
09746
09747
09748 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09749 (p->sessionversion_remote < 0) ||
09750 (p->sessionversion_remote < rua_version)) {
09751 p->sessionversion_remote = rua_version;
09752 } else {
09753 if (p->t38.state == T38_LOCAL_REINVITE) {
09754 p->sessionversion_remote = rua_version;
09755 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);
09756 } else {
09757 p->session_modify = FALSE;
09758 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09759 return FALSE;
09760 }
09761 }
09762
09763 return TRUE;
09764 }
09765
09766 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09767 {
09768 char proto[4], host[258];
09769 int af;
09770
09771
09772 if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09773 if (!strcmp("IP4", proto)) {
09774 af = AF_INET;
09775 } else if (!strcmp("IP6", proto)) {
09776 af = AF_INET6;
09777 } else {
09778 ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09779 return FALSE;
09780 }
09781 if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09782 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09783 return FALSE;
09784 }
09785 return TRUE;
09786 } else {
09787 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09788 return FALSE;
09789 }
09790 return FALSE;
09791 }
09792
09793 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09794 {
09795 int found = FALSE;
09796
09797 if (!strcasecmp(a, "sendonly")) {
09798 if (*sendonly == -1)
09799 *sendonly = 1;
09800 found = TRUE;
09801 } else if (!strcasecmp(a, "inactive")) {
09802 if (*sendonly == -1)
09803 *sendonly = 2;
09804 found = TRUE;
09805 } else if (!strcasecmp(a, "sendrecv")) {
09806 if (*sendonly == -1)
09807 *sendonly = 0;
09808 found = TRUE;
09809 }
09810 return found;
09811 }
09812
09813 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09814 {
09815 int found = FALSE;
09816 int codec;
09817 char mimeSubtype[128];
09818 char fmtp_string[64];
09819 unsigned int sample_rate;
09820 int debug = sip_debug_test_pvt(p);
09821
09822 if (!strncasecmp(a, "ptime", 5)) {
09823 char *tmp = strrchr(a, ':');
09824 long int framing = 0;
09825 if (tmp) {
09826 tmp++;
09827 framing = strtol(tmp, NULL, 10);
09828 if (framing == LONG_MIN || framing == LONG_MAX) {
09829 framing = 0;
09830 ast_debug(1, "Can't read framing from SDP: %s\n", a);
09831 }
09832 }
09833 if (framing && p->autoframing) {
09834 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09835 int codec_n;
09836 for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09837 struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09838 if (!format.asterisk_format)
09839 continue;
09840 ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(&format.format), framing);
09841 ast_codec_pref_setsize(pref, &format.format, framing);
09842 }
09843 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09844 }
09845 found = TRUE;
09846 } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09847
09848 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09849 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09850 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09851 if (debug)
09852 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09853
09854 (*last_rtpmap_codec)++;
09855 found = TRUE;
09856 } else {
09857 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09858 if (debug)
09859 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09860 }
09861 } else {
09862 if (debug)
09863 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09864 }
09865 } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09866 struct ast_format *format;
09867
09868 if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
09869 unsigned int bit_rate;
09870 int val = 0;
09871
09872 switch ((int) format->id) {
09873 case AST_FORMAT_SIREN7:
09874 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09875 if (bit_rate != 32000) {
09876 ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09877 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09878 } else {
09879 found = TRUE;
09880 }
09881 }
09882 break;
09883 case AST_FORMAT_SIREN14:
09884 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09885 if (bit_rate != 48000) {
09886 ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09887 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09888 } else {
09889 found = TRUE;
09890 }
09891 }
09892 break;
09893 case AST_FORMAT_G719:
09894 if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09895 if (bit_rate != 64000) {
09896 ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
09897 ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09898 } else {
09899 found = TRUE;
09900 }
09901 }
09902 break;
09903 case AST_FORMAT_CELT:
09904 if (sscanf(fmtp_string, "framesize=%30u", &val) == 1) {
09905 ast_format_append(format, CELT_ATTR_KEY_FRAME_SIZE, val, AST_FORMAT_ATTR_END);
09906 }
09907 case AST_FORMAT_SILK:
09908 if (sscanf(fmtp_string, "maxaveragebitrate=%30u", &val) == 1) {
09909 ast_format_append(format, SILK_ATTR_KEY_MAX_BITRATE, val, AST_FORMAT_ATTR_END);
09910 }
09911 if (sscanf(fmtp_string, "usedtx=%30u", &val) == 1) {
09912 ast_format_append(format, SILK_ATTR_KEY_DTX, val ? 1 : 0, AST_FORMAT_ATTR_END);
09913 }
09914 if (sscanf(fmtp_string, "useinbandfec=%30u", &val) == 1) {
09915 ast_format_append(format, SILK_ATTR_KEY_FEC, val ? 1 : 0, AST_FORMAT_ATTR_END);
09916 }
09917 break;
09918 }
09919 }
09920 }
09921
09922 return found;
09923 }
09924
09925 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09926 {
09927 int found = FALSE;
09928 int codec;
09929 char mimeSubtype[128];
09930 unsigned int sample_rate;
09931 int debug = sip_debug_test_pvt(p);
09932
09933 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09934
09935 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09936
09937 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09938 if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
09939 if (debug)
09940 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09941
09942 (*last_rtpmap_codec)++;
09943 found = TRUE;
09944 } else {
09945 ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09946 if (debug)
09947 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09948 }
09949 }
09950 } else {
09951 if (debug)
09952 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09953 }
09954 }
09955
09956 return found;
09957 }
09958
09959 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)
09960 {
09961 int found = FALSE;
09962 int codec;
09963 char mimeSubtype[128];
09964 unsigned int sample_rate;
09965 char *red_cp;
09966 int debug = sip_debug_test_pvt(p);
09967
09968 if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09969
09970 if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09971 if (!strncasecmp(mimeSubtype, "T140", 4)) {
09972 if (p->trtp) {
09973
09974 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09975 found = TRUE;
09976 }
09977 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
09978 if (p->trtp) {
09979 ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09980 sprintf(red_fmtp, "fmtp:%d ", codec);
09981 if (debug)
09982 ast_verbose("RED submimetype has payload type: %d\n", codec);
09983 found = TRUE;
09984 }
09985 }
09986 } else {
09987 if (debug)
09988 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09989 }
09990 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09991
09992 red_cp = &red_fmtp[strlen(red_fmtp)];
09993 strncpy(red_fmtp, a, 100);
09994
09995 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09996 red_cp = strtok(red_cp, "/");
09997 while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09998 sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09999 red_cp = strtok(NULL, "/");
10000 }
10001 red_cp = red_fmtp;
10002 found = TRUE;
10003 }
10004
10005 return found;
10006 }
10007
10008 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
10009 {
10010 int found = FALSE;
10011 char s[256];
10012 unsigned int x;
10013
10014 if (initialize_udptl(p)) {
10015 return found;
10016 }
10017
10018 if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
10019 ast_debug(3, "MaxBufferSize:%d\n", x);
10020 found = TRUE;
10021 } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
10022 ast_debug(3, "T38MaxBitRate: %d\n", x);
10023 switch (x) {
10024 case 14400:
10025 p->t38.their_parms.rate = AST_T38_RATE_14400;
10026 break;
10027 case 12000:
10028 p->t38.their_parms.rate = AST_T38_RATE_12000;
10029 break;
10030 case 9600:
10031 p->t38.their_parms.rate = AST_T38_RATE_9600;
10032 break;
10033 case 7200:
10034 p->t38.their_parms.rate = AST_T38_RATE_7200;
10035 break;
10036 case 4800:
10037 p->t38.their_parms.rate = AST_T38_RATE_4800;
10038 break;
10039 case 2400:
10040 p->t38.their_parms.rate = AST_T38_RATE_2400;
10041 break;
10042 }
10043 found = TRUE;
10044 } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
10045 ast_debug(3, "FaxVersion: %u\n", x);
10046 p->t38.their_parms.version = x;
10047 found = TRUE;
10048 } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
10049
10050 if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
10051 ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
10052 x = p->t38_maxdatagram;
10053 }
10054 ast_debug(3, "FaxMaxDatagram: %u\n", x);
10055 ast_udptl_set_far_max_datagram(p->udptl, x);
10056 found = TRUE;
10057 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
10058 if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
10059 ast_debug(3, "FillBitRemoval: %d\n", x);
10060 if (x == 1) {
10061 p->t38.their_parms.fill_bit_removal = TRUE;
10062 }
10063 } else {
10064 ast_debug(3, "FillBitRemoval\n");
10065 p->t38.their_parms.fill_bit_removal = TRUE;
10066 }
10067 found = TRUE;
10068 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
10069 if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
10070 ast_debug(3, "Transcoding MMR: %d\n", x);
10071 if (x == 1) {
10072 p->t38.their_parms.transcoding_mmr = TRUE;
10073 }
10074 } else {
10075 ast_debug(3, "Transcoding MMR\n");
10076 p->t38.their_parms.transcoding_mmr = TRUE;
10077 }
10078 found = TRUE;
10079 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
10080 if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
10081 ast_debug(3, "Transcoding JBIG: %d\n", x);
10082 if (x == 1) {
10083 p->t38.their_parms.transcoding_jbig = TRUE;
10084 }
10085 } else {
10086 ast_debug(3, "Transcoding JBIG\n");
10087 p->t38.their_parms.transcoding_jbig = TRUE;
10088 }
10089 found = TRUE;
10090 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
10091 ast_debug(3, "RateManagement: %s\n", s);
10092 if (!strcasecmp(s, "localTCF"))
10093 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
10094 else if (!strcasecmp(s, "transferredTCF"))
10095 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
10096 found = TRUE;
10097 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
10098 ast_debug(3, "UDP EC: %s\n", s);
10099 if (!strcasecmp(s, "t38UDPRedundancy")) {
10100 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
10101 } else if (!strcasecmp(s, "t38UDPFEC")) {
10102 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
10103 } else {
10104 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10105 }
10106 found = TRUE;
10107 }
10108
10109 return found;
10110 }
10111
10112
10113
10114
10115 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
10116 {
10117 int res;
10118 if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
10119 res = add_header(req, "Supported", "replaces, timer");
10120 } else {
10121 res = add_header(req, "Supported", "replaces");
10122 }
10123 return res;
10124 }
10125
10126
10127 static int add_header(struct sip_request *req, const char *var, const char *value)
10128 {
10129 if (req->headers == SIP_MAX_HEADERS) {
10130 ast_log(LOG_WARNING, "Out of SIP header space\n");
10131 return -1;
10132 }
10133
10134 if (req->lines) {
10135 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
10136 return -1;
10137 }
10138
10139 if (sip_cfg.compactheaders) {
10140 var = find_alias(var, var);
10141 }
10142
10143 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
10144 req->header[req->headers] = ast_str_strlen(req->data);
10145
10146 req->headers++;
10147
10148 return 0;
10149 }
10150
10151
10152
10153
10154
10155 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10156 {
10157 char clen[10];
10158
10159 snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10160
10161 return add_header(req, "Max-Forwards", clen);
10162 }
10163
10164
10165 static int finalize_content(struct sip_request *req)
10166 {
10167 char clen[10];
10168
10169 if (req->lines) {
10170 ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10171 return -1;
10172 }
10173
10174 snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
10175 add_header(req, "Content-Length", clen);
10176
10177 if (ast_str_strlen(req->content)) {
10178 ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10179 }
10180 req->lines = ast_str_strlen(req->content) ? 1 : 0;
10181 return 0;
10182 }
10183
10184
10185 static int add_content(struct sip_request *req, const char *line)
10186 {
10187 if (req->lines) {
10188 ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10189 return -1;
10190 }
10191
10192 ast_str_append(&req->content, 0, "%s", line);
10193 return 0;
10194 }
10195
10196
10197 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10198 {
10199 const char *tmp = sip_get_header(orig, field);
10200
10201 if (!ast_strlen_zero(tmp))
10202 return add_header(req, field, tmp);
10203 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10204 return -1;
10205 }
10206
10207
10208 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10209 {
10210 int start = 0;
10211 int copied = 0;
10212 for (;;) {
10213 const char *tmp = __get_header(orig, field, &start);
10214
10215 if (ast_strlen_zero(tmp))
10216 break;
10217
10218 add_header(req, field, tmp);
10219 copied++;
10220 }
10221 return copied ? 0 : -1;
10222 }
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10233 {
10234 int copied = 0;
10235 int start = 0;
10236
10237 for (;;) {
10238 char new[512];
10239 const char *oh = __get_header(orig, field, &start);
10240
10241 if (ast_strlen_zero(oh))
10242 break;
10243
10244 if (!copied) {
10245 char leftmost[512], *others, *rport;
10246
10247
10248 ast_copy_string(leftmost, oh, sizeof(leftmost));
10249 others = strchr(leftmost, ',');
10250 if (others)
10251 *others++ = '\0';
10252
10253
10254 rport = strstr(leftmost, ";rport");
10255 if (rport && *(rport+6) == '=')
10256 rport = NULL;
10257
10258 if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10259
10260 char *end;
10261
10262 rport = strstr(leftmost, ";rport");
10263
10264 if (rport) {
10265 end = strchr(rport + 1, ';');
10266 if (end)
10267 memmove(rport, end, strlen(end) + 1);
10268 else
10269 *rport = '\0';
10270 }
10271
10272
10273 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10274 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10275 ast_sockaddr_port(&p->recv),
10276 others ? "," : "", others ? others : "");
10277 } else {
10278
10279 snprintf(new, sizeof(new), "%s;received=%s%s%s",
10280 leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10281 others ? "," : "", others ? others : "");
10282 }
10283 oh = new;
10284 }
10285 add_header(req, field, oh);
10286 copied++;
10287 }
10288 if (!copied) {
10289 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10290 return -1;
10291 }
10292 return 0;
10293 }
10294
10295
10296 static void add_route(struct sip_request *req, struct sip_route *route)
10297 {
10298 char r[SIPBUFSIZE*2], *p;
10299 int n, rem = sizeof(r);
10300
10301 if (!route)
10302 return;
10303
10304 p = r;
10305 for (;route ; route = route->next) {
10306 n = strlen(route->hop);
10307 if (rem < n+3)
10308 break;
10309 if (p != r) {
10310 *p++ = ',';
10311 --rem;
10312 }
10313 *p++ = '<';
10314 ast_copy_string(p, route->hop, rem);
10315 p += n;
10316 *p++ = '>';
10317 rem -= (n+2);
10318 }
10319 *p = '\0';
10320 add_header(req, "Route", r);
10321 }
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332 static void set_destination(struct sip_pvt *p, char *uri)
10333 {
10334 char *h, *maddr, hostname[256];
10335 int hn;
10336 int debug=sip_debug_test_pvt(p);
10337 int tls_on = FALSE;
10338
10339 if (debug)
10340 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10341
10342
10343 h = strchr(uri, '@');
10344 if (h)
10345 ++h;
10346 else {
10347 h = uri;
10348 if (!strncasecmp(h, "sip:", 4)) {
10349 h += 4;
10350 } else if (!strncasecmp(h, "sips:", 5)) {
10351 h += 5;
10352 tls_on = TRUE;
10353 }
10354 }
10355 hn = strcspn(h, ";>") + 1;
10356 if (hn > sizeof(hostname))
10357 hn = sizeof(hostname);
10358 ast_copy_string(hostname, h, hn);
10359
10360 h += hn - 1;
10361
10362
10363
10364 if (ast_sockaddr_resolve_first(&p->sa, hostname, 0)) {
10365 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10366 return;
10367 }
10368
10369
10370 maddr = strstr(h, "maddr=");
10371 if (maddr) {
10372 int port;
10373
10374 maddr += 6;
10375 hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10376 "0123456789-.:[]") + 1;
10377 if (hn > sizeof(hostname))
10378 hn = sizeof(hostname);
10379 ast_copy_string(hostname, maddr, hn);
10380
10381 port = ast_sockaddr_port(&p->sa);
10382
10383
10384
10385 if (ast_sockaddr_resolve_first(&p->sa, hostname, PARSE_PORT_FORBID)) {
10386 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10387 return;
10388 }
10389
10390 ast_sockaddr_set_port(&p->sa, port);
10391 }
10392
10393 if (!ast_sockaddr_port(&p->sa)) {
10394 ast_sockaddr_set_port(&p->sa, tls_on ?
10395 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10396 }
10397
10398 if (debug) {
10399 ast_verbose("set_destination: set destination to %s\n",
10400 ast_sockaddr_stringify(&p->sa));
10401 }
10402 }
10403
10404
10405 static int init_resp(struct sip_request *resp, const char *msg)
10406 {
10407
10408 memset(resp, 0, sizeof(*resp));
10409 resp->method = SIP_RESPONSE;
10410 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10411 goto e_return;
10412 if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10413 goto e_free_data;
10414 resp->header[0] = 0;
10415 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10416 resp->headers++;
10417 return 0;
10418
10419 e_free_data:
10420 ast_free(resp->data);
10421 resp->data = NULL;
10422 e_return:
10423 return -1;
10424 }
10425
10426
10427 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10428 {
10429
10430 memset(req, 0, sizeof(*req));
10431 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10432 goto e_return;
10433 if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10434 goto e_free_data;
10435 req->method = sipmethod;
10436 req->header[0] = 0;
10437 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10438 req->headers++;
10439 return 0;
10440
10441 e_free_data:
10442 ast_free(req->data);
10443 req->data = NULL;
10444 e_return:
10445 return -1;
10446 }
10447
10448
10449 static void deinit_req(struct sip_request *req)
10450 {
10451 if (req->data) {
10452 ast_free(req->data);
10453 req->data = NULL;
10454 }
10455 if (req->content) {
10456 ast_free(req->content);
10457 req->content = NULL;
10458 }
10459 }
10460
10461
10462
10463 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479 switch (method) {
10480
10481 case SIP_INVITE:
10482 case SIP_UPDATE:
10483 case SIP_SUBSCRIBE:
10484 case SIP_NOTIFY:
10485 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10486 return 1;
10487 break;
10488
10489
10490 case SIP_REGISTER:
10491 case SIP_OPTIONS:
10492 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10493 return 1;
10494 break;
10495
10496
10497 case SIP_BYE:
10498 case SIP_PRACK:
10499 case SIP_MESSAGE:
10500 case SIP_PUBLISH:
10501 if (msg[0] == '3' || !strncmp(msg, "485", 3))
10502 return 1;
10503 break;
10504
10505
10506 case SIP_REFER:
10507 if (msg[0] >= '2' && msg[0] <= '6')
10508 return 1;
10509 break;
10510
10511
10512 case SIP_ACK:
10513 case SIP_CANCEL:
10514 case SIP_INFO:
10515 case SIP_PING:
10516 default:
10517 return 0;
10518 }
10519 return 0;
10520 }
10521
10522
10523 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10524 {
10525 char newto[256];
10526 const char *ot;
10527
10528 init_resp(resp, msg);
10529 copy_via_headers(p, resp, req, "Via");
10530 if (msg[0] == '1' || msg[0] == '2')
10531 copy_all_header(resp, req, "Record-Route");
10532 copy_header(resp, req, "From");
10533 ot = sip_get_header(req, "To");
10534 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10535
10536
10537 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10538 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10539 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10540 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10541 else
10542 ast_copy_string(newto, ot, sizeof(newto));
10543 ot = newto;
10544 }
10545 add_header(resp, "To", ot);
10546 copy_header(resp, req, "Call-ID");
10547 copy_header(resp, req, "CSeq");
10548 if (!ast_strlen_zero(global_useragent))
10549 add_header(resp, "Server", global_useragent);
10550 add_header(resp, "Allow", ALLOWED_METHODS);
10551 add_supported_header(p, resp);
10552
10553
10554 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
10555 char se_hdr[256];
10556 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10557 strefresher2str(p->stimer->st_ref));
10558 add_header(resp, "Session-Expires", se_hdr);
10559 }
10560
10561 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
10562
10563
10564 char tmp[256];
10565
10566 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10567 add_header(resp, "Expires", tmp);
10568 if (p->expiry) {
10569 char contact[SIPBUFSIZE];
10570 const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10571 char *brackets = strchr(contact_uri, '<');
10572 snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10573 add_header(resp, "Contact", contact);
10574 }
10575 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10576 add_header(resp, "Contact", p->our_contact);
10577 }
10578
10579 if (!ast_strlen_zero(p->url)) {
10580 add_header(resp, "Access-URL", p->url);
10581 ast_string_field_set(p, url, NULL);
10582 }
10583
10584
10585
10586
10587
10588
10589
10590 p->sa = p->recv;
10591
10592 if (process_via(p, req)) {
10593 ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10594 }
10595
10596 return 0;
10597 }
10598
10599
10600 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10601 {
10602 struct sip_request *orig = &p->initreq;
10603 char stripped[80];
10604 char tmp[80];
10605 char newto[256];
10606 const char *c;
10607 const char *ot, *of;
10608 int is_strict = FALSE;
10609 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
10610
10611 memset(req, 0, sizeof(struct sip_request));
10612
10613 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10614
10615 if (!seqno) {
10616 p->ocseq++;
10617 seqno = p->ocseq;
10618 }
10619
10620
10621 if (sipmethod == SIP_CANCEL) {
10622 p->branch = p->invite_branch;
10623 build_via(p);
10624 } else if (newbranch && (sipmethod == SIP_INVITE)) {
10625 p->branch ^= ast_random();
10626 p->invite_branch = p->branch;
10627 build_via(p);
10628 } else if (newbranch) {
10629 p->branch ^= ast_random();
10630 build_via(p);
10631 }
10632
10633
10634 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10635 is_strict = TRUE;
10636 if (sipdebug)
10637 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10638 }
10639
10640 if (sipmethod == SIP_CANCEL)
10641 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10642 else if (sipmethod == SIP_ACK) {
10643
10644
10645 if (!ast_strlen_zero(p->okcontacturi))
10646 c = is_strict ? p->route->hop : p->okcontacturi;
10647 else
10648 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10649 } else if (!ast_strlen_zero(p->okcontacturi))
10650 c = is_strict ? p->route->hop : p->okcontacturi;
10651 else if (!ast_strlen_zero(p->uri))
10652 c = p->uri;
10653 else {
10654 char *n;
10655
10656 ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
10657 sizeof(stripped));
10658 n = get_in_brackets(stripped);
10659 c = remove_uri_parameters(n);
10660 }
10661 init_req(req, sipmethod, c);
10662
10663 snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10664
10665 add_header(req, "Via", p->via);
10666 if (p->route) {
10667 set_destination(p, p->route->hop);
10668 add_route(req, is_strict ? p->route->next : p->route);
10669 }
10670 add_header_max_forwards(p, req);
10671
10672 ot = sip_get_header(orig, "To");
10673 of = sip_get_header(orig, "From");
10674
10675
10676
10677 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10678
10679
10680 if (is_outbound && !ast_strlen_zero(p->theirtag))
10681 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10682 else if (!is_outbound)
10683 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10684 else
10685 snprintf(newto, sizeof(newto), "%s", ot);
10686 ot = newto;
10687 }
10688
10689 if (is_outbound) {
10690 add_header(req, "From", of);
10691 add_header(req, "To", ot);
10692 } else {
10693 add_header(req, "From", ot);
10694 add_header(req, "To", of);
10695 }
10696
10697 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10698 add_header(req, "Contact", p->our_contact);
10699
10700 copy_header(req, orig, "Call-ID");
10701 add_header(req, "CSeq", tmp);
10702
10703 if (!ast_strlen_zero(global_useragent))
10704 add_header(req, "User-Agent", global_useragent);
10705
10706 if (!ast_strlen_zero(p->url)) {
10707 add_header(req, "Access-URL", p->url);
10708 ast_string_field_set(p, url, NULL);
10709 }
10710
10711
10712
10713
10714
10715
10716
10717
10718 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10719 && sipmethod == SIP_INVITE) {
10720 char se_hdr[256];
10721 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10722 strefresher2str(p->stimer->st_ref));
10723 add_header(req, "Session-Expires", se_hdr);
10724 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10725 add_header(req, "Min-SE", se_hdr);
10726 }
10727
10728 return 0;
10729 }
10730
10731
10732 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10733 {
10734 struct sip_request resp;
10735 uint32_t seqno = 0;
10736
10737 if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10738 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
10739 return -1;
10740 }
10741 respprep(&resp, p, msg, req);
10742
10743 if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10744 && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10745 && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10746 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10747 add_rpid(&resp, p);
10748 }
10749 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10750 add_cc_call_info_to_response(p, &resp);
10751 }
10752
10753
10754 if (!strncmp(msg, "302", 3)) {
10755 add_diversion_header(&resp, p);
10756 }
10757
10758
10759
10760 if (p->method == SIP_INVITE && msg[0] != '1') {
10761 char buf[20];
10762
10763 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10764 int hangupcause = 0;
10765
10766 if (p->owner && p->owner->hangupcause) {
10767 hangupcause = p->owner->hangupcause;
10768 } else if (p->hangupcause) {
10769 hangupcause = p->hangupcause;
10770 } else {
10771 int respcode;
10772 if (sscanf(msg, "%30d ", &respcode))
10773 hangupcause = hangup_sip2cause(respcode);
10774 }
10775
10776 if (hangupcause) {
10777 sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10778 add_header(&resp, "Reason", buf);
10779 }
10780 }
10781
10782 if (p->owner && p->owner->hangupcause) {
10783 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10784 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10785 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10786 }
10787 }
10788 return send_response(p, &resp, reliable, seqno);
10789 }
10790
10791 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)
10792 {
10793 struct sip_request resp;
10794
10795 if (need_new_etag) {
10796 create_new_sip_etag(esc_entry, 1);
10797 }
10798 respprep(&resp, p, msg, req);
10799 add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10800
10801 return send_response(p, &resp, 0, 0);
10802 }
10803
10804 static int temp_pvt_init(void *data)
10805 {
10806 struct sip_pvt *p = data;
10807
10808 p->do_history = 0;
10809 return ast_string_field_init(p, 512);
10810 }
10811
10812 static void temp_pvt_cleanup(void *data)
10813 {
10814 struct sip_pvt *p = data;
10815
10816 ast_string_field_free_memory(p);
10817
10818 ast_free(data);
10819 }
10820
10821
10822 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)
10823 {
10824 struct sip_pvt *p = NULL;
10825
10826 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10827 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10828 return -1;
10829 }
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839 p->method = intended_method;
10840
10841 if (!addr) {
10842 ast_sockaddr_copy(&p->ourip, &internip);
10843 } else {
10844 ast_sockaddr_copy(&p->sa, addr);
10845 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10846 }
10847
10848 p->branch = ast_random();
10849 make_our_tag(p->tag, sizeof(p->tag));
10850 p->ocseq = INITIAL_CSEQ;
10851
10852 if (useglobal_nat && addr) {
10853 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10854 ast_sockaddr_copy(&p->recv, addr);
10855 do_setnat(p);
10856 }
10857
10858 ast_string_field_set(p, fromdomain, default_fromdomain);
10859 p->fromdomainport = default_fromdomainport;
10860 build_via(p);
10861 ast_string_field_set(p, callid, callid);
10862
10863 copy_socket_data(&p->socket, &req->socket);
10864
10865
10866 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10867
10868
10869 ast_string_field_init(p, 0);
10870
10871 return 0;
10872 }
10873
10874
10875 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10876 {
10877 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10878 }
10879
10880
10881 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10882 {
10883 struct sip_request resp;
10884 respprep(&resp, p, msg, req);
10885 append_date(&resp);
10886 add_header(&resp, "Unsupported", unsupported);
10887 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10888 }
10889
10890
10891 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10892 {
10893 struct sip_request resp;
10894 char minse_str[20];
10895
10896 respprep(&resp, p, msg, req);
10897 append_date(&resp);
10898
10899 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10900 add_header(&resp, "Min-SE", minse_str);
10901 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10902 }
10903
10904
10905
10906
10907
10908 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10909 {
10910 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10911 }
10912
10913
10914 static void append_date(struct sip_request *req)
10915 {
10916 char tmpdat[256];
10917 struct tm tm;
10918 time_t t = time(NULL);
10919
10920 gmtime_r(&t, &tm);
10921 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10922 add_header(req, "Date", tmpdat);
10923 }
10924
10925
10926 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
10927 {
10928 struct sip_request resp;
10929 respprep(&resp, p, msg, req);
10930 add_header(&resp, "Retry-After", seconds);
10931 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10932 }
10933
10934
10935 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10936 {
10937 struct sip_request resp;
10938 respprep(&resp, p, msg, req);
10939 append_date(&resp);
10940 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10941 }
10942
10943
10944 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10945 {
10946 struct sip_request resp;
10947 respprep(&resp, p, msg, req);
10948 add_header(&resp, "Accept", "application/sdp");
10949 return send_response(p, &resp, reliable, 0);
10950 }
10951
10952
10953 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10954 {
10955 struct sip_request resp;
10956 char tmp[32];
10957
10958 snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10959 respprep(&resp, p, msg, req);
10960 add_header(&resp, "Min-Expires", tmp);
10961 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10962 }
10963
10964
10965 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)
10966 {
10967 struct sip_request resp;
10968 char tmp[512];
10969 uint32_t seqno = 0;
10970
10971 if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10972 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
10973 return -1;
10974 }
10975
10976 get_realm(p, req);
10977
10978
10979
10980 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10981 respprep(&resp, p, msg, req);
10982 add_header(&resp, header, tmp);
10983 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10984 return send_response(p, &resp, reliable, seqno);
10985 }
10986
10987
10988
10989
10990
10991
10992
10993 static int get_domain(const char *str, char *domain, int len)
10994 {
10995 char tmpf[256];
10996 char *a, *from;
10997
10998 *domain = '\0';
10999 ast_copy_string(tmpf, str, sizeof(tmpf));
11000 from = get_in_brackets(tmpf);
11001 if (!ast_strlen_zero(from)) {
11002 if (strncasecmp(from, "sip:", 4)) {
11003 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
11004 return -1;
11005 }
11006 from += 4;
11007 } else
11008 from = NULL;
11009
11010 if (from) {
11011 int bracket = 0;
11012
11013
11014 if ((a = strchr(from, ';')))
11015 *a = '\0';
11016
11017 for (a = from; *a != '\0'; ++a) {
11018 if (*a == ':' && bracket == 0) {
11019 *a = '\0';
11020 break;
11021 } else if (*a == '[') {
11022 ++bracket;
11023 } else if (*a == ']') {
11024 --bracket;
11025 }
11026 }
11027 if ((a = strchr(from, '@'))) {
11028 *a = '\0';
11029 ast_copy_string(domain, a + 1, len);
11030 } else
11031 ast_copy_string(domain, from, len);
11032 }
11033
11034 return ast_strlen_zero(domain);
11035 }
11036
11037
11038
11039
11040
11041 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
11042 {
11043 char domain[MAXHOSTNAMELEN];
11044
11045 if (!ast_strlen_zero(p->realm))
11046 return;
11047
11048 if (sip_cfg.domainsasrealm &&
11049 !AST_LIST_EMPTY(&domain_list))
11050 {
11051
11052 if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
11053 if (check_sip_domain(domain, NULL, 0)) {
11054 ast_string_field_set(p, realm, domain);
11055 return;
11056 }
11057 }
11058
11059 if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
11060 if (check_sip_domain(domain, NULL, 0)) {
11061 ast_string_field_set(p, realm, domain);
11062 return;
11063 }
11064 }
11065 }
11066
11067
11068 ast_string_field_set(p, realm, sip_cfg.realm);
11069 }
11070
11071
11072
11073
11074
11075
11076
11077
11078 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
11079 {
11080 int res;
11081
11082 if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
11083 p->last_provisional = msg;
11084 update_provisional_keepalive(p, with_sdp);
11085 }
11086
11087 return res;
11088 }
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098 static void destroy_msg_headers(struct sip_pvt *pvt)
11099 {
11100 struct sip_msg_hdr *doomed;
11101
11102 while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
11103 ast_free(doomed);
11104 }
11105 }
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117 static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
11118 {
11119 size_t hdr_len_name;
11120 size_t hdr_len_value;
11121 struct sip_msg_hdr *node;
11122 char *pos;
11123
11124 hdr_len_name = strlen(hdr_name) + 1;
11125 hdr_len_value = strlen(hdr_value) + 1;
11126
11127 node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
11128 if (!node) {
11129 return;
11130 }
11131 pos = node->stuff;
11132 node->name = pos;
11133 strcpy(pos, hdr_name);
11134 pos += hdr_len_name;
11135 node->value = pos;
11136 strcpy(pos, hdr_value);
11137
11138 AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
11139 }
11140
11141
11142 static int add_text(struct sip_request *req, struct sip_pvt *p)
11143 {
11144 const char *content_type = NULL;
11145 struct sip_msg_hdr *node;
11146
11147
11148 AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
11149 if (!strcasecmp(node->name, "Content-Type")) {
11150
11151 content_type = node->value;
11152 } else {
11153 add_header(req, node->name, node->value);
11154 }
11155 }
11156 if (ast_strlen_zero(content_type)) {
11157
11158 content_type = "text/plain;charset=UTF-8";
11159 }
11160 add_header(req, "Content-Type", content_type);
11161
11162
11163 add_content(req, p->msg_body);
11164 return 0;
11165 }
11166
11167
11168
11169
11170
11171 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
11172 {
11173 char tmp[256];
11174 int event;
11175 if (mode) {
11176
11177 if ('0' <= digit && digit <= '9') {
11178 event = digit - '0';
11179 } else if (digit == '*') {
11180 event = 10;
11181 } else if (digit == '#') {
11182 event = 11;
11183 } else if ('A' <= digit && digit <= 'D') {
11184 event = 12 + digit - 'A';
11185 } else if ('a' <= digit && digit <= 'd') {
11186 event = 12 + digit - 'a';
11187 } else {
11188
11189 event = 0;
11190 }
11191 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
11192 add_header(req, "Content-Type", "application/dtmf");
11193 add_content(req, tmp);
11194 } else {
11195
11196 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
11197 add_header(req, "Content-Type", "application/dtmf-relay");
11198 add_content(req, tmp);
11199 }
11200 return 0;
11201 }
11202
11203
11204
11205
11206
11207 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
11208 {
11209 struct ast_str *tmp = ast_str_alloca(256);
11210 char tmp2[256];
11211 char *lid_num = NULL;
11212 char *lid_name = NULL;
11213 int lid_pres;
11214 const char *fromdomain;
11215 const char *privacy = NULL;
11216 const char *screen = NULL;
11217 const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11218
11219 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11220 return 0;
11221 }
11222
11223 if (p->owner && p->owner->connected.id.number.valid
11224 && p->owner->connected.id.number.str) {
11225 lid_num = p->owner->connected.id.number.str;
11226 }
11227 if (p->owner && p->owner->connected.id.name.valid
11228 && p->owner->connected.id.name.str) {
11229 lid_name = p->owner->connected.id.name.str;
11230 }
11231 lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
11232
11233 if (ast_strlen_zero(lid_num))
11234 return 0;
11235 if (ast_strlen_zero(lid_name))
11236 lid_name = lid_num;
11237 fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11238
11239 lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
11240
11241 if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11242 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11243 ast_str_set(&tmp, -1, "%s", anonymous_string);
11244 } else {
11245 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11246 }
11247 add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11248 } else {
11249 ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "calling" : "called");
11250
11251 switch (lid_pres) {
11252 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11253 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11254 privacy = "off";
11255 screen = "no";
11256 break;
11257 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11258 case AST_PRES_ALLOWED_NETWORK_NUMBER:
11259 privacy = "off";
11260 screen = "yes";
11261 break;
11262 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11263 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11264 privacy = "full";
11265 screen = "no";
11266 break;
11267 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11268 case AST_PRES_PROHIB_NETWORK_NUMBER:
11269 privacy = "full";
11270 screen = "yes";
11271 break;
11272 case AST_PRES_NUMBER_NOT_AVAILABLE:
11273 break;
11274 default:
11275 if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11276 privacy = "full";
11277 }
11278 else
11279 privacy = "off";
11280 screen = "no";
11281 break;
11282 }
11283
11284 if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11285 ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11286 }
11287
11288 add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11289 }
11290 return 0;
11291 }
11292
11293
11294
11295 static int add_vidupdate(struct sip_request *req)
11296 {
11297 const char *xml_is_a_huge_waste_of_space =
11298 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11299 " <media_control>\r\n"
11300 " <vc_primitive>\r\n"
11301 " <to_encoder>\r\n"
11302 " <picture_fast_update>\r\n"
11303 " </picture_fast_update>\r\n"
11304 " </to_encoder>\r\n"
11305 " </vc_primitive>\r\n"
11306 " </media_control>\r\n";
11307 add_header(req, "Content-Type", "application/media_control+xml");
11308 add_content(req, xml_is_a_huge_waste_of_space);
11309 return 0;
11310 }
11311
11312
11313 static void add_codec_to_sdp(const struct sip_pvt *p,
11314 struct ast_format *format,
11315 struct ast_str **m_buf,
11316 struct ast_str **a_buf,
11317 int debug,
11318 int *min_packet_size)
11319 {
11320 int rtp_code;
11321 struct ast_format_list fmt;
11322 int val = 0;
11323
11324 if (debug)
11325 ast_verbose("Adding codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
11326 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1)
11327 return;
11328
11329 if (p->rtp) {
11330 struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11331 fmt = ast_codec_pref_getsize(pref, format);
11332 } else
11333 return;
11334 ast_str_append(m_buf, 0, " %d", rtp_code);
11335 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n",
11336 rtp_code,
11337 ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11338 ast_rtp_lookup_sample_rate2(1, format, 0));
11339
11340 switch ((int) format->id) {
11341 case AST_FORMAT_G729A:
11342
11343 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11344 break;
11345 case AST_FORMAT_G723_1:
11346
11347 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11348 break;
11349 case AST_FORMAT_ILBC:
11350
11351 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11352 break;
11353 case AST_FORMAT_SIREN7:
11354
11355 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11356 break;
11357 case AST_FORMAT_SIREN14:
11358
11359 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11360 break;
11361 case AST_FORMAT_G719:
11362
11363 ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11364 break;
11365 case AST_FORMAT_CELT:
11366 if (!ast_format_get_value(format, CELT_ATTR_KEY_FRAME_SIZE, &val) && val > 0) {
11367 ast_str_append(a_buf, 0, "a=fmtp:%d framesize=%u\r\n", rtp_code, val);
11368 }
11369 break;
11370 case AST_FORMAT_SILK:
11371 if (!ast_format_get_value(format, SILK_ATTR_KEY_MAX_BITRATE, &val) && val > 5000 && val < 40000) {
11372 ast_str_append(a_buf, 0, "a=fmtp:%d maxaveragebitrate=%u\r\n", rtp_code, val);
11373 }
11374 if (!ast_format_get_value(format, SILK_ATTR_KEY_DTX, &val)) {
11375 ast_str_append(a_buf, 0, "a=fmtp:%d usedtx=%u\r\n", rtp_code, val ? 1 : 0);
11376 }
11377 if (!ast_format_get_value(format, SILK_ATTR_KEY_FEC, &val)) {
11378 ast_str_append(a_buf, 0, "a=fmtp:%d useinbandfec=%u\r\n", rtp_code, val ? 1 : 0);
11379 }
11380 break;
11381 }
11382
11383 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11384 *min_packet_size = fmt.cur_ms;
11385
11386
11387 if ((*min_packet_size)==0 && fmt.cur_ms)
11388 *min_packet_size = fmt.cur_ms;
11389 }
11390
11391
11392
11393 static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
11394 struct ast_str **m_buf, struct ast_str **a_buf,
11395 int debug, int *min_packet_size)
11396 {
11397 int rtp_code;
11398
11399 if (!p->vrtp)
11400 return;
11401
11402 if (debug)
11403 ast_verbose("Adding video codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
11404
11405 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1)
11406 return;
11407
11408 ast_str_append(m_buf, 0, " %d", rtp_code);
11409 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11410 ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
11411 ast_rtp_lookup_sample_rate2(1, format, 0));
11412
11413 }
11414
11415
11416 static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
11417 struct ast_str **m_buf, struct ast_str **a_buf,
11418 int debug, int *min_packet_size)
11419 {
11420 int rtp_code;
11421
11422 if (!p->trtp)
11423 return;
11424
11425 if (debug)
11426 ast_verbose("Adding text codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
11427
11428 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
11429 return;
11430
11431 ast_str_append(m_buf, 0, " %d", rtp_code);
11432 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11433 ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
11434 ast_rtp_lookup_sample_rate2(1, format, 0));
11435
11436
11437 if (format->id == AST_FORMAT_T140RED) {
11438 struct ast_format tmp_fmt;
11439 int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, ast_format_set(&tmp_fmt, AST_FORMAT_T140, 0), 0);
11440 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11441 t140code,
11442 t140code,
11443 t140code);
11444
11445 }
11446 }
11447
11448
11449
11450 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11451 {
11452 switch (rate) {
11453 case AST_T38_RATE_2400:
11454 return 2400;
11455 case AST_T38_RATE_4800:
11456 return 4800;
11457 case AST_T38_RATE_7200:
11458 return 7200;
11459 case AST_T38_RATE_9600:
11460 return 9600;
11461 case AST_T38_RATE_12000:
11462 return 12000;
11463 case AST_T38_RATE_14400:
11464 return 14400;
11465 default:
11466 return 0;
11467 }
11468 }
11469
11470
11471 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11472 struct ast_str **m_buf, struct ast_str **a_buf,
11473 int debug)
11474 {
11475 int rtp_code;
11476
11477 if (debug)
11478 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
11479 if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
11480 return;
11481
11482 ast_str_append(m_buf, 0, " %d", rtp_code);
11483 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11484 ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
11485 ast_rtp_lookup_sample_rate2(0, NULL, format));
11486 if (format == AST_RTP_DTMF)
11487 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11488 }
11489
11490
11491
11492
11493 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11494 struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11495 struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11496 struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11497 {
11498 int use_externip = 0;
11499
11500
11501 ast_rtp_instance_get_local_address(p->rtp, addr);
11502 if (p->vrtp) {
11503 ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11504 }
11505 if (p->trtp) {
11506 ast_rtp_instance_get_local_address(p->trtp, taddr);
11507 }
11508
11509
11510
11511
11512 use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11513
11514
11515
11516 if (!ast_sockaddr_isnull(&p->redirip)) {
11517 ast_sockaddr_copy(dest, &p->redirip);
11518 } else {
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530 ast_sockaddr_copy(dest,
11531 !ast_sockaddr_isnull(&media_address) ? &media_address :
11532 !ast_sockaddr_is_any(addr) && !use_externip ? addr :
11533 &p->ourip);
11534 ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11535 }
11536
11537 if (needvideo) {
11538
11539 if (!ast_sockaddr_isnull(&p->vredirip)) {
11540 ast_sockaddr_copy(vdest, &p->vredirip);
11541 } else {
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553 ast_sockaddr_copy(vdest,
11554 !ast_sockaddr_isnull(&media_address) ? &media_address :
11555 !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr :
11556 &p->ourip);
11557 ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11558 }
11559 }
11560
11561 if (needtext) {
11562
11563 if (!ast_sockaddr_isnull(&p->tredirip)) {
11564 ast_sockaddr_copy(tdest, &p->tredirip);
11565 } else {
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577 ast_sockaddr_copy(tdest,
11578 !ast_sockaddr_isnull(&media_address) ? &media_address :
11579 !ast_sockaddr_is_any(taddr) && !use_externip ? taddr :
11580 &p->ourip);
11581 ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11582 }
11583 }
11584 }
11585
11586 static void get_crypto_attrib(struct sip_pvt *p, struct sip_srtp *srtp, const char **a_crypto)
11587 {
11588 int taglen = 80;
11589
11590
11591 if (srtp) {
11592 if (!srtp->crypto) {
11593 srtp->crypto = sdp_crypto_setup();
11594 }
11595
11596
11597 if (ast_test_flag(srtp, SRTP_CRYPTO_TAG_80)) {
11598 taglen = 80;
11599 } else if (ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32) ||
11600 ast_test_flag(srtp, SRTP_CRYPTO_TAG_32)) {
11601 taglen = 32;
11602 }
11603
11604 if (srtp->crypto && (sdp_crypto_offer(srtp->crypto, taglen) >= 0)) {
11605 *a_crypto = sdp_crypto_attrib(srtp->crypto);
11606 }
11607
11608 if (!*a_crypto) {
11609 ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11610 }
11611 }
11612 }
11613
11614
11615
11616
11617
11618
11619
11620 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11621 {
11622 struct ast_format_cap *alreadysent = ast_format_cap_alloc_nolock();
11623 struct ast_format_cap *tmpcap = ast_format_cap_alloc_nolock();
11624 int res = AST_SUCCESS;
11625 int doing_directmedia = FALSE;
11626 struct ast_sockaddr addr = { {0,} };
11627 struct ast_sockaddr vaddr = { {0,} };
11628 struct ast_sockaddr taddr = { {0,} };
11629 struct ast_sockaddr udptladdr = { {0,} };
11630 struct ast_sockaddr dest = { {0,} };
11631 struct ast_sockaddr vdest = { {0,} };
11632 struct ast_sockaddr tdest = { {0,} };
11633 struct ast_sockaddr udptldest = { {0,} };
11634
11635
11636 char *version = "v=0\r\n";
11637 char subject[256];
11638 char owner[256];
11639 char connection[256];
11640 char *session_time = "t=0 0\r\n";
11641 char bandwidth[256] = "";
11642 char *hold = "";
11643 struct ast_str *m_audio = ast_str_alloca(256);
11644 struct ast_str *m_video = ast_str_alloca(256);
11645 struct ast_str *m_text = ast_str_alloca(256);
11646 struct ast_str *m_modem = ast_str_alloca(256);
11647 struct ast_str *a_audio = ast_str_alloca(1024);
11648 struct ast_str *a_video = ast_str_alloca(1024);
11649 struct ast_str *a_text = ast_str_alloca(1024);
11650 struct ast_str *a_modem = ast_str_alloca(1024);
11651 const char *a_crypto = NULL;
11652 const char *v_a_crypto = NULL;
11653 const char *t_a_crypto = NULL;
11654
11655 int x;
11656 struct ast_format tmp_fmt;
11657 int needaudio = FALSE;
11658 int needvideo = FALSE;
11659 int needtext = FALSE;
11660 int debug = sip_debug_test_pvt(p);
11661 int min_audio_packet_size = 0;
11662 int min_video_packet_size = 0;
11663 int min_text_packet_size = 0;
11664
11665 char codecbuf[SIPBUFSIZE];
11666 char buf[SIPBUFSIZE];
11667 char dummy_answer[256];
11668
11669
11670 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11671
11672 if (!alreadysent || !tmpcap) {
11673 res = AST_FAILURE;
11674 goto add_sdp_cleanup;
11675 }
11676 if (!p->rtp) {
11677 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11678 res = AST_FAILURE;
11679 goto add_sdp_cleanup;
11680
11681 }
11682
11683
11684
11685
11686 if (!p->sessionid) {
11687 p->sessionid = (int)ast_random();
11688 p->sessionversion = p->sessionid;
11689 } else {
11690 if (oldsdp == FALSE)
11691 p->sessionversion++;
11692 }
11693
11694 if (add_audio) {
11695 doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && !(ast_format_cap_is_empty(p->redircaps))) ? TRUE : FALSE;
11696
11697 if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_VIDEO)) && !p->novideo) {
11698 ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
11699 if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_VIDEO)) {
11700 ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11701 } else if (p->vrtp) {
11702 needvideo = TRUE;
11703 ast_debug(2, "This call needs video offers!\n");
11704 } else {
11705 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11706 }
11707 }
11708
11709 if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_TEXT)) && !p->notext) {
11710 if (sipdebug_text)
11711 ast_verbose("We think we can do text\n");
11712 if (p->trtp) {
11713 if (sipdebug_text) {
11714 ast_verbose("And we have a text rtp object\n");
11715 }
11716 needtext = TRUE;
11717 ast_debug(2, "This call needs text offers! \n");
11718 } else {
11719 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11720 }
11721 }
11722 }
11723
11724 get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11725
11726 snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11727 ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11728 p->sessionid, p->sessionversion,
11729 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11730 "IP6" : "IP4",
11731 ast_sockaddr_stringify_addr_remote(&dest));
11732
11733 snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11734 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11735 "IP6" : "IP4",
11736 ast_sockaddr_stringify_addr_remote(&dest));
11737
11738 if (add_audio) {
11739 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11740 hold = "a=recvonly\r\n";
11741 doing_directmedia = FALSE;
11742 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11743 hold = "a=inactive\r\n";
11744 doing_directmedia = FALSE;
11745 } else {
11746 hold = "a=sendrecv\r\n";
11747 }
11748
11749 ast_format_cap_copy(tmpcap, p->jointcaps);
11750
11751
11752 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap),
11753 p->novideo ? "True" : "False", p->notext ? "True" : "False");
11754 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcaps));
11755
11756 if (doing_directmedia) {
11757 ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
11758 ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap));
11759 }
11760
11761
11762 if (ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_AUDIO))
11763 needaudio = TRUE;
11764
11765 if (debug) {
11766 ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11767 }
11768
11769
11770
11771 if (needvideo) {
11772 get_crypto_attrib(p, p->vsrtp, &v_a_crypto);
11773 ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11774 v_a_crypto ? "SAVP" : "AVP");
11775
11776
11777 if (p->maxcallbitrate)
11778 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11779 if (debug) {
11780 ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11781 }
11782 }
11783
11784
11785
11786 if (needtext) {
11787 if (sipdebug_text)
11788 ast_verbose("Lets set up the text sdp\n");
11789 get_crypto_attrib(p, p->tsrtp, &t_a_crypto);
11790 ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11791 t_a_crypto ? "SAVP" : "AVP");
11792 if (debug) {
11793 ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11794 }
11795 }
11796
11797
11798
11799
11800
11801
11802 get_crypto_attrib(p, p->srtp, &a_crypto);
11803 ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11804 a_crypto ? "SAVP" : "AVP");
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815 if (ast_format_cap_has_joint(tmpcap, p->prefcaps)) {
11816 ast_format_cap_iter_start(p->prefcaps);
11817 while (!(ast_format_cap_iter_next(p->prefcaps, &tmp_fmt))) {
11818 if (AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_AUDIO) {
11819 continue;
11820 }
11821 add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
11822 ast_format_cap_add(alreadysent, &tmp_fmt);
11823 }
11824 ast_format_cap_iter_end(p->prefcaps);
11825 }
11826
11827
11828 for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
11829 if (!(ast_codec_pref_index(&p->prefs, x, &tmp_fmt)))
11830 break;
11831
11832 if (!(ast_format_cap_iscompatible(tmpcap, &tmp_fmt)))
11833 continue;
11834
11835 if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
11836 continue;
11837
11838 if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
11839 add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
11840 } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
11841 add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
11842 } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
11843 add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
11844 }
11845
11846 ast_format_cap_add(alreadysent, &tmp_fmt);
11847 }
11848
11849
11850 ast_format_cap_iter_start(tmpcap);
11851 while (!(ast_format_cap_iter_next(tmpcap, &tmp_fmt))) {
11852 if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
11853 continue;
11854
11855 if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
11856 add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
11857 } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
11858 add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
11859 } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
11860 add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
11861 }
11862 }
11863 ast_format_cap_iter_end(tmpcap);
11864
11865
11866 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11867 if (!(p->jointnoncodeccapability & x))
11868 continue;
11869
11870 add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11871 }
11872
11873 ast_debug(3, "-- Done with adding codecs to SDP\n");
11874
11875 if (!p->owner || !ast_internal_timing_enabled(p->owner))
11876 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11877
11878 if (min_audio_packet_size)
11879 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11880
11881
11882 if (min_video_packet_size)
11883 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11884
11885
11886 if (min_text_packet_size)
11887 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11888
11889 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
11890 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
11891 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
11892 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11893 }
11894
11895 if (add_t38) {
11896
11897 ast_udptl_get_us(p->udptl, &udptladdr);
11898
11899
11900 if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11901 ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11902 } else {
11903 ast_sockaddr_copy(&udptldest, &p->ourip);
11904 ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11905 }
11906
11907 if (debug) {
11908 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11909 }
11910
11911
11912
11913
11914 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11915
11916 if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11917 ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11918 (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11919 "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11920 }
11921
11922 ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11923 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11924 if (p->t38.our_parms.fill_bit_removal) {
11925 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11926 }
11927 if (p->t38.our_parms.transcoding_mmr) {
11928 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11929 }
11930 if (p->t38.our_parms.transcoding_jbig) {
11931 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11932 }
11933 switch (p->t38.our_parms.rate_management) {
11934 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11935 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11936 break;
11937 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11938 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11939 break;
11940 }
11941 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11942 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11943 case UDPTL_ERROR_CORRECTION_NONE:
11944 break;
11945 case UDPTL_ERROR_CORRECTION_FEC:
11946 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11947 break;
11948 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11949 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11950 break;
11951 }
11952 }
11953
11954 if (needaudio)
11955 ast_str_append(&m_audio, 0, "\r\n");
11956 if (needvideo)
11957 ast_str_append(&m_video, 0, "\r\n");
11958 if (needtext)
11959 ast_str_append(&m_text, 0, "\r\n");
11960
11961 add_header(resp, "Content-Type", "application/sdp");
11962 add_content(resp, version);
11963 add_content(resp, owner);
11964 add_content(resp, subject);
11965 add_content(resp, connection);
11966
11967 if (needvideo) {
11968 add_content(resp, bandwidth);
11969 }
11970 add_content(resp, session_time);
11971
11972 if (p->offered_media[SDP_AUDIO].order_offered ||
11973 p->offered_media[SDP_VIDEO].order_offered ||
11974 p->offered_media[SDP_TEXT].order_offered ||
11975 p->offered_media[SDP_IMAGE].order_offered) {
11976 int i;
11977
11978 for (i = 1; i <= 3; i++) {
11979 if (p->offered_media[SDP_AUDIO].order_offered == i) {
11980 if (needaudio) {
11981 add_content(resp, m_audio->str);
11982 add_content(resp, a_audio->str);
11983 add_content(resp, hold);
11984 if (a_crypto) {
11985 add_content(resp, a_crypto);
11986 }
11987 } else {
11988 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
11989 add_content(resp, dummy_answer);
11990 }
11991 } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
11992 if (needvideo) {
11993 add_content(resp, m_video->str);
11994 add_content(resp, a_video->str);
11995 add_content(resp, hold);
11996 if (v_a_crypto) {
11997 add_content(resp, v_a_crypto);
11998 }
11999 } else {
12000 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
12001 add_content(resp, dummy_answer);
12002 }
12003 } else if (p->offered_media[SDP_TEXT].order_offered == i) {
12004 if (needtext) {
12005 add_content(resp, m_text->str);
12006 add_content(resp, a_text->str);
12007 add_content(resp, hold);
12008 if (t_a_crypto) {
12009 add_content(resp, t_a_crypto);
12010 }
12011 } else {
12012 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
12013 add_content(resp, dummy_answer);
12014 }
12015 } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
12016 if (add_t38) {
12017 add_content(resp, m_modem->str);
12018 add_content(resp, a_modem->str);
12019 } else {
12020 add_content(resp, "m=image 0 udptl t38\r\n");
12021 }
12022 }
12023 }
12024 } else {
12025
12026 if (needaudio) {
12027 add_content(resp, m_audio->str);
12028 add_content(resp, a_audio->str);
12029 add_content(resp, hold);
12030 if (a_crypto) {
12031 add_content(resp, a_crypto);
12032 }
12033 }
12034 if (needvideo) {
12035 add_content(resp, m_video->str);
12036 add_content(resp, a_video->str);
12037 add_content(resp, hold);
12038 if (v_a_crypto) {
12039 add_content(resp, v_a_crypto);
12040 }
12041 }
12042 if (needtext) {
12043 add_content(resp, m_text->str);
12044 add_content(resp, a_text->str);
12045 add_content(resp, hold);
12046 if (t_a_crypto) {
12047 add_content(resp, t_a_crypto);
12048 }
12049 }
12050 if (add_t38) {
12051 add_content(resp, m_modem->str);
12052 add_content(resp, a_modem->str);
12053 }
12054 }
12055
12056
12057 p->lastrtprx = p->lastrtptx = time(NULL);
12058
12059
12060
12061
12062
12063 ao2_lock(dialogs_rtpcheck);
12064 ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
12065 ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
12066 ao2_unlock(dialogs_rtpcheck);
12067
12068 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmpcap));
12069
12070 add_sdp_cleanup:
12071 alreadysent = ast_format_cap_destroy(alreadysent);
12072 tmpcap = ast_format_cap_destroy(tmpcap);
12073
12074 return res;
12075 }
12076
12077
12078 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
12079 {
12080 struct sip_request resp;
12081 uint32_t seqno;
12082
12083 if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12084 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
12085 return -1;
12086 }
12087 respprep(&resp, p, msg, req);
12088 if (p->udptl) {
12089 add_sdp(&resp, p, 0, 0, 1);
12090 } else
12091 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
12092 if (retrans && !p->pendinginvite)
12093 p->pendinginvite = seqno;
12094 return send_response(p, &resp, retrans, seqno);
12095 }
12096
12097
12098 static void copy_request(struct sip_request *dst, const struct sip_request *src)
12099 {
12100
12101
12102
12103 struct ast_str *duplicate = dst->data;
12104 struct ast_str *duplicate_content = dst->content;
12105
12106
12107
12108 memcpy(dst, src, sizeof(*dst));
12109 dst->data = duplicate;
12110 dst->content = duplicate_content;
12111
12112
12113 if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1)))
12114 return;
12115 ast_str_copy_string(&dst->data, src->data);
12116
12117
12118 if (src->content) {
12119 if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1)))
12120 return;
12121 ast_str_copy_string(&dst->content, src->content);
12122 }
12123 }
12124
12125 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
12126 {
12127 char uri[SIPBUFSIZE];
12128 struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
12129 struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
12130 struct sip_cc_agent_pvt *agent_pvt;
12131
12132 if (!agent) {
12133
12134
12135
12136 ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
12137 return;
12138 }
12139
12140 agent_pvt = agent->private_data;
12141
12142 if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
12143 ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
12144 } else {
12145 generate_uri(p, uri, sizeof(uri));
12146 ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
12147 }
12148
12149
12150
12151
12152 ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
12153 add_header(resp, "Call-Info", ast_str_buffer(header));
12154 ao2_ref(agent, -1);
12155 }
12156
12157
12158
12159
12160 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)
12161 {
12162 struct sip_request resp;
12163 uint32_t seqno;
12164 if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12165 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
12166 return -1;
12167 }
12168 respprep(&resp, p, msg, req);
12169 if (rpid == TRUE) {
12170 add_rpid(&resp, p);
12171 }
12172 if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12173 add_cc_call_info_to_response(p, &resp);
12174 }
12175 if (p->rtp) {
12176 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12177 ast_debug(1, "Setting framing from config on incoming call\n");
12178 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
12179 }
12180 ast_rtp_instance_activate(p->rtp);
12181 try_suggested_sip_codec(p);
12182 if (p->t38.state == T38_ENABLED) {
12183 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
12184 } else {
12185 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
12186 }
12187 } else
12188 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
12189 if (reliable && !p->pendinginvite)
12190 p->pendinginvite = seqno;
12191 return send_response(p, &resp, reliable, seqno);
12192 }
12193
12194
12195 static int determine_firstline_parts(struct sip_request *req)
12196 {
12197 char *e = ast_skip_blanks(req->data->str);
12198 char *local_rlPart1;
12199
12200 if (!*e)
12201 return -1;
12202 req->rlPart1 = e - req->data->str;
12203 local_rlPart1 = e;
12204 e = ast_skip_nonblanks(e);
12205 if (*e)
12206 *e++ = '\0';
12207
12208 e = ast_skip_blanks(e);
12209 if ( !*e )
12210 return -1;
12211 ast_trim_blanks(e);
12212
12213 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
12214 if (strlen(e) < 3)
12215 return -1;
12216 req->rlPart2 = e - req->data->str;
12217 } else {
12218 if ( *e == '<' ) {
12219 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
12220 e++;
12221 if (!*e)
12222 return -1;
12223 }
12224 req->rlPart2 = e - req->data->str;
12225 e = ast_skip_nonblanks(e);
12226 if (*e)
12227 *e++ = '\0';
12228 e = ast_skip_blanks(e);
12229 if (strcasecmp(e, "SIP/2.0") ) {
12230 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
12231 return -1;
12232 }
12233 }
12234 return 1;
12235 }
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
12251 {
12252 struct sip_request req;
12253
12254 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
12255
12256 add_header(&req, "Allow", ALLOWED_METHODS);
12257 add_supported_header(p, &req);
12258 if (sipdebug) {
12259 if (oldsdp == TRUE)
12260 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
12261 else
12262 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
12263 }
12264
12265 if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
12266 add_rpid(&req, p);
12267
12268 if (p->do_history) {
12269 append_history(p, "ReInv", "Re-invite sent");
12270 }
12271 memset(p->offered_media, 0, sizeof(p->offered_media));
12272
12273 try_suggested_sip_codec(p);
12274 if (t38version) {
12275 add_sdp(&req, p, oldsdp, FALSE, TRUE);
12276 } else {
12277 add_sdp(&req, p, oldsdp, TRUE, FALSE);
12278 }
12279
12280
12281 initialize_initreq(p, &req);
12282 p->lastinvite = p->ocseq;
12283 ast_set_flag(&p->flags[0], SIP_OUTGOING);
12284
12285 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12286 }
12287
12288
12289 static char *remove_uri_parameters(char *uri)
12290 {
12291 char *atsign;
12292 atsign = strchr(uri, '@');
12293 if (!atsign) {
12294 atsign = uri;
12295 }
12296 atsign = strchr(atsign, ';');
12297 if (atsign)
12298 *atsign = '\0';
12299 return uri;
12300 }
12301
12302
12303 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12304 {
12305 char stripped[SIPBUFSIZE];
12306 char *c;
12307
12308 ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
12309 c = get_in_brackets(stripped);
12310
12311 c = remove_uri_parameters(c);
12312 if (!ast_strlen_zero(c)) {
12313 ast_string_field_set(p, uri, c);
12314 }
12315
12316 }
12317
12318
12319 static void build_contact(struct sip_pvt *p)
12320 {
12321 char tmp[SIPBUFSIZE];
12322 char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
12323
12324 if (p->socket.type == SIP_TRANSPORT_UDP) {
12325 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12326 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12327 } else {
12328 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12329 ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12330 sip_get_transport(p->socket.type));
12331 }
12332 }
12333
12334
12335 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12336 {
12337 struct ast_str *invite = ast_str_alloca(256);
12338 char from[256];
12339 char to[256];
12340 char tmp_n[SIPBUFSIZE/2];
12341 char tmp_l[SIPBUFSIZE/2];
12342 const char *l = NULL;
12343 const char *n = NULL;
12344 const char *d = NULL;
12345 const char *urioptions = "";
12346 int ourport;
12347 int cid_has_name = 1;
12348 int cid_has_num = 1;
12349
12350 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12351 const char *s = p->username;
12352
12353
12354
12355
12356
12357
12358 if (*s == '+')
12359 s++;
12360 for (; *s; s++) {
12361 if (!strchr(AST_DIGIT_ANYNUM, *s) )
12362 break;
12363 }
12364
12365 if (!*s)
12366 urioptions = ";user=phone";
12367 }
12368
12369
12370 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12371
12372 d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12373 if (p->owner) {
12374 if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12375 l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12376 n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12377 } else {
12378
12379
12380 l = CALLERID_UNKNOWN;
12381 n = l;
12382 d = FROMDOMAIN_INVALID;
12383 }
12384 }
12385
12386
12387
12388
12389
12390
12391
12392 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12393 l = p->mwi_from;
12394 }
12395
12396 if (ast_strlen_zero(l)) {
12397 cid_has_num = 0;
12398 l = default_callerid;
12399 }
12400 if (ast_strlen_zero(n)) {
12401 cid_has_name = 0;
12402 n = l;
12403 }
12404
12405
12406 if (!ast_strlen_zero(p->fromuser))
12407 l = p->fromuser;
12408 else
12409 ast_string_field_set(p, fromuser, l);
12410
12411
12412 if (!ast_strlen_zero(p->fromname))
12413 n = p->fromname;
12414 else
12415 ast_string_field_set(p, fromname, n);
12416
12417 if (sip_cfg.pedanticsipchecking) {
12418 ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12419 n = tmp_n;
12420 ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
12421 l = tmp_l;
12422 }
12423
12424 ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12425
12426
12427 if (cid_has_name || !cid_has_num) {
12428 snprintf(from, sizeof(from), "\"%s\" ", n);
12429 } else {
12430 from[0] = '\0';
12431 }
12432
12433 if (!sip_standard_port(p->socket.type, ourport)) {
12434 size_t offset = strlen(from);
12435 snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", l, d, ourport, p->tag);
12436 } else {
12437 size_t offset = strlen(from);
12438 snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", l, d, p->tag);
12439 }
12440
12441 if (!ast_strlen_zero(explicit_uri)) {
12442 ast_str_set(&invite, 0, "%s", explicit_uri);
12443 } else {
12444
12445 if (!ast_strlen_zero(p->fullcontact)) {
12446
12447 ast_str_append(&invite, 0, "%s", p->fullcontact);
12448 } else {
12449
12450 ast_str_append(&invite, 0, "sip:");
12451 if (!ast_strlen_zero(p->username)) {
12452 n = p->username;
12453 if (sip_cfg.pedanticsipchecking) {
12454 ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
12455 n = tmp_n;
12456 }
12457 ast_str_append(&invite, 0, "%s@", n);
12458 }
12459 ast_str_append(&invite, 0, "%s", p->tohost);
12460 if (p->portinuri) {
12461 ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12462 }
12463 ast_str_append(&invite, 0, "%s", urioptions);
12464 }
12465 }
12466
12467
12468 if (p->options && !ast_strlen_zero(p->options->uri_options))
12469 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12470
12471
12472
12473
12474 ast_string_field_set(p, uri, invite->str);
12475
12476 if (!ast_strlen_zero(p->todnid)) {
12477
12478 if (!strchr(p->todnid, '@')) {
12479
12480 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12481 } else {
12482 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12483 }
12484 } else {
12485 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12486
12487 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12488 } else if (p->options && p->options->vxml_url) {
12489
12490 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12491 } else {
12492 snprintf(to, sizeof(to), "<%s>", p->uri);
12493 }
12494 }
12495
12496 init_req(req, sipmethod, p->uri);
12497
12498 snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12499
12500 add_header(req, "Via", p->via);
12501 add_header_max_forwards(p, req);
12502
12503
12504
12505
12506 add_route(req, p->route);
12507
12508 add_header(req, "From", from);
12509 add_header(req, "To", to);
12510 ast_string_field_set(p, exten, l);
12511 build_contact(p);
12512 add_header(req, "Contact", p->our_contact);
12513 add_header(req, "Call-ID", p->callid);
12514 add_header(req, "CSeq", tmp_n);
12515 if (!ast_strlen_zero(global_useragent)) {
12516 add_header(req, "User-Agent", global_useragent);
12517 }
12518 }
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12529 {
12530 const char *diverting_number;
12531 const char *diverting_name;
12532 const char *reason;
12533 char header_text[256];
12534
12535 if (!pvt->owner) {
12536 return;
12537 }
12538
12539 diverting_number = pvt->owner->redirecting.from.number.str;
12540 if (!pvt->owner->redirecting.from.number.valid
12541 || ast_strlen_zero(diverting_number)) {
12542 return;
12543 }
12544
12545 reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12546
12547
12548 diverting_name = pvt->owner->redirecting.from.name.str;
12549 if (!pvt->owner->redirecting.from.name.valid
12550 || ast_strlen_zero(diverting_name)) {
12551 snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12552 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12553 } else {
12554 snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12555 diverting_name, diverting_number,
12556 ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12557 }
12558
12559 add_header(req, "Diversion", header_text);
12560 }
12561
12562 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12563 {
12564 struct sip_pvt *pvt;
12565 int expires;
12566
12567 epa_entry->publish_type = publish_type;
12568
12569 if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12570 return -1;
12571 }
12572
12573 sip_pvt_lock(pvt);
12574
12575 if (create_addr(pvt, epa_entry->destination, NULL, TRUE, NULL)) {
12576 sip_pvt_unlock(pvt);
12577 dialog_unlink_all(pvt);
12578 dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12579 return -1;
12580 }
12581 ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12582 ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12583 expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12584 pvt->expiry = expires;
12585
12586
12587 ao2_ref(epa_entry, +1);
12588 pvt->epa_entry = epa_entry;
12589
12590 transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12591 sip_pvt_unlock(pvt);
12592 sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12593 dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12594 return 0;
12595 }
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12607 {
12608 struct sip_request req;
12609 struct ast_variable *var;
12610
12611 req.method = sipmethod;
12612 if (init) {
12613 p->branch ^= ast_random();
12614 p->invite_branch = p->branch;
12615 build_via(p);
12616 }
12617 if (init > 1) {
12618 initreqprep(&req, p, sipmethod, explicit_uri);
12619 } else {
12620
12621 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12622 }
12623
12624 if (p->options && p->options->auth) {
12625 add_header(&req, p->options->authheader, p->options->auth);
12626 }
12627 append_date(&req);
12628 if (sipmethod == SIP_REFER) {
12629 if (p->refer) {
12630 char buf[SIPBUFSIZE];
12631 if (!ast_strlen_zero(p->refer->refer_to)) {
12632 add_header(&req, "Refer-To", p->refer->refer_to);
12633 }
12634 if (!ast_strlen_zero(p->refer->referred_by)) {
12635 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12636 add_header(&req, "Referred-By", buf);
12637 }
12638 }
12639 } else if (sipmethod == SIP_SUBSCRIBE) {
12640 char buf[SIPBUFSIZE];
12641 if (p->subscribed == MWI_NOTIFICATION) {
12642 add_header(&req, "Event", "message-summary");
12643 add_header(&req, "Accept", "application/simple-message-summary");
12644 } else if (p->subscribed == CALL_COMPLETION) {
12645 add_header(&req, "Event", "call-completion");
12646 add_header(&req, "Accept", "application/call-completion");
12647 }
12648 snprintf(buf, sizeof(buf), "%d", p->expiry);
12649 add_header(&req, "Expires", buf);
12650 }
12651
12652
12653
12654 if (p->options && !ast_strlen_zero(p->options->replaces)) {
12655 add_header(&req, "Replaces", p->options->replaces);
12656 add_header(&req, "Require", "replaces");
12657 }
12658
12659
12660 if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12661 char i2astr[10];
12662
12663 if (!p->stimer->st_interval) {
12664 p->stimer->st_interval = st_get_se(p, TRUE);
12665 }
12666
12667 p->stimer->st_active = TRUE;
12668
12669 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12670 add_header(&req, "Session-Expires", i2astr);
12671 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12672 add_header(&req, "Min-SE", i2astr);
12673 }
12674
12675 add_header(&req, "Allow", ALLOWED_METHODS);
12676 add_supported_header(p, &req);
12677
12678 if (p->options && p->options->addsipheaders && p->owner) {
12679 struct ast_channel *chan = p->owner;
12680 struct varshead *headp;
12681
12682 ast_channel_lock(chan);
12683
12684 headp = &chan->varshead;
12685
12686 if (!headp) {
12687 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12688 } else {
12689 const struct ast_var_t *current;
12690 AST_LIST_TRAVERSE(headp, current, entries) {
12691
12692 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12693 char *content, *end;
12694 const char *header = ast_var_value(current);
12695 char *headdup = ast_strdupa(header);
12696
12697
12698 if (*headdup == '"') {
12699 headdup++;
12700 }
12701 if ((content = strchr(headdup, ':'))) {
12702 *content++ = '\0';
12703 content = ast_skip_blanks(content);
12704
12705 end = content + strlen(content) -1;
12706 if (*end == '"') {
12707 *end = '\0';
12708 }
12709
12710 add_header(&req, headdup, content);
12711 if (sipdebug) {
12712 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12713 }
12714 }
12715 }
12716 }
12717 }
12718
12719 ast_channel_unlock(chan);
12720 }
12721 if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12722 add_rpid(&req, p);
12723 if (sipmethod == SIP_INVITE) {
12724 add_diversion_header(&req, p);
12725 }
12726 if (sdp) {
12727 memset(p->offered_media, 0, sizeof(p->offered_media));
12728 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12729 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
12730 add_sdp(&req, p, FALSE, FALSE, TRUE);
12731 } else if (p->rtp) {
12732 try_suggested_sip_codec(p);
12733 add_sdp(&req, p, FALSE, TRUE, FALSE);
12734 }
12735 } else if (p->notify) {
12736 for (var = p->notify->headers; var; var = var->next) {
12737 add_header(&req, var->name, var->value);
12738 }
12739 if (ast_str_strlen(p->notify->content)) {
12740 add_content(&req, ast_str_buffer(p->notify->content));
12741 }
12742 } else if (sipmethod == SIP_PUBLISH) {
12743 char expires[SIPBUFSIZE];
12744
12745 switch (p->epa_entry->static_data->event) {
12746 case CALL_COMPLETION:
12747 snprintf(expires, sizeof(expires), "%d", p->expiry);
12748 add_header(&req, "Event", "call-completion");
12749 add_header(&req, "Expires", expires);
12750 if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12751 add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12752 }
12753
12754 if (!ast_strlen_zero(p->epa_entry->body)) {
12755 add_header(&req, "Content-Type", "application/pidf+xml");
12756 add_content(&req, p->epa_entry->body);
12757 }
12758 default:
12759 break;
12760 }
12761 }
12762
12763 if (!p->initreq.headers || init > 2) {
12764 initialize_initreq(p, &req);
12765 }
12766 if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12767 p->lastinvite = p->ocseq;
12768 }
12769 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12770 }
12771
12772
12773 static int sip_subscribe_mwi_do(const void *data)
12774 {
12775 struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12776
12777 if (!mwi) {
12778 return -1;
12779 }
12780
12781 mwi->resub = -1;
12782 __sip_subscribe_mwi_do(mwi);
12783 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12784
12785 return 0;
12786 }
12787
12788 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12789 {
12790 struct sip_registry *reg = data;
12791 const char *old_str;
12792
12793
12794 if (ast_sockaddr_isnull(new)) {
12795 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12796 return;
12797 }
12798
12799 if (!ast_sockaddr_port(new)) {
12800 ast_sockaddr_set_port(new, reg->portno);
12801 }
12802
12803 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12804
12805 ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12806 ast_sockaddr_copy(®->us, new);
12807 }
12808
12809 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12810 {
12811 struct sip_peer *peer = data;
12812 const char *old_str;
12813
12814
12815 if (ast_sockaddr_isnull(new)) {
12816 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12817 return;
12818 }
12819
12820 if (!ast_sockaddr_isnull(&peer->addr)) {
12821 ao2_unlink(peers_by_ip, peer);
12822 }
12823
12824 if (!ast_sockaddr_port(new)) {
12825 ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12826 }
12827
12828 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12829 ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12830
12831 ao2_lock(peer);
12832 ast_sockaddr_copy(&peer->addr, new);
12833 ao2_unlock(peer);
12834
12835 ao2_link(peers_by_ip, peer);
12836 }
12837
12838 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12839 {
12840 struct sip_subscription_mwi *mwi = data;
12841 const char *old_str;
12842
12843
12844 if (ast_sockaddr_isnull(new)) {
12845 ast_debug(1, "Empty sockaddr change...ignoring!\n");
12846 return;
12847 }
12848
12849 old_str = ast_strdupa(ast_sockaddr_stringify(old));
12850 ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12851 ast_sockaddr_copy(&mwi->us, new);
12852 }
12853
12854
12855 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12856 {
12857
12858 if (!mwi->dnsmgr) {
12859 char transport[MAXHOSTNAMELEN];
12860 snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12861
12862 mwi->us.ss.ss_family = get_address_family_filter(&bindaddr);
12863 ASTOBJ_REF(mwi);
12864 ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, mwi);
12865 if (!mwi->dnsmgr) {
12866 ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12867 }
12868 }
12869
12870
12871 if (mwi->call) {
12872 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12873 return 0;
12874 }
12875
12876
12877 if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12878 return -1;
12879 }
12880
12881 ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12882
12883 if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12884 ast_sockaddr_set_port(&mwi->us, mwi->portno);
12885 }
12886
12887
12888 if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0, NULL)) {
12889 dialog_unlink_all(mwi->call);
12890 mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12891 return 0;
12892 }
12893
12894 mwi->call->expiry = mwi_expiry;
12895
12896 if (!mwi->dnsmgr && mwi->portno) {
12897 ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12898 ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12899 } else {
12900 mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12901 }
12902
12903
12904 if (!ast_strlen_zero(mwi->authuser)) {
12905 ast_string_field_set(mwi->call, peername, mwi->authuser);
12906 ast_string_field_set(mwi->call, authname, mwi->authuser);
12907 ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12908 } else {
12909 ast_string_field_set(mwi->call, peername, mwi->username);
12910 ast_string_field_set(mwi->call, authname, mwi->username);
12911 ast_string_field_set(mwi->call, fromuser, mwi->username);
12912 }
12913 ast_string_field_set(mwi->call, username, mwi->username);
12914 if (!ast_strlen_zero(mwi->secret)) {
12915 ast_string_field_set(mwi->call, peersecret, mwi->secret);
12916 }
12917 set_socket_transport(&mwi->call->socket, mwi->transport);
12918 mwi->call->socket.port = htons(mwi->portno);
12919 ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12920 build_contact(mwi->call);
12921 build_via(mwi->call);
12922
12923
12924 change_callid_pvt(mwi->call, NULL);
12925
12926 ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12927
12928
12929 mwi->call->mwi = ASTOBJ_REF(mwi);
12930
12931 mwi->call->subscribed = MWI_NOTIFICATION;
12932
12933
12934 transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12935
12936 return 0;
12937 }
12938
12939
12940 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12941 {
12942 struct ast_channel *c = obj;
12943 struct sip_pvt *p = data;
12944 int res;
12945
12946 ast_channel_lock(c);
12947
12948 res = (c->pbx &&
12949 (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12950 (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12951
12952 ast_channel_unlock(c);
12953
12954 return res ? CMP_MATCH | CMP_STOP : 0;
12955 }
12956
12957
12958 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)
12959 {
12960 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12961 const char *statestring = "terminated";
12962 const char *pidfstate = "--";
12963 const char *pidfnote= "Ready";
12964 char hint[AST_MAX_EXTENSION];
12965
12966 switch (state) {
12967 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12968 statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12969 local_state = NOTIFY_INUSE;
12970 pidfstate = "busy";
12971 pidfnote = "Ringing";
12972 break;
12973 case AST_EXTENSION_RINGING:
12974 statestring = "early";
12975 local_state = NOTIFY_INUSE;
12976 pidfstate = "busy";
12977 pidfnote = "Ringing";
12978 break;
12979 case AST_EXTENSION_INUSE:
12980 statestring = "confirmed";
12981 local_state = NOTIFY_INUSE;
12982 pidfstate = "busy";
12983 pidfnote = "On the phone";
12984 break;
12985 case AST_EXTENSION_BUSY:
12986 statestring = "confirmed";
12987 local_state = NOTIFY_CLOSED;
12988 pidfstate = "busy";
12989 pidfnote = "On the phone";
12990 break;
12991 case AST_EXTENSION_UNAVAILABLE:
12992 statestring = "terminated";
12993 local_state = NOTIFY_CLOSED;
12994 pidfstate = "away";
12995 pidfnote = "Unavailable";
12996 break;
12997 case AST_EXTENSION_ONHOLD:
12998 statestring = "confirmed";
12999 local_state = NOTIFY_CLOSED;
13000 pidfstate = "busy";
13001 pidfnote = "On hold";
13002 break;
13003 case AST_EXTENSION_NOT_INUSE:
13004 default:
13005
13006 break;
13007 }
13008
13009
13010 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
13011 char *hint2 = hint, *individual_hint = NULL;
13012 int hint_count = 0, unavailable_count = 0;
13013
13014 while ((individual_hint = strsep(&hint2, "&"))) {
13015 hint_count++;
13016
13017 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
13018 unavailable_count++;
13019 }
13020
13021
13022
13023
13024 if (hint_count > 0 && hint_count == unavailable_count) {
13025 local_state = NOTIFY_CLOSED;
13026 pidfstate = "away";
13027 pidfnote = "Not online";
13028 }
13029 }
13030
13031 switch (subscribed) {
13032 case XPIDF_XML:
13033 case CPIM_PIDF_XML:
13034 ast_str_append(tmp, 0,
13035 "<?xml version=\"1.0\"?>\n"
13036 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
13037 "<presence>\n");
13038 ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
13039 ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
13040 ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
13041 ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
13042 ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
13043 ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
13044 break;
13045 case PIDF_XML:
13046 ast_str_append(tmp, 0,
13047 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
13048 "<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);
13049 ast_str_append(tmp, 0, "<pp:person><status>\n");
13050 if (pidfstate[0] != '-') {
13051 ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
13052 }
13053 ast_str_append(tmp, 0, "</status></pp:person>\n");
13054 ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote);
13055 ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten);
13056 ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
13057 if (pidfstate[0] == 'b')
13058 ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
13059 else
13060 ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
13061 ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
13062 break;
13063 case DIALOG_INFO_XML:
13064 ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
13065 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);
13066 if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
13067 const char *local_display = exten;
13068 char *local_target = ast_strdupa(mto);
13069
13070
13071
13072
13073 if (sip_cfg.notifycid) {
13074 struct ast_channel *caller;
13075
13076 if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
13077 char *cid_num;
13078 int need;
13079
13080 ast_channel_lock(caller);
13081 cid_num = S_COR(caller->caller.id.number.valid,
13082 caller->caller.id.number.str, "");
13083 need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
13084 local_target = alloca(need);
13085 snprintf(local_target, need, "sip:%s@%s", cid_num, p->fromdomain);
13086 local_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
13087 caller->caller.id.name.str, ""));
13088 ast_channel_unlock(caller);
13089 caller = ast_channel_unref(caller);
13090 }
13091
13092
13093
13094 if (sip_cfg.pedanticsipchecking) {
13095 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
13096 exten, p->callid, p->theirtag, p->tag);
13097 } else {
13098 ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
13099 exten, p->callid);
13100 }
13101 ast_str_append(tmp, 0,
13102 "<remote>\n"
13103
13104
13105 "<identity display=\"%s\">%s</identity>\n"
13106 "<target uri=\"%s\"/>\n"
13107 "</remote>\n"
13108 "<local>\n"
13109 "<identity>%s</identity>\n"
13110 "<target uri=\"%s\"/>\n"
13111 "</local>\n",
13112 local_display, local_target, local_target, mto, mto);
13113 } else {
13114 ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
13115 }
13116
13117 } else {
13118 ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
13119 }
13120 ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
13121 if (state == AST_EXTENSION_ONHOLD) {
13122 ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
13123 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
13124 "</target>\n</local>\n", mto);
13125 }
13126 ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
13127 break;
13128 case NONE:
13129 default:
13130 break;
13131 }
13132 }
13133
13134 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
13135 {
13136 struct sip_request req;
13137 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
13138 char uri[SIPBUFSIZE];
13139 char state_str[64];
13140 char subscription_state_hdr[64];
13141
13142 if (state < CC_QUEUED || state > CC_READY) {
13143 ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
13144 return -1;
13145 }
13146
13147 reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
13148 snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
13149 add_header(&req, "Event", "call-completion");
13150 add_header(&req, "Content-Type", "application/call-completion");
13151 snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
13152 add_header(&req, "Subscription-State", subscription_state_hdr);
13153 if (state == CC_READY) {
13154 generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
13155 snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
13156 }
13157 add_content(&req, state_str);
13158 if (state == CC_READY) {
13159 add_content(&req, uri);
13160 }
13161 return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
13162 }
13163
13164
13165 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
13166 {
13167 struct ast_str *tmp = ast_str_alloca(4000);
13168 char from[256], to[256];
13169 char *c, *mfrom, *mto;
13170 struct sip_request req;
13171 const struct cfsubscription_types *subscriptiontype;
13172
13173 memset(from, 0, sizeof(from));
13174 memset(to, 0, sizeof(to));
13175
13176 subscriptiontype = find_subscription_type(p->subscribed);
13177
13178 ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
13179 c = get_in_brackets(from);
13180 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13181 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
13182 return -1;
13183 }
13184
13185 mfrom = remove_uri_parameters(c);
13186
13187 ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
13188 c = get_in_brackets(to);
13189 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13190 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
13191 return -1;
13192 }
13193 mto = remove_uri_parameters(c);
13194
13195 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13196
13197 switch(state) {
13198 case AST_EXTENSION_DEACTIVATED:
13199 if (timeout)
13200 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13201 else {
13202 add_header(&req, "Subscription-State", "terminated;reason=probation");
13203 add_header(&req, "Retry-After", "60");
13204 }
13205 break;
13206 case AST_EXTENSION_REMOVED:
13207 add_header(&req, "Subscription-State", "terminated;reason=noresource");
13208 break;
13209 default:
13210 if (p->expiry)
13211 add_header(&req, "Subscription-State", "active");
13212 else
13213 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13214 }
13215
13216 switch (p->subscribed) {
13217 case XPIDF_XML:
13218 case CPIM_PIDF_XML:
13219 add_header(&req, "Event", subscriptiontype->event);
13220 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13221 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13222 p->dialogver++;
13223 break;
13224 case PIDF_XML:
13225 add_header(&req, "Event", subscriptiontype->event);
13226 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13227 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13228 p->dialogver++;
13229 break;
13230 case DIALOG_INFO_XML:
13231 add_header(&req, "Event", subscriptiontype->event);
13232 state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13233 add_header(&req, "Content-Type", subscriptiontype->mediatype);
13234 p->dialogver++;
13235 break;
13236 case NONE:
13237 default:
13238 break;
13239 }
13240
13241 add_content(&req, tmp->str);
13242
13243 p->pendinginvite = p->ocseq;
13244
13245 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13246 }
13247
13248
13249
13250
13251
13252
13253
13254 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
13255 {
13256 struct sip_request req;
13257 struct ast_str *out = ast_str_alloca(500);
13258 int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13259 const char *domain;
13260 const char *exten = S_OR(vmexten, default_vmexten);
13261
13262 initreqprep(&req, p, SIP_NOTIFY, NULL);
13263 add_header(&req, "Event", "message-summary");
13264 add_header(&req, "Content-Type", default_notifymime);
13265 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
13266
13267
13268 domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13269
13270 if (!sip_standard_port(p->socket.type, ourport)) {
13271 if (p->socket.type == SIP_TRANSPORT_UDP) {
13272 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13273 } else {
13274 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
13275 }
13276 } else {
13277 if (p->socket.type == SIP_TRANSPORT_UDP) {
13278 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13279 } else {
13280 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
13281 }
13282 }
13283
13284
13285
13286 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13287 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13288
13289 if (p->subscribed) {
13290 if (p->expiry) {
13291 add_header(&req, "Subscription-State", "active");
13292 } else {
13293 add_header(&req, "Subscription-State", "terminated;reason=timeout");
13294 }
13295 }
13296
13297 add_content(&req, out->str);
13298
13299 if (!p->initreq.headers) {
13300 initialize_initreq(p, &req);
13301 }
13302 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13303 }
13304
13305
13306 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13307 {
13308 struct sip_request req;
13309 char tmp[SIPBUFSIZE/2];
13310
13311 reqprep(&req, p, SIP_NOTIFY, 0, 1);
13312 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13313 add_header(&req, "Event", tmp);
13314 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13315 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13316 add_header(&req, "Allow", ALLOWED_METHODS);
13317 add_supported_header(p, &req);
13318
13319 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13320 add_content(&req, tmp);
13321
13322 if (!p->initreq.headers) {
13323 initialize_initreq(p, &req);
13324 }
13325
13326 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13327 }
13328
13329 static int manager_sipnotify(struct mansession *s, const struct message *m)
13330 {
13331 const char *channame = astman_get_header(m, "Channel");
13332 struct ast_variable *vars = astman_get_variables(m);
13333 struct sip_pvt *p;
13334 struct ast_variable *header, *var;
13335
13336 if (ast_strlen_zero(channame)) {
13337 astman_send_error(s, m, "SIPNotify requires a channel name");
13338 return 0;
13339 }
13340
13341 if (!strncasecmp(channame, "sip/", 4)) {
13342 channame += 4;
13343 }
13344
13345 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13346 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13347 return 0;
13348 }
13349
13350 if (create_addr(p, channame, NULL, 0, NULL)) {
13351
13352 dialog_unlink_all(p);
13353 dialog_unref(p, "unref dialog inside for loop" );
13354
13355 astman_send_error(s, m, "Could not create address");
13356 return 0;
13357 }
13358
13359
13360 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13361 sip_notify_allocate(p);
13362
13363 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13364
13365 for (var = vars; var; var = var->next) {
13366 if (!strcasecmp(var->name, "Content")) {
13367 if (ast_str_strlen(p->notify->content))
13368 ast_str_append(&p->notify->content, 0, "\r\n");
13369 ast_str_append(&p->notify->content, 0, "%s", var->value);
13370 } else if (!strcasecmp(var->name, "Content-Length")) {
13371 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring");
13372 } else {
13373 header->next = ast_variable_new(var->name, var->value, "");
13374 header = header->next;
13375 }
13376 }
13377
13378 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13379 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13380 dialog_unref(p, "bump down the count of p since we're done with it.");
13381
13382 astman_send_ack(s, m, "Notify Sent");
13383 ast_variables_destroy(vars);
13384 return 0;
13385 }
13386
13387
13388
13389 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13390 {
13391 struct sip_request resp;
13392
13393 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13394 return;
13395 }
13396
13397 respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13398 add_diversion_header(&resp, p);
13399 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13400 }
13401
13402
13403 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13404 {
13405
13406 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13407 return;
13408 }
13409 if (!p->owner->connected.id.number.valid
13410 || ast_strlen_zero(p->owner->connected.id.number.str)) {
13411 return;
13412 }
13413
13414 append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13415 ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13416 S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13417 S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13418
13419 if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13420 struct sip_request req;
13421
13422 if (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED) {
13423 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13424
13425 add_header(&req, "Allow", ALLOWED_METHODS);
13426 add_supported_header(p, &req);
13427 add_rpid(&req, p);
13428 add_sdp(&req, p, FALSE, TRUE, FALSE);
13429
13430 initialize_initreq(p, &req);
13431 p->lastinvite = p->ocseq;
13432 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13433 p->invitestate = INV_CALLING;
13434 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13435 } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) {
13436 reqprep(&req, p, SIP_UPDATE, 0, 1);
13437 add_rpid(&req, p);
13438 add_header(&req, "X-Asterisk-rpid-update", "Yes");
13439 send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13440 } else {
13441
13442 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13443 }
13444 } else {
13445 ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13446 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13447 struct sip_request resp;
13448
13449 if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13450 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13451 respprep(&resp, p, "180 Ringing", &p->initreq);
13452 add_rpid(&resp, p);
13453 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13454 ast_set_flag(&p->flags[0], SIP_RINGING);
13455 } else if (p->owner->_state == AST_STATE_RINGING) {
13456 ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13457 respprep(&resp, p, "183 Session Progress", &p->initreq);
13458 add_rpid(&resp, p);
13459 send_response(p, &resp, XMIT_UNRELIABLE, 0);
13460 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13461 } else {
13462 ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", ast_channel_name(p->owner), ast_state2str(p->owner->_state));
13463 }
13464 }
13465 }
13466 }
13467
13468 static const struct _map_x_s regstatestrings[] = {
13469 { REG_STATE_FAILED, "Failed" },
13470 { REG_STATE_UNREGISTERED, "Unregistered"},
13471 { REG_STATE_REGSENT, "Request Sent"},
13472 { REG_STATE_AUTHSENT, "Auth. Sent"},
13473 { REG_STATE_REGISTERED, "Registered"},
13474 { REG_STATE_REJECTED, "Rejected"},
13475 { REG_STATE_TIMEOUT, "Timeout"},
13476 { REG_STATE_NOAUTH, "No Authentication"},
13477 { -1, NULL }
13478 };
13479
13480
13481 static const char *regstate2str(enum sipregistrystate regstate)
13482 {
13483 return map_x_s(regstatestrings, regstate, "Unknown");
13484 }
13485
13486
13487
13488
13489
13490
13491
13492 static int sip_reregister(const void *data)
13493 {
13494
13495 struct sip_registry *r = (struct sip_registry *) data;
13496
13497
13498 if (!r) {
13499 return 0;
13500 }
13501
13502 if (r->call && r->call->do_history) {
13503 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13504 }
13505
13506
13507 if (sipdebug) {
13508 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
13509 }
13510
13511 r->expire = -1;
13512 r->expiry = r->configured_expiry;
13513 __sip_do_register(r);
13514 registry_unref(r, "unref the re-register scheduled event");
13515 return 0;
13516 }
13517
13518
13519
13520
13521 static int __sip_do_register(struct sip_registry *r)
13522 {
13523 int res;
13524
13525 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13526 return res;
13527 }
13528
13529
13530
13531
13532
13533
13534
13535 static int sip_reg_timeout(const void *data)
13536 {
13537
13538
13539 struct sip_registry *r = (struct sip_registry *)data;
13540 struct sip_pvt *p;
13541
13542
13543 if (!r) {
13544 return 0;
13545 }
13546
13547 if (r->dnsmgr) {
13548
13549 ast_dnsmgr_refresh(r->dnsmgr);
13550 }
13551
13552
13553
13554
13555
13556 if (r->call) {
13557
13558
13559 p = r->call;
13560 sip_pvt_lock(p);
13561 pvt_set_needdestroy(p, "registration timeout");
13562
13563 __sip_pretend_ack(p);
13564 sip_pvt_unlock(p);
13565
13566
13567
13568 if (p->registry) {
13569 p->registry = registry_unref(p->registry, "p->registry unreffed");
13570 }
13571 r->call = dialog_unref(r->call, "unrefing r->call");
13572 }
13573
13574 r->timeout = -1;
13575 if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13576
13577
13578
13579 ast_log(LOG_NOTICE, " -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13580 r->regstate = REG_STATE_FAILED;
13581 } else {
13582 r->regstate = REG_STATE_UNREGISTERED;
13583 transmit_register(r, SIP_REGISTER, NULL, NULL);
13584 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13585 }
13586 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));
13587 registry_unref(r, "unreffing registry_unref r");
13588 return 0;
13589 }
13590
13591 static const char *sip_sanitized_host(const char *host)
13592 {
13593 struct ast_sockaddr addr = { { 0, 0, }, };
13594
13595
13596
13597
13598 if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13599 return host;
13600 }
13601 return ast_sockaddr_stringify_host_remote(&addr);
13602 }
13603
13604
13605
13606
13607 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13608 {
13609 struct sip_request req;
13610 char from[256];
13611 char to[256];
13612 char tmp[80];
13613 char addr[80];
13614 struct sip_pvt *p;
13615 struct sip_peer *peer = NULL;
13616 int res;
13617 int portno = 0;
13618
13619
13620 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13621 if (r) {
13622 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13623 }
13624 return 0;
13625 }
13626
13627 if (r->dnsmgr == NULL) {
13628 char transport[MAXHOSTNAMELEN];
13629 peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13630 snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport));
13631 r->us.ss.ss_family = get_address_family_filter(&bindaddr);
13632
13633
13634
13635
13636
13637 if (!obproxy_get(r->call, peer)) {
13638 registry_addref(r, "add reg ref for dnsmgr");
13639 ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13640 if (!r->dnsmgr) {
13641
13642 registry_unref(r, "remove reg ref, dnsmgr disabled");
13643 }
13644 }
13645 if (peer) {
13646 peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13647 }
13648 }
13649
13650 if (r->call) {
13651 if (!auth) {
13652 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13653 return 0;
13654 } else {
13655 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13656 make_our_tag(p->tag, sizeof(p->tag));
13657 ast_string_field_set(p, theirtag, NULL);
13658 }
13659 } else {
13660
13661 if (!r->callid_valid) {
13662 build_callid_registry(r, &internip, default_fromdomain);
13663 r->callid_valid = TRUE;
13664 }
13665
13666 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13667 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13668 return 0;
13669 }
13670
13671 if (p->do_history) {
13672 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13673 }
13674
13675
13676 if (!ast_sockaddr_isnull(&r->us)) {
13677 if (!ast_sockaddr_port(&r->us) && r->portno) {
13678 ast_sockaddr_set_port(&r->us, r->portno);
13679 }
13680
13681
13682
13683
13684
13685 if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13686 if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13687 on_dns_update_peer(&peer->addr, &r->us, peer);
13688 }
13689 peer = sip_unref_peer(peer, "unref after sip_find_peer");
13690 }
13691 }
13692
13693
13694 if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0, NULL)) {
13695
13696
13697 dialog_unlink_all(p);
13698 p = dialog_unref(p, "unref dialog after unlink_all");
13699 if (r->timeout > -1) {
13700 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13701 registry_unref(_data, "del for REPLACE of registry ptr"),
13702 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13703 registry_addref(r,"add for REPLACE registry ptr"));
13704 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13705 } else {
13706 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13707 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);
13708 }
13709 r->regattempts++;
13710 return 0;
13711 }
13712
13713
13714 ast_string_field_set(r, callid, p->callid);
13715
13716 if (!r->dnsmgr && r->portno) {
13717 ast_sockaddr_set_port(&p->sa, r->portno);
13718 ast_sockaddr_set_port(&p->recv, r->portno);
13719 }
13720 if (!ast_strlen_zero(p->fromdomain)) {
13721 portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13722 } else if (!ast_strlen_zero(r->regdomain)) {
13723 portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13724 } else {
13725 portno = ast_sockaddr_port(&p->sa);
13726 }
13727
13728 ast_set_flag(&p->flags[0], SIP_OUTGOING);
13729 r->call = dialog_ref(p, "copying dialog into registry r->call");
13730 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
13731 if (!ast_strlen_zero(r->secret)) {
13732 ast_string_field_set(p, peersecret, r->secret);
13733 }
13734 if (!ast_strlen_zero(r->md5secret))
13735 ast_string_field_set(p, peermd5secret, r->md5secret);
13736
13737
13738 if (!ast_strlen_zero(r->authuser)) {
13739 ast_string_field_set(p, peername, r->authuser);
13740 ast_string_field_set(p, authname, r->authuser);
13741 } else if (!ast_strlen_zero(r->username)) {
13742 ast_string_field_set(p, peername, r->username);
13743 ast_string_field_set(p, authname, r->username);
13744 ast_string_field_set(p, fromuser, r->username);
13745 }
13746 if (!ast_strlen_zero(r->username)) {
13747 ast_string_field_set(p, username, r->username);
13748 }
13749
13750 if (!ast_strlen_zero(r->callback)) {
13751 ast_string_field_set(p, exten, r->callback);
13752 }
13753
13754
13755 set_socket_transport(&p->socket, r->transport);
13756 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13757 p->socket.port =
13758 htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13759 }
13760
13761
13762
13763
13764
13765
13766 ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13767 build_contact(p);
13768 }
13769
13770
13771 if (auth == NULL) {
13772 if (r->timeout > -1) {
13773 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13774 }
13775 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13776 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13777 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13778 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13779 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
13780 }
13781
13782 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13783 if (!ast_strlen_zero(p->theirtag)) {
13784 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13785 } else {
13786 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13787 }
13788
13789
13790
13791 if (portno && portno != STANDARD_SIP_PORT) {
13792 snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13793 } else {
13794 snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13795 }
13796
13797 ast_string_field_set(p, uri, addr);
13798
13799 p->branch ^= ast_random();
13800
13801 init_req(&req, sipmethod, addr);
13802
13803
13804 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13805 p->ocseq = r->ocseq;
13806
13807 build_via(p);
13808 add_header(&req, "Via", p->via);
13809 add_header_max_forwards(p, &req);
13810 add_header(&req, "From", from);
13811 add_header(&req, "To", to);
13812 add_header(&req, "Call-ID", p->callid);
13813 add_header(&req, "CSeq", tmp);
13814 if (!ast_strlen_zero(global_useragent))
13815 add_header(&req, "User-Agent", global_useragent);
13816
13817 if (auth) {
13818 add_header(&req, authheader, auth);
13819 } else if (!ast_strlen_zero(r->nonce)) {
13820 char digest[1024];
13821
13822
13823
13824
13825
13826
13827 if (sipdebug) {
13828 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13829 }
13830 ast_string_field_set(p, realm, r->realm);
13831 ast_string_field_set(p, nonce, r->nonce);
13832 ast_string_field_set(p, domain, r->authdomain);
13833 ast_string_field_set(p, opaque, r->opaque);
13834 ast_string_field_set(p, qop, r->qop);
13835 p->noncecount = ++r->noncecount;
13836
13837 memset(digest, 0, sizeof(digest));
13838 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13839 add_header(&req, "Authorization", digest);
13840 } else {
13841 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13842 }
13843 }
13844
13845 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13846 add_header(&req, "Expires", tmp);
13847 add_header(&req, "Contact", p->our_contact);
13848
13849 initialize_initreq(p, &req);
13850 if (sip_debug_test_pvt(p)) {
13851 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13852 }
13853 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13854 r->regattempts++;
13855 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13856 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13857 dialog_unref(p, "p is finished here at the end of transmit_register");
13858 return res;
13859 }
13860
13861
13862
13863
13864
13865 static int transmit_message(struct sip_pvt *p, int init, int auth)
13866 {
13867 struct sip_request req;
13868
13869 if (init) {
13870 initreqprep(&req, p, SIP_MESSAGE, NULL);
13871 initialize_initreq(p, &req);
13872 } else {
13873 reqprep(&req, p, SIP_MESSAGE, 0, 1);
13874 }
13875 if (auth) {
13876 return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
13877 } else {
13878 add_text(&req, p);
13879 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13880 }
13881 }
13882
13883
13884 static int sip_refer_allocate(struct sip_pvt *p)
13885 {
13886 p->refer = ast_calloc(1, sizeof(struct sip_refer));
13887 return p->refer ? 1 : 0;
13888 }
13889
13890
13891 static int sip_notify_allocate(struct sip_pvt *p)
13892 {
13893 p->notify = ast_calloc(1, sizeof(struct sip_notify));
13894 if (p->notify) {
13895 p->notify->content = ast_str_create(128);
13896 }
13897 return p->notify ? 1 : 0;
13898 }
13899
13900
13901
13902
13903
13904
13905 static int transmit_refer(struct sip_pvt *p, const char *dest)
13906 {
13907 struct sip_request req = {
13908 .headers = 0,
13909 };
13910 char from[256];
13911 const char *of;
13912 char *c;
13913 char referto[256];
13914 int use_tls=FALSE;
13915
13916 if (sipdebug) {
13917 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13918 }
13919
13920
13921 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13922 of = sip_get_header(&p->initreq, "To");
13923 } else {
13924 of = sip_get_header(&p->initreq, "From");
13925 }
13926
13927 ast_copy_string(from, of, sizeof(from));
13928 of = get_in_brackets(from);
13929 ast_string_field_set(p, from, of);
13930 if (!strncasecmp(of, "sip:", 4)) {
13931 of += 4;
13932 } else if (!strncasecmp(of, "sips:", 5)) {
13933 of += 5;
13934 use_tls = TRUE;
13935 } else {
13936 ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13937 }
13938
13939 if ((c = strchr(dest, '@'))) {
13940 c = NULL;
13941 } else if ((c = strchr(of, '@'))) {
13942 *c++ = '\0';
13943 }
13944 if (c) {
13945 snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13946 } else {
13947 snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13948 }
13949
13950
13951 sip_refer_allocate(p);
13952 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
13953 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
13954 p->refer->status = REFER_SENT;
13955
13956 reqprep(&req, p, SIP_REFER, 0, 1);
13957
13958 add_header(&req, "Refer-To", referto);
13959 add_header(&req, "Allow", ALLOWED_METHODS);
13960 add_supported_header(p, &req);
13961 if (!ast_strlen_zero(p->our_contact)) {
13962 add_header(&req, "Referred-By", p->our_contact);
13963 }
13964
13965 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975 }
13976
13977
13978 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
13979 {
13980 struct sip_request req;
13981 struct ast_str *str = ast_str_alloca(512);
13982 const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
13983 enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
13984
13985 reqprep(&req, p, SIP_INFO, 0, 1);
13986
13987 if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
13988 ast_str_append(&str, 0, "type=active;");
13989 } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
13990 ast_str_append(&str, 0, "type=terminated;");
13991 } else {
13992
13993 return -1;
13994 }
13995
13996 switch (charging) {
13997 case AST_AOC_CHARGE_FREE:
13998 ast_str_append(&str, 0, "free-of-charge;");
13999 break;
14000 case AST_AOC_CHARGE_CURRENCY:
14001 ast_str_append(&str, 0, "charging;");
14002 ast_str_append(&str, 0, "charging-info=currency;");
14003 ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
14004 ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
14005 if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
14006 ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
14007 }
14008 break;
14009 case AST_AOC_CHARGE_UNIT:
14010 ast_str_append(&str, 0, "charging;");
14011 ast_str_append(&str, 0, "charging-info=pulse;");
14012 if (unit_entry) {
14013 ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
14014 }
14015 break;
14016 default:
14017 ast_str_append(&str, 0, "not-available;");
14018 };
14019
14020 add_header(&req, "AOC", ast_str_buffer(str));
14021
14022 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14023 }
14024
14025
14026 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
14027 {
14028 struct sip_request req;
14029
14030 reqprep(&req, p, SIP_INFO, 0, 1);
14031 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
14032 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14033 }
14034
14035
14036 static int transmit_info_with_vidupdate(struct sip_pvt *p)
14037 {
14038 struct sip_request req;
14039
14040 reqprep(&req, p, SIP_INFO, 0, 1);
14041 add_vidupdate(&req);
14042 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14043 }
14044
14045
14046
14047
14048 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14049 {
14050 struct sip_request resp;
14051
14052 if (sipmethod == SIP_ACK) {
14053 p->invitestate = INV_CONFIRMED;
14054 }
14055
14056 reqprep(&resp, p, sipmethod, seqno, newbranch);
14057 if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
14058 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
14059 }
14060
14061 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14062 }
14063
14064
14065 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
14066 {
14067 if (code == WWW_AUTH) {
14068 *header = "WWW-Authenticate";
14069 *respheader = "Authorization";
14070 } else if (code == PROXY_AUTH) {
14071 *header = "Proxy-Authenticate";
14072 *respheader = "Proxy-Authorization";
14073 } else {
14074 ast_verbose("-- wrong response code %d\n", code);
14075 *header = *respheader = "Invalid";
14076 }
14077 }
14078
14079
14080 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14081 {
14082 struct sip_request resp;
14083
14084 reqprep(&resp, p, sipmethod, seqno, newbranch);
14085 if (!ast_strlen_zero(p->realm)) {
14086 char digest[1024];
14087
14088 memset(digest, 0, sizeof(digest));
14089 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
14090 char *dummy, *response;
14091 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
14092 sip_auth_headers(code, &dummy, &response);
14093 add_header(&resp, response, digest);
14094 } else {
14095 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
14096 }
14097 }
14098
14099 switch (sipmethod) {
14100 case SIP_BYE:
14101 {
14102 char buf[20];
14103
14104
14105
14106
14107
14108 if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
14109 snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
14110 add_header(&resp, "Reason", buf);
14111 }
14112
14113 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
14114 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
14115 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
14116 break;
14117 }
14118 case SIP_MESSAGE:
14119 add_text(&resp, p);
14120 break;
14121 default:
14122 break;
14123 }
14124
14125 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14126 }
14127
14128
14129 static void destroy_association(struct sip_peer *peer)
14130 {
14131 int realtimeregs = ast_check_realtime("sipregs");
14132 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
14133
14134 if (!sip_cfg.ignore_regexpire) {
14135 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14136 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
14137 } else {
14138 ast_db_del("SIP/Registry", peer->name);
14139 ast_db_del("SIP/PeerMethods", peer->name);
14140 }
14141 }
14142 }
14143
14144 static void set_socket_transport(struct sip_socket *socket, int transport)
14145 {
14146
14147 if (socket->type != transport) {
14148 socket->fd = -1;
14149 socket->type = transport;
14150 if (socket->tcptls_session) {
14151 ao2_ref(socket->tcptls_session, -1);
14152 socket->tcptls_session = NULL;
14153 }
14154 }
14155 }
14156
14157
14158 static int expire_register(const void *data)
14159 {
14160 struct sip_peer *peer = (struct sip_peer *)data;
14161
14162 if (!peer) {
14163 return 0;
14164 }
14165
14166 peer->expire = -1;
14167 peer->portinuri = 0;
14168
14169 destroy_association(peer);
14170 set_socket_transport(&peer->socket, peer->default_outbound_transport);
14171
14172 if (peer->socket.tcptls_session) {
14173 ao2_ref(peer->socket.tcptls_session, -1);
14174 peer->socket.tcptls_session = NULL;
14175 }
14176
14177 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
14178 register_peer_exten(peer, FALSE);
14179 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
14180
14181
14182
14183
14184 if (peer->is_realtime) {
14185 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
14186 }
14187
14188 if (peer->selfdestruct ||
14189 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
14190 unlink_peer_from_tables(peer);
14191 } else if (!ast_sockaddr_isnull(&peer->addr)) {
14192
14193
14194
14195 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14196 }
14197
14198
14199
14200 memset(&peer->addr, 0, sizeof(peer->addr));
14201
14202 sip_unref_peer(peer, "removing peer ref for expire_register");
14203
14204 return 0;
14205 }
14206
14207
14208 static int sip_poke_peer_s(const void *data)
14209 {
14210 struct sip_peer *peer = (struct sip_peer *)data;
14211 struct sip_peer *foundpeer;
14212
14213 peer->pokeexpire = -1;
14214
14215 foundpeer = ao2_find(peers, peer, OBJ_POINTER);
14216 if (!foundpeer) {
14217 sip_unref_peer(peer, "removing poke peer ref");
14218 return 0;
14219 } else if (foundpeer->name != peer->name) {
14220 sip_unref_peer(foundpeer, "removing above peer ref");
14221 sip_unref_peer(peer, "removing poke peer ref");
14222 return 0;
14223 }
14224
14225 sip_unref_peer(foundpeer, "removing above peer ref");
14226 sip_poke_peer(peer, 0);
14227 sip_unref_peer(peer, "removing poke peer ref");
14228
14229 return 0;
14230 }
14231
14232
14233 static void reg_source_db(struct sip_peer *peer)
14234 {
14235 char data[256];
14236 struct ast_sockaddr sa;
14237 int expire;
14238 char full_addr[128];
14239 AST_DECLARE_APP_ARGS(args,
14240 AST_APP_ARG(addr);
14241 AST_APP_ARG(port);
14242 AST_APP_ARG(expiry_str);
14243 AST_APP_ARG(username);
14244 AST_APP_ARG(contact);
14245 );
14246
14247
14248 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14249 return;
14250 }
14251 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
14252 return;
14253 }
14254
14255 AST_NONSTANDARD_RAW_ARGS(args, data, ':');
14256
14257 snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
14258
14259 if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
14260 return;
14261 }
14262
14263 if (args.expiry_str) {
14264 expire = atoi(args.expiry_str);
14265 } else {
14266 return;
14267 }
14268
14269 if (args.username) {
14270 ast_string_field_set(peer, username, args.username);
14271 }
14272 if (args.contact) {
14273 ast_string_field_set(peer, fullcontact, args.contact);
14274 }
14275
14276 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
14277 peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
14278
14279 ast_sockaddr_copy(&peer->addr, &sa);
14280 if (sipsock < 0) {
14281
14282 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
14283 sip_unref_peer(_data, "removing poke peer ref"),
14284 sip_unref_peer(peer, "removing poke peer ref"),
14285 sip_ref_peer(peer, "adding poke peer ref"));
14286 } else {
14287 sip_poke_peer(peer, 0);
14288 }
14289 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
14290 sip_unref_peer(_data, "remove registration ref"),
14291 sip_unref_peer(peer, "remove registration ref"),
14292 sip_ref_peer(peer, "add registration ref"));
14293 register_peer_exten(peer, TRUE);
14294 }
14295
14296
14297 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14298 {
14299 char contact[SIPBUFSIZE];
14300 char *c;
14301
14302
14303 ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
14304 c = get_in_brackets(contact);
14305
14306
14307 ast_string_field_set(pvt, fullcontact, c);
14308
14309
14310 ast_string_field_set(pvt, okcontacturi, c);
14311
14312
14313
14314 return TRUE;
14315 }
14316
14317
14318
14319
14320
14321
14322
14323 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14324 {
14325 int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14326 if (sip_cfg.legacy_useroption_parsing) {
14327 char *p;
14328 if ((p = strchr(uri, (int)';'))) {
14329 *p = '\0';
14330 }
14331 }
14332 return ret;
14333 }
14334
14335 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14336 {
14337 char *hostport, *transport;
14338 char contact_buf[256];
14339 char *contact;
14340
14341
14342 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14343 contact = contact_buf;
14344
14345
14346
14347
14348
14349
14350
14351
14352 if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14353 &transport)) {
14354 ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14355 }
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366 if (ast_strlen_zero(hostport)) {
14367 ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14368 return -1;
14369 }
14370
14371 if (ast_sockaddr_resolve_first(addr, hostport, 0)) {
14372 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14373 "resolve in DNS) : '%s'\n", hostport);
14374 return -1;
14375 }
14376
14377
14378 if (!ast_sockaddr_port(addr)) {
14379 ast_sockaddr_set_port(addr,
14380 (get_transport_str2enum(transport) ==
14381 SIP_TRANSPORT_TLS ||
14382 !strncasecmp(fullcontact, "sips", 4)) ?
14383 STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14384 }
14385
14386 return 0;
14387 }
14388
14389
14390 static int set_address_from_contact(struct sip_pvt *pvt)
14391 {
14392 if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14393
14394
14395
14396 pvt->sa = pvt->recv;
14397 return 0;
14398 }
14399
14400 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14401 }
14402
14403
14404 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14405 {
14406 char contact[SIPBUFSIZE];
14407 char data[SIPBUFSIZE];
14408 const char *expires = sip_get_header(req, "Expires");
14409 int expire = atoi(expires);
14410 char *curi = NULL, *hostport = NULL, *transport = NULL;
14411 int transport_type;
14412 const char *useragent;
14413 struct ast_sockaddr oldsin, testsa;
14414 char *firstcuri = NULL;
14415 int start = 0;
14416 int wildcard_found = 0;
14417 int single_binding_found = 0;
14418
14419 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14420
14421 if (ast_strlen_zero(expires)) {
14422 char *s = strcasestr(contact, ";expires=");
14423 if (s) {
14424 expires = strsep(&s, ";");
14425 if (sscanf(expires + 9, "%30d", &expire) != 1) {
14426 expire = default_expiry;
14427 }
14428 } else {
14429
14430 expire = default_expiry;
14431 }
14432 }
14433
14434 copy_socket_data(&pvt->socket, &req->socket);
14435
14436 do {
14437
14438 curi = contact;
14439 if (strchr(contact, '<') == NULL)
14440 strsep(&curi, ";");
14441 curi = get_in_brackets(contact);
14442 if (!firstcuri) {
14443 firstcuri = ast_strdupa(curi);
14444 }
14445
14446 if (!strcasecmp(curi, "*")) {
14447 wildcard_found = 1;
14448 } else {
14449 single_binding_found = 1;
14450 }
14451
14452 if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14453
14454
14455 return PARSE_REGISTER_FAILED;
14456 }
14457
14458 ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14459 } while (!ast_strlen_zero(contact));
14460 curi = firstcuri;
14461
14462
14463
14464
14465
14466 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14467
14468 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14469 pvt->expiry = ast_sched_when(sched, peer->expire);
14470 }
14471 return PARSE_REGISTER_QUERY;
14472 } else if (!strcasecmp(curi, "*") || !expire) {
14473
14474 AST_SCHED_DEL_UNREF(sched, peer->expire,
14475 sip_unref_peer(peer, "remove register expire ref"));
14476 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14477 expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
14478 return PARSE_REGISTER_UPDATE;
14479 }
14480
14481
14482 ast_string_field_set(peer, fullcontact, curi);
14483
14484
14485 ast_string_field_build(pvt, our_contact, "<%s>", curi);
14486
14487
14488 if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14489 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14490 }
14491
14492
14493 if (!(transport_type = get_transport_str2enum(transport))) {
14494 transport_type = pvt->socket.type;
14495 }
14496
14497
14498
14499
14500 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14501 set_socket_transport(&peer->socket, transport_type);
14502 }
14503
14504 oldsin = peer->addr;
14505
14506
14507 if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14508 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14509 }
14510
14511 if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14512
14513 ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14514
14515
14516 if (ast_sockaddr_resolve_first(&testsa, hostport, 0)) {
14517 ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14518 ast_string_field_set(peer, fullcontact, "");
14519 ast_string_field_set(pvt, our_contact, "");
14520 return PARSE_REGISTER_FAILED;
14521 }
14522
14523
14524
14525 peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14526
14527 if (!ast_sockaddr_port(&testsa)) {
14528 ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14529 }
14530
14531 ast_sockaddr_copy(&peer->addr, &testsa);
14532 } else {
14533
14534
14535 ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14536 peer->addr = pvt->recv;
14537 }
14538
14539
14540 if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14541 ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14542 ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14543 ast_sockaddr_stringify_addr(&testsa));
14544 ast_string_field_set(peer, fullcontact, "");
14545 ast_string_field_set(pvt, our_contact, "");
14546 return PARSE_REGISTER_DENIED;
14547 }
14548
14549
14550
14551
14552 if ((peer->socket.type == pvt->socket.type) &&
14553 !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14554 copy_socket_data(&peer->socket, &pvt->socket);
14555 }
14556
14557
14558 if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14559 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14560 }
14561
14562
14563 peer->sipoptions = pvt->sipoptions;
14564
14565 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14566 ast_string_field_set(peer, username, curi);
14567 }
14568
14569 AST_SCHED_DEL_UNREF(sched, peer->expire,
14570 sip_unref_peer(peer, "remove register expire ref"));
14571
14572 if (expire > max_expiry) {
14573 expire = max_expiry;
14574 }
14575 if (expire < min_expiry) {
14576 expire = min_expiry;
14577 }
14578 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14579 peer->expire = -1;
14580 } else {
14581 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14582 sip_ref_peer(peer, "add registration ref"));
14583 if (peer->expire == -1) {
14584 sip_unref_peer(peer, "remote registration ref");
14585 }
14586 }
14587 pvt->expiry = expire;
14588 snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14589 expire, peer->username, peer->fullcontact);
14590
14591 if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14592 ast_db_put("SIP/Registry", peer->name, data);
14593 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));
14594
14595
14596 if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14597 ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
14598 ast_sockaddr_stringify(&peer->addr));
14599 }
14600 sip_poke_peer(peer, 0);
14601 register_peer_exten(peer, 1);
14602
14603
14604 useragent = sip_get_header(req, "User-Agent");
14605 if (strcasecmp(useragent, peer->useragent)) {
14606 ast_string_field_set(peer, useragent, useragent);
14607 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14608 }
14609 return PARSE_REGISTER_UPDATE;
14610 }
14611
14612
14613 static void free_old_route(struct sip_route *route)
14614 {
14615 struct sip_route *next;
14616
14617 while (route) {
14618 next = route->next;
14619 ast_free(route);
14620 route = next;
14621 }
14622 }
14623
14624
14625 static void list_route(struct sip_route *route)
14626 {
14627 if (!route) {
14628 ast_verbose("list_route: no route\n");
14629 } else {
14630 for (;route; route = route->next)
14631 ast_verbose("list_route: hop: <%s>\n", route->hop);
14632 }
14633 }
14634
14635
14636 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
14637 {
14638 struct sip_route *thishop, *head, *tail;
14639 int start = 0;
14640 int len;
14641 const char *rr, *c;
14642
14643
14644 if (p->route && p->route_persistent) {
14645 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14646 return;
14647 }
14648
14649 if (p->route) {
14650 free_old_route(p->route);
14651 p->route = NULL;
14652 }
14653
14654
14655 p->route_persistent = 1;
14656
14657
14658
14659
14660
14661
14662 head = NULL;
14663 tail = head;
14664
14665 for (;;) {
14666
14667 char rr_copy[256];
14668 char *rr_copy_ptr;
14669 char *rr_iter;
14670 rr = __get_header(req, "Record-Route", &start);
14671 if (*rr == '\0') {
14672 break;
14673 }
14674 ast_copy_string(rr_copy, rr, sizeof(rr_copy));
14675 rr_copy_ptr = rr_copy;
14676 while ((rr_iter = strsep(&rr_copy_ptr, ","))) {
14677 char *uri = get_in_brackets(rr_iter);
14678 len = strlen(uri) + 1;
14679
14680 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14681
14682 ast_copy_string(thishop->hop, uri, len);
14683 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14684
14685 if (backwards) {
14686
14687 thishop->next = head;
14688 head = thishop;
14689
14690 if (!tail) {
14691 tail = thishop;
14692 }
14693 } else {
14694 thishop->next = NULL;
14695
14696 if (tail) {
14697 tail->next = thishop;
14698 } else {
14699 head = thishop;
14700 }
14701 tail = thishop;
14702 }
14703 }
14704 }
14705 }
14706
14707
14708 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14709
14710
14711 char *contact = ast_strdupa(sip_get_header(req, "Contact"));
14712 if (!ast_strlen_zero(contact)) {
14713 ast_debug(2, "build_route: Contact hop: %s\n", contact);
14714
14715 c = get_in_brackets(contact);
14716 len = strlen(c) + 1;
14717 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14718
14719 ast_copy_string(thishop->hop, c, len);
14720 thishop->next = NULL;
14721
14722 if (tail) {
14723 tail->next = thishop;
14724 } else {
14725 head = thishop;
14726 }
14727 }
14728 }
14729 }
14730
14731
14732 p->route = head;
14733
14734
14735 if (sip_debug_test_pvt(p)) {
14736 list_route(p->route);
14737 }
14738 }
14739
14740
14741
14742
14743
14744
14745
14746 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14747 {
14748 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14749 ast_string_field_build(p, randdata, "%08lx", ast_random());
14750 p->stalenonce = 0;
14751 }
14752 }
14753
14754
14755 void sip_digest_parser(char *c, struct digestkeys *keys)
14756 {
14757 struct digestkeys *i = i;
14758
14759 while(c && *(c = ast_skip_blanks(c)) ) {
14760 for (i = keys; i->key != NULL; i++) {
14761 const char *separator = ",";
14762
14763 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14764 continue;
14765 }
14766
14767 c += strlen(i->key);
14768 if (*c == '"') {
14769 c++;
14770 separator = "\"";
14771 }
14772 i->s = c;
14773 strsep(&c, separator);
14774 break;
14775 }
14776 if (i->key == NULL) {
14777 strsep(&c, " ,");
14778 }
14779 }
14780 }
14781
14782
14783
14784
14785
14786
14787 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14788 const char *secret, const char *md5secret, int sipmethod,
14789 const char *uri, enum xmittype reliable, int ignore)
14790 {
14791 const char *response;
14792 char *reqheader, *respheader;
14793 const char *authtoken;
14794 char a1_hash[256];
14795 char resp_hash[256]="";
14796 char *c;
14797 int wrongnonce = FALSE;
14798 int good_response;
14799 const char *usednonce = p->randdata;
14800 struct ast_str *buf;
14801 int res;
14802
14803
14804 struct digestkeys keys[] = {
14805 [K_RESP] = { "response=", "" },
14806 [K_URI] = { "uri=", "" },
14807 [K_USER] = { "username=", "" },
14808 [K_NONCE] = { "nonce=", "" },
14809 [K_LAST] = { NULL, NULL}
14810 };
14811
14812
14813 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
14814 return AUTH_SUCCESSFUL;
14815 }
14816
14817
14818
14819 response = "401 Unauthorized";
14820
14821
14822
14823
14824
14825 sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
14826
14827 authtoken = sip_get_header(req, reqheader);
14828 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14829
14830
14831 if (!reliable) {
14832
14833
14834 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14835
14836 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14837 }
14838 return AUTH_CHALLENGE_SENT;
14839 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14840
14841 set_nonce_randdata(p, 1);
14842 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14843
14844 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14845 return AUTH_CHALLENGE_SENT;
14846 }
14847
14848
14849
14850
14851
14852
14853 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14854 return AUTH_SECRET_FAILED;
14855 }
14856
14857
14858 res = ast_str_set(&buf, 0, "%s", authtoken);
14859
14860 if (res == AST_DYNSTR_BUILD_FAILED) {
14861 return AUTH_SECRET_FAILED;
14862 }
14863
14864 c = buf->str;
14865
14866 sip_digest_parser(c, keys);
14867
14868
14869 if (strcmp(username, keys[K_USER].s)) {
14870 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14871 username, keys[K_USER].s);
14872
14873 return AUTH_USERNAME_MISMATCH;
14874 }
14875
14876
14877
14878 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
14879 wrongnonce = TRUE;
14880 usednonce = keys[K_NONCE].s;
14881 } else {
14882 p->stalenonce = 1;
14883 }
14884
14885 if (!ast_strlen_zero(md5secret)) {
14886 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14887 } else {
14888 char a1[256];
14889
14890 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14891 ast_md5_hash(a1_hash, a1);
14892 }
14893
14894
14895 {
14896 char a2[256];
14897 char a2_hash[256];
14898 char resp[256];
14899
14900 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14901 S_OR(keys[K_URI].s, uri));
14902 ast_md5_hash(a2_hash, a2);
14903 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14904 ast_md5_hash(resp_hash, resp);
14905 }
14906
14907 good_response = keys[K_RESP].s &&
14908 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14909 if (wrongnonce) {
14910 if (good_response) {
14911 if (sipdebug)
14912 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
14913
14914 set_nonce_randdata(p, 0);
14915 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14916 } else {
14917
14918 if (!req->ignore) {
14919 if (sipdebug) {
14920 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
14921 }
14922 set_nonce_randdata(p, 1);
14923 } else {
14924 if (sipdebug) {
14925 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
14926 }
14927 }
14928 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14929 }
14930
14931
14932 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14933 return AUTH_CHALLENGE_SENT;
14934 }
14935 if (good_response) {
14936 append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14937 return AUTH_SUCCESSFUL;
14938 }
14939
14940
14941
14942
14943
14944
14945 return AUTH_SECRET_FAILED;
14946 }
14947
14948
14949 static void sip_peer_hold(struct sip_pvt *p, int hold)
14950 {
14951 if (!p->relatedpeer) {
14952 return;
14953 }
14954
14955
14956 ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14957
14958
14959 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
14960
14961 return;
14962 }
14963
14964
14965 static void mwi_event_cb(const struct ast_event *event, void *userdata)
14966 {
14967 struct sip_peer *peer = userdata;
14968
14969 sip_send_mwi_to_peer(peer, 0);
14970 }
14971
14972 static void network_change_event_subscribe(void)
14973 {
14974 if (!network_change_event_subscription) {
14975 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
14976 network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
14977 }
14978 }
14979
14980 static void network_change_event_unsubscribe(void)
14981 {
14982 if (network_change_event_subscription) {
14983 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
14984 }
14985 }
14986
14987 static int network_change_event_sched_cb(const void *data)
14988 {
14989 network_change_event_sched_id = -1;
14990 sip_send_all_registers();
14991 sip_send_all_mwi_subscriptions();
14992 return 0;
14993 }
14994
14995 static void network_change_event_cb(const struct ast_event *event, void *userdata)
14996 {
14997 ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
14998 if (network_change_event_sched_id == -1) {
14999 network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
15000 }
15001 }
15002
15003 static void cb_extensionstate_destroy(int id, void *data)
15004 {
15005 struct sip_pvt *p = data;
15006
15007 dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
15008 }
15009
15010
15011
15012
15013 static int cb_extensionstate(const char *context, const char *exten, enum ast_extension_states state, void *data)
15014 {
15015 struct sip_pvt *p = data;
15016
15017 sip_pvt_lock(p);
15018
15019 switch(state) {
15020 case AST_EXTENSION_DEACTIVATED:
15021 case AST_EXTENSION_REMOVED:
15022 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15023 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
15024 p->subscribed = NONE;
15025 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
15026 break;
15027 default:
15028 p->laststate = state;
15029 break;
15030 }
15031 if (p->subscribed != NONE) {
15032 if (!p->pendinginvite) {
15033 transmit_state_notify(p, state, 1, FALSE);
15034 } else {
15035
15036
15037 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
15038 }
15039 }
15040 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
15041 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
15042
15043 sip_pvt_unlock(p);
15044
15045 return 0;
15046 }
15047
15048
15049
15050
15051 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
15052 {
15053
15054
15055 const char *response = "407 Proxy Authentication Required";
15056 const char *reqheader = "Proxy-Authorization";
15057 const char *respheader = "Proxy-Authenticate";
15058 const char *authtoken;
15059 struct ast_str *buf;
15060 char *c;
15061
15062
15063 enum keys { K_NONCE, K_LAST };
15064 struct x {
15065 const char *key;
15066 const char *s;
15067 } *i, keys[] = {
15068 [K_NONCE] = { "nonce=", "" },
15069 [K_LAST] = { NULL, NULL}
15070 };
15071
15072 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
15073 response = "401 Unauthorized";
15074 reqheader = "Authorization";
15075 respheader = "WWW-Authenticate";
15076 }
15077 authtoken = sip_get_header(req, reqheader);
15078 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
15079
15080
15081 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
15082
15083 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15084 return;
15085 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
15086
15087 set_nonce_randdata(p, 1);
15088 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
15089
15090 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15091 return;
15092 }
15093
15094 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
15095 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15096 return;
15097 }
15098
15099
15100 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
15101 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15102 return;
15103 }
15104
15105 c = buf->str;
15106
15107 while (c && *(c = ast_skip_blanks(c))) {
15108 for (i = keys; i->key != NULL; i++) {
15109 const char *separator = ",";
15110
15111 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
15112 continue;
15113 }
15114
15115 c += strlen(i->key);
15116 if (*c == '"') {
15117 c++;
15118 separator = "\"";
15119 }
15120 i->s = c;
15121 strsep(&c, separator);
15122 break;
15123 }
15124 if (i->key == NULL) {
15125 strsep(&c, " ,");
15126 }
15127 }
15128
15129
15130 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
15131 if (!req->ignore) {
15132 set_nonce_randdata(p, 1);
15133 }
15134 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15135
15136
15137 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15138 } else {
15139 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15140 }
15141 }
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157 static char *terminate_uri(char *uri)
15158 {
15159 char *t = uri;
15160 while (*t && *t > ' ' && *t != ';') {
15161 t++;
15162 }
15163 *t = '\0';
15164 return uri;
15165 }
15166
15167
15168
15169
15170
15171
15172
15173 static void extract_host_from_hostport(char **hostport)
15174 {
15175 char *dont_care;
15176 ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
15177 }
15178
15179
15180
15181
15182
15183
15184 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
15185 struct sip_request *req, const char *uri)
15186 {
15187 enum check_auth_result res = AUTH_NOT_FOUND;
15188 struct sip_peer *peer;
15189 char tmp[256];
15190 char *c, *name, *unused_password, *domain;
15191 char *uri2 = ast_strdupa(uri);
15192
15193 terminate_uri(uri2);
15194
15195 ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
15196
15197 c = get_in_brackets(tmp);
15198 c = remove_uri_parameters(c);
15199
15200 if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
15201 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
15202 return -1;
15203 }
15204
15205 SIP_PEDANTIC_DECODE(name);
15206 SIP_PEDANTIC_DECODE(domain);
15207
15208 extract_host_from_hostport(&domain);
15209
15210 if (ast_strlen_zero(domain)) {
15211
15212 transmit_response(p, "404 Not found", &p->initreq);
15213 return AUTH_UNKNOWN_DOMAIN;
15214 }
15215
15216 if (ast_strlen_zero(name)) {
15217
15218
15219
15220
15221
15222
15223
15224 name = domain;
15225 }
15226
15227
15228
15229
15230
15231 if (!AST_LIST_EMPTY(&domain_list)) {
15232 if (!check_sip_domain(domain, NULL, 0)) {
15233 if (sip_cfg.alwaysauthreject) {
15234 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15235 } else {
15236 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
15237 }
15238 return AUTH_UNKNOWN_DOMAIN;
15239 }
15240 }
15241
15242 ast_string_field_set(p, exten, name);
15243 build_contact(p);
15244 if (req->ignore) {
15245
15246 const char *expires = sip_get_header(req, "Expires");
15247 int expire = atoi(expires);
15248
15249 if (ast_strlen_zero(expires)) {
15250 if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
15251 expire = atoi(expires + 9);
15252 }
15253 }
15254 if (!ast_strlen_zero(expires) && expire == 0) {
15255 transmit_response_with_date(p, "200 OK", req);
15256 return 0;
15257 }
15258 }
15259 peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
15260
15261 if (!(peer && ast_apply_ha(peer->ha, addr))) {
15262
15263 if (peer) {
15264 sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
15265 peer = NULL;
15266 res = AUTH_ACL_FAILED;
15267 } else {
15268 res = AUTH_NOT_FOUND;
15269 }
15270 }
15271
15272 if (peer) {
15273 ao2_lock(peer);
15274 if (!peer->host_dynamic) {
15275 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
15276 res = AUTH_PEER_NOT_DYNAMIC;
15277 } else {
15278 if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
15279 if (p->natdetected) {
15280 ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
15281 } else {
15282 ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
15283 }
15284 }
15285 if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
15286 if (p->natdetected) {
15287 ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
15288 } else {
15289 ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
15290 }
15291 }
15292
15293 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
15294 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15295 if (sip_cancel_destroy(p))
15296 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15297
15298 if (check_request_transport(peer, req)) {
15299 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15300 transmit_response_with_date(p, "403 Forbidden", req);
15301 res = AUTH_BAD_TRANSPORT;
15302 } else {
15303
15304
15305
15306 switch (parse_register_contact(p, peer, req)) {
15307 case PARSE_REGISTER_DENIED:
15308 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15309 transmit_response_with_date(p, "603 Denied", req);
15310 res = 0;
15311 break;
15312 case PARSE_REGISTER_FAILED:
15313 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15314 transmit_response_with_date(p, "400 Bad Request", req);
15315 res = 0;
15316 break;
15317 case PARSE_REGISTER_QUERY:
15318 ast_string_field_set(p, fullcontact, peer->fullcontact);
15319 transmit_response_with_date(p, "200 OK", req);
15320 res = 0;
15321 break;
15322 case PARSE_REGISTER_UPDATE:
15323 ast_string_field_set(p, fullcontact, peer->fullcontact);
15324 update_peer(peer, p->expiry);
15325
15326 transmit_response_with_date(p, "200 OK", req);
15327 res = 0;
15328 break;
15329 }
15330 }
15331
15332 }
15333 }
15334 ao2_unlock(peer);
15335 }
15336 if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
15337
15338 peer = temp_peer(name);
15339 if (peer) {
15340 ao2_t_link(peers, peer, "link peer into peer table");
15341 if (!ast_sockaddr_isnull(&peer->addr)) {
15342 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15343 }
15344 ao2_lock(peer);
15345 if (sip_cancel_destroy(p))
15346 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
15347 switch (parse_register_contact(p, peer, req)) {
15348 case PARSE_REGISTER_DENIED:
15349 ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15350 transmit_response_with_date(p, "403 Forbidden (ACL)", req);
15351 res = 0;
15352 break;
15353 case PARSE_REGISTER_FAILED:
15354 ast_log(LOG_WARNING, "Failed to parse contact info\n");
15355 transmit_response_with_date(p, "400 Bad Request", req);
15356 res = 0;
15357 break;
15358 case PARSE_REGISTER_QUERY:
15359 ast_string_field_set(p, fullcontact, peer->fullcontact);
15360 transmit_response_with_date(p, "200 OK", req);
15361 res = 0;
15362 break;
15363 case PARSE_REGISTER_UPDATE:
15364 ast_string_field_set(p, fullcontact, peer->fullcontact);
15365
15366 transmit_response_with_date(p, "200 OK", req);
15367 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));
15368 res = 0;
15369 break;
15370 }
15371 ao2_unlock(peer);
15372 }
15373 }
15374 if (!res) {
15375 ao2_unlock(p);
15376 sip_send_mwi_to_peer(peer, 0);
15377 ao2_lock(p);
15378 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
15379 }
15380 if (res < 0) {
15381 switch (res) {
15382 case AUTH_SECRET_FAILED:
15383
15384 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15385 if (global_authfailureevents) {
15386 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15387 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15388 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15389 "ChannelType: SIP\r\n"
15390 "Peer: SIP/%s\r\n"
15391 "PeerStatus: Rejected\r\n"
15392 "Cause: AUTH_SECRET_FAILED\r\n"
15393 "Address: %s\r\n"
15394 "Port: %s\r\n",
15395 name, peer_addr, peer_port);
15396 }
15397 break;
15398 case AUTH_USERNAME_MISMATCH:
15399
15400
15401
15402
15403 case AUTH_NOT_FOUND:
15404 case AUTH_PEER_NOT_DYNAMIC:
15405 case AUTH_ACL_FAILED:
15406 if (sip_cfg.alwaysauthreject) {
15407 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15408 if (global_authfailureevents) {
15409 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15410 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15411 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15412 "ChannelType: SIP\r\n"
15413 "Peer: SIP/%s\r\n"
15414 "PeerStatus: Rejected\r\n"
15415 "Cause: %s\r\n"
15416 "Address: %s\r\n"
15417 "Port: %s\r\n",
15418 name,
15419 res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15420 peer_addr, peer_port);
15421 }
15422 } else {
15423
15424 if (res == AUTH_PEER_NOT_DYNAMIC) {
15425 transmit_response(p, "403 Forbidden", &p->initreq);
15426 if (global_authfailureevents) {
15427 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15428 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15429 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15430 "ChannelType: SIP\r\n"
15431 "Peer: SIP/%s\r\n"
15432 "PeerStatus: Rejected\r\n"
15433 "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15434 "Address: %s\r\n"
15435 "Port: %s\r\n",
15436 name, peer_addr, peer_port);
15437 }
15438 } else {
15439 transmit_response(p, "404 Not found", &p->initreq);
15440 if (global_authfailureevents) {
15441 const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15442 const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15443 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15444 "ChannelType: SIP\r\n"
15445 "Peer: SIP/%s\r\n"
15446 "PeerStatus: Rejected\r\n"
15447 "Cause: %s\r\n"
15448 "Address: %s\r\n"
15449 "Port: %s\r\n",
15450 name,
15451 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15452 peer_addr, peer_port);
15453 }
15454 }
15455 }
15456 break;
15457 case AUTH_BAD_TRANSPORT:
15458 default:
15459 break;
15460 }
15461 }
15462 if (peer) {
15463 sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
15464 }
15465
15466 return res;
15467 }
15468
15469
15470 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15471
15472 if (!strcmp(reason, "unknown")) {
15473 ast_string_field_set(p, redircause, "UNKNOWN");
15474 } else if (!strcmp(reason, "user-busy")) {
15475 ast_string_field_set(p, redircause, "BUSY");
15476 } else if (!strcmp(reason, "no-answer")) {
15477 ast_string_field_set(p, redircause, "NOANSWER");
15478 } else if (!strcmp(reason, "unavailable")) {
15479 ast_string_field_set(p, redircause, "UNREACHABLE");
15480 } else if (!strcmp(reason, "unconditional")) {
15481 ast_string_field_set(p, redircause, "UNCONDITIONAL");
15482 } else if (!strcmp(reason, "time-of-day")) {
15483 ast_string_field_set(p, redircause, "UNKNOWN");
15484 } else if (!strcmp(reason, "do-not-disturb")) {
15485 ast_string_field_set(p, redircause, "UNKNOWN");
15486 } else if (!strcmp(reason, "deflection")) {
15487 ast_string_field_set(p, redircause, "UNKNOWN");
15488 } else if (!strcmp(reason, "follow-me")) {
15489 ast_string_field_set(p, redircause, "UNKNOWN");
15490 } else if (!strcmp(reason, "out-of-service")) {
15491 ast_string_field_set(p, redircause, "UNREACHABLE");
15492 } else if (!strcmp(reason, "away")) {
15493 ast_string_field_set(p, redircause, "UNREACHABLE");
15494 } else {
15495 ast_string_field_set(p, redircause, "UNKNOWN");
15496 }
15497 }
15498
15499
15500
15501
15502
15503 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15504 {
15505 char pai[256];
15506 char privacy[64];
15507 char *cid_num = NULL;
15508 char *cid_name = NULL;
15509 char emptyname[1] = "";
15510 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15511 char *uri = NULL;
15512 int is_anonymous = 0, do_update = 1, no_name = 0;
15513
15514 ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
15515
15516 if (ast_strlen_zero(pai)) {
15517 return 0;
15518 }
15519
15520
15521 if (get_name_and_number(pai, &cid_name, &cid_num)) {
15522 return 0;
15523 }
15524
15525 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15526 ast_shrink_phone_number(cid_num);
15527 }
15528
15529 uri = get_in_brackets(pai);
15530 if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15531 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15532
15533
15534
15535 ast_free(cid_num);
15536 is_anonymous = 1;
15537 cid_num = (char *)p->cid_num;
15538 }
15539
15540 ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
15541 if (!ast_strlen_zero(privacy) && strncmp(privacy, "id", 2)) {
15542 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15543 }
15544 if (!cid_name) {
15545 no_name = 1;
15546 cid_name = (char *)emptyname;
15547 }
15548
15549 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15550 do_update = 0;
15551 } else {
15552
15553 ast_string_field_set(p, cid_num, cid_num);
15554 ast_string_field_set(p, cid_name, cid_name);
15555 p->callingpres = callingpres;
15556
15557 if (p->owner) {
15558 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15559 p->owner->caller.id.name.presentation = callingpres;
15560 p->owner->caller.id.number.presentation = callingpres;
15561 }
15562 }
15563
15564
15565 if (!is_anonymous) {
15566 ast_free(cid_num);
15567 }
15568 if (!no_name) {
15569 ast_free(cid_name);
15570 }
15571
15572 return do_update;
15573 }
15574
15575
15576
15577
15578
15579 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15580 {
15581 char tmp[256];
15582 struct sip_request *req;
15583 char *cid_num = "";
15584 char *cid_name = "";
15585 int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15586 char *privacy = "";
15587 char *screen = "";
15588 char *start, *end;
15589
15590 if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15591 return 0;
15592 req = oreq;
15593 if (!req)
15594 req = &p->initreq;
15595 ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
15596 if (ast_strlen_zero(tmp)) {
15597 return get_pai(p, req);
15598 }
15599
15600 start = tmp;
15601 if (*start == '"') {
15602 *start++ = '\0';
15603 end = strchr(start, '"');
15604 if (!end)
15605 return 0;
15606 *end++ = '\0';
15607 cid_name = start;
15608 start = ast_skip_blanks(end);
15609 }
15610
15611 if (*start != '<')
15612 return 0;
15613 *start++ = '\0';
15614 end = strchr(start, '@');
15615 if (!end)
15616 return 0;
15617 *end++ = '\0';
15618 if (strncasecmp(start, "sip:", 4))
15619 return 0;
15620 cid_num = start + 4;
15621 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15622 ast_shrink_phone_number(cid_num);
15623 start = end;
15624
15625 end = strchr(start, '>');
15626 if (!end)
15627 return 0;
15628 *end++ = '\0';
15629 if (*end) {
15630 start = end;
15631 if (*start != ';')
15632 return 0;
15633 *start++ = '\0';
15634 while (!ast_strlen_zero(start)) {
15635 end = strchr(start, ';');
15636 if (end)
15637 *end++ = '\0';
15638 if (!strncasecmp(start, "privacy=", 8))
15639 privacy = start + 8;
15640 else if (!strncasecmp(start, "screen=", 7))
15641 screen = start + 7;
15642 start = end;
15643 }
15644
15645 if (!strcasecmp(privacy, "full")) {
15646 if (!strcasecmp(screen, "yes"))
15647 callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15648 else if (!strcasecmp(screen, "no"))
15649 callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15650 } else {
15651 if (!strcasecmp(screen, "yes"))
15652 callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15653 else if (!strcasecmp(screen, "no"))
15654 callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15655 }
15656 }
15657
15658
15659 if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15660 return 0;
15661
15662 ast_string_field_set(p, cid_num, cid_num);
15663 ast_string_field_set(p, cid_name, cid_name);
15664 p->callingpres = callingpres;
15665
15666 if (p->owner) {
15667 ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15668 p->owner->caller.id.name.presentation = callingpres;
15669 p->owner->caller.id.number.presentation = callingpres;
15670 }
15671
15672 return 1;
15673 }
15674
15675
15676 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15677 {
15678 char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15679 char *params, *reason_param = NULL;
15680 struct sip_request *req;
15681
15682 req = oreq ? oreq : &p->initreq;
15683
15684 ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
15685 if (ast_strlen_zero(tmp))
15686 return -1;
15687
15688 if ((params = strchr(tmp, '>'))) {
15689 params = strchr(params, ';');
15690 }
15691
15692 exten = get_in_brackets(tmp);
15693 if (!strncasecmp(exten, "sip:", 4)) {
15694 exten += 4;
15695 } else if (!strncasecmp(exten, "sips:", 5)) {
15696 exten += 5;
15697 } else {
15698 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
15699 return -1;
15700 }
15701
15702
15703 if (params) {
15704 *params = '\0';
15705 params++;
15706 while (*params == ';' || *params == ' ')
15707 params++;
15708
15709 if ((reason_param = strcasestr(params, "reason="))) {
15710 char *end;
15711 reason_param+=7;
15712 if ((end = strchr(reason_param, ';'))) {
15713 *end = '\0';
15714 }
15715
15716 if (*reason_param == '"')
15717 ast_strip_quoted(reason_param, "\"", "\"");
15718 if (!ast_strlen_zero(reason_param)) {
15719 sip_set_redirstr(p, reason_param);
15720 if (p->owner) {
15721 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15722 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15723 }
15724 }
15725 }
15726 }
15727
15728 rdomain = exten;
15729 rexten = strsep(&rdomain, "@");
15730 if (p->owner)
15731 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15732
15733 if (sip_debug_test_pvt(p))
15734 ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, reason ? reason_param : "");
15735
15736
15737
15738 if (*tmp == '\"') {
15739 char *end_quote;
15740 rname = tmp + 1;
15741 end_quote = strchr(rname, '\"');
15742 *end_quote = '\0';
15743 }
15744
15745 if (number) {
15746 *number = ast_strdup(rexten);
15747 }
15748
15749 if (name && rname) {
15750 *name = ast_strdup(rname);
15751 }
15752
15753 if (reason && !ast_strlen_zero(reason_param)) {
15754 *reason = sip_reason_str_to_code(reason_param);
15755 }
15756
15757 return 0;
15758 }
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15775 {
15776 char tmp[256] = "", *uri, *unused_password, *domain;
15777 char tmpf[256] = "", *from = NULL;
15778 struct sip_request *req;
15779 char *decoded_uri;
15780
15781 req = oreq;
15782 if (!req) {
15783 req = &p->initreq;
15784 }
15785
15786
15787 if (req->rlPart2)
15788 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15789
15790 uri = ast_strdupa(get_in_brackets(tmp));
15791
15792 if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15793 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15794 return SIP_GET_DEST_INVALID_URI;
15795 }
15796
15797 SIP_PEDANTIC_DECODE(domain);
15798 SIP_PEDANTIC_DECODE(uri);
15799
15800 extract_host_from_hostport(&domain);
15801
15802 if (ast_strlen_zero(uri)) {
15803
15804
15805
15806
15807
15808 uri = "s";
15809 }
15810
15811 ast_string_field_set(p, domain, domain);
15812
15813
15814
15815
15816
15817 ast_copy_string(tmpf, sip_get_header(req, "From"), sizeof(tmpf));
15818 if (!ast_strlen_zero(tmpf)) {
15819 from = get_in_brackets(tmpf);
15820 if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15821 ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15822 return SIP_GET_DEST_INVALID_URI;
15823 }
15824
15825 SIP_PEDANTIC_DECODE(from);
15826 SIP_PEDANTIC_DECODE(domain);
15827
15828 extract_host_from_hostport(&domain);
15829
15830 ast_string_field_set(p, fromdomain, domain);
15831 }
15832
15833 if (!AST_LIST_EMPTY(&domain_list)) {
15834 char domain_context[AST_MAX_EXTENSION];
15835
15836 domain_context[0] = '\0';
15837 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15838 if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15839 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15840 return SIP_GET_DEST_REFUSED;
15841 }
15842 }
15843
15844
15845 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15846 ast_string_field_set(p, context, domain_context);
15847 }
15848 }
15849
15850
15851 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15852 ast_string_field_set(p, context, p->subscribecontext);
15853 }
15854
15855 if (sip_debug_test_pvt(p)) {
15856 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15857 }
15858
15859
15860
15861 decoded_uri = ast_strdupa(uri);
15862 ast_uri_decode(decoded_uri, ast_uri_sip_user);
15863
15864
15865 if (req->method == SIP_SUBSCRIBE) {
15866 char hint[AST_MAX_EXTENSION];
15867 int which = 0;
15868 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15869 (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15870 if (!oreq) {
15871 ast_string_field_set(p, exten, which ? decoded_uri : uri);
15872 }
15873 return SIP_GET_DEST_EXTEN_FOUND;
15874 } else {
15875 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15876 }
15877 } else {
15878 struct ast_cc_agent *agent;
15879
15880
15881
15882 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15883 if (!oreq) {
15884 ast_string_field_set(p, exten, uri);
15885 }
15886 return SIP_GET_DEST_EXTEN_FOUND;
15887 }
15888 if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15889 || !strcmp(decoded_uri, ast_pickup_ext())) {
15890 if (!oreq) {
15891 ast_string_field_set(p, exten, decoded_uri);
15892 }
15893 return SIP_GET_DEST_EXTEN_FOUND;
15894 }
15895 if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15896 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15897
15898
15899
15900 ast_string_field_set(p, exten, agent_pvt->original_exten);
15901
15902
15903
15904 ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15905 agent->device_name);
15906 if (cc_recall_core_id) {
15907 *cc_recall_core_id = agent->core_id;
15908 }
15909 ao2_ref(agent, -1);
15910 return SIP_GET_DEST_EXTEN_FOUND;
15911 }
15912 }
15913
15914 if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15915 && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15916 || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15917 || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15918
15919 return SIP_GET_DEST_EXTEN_MATCHMORE;
15920 }
15921
15922 return SIP_GET_DEST_EXTEN_NOT_FOUND;
15923 }
15924
15925
15926
15927
15928 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15929 {
15930 struct sip_pvt *sip_pvt_ptr;
15931 struct sip_pvt tmp_dialog = {
15932 .callid = callid,
15933 };
15934
15935 if (totag) {
15936 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15937 }
15938
15939
15940
15941 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15942 if (sip_pvt_ptr) {
15943
15944 sip_pvt_lock(sip_pvt_ptr);
15945 if (sip_cfg.pedanticsipchecking) {
15946 unsigned char frommismatch = 0, tomismatch = 0;
15947
15948 if (ast_strlen_zero(fromtag)) {
15949 sip_pvt_unlock(sip_pvt_ptr);
15950 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15951 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15952 return NULL;
15953 }
15954
15955 if (ast_strlen_zero(totag)) {
15956 sip_pvt_unlock(sip_pvt_ptr);
15957 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15958 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15959 return NULL;
15960 }
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
15976 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
15977
15978 if (frommismatch || tomismatch) {
15979 sip_pvt_unlock(sip_pvt_ptr);
15980 if (frommismatch) {
15981 ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
15982 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15983 fromtag, sip_pvt_ptr->theirtag);
15984 }
15985 if (tomismatch) {
15986 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
15987 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15988 totag, sip_pvt_ptr->tag);
15989 }
15990 return NULL;
15991 }
15992 }
15993
15994 if (totag)
15995 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
15996 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
15997 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
15998
15999
16000 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
16001 sip_pvt_unlock(sip_pvt_ptr);
16002 usleep(1);
16003 sip_pvt_lock(sip_pvt_ptr);
16004 }
16005 }
16006
16007 return sip_pvt_ptr;
16008 }
16009
16010
16011
16012
16013
16014
16015
16016
16017 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
16018 {
16019
16020 const char *p_referred_by = NULL;
16021 char *h_refer_to = NULL;
16022 char *h_referred_by = NULL;
16023 char *refer_to;
16024 const char *p_refer_to;
16025 char *referred_by_uri = NULL;
16026 char *ptr;
16027 struct sip_request *req = NULL;
16028 const char *transfer_context = NULL;
16029 struct sip_refer *referdata;
16030
16031
16032 req = outgoing_req;
16033 referdata = transferer->refer;
16034
16035 if (!req) {
16036 req = &transferer->initreq;
16037 }
16038
16039 p_refer_to = sip_get_header(req, "Refer-To");
16040 if (ast_strlen_zero(p_refer_to)) {
16041 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
16042 return -2;
16043 }
16044 h_refer_to = ast_strdupa(p_refer_to);
16045 refer_to = get_in_brackets(h_refer_to);
16046 if (!strncasecmp(refer_to, "sip:", 4)) {
16047 refer_to += 4;
16048 } else if (!strncasecmp(refer_to, "sips:", 5)) {
16049 refer_to += 5;
16050 } else {
16051 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
16052 return -3;
16053 }
16054
16055
16056 p_referred_by = sip_get_header(req, "Referred-By");
16057
16058
16059 if (transferer->owner) {
16060 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
16061 if (peer) {
16062 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
16063 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
16064 }
16065 }
16066
16067 if (!ast_strlen_zero(p_referred_by)) {
16068 char *lessthan;
16069 h_referred_by = ast_strdupa(p_referred_by);
16070
16071
16072 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
16073 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
16074 *(lessthan - 1) = '\0';
16075 }
16076
16077 referred_by_uri = get_in_brackets(h_referred_by);
16078
16079 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
16080 referred_by_uri += 4;
16081 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
16082 referred_by_uri += 5;
16083 } else {
16084 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
16085 referred_by_uri = NULL;
16086 }
16087 }
16088
16089
16090 if ((ptr = strcasestr(refer_to, "replaces="))) {
16091 char *to = NULL, *from = NULL;
16092
16093
16094 referdata->attendedtransfer = 1;
16095 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
16096 ast_uri_decode(referdata->replaces_callid, ast_uri_sip_user);
16097 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
16098 *ptr++ = '\0';
16099 }
16100
16101 if (ptr) {
16102
16103 to = strcasestr(ptr, "to-tag=");
16104 from = strcasestr(ptr, "from-tag=");
16105 }
16106
16107
16108 if (to) {
16109 ptr = to + 7;
16110 if ((to = strchr(ptr, '&'))) {
16111 *to = '\0';
16112 }
16113 if ((to = strchr(ptr, ';'))) {
16114 *to = '\0';
16115 }
16116 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
16117 }
16118
16119 if (from) {
16120 ptr = from + 9;
16121 if ((to = strchr(ptr, '&'))) {
16122 *to = '\0';
16123 }
16124 if ((to = strchr(ptr, ';'))) {
16125 *to = '\0';
16126 }
16127 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
16128 }
16129
16130 if (!strcmp(referdata->replaces_callid, transferer->callid) &&
16131 (!sip_cfg.pedanticsipchecking ||
16132 (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
16133 !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
16134 ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
16135 return -4;
16136 }
16137
16138 if (!sip_cfg.pedanticsipchecking) {
16139 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
16140 } else {
16141 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>" );
16142 }
16143 }
16144
16145 if ((ptr = strchr(refer_to, '@'))) {
16146 char *urioption = NULL, *domain;
16147 int bracket = 0;
16148 *ptr++ = '\0';
16149
16150 if ((urioption = strchr(ptr, ';'))) {
16151 *urioption++ = '\0';
16152 }
16153
16154 domain = ptr;
16155
16156
16157 for (; *ptr != '\0'; ++ptr) {
16158 if (*ptr == ':' && bracket == 0) {
16159 *ptr = '\0';
16160 break;
16161 } else if (*ptr == '[') {
16162 ++bracket;
16163 } else if (*ptr == ']') {
16164 --bracket;
16165 }
16166 }
16167
16168 SIP_PEDANTIC_DECODE(domain);
16169 SIP_PEDANTIC_DECODE(urioption);
16170
16171
16172 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
16173 if (urioption) {
16174 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
16175 }
16176 }
16177
16178 if ((ptr = strchr(refer_to, ';')))
16179 *ptr = '\0';
16180
16181 SIP_PEDANTIC_DECODE(refer_to);
16182 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
16183
16184 if (referred_by_uri) {
16185 if ((ptr = strchr(referred_by_uri, ';')))
16186 *ptr = '\0';
16187 SIP_PEDANTIC_DECODE(referred_by_uri);
16188 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
16189 } else {
16190 referdata->referred_by[0] = '\0';
16191 }
16192
16193
16194 if (transferer->owner)
16195 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
16196
16197
16198 if (ast_strlen_zero(transfer_context)) {
16199 transfer_context = S_OR(transferer->owner->macrocontext,
16200 S_OR(transferer->context, sip_cfg.default_context));
16201 }
16202
16203 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
16204
16205
16206 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
16207 if (sip_debug_test_pvt(transferer)) {
16208 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
16209 }
16210
16211 return 0;
16212 }
16213 if (sip_debug_test_pvt(transferer))
16214 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
16215
16216
16217 return -1;
16218 }
16219
16220
16221
16222
16223
16224 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
16225 {
16226 char tmp[256] = "", *c, *a;
16227 struct sip_request *req = oreq ? oreq : &p->initreq;
16228 struct sip_refer *referdata = NULL;
16229 const char *transfer_context = NULL;
16230
16231 if (!p->refer && !sip_refer_allocate(p))
16232 return -1;
16233
16234 referdata = p->refer;
16235
16236 ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
16237 c = get_in_brackets(tmp);
16238
16239 if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
16240 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
16241 return -1;
16242 }
16243
16244 SIP_PEDANTIC_DECODE(c);
16245 SIP_PEDANTIC_DECODE(a);
16246
16247 if (!ast_strlen_zero(a)) {
16248 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
16249 }
16250
16251 if (sip_debug_test_pvt(p))
16252 ast_verbose("Looking for %s in %s\n", c, p->context);
16253
16254 if (p->owner)
16255 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
16256
16257
16258 if (ast_strlen_zero(transfer_context)) {
16259 transfer_context = S_OR(p->owner->macrocontext,
16260 S_OR(p->context, sip_cfg.default_context));
16261 }
16262 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
16263
16264 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
16265 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
16266 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
16267 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
16268 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
16269
16270 ast_string_field_set(p, context, transfer_context);
16271 return 0;
16272 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
16273 return 1;
16274 }
16275
16276 return -1;
16277 }
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16290 {
16291 char via[256];
16292 char *cur, *opts;
16293
16294 ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
16295
16296
16297 opts = strchr(via, ',');
16298 if (opts)
16299 *opts = '\0';
16300
16301
16302 opts = strchr(via, ';');
16303 if (!opts)
16304 return;
16305 *opts++ = '\0';
16306 while ( (cur = strsep(&opts, ";")) ) {
16307 if (!strncmp(cur, "rport=", 6)) {
16308 int port = strtol(cur+6, NULL, 10);
16309
16310 ast_sockaddr_set_port(&p->ourip, port);
16311 } else if (!strncmp(cur, "received=", 9)) {
16312 if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16313 ;
16314 }
16315 }
16316 }
16317
16318
16319 static void check_via(struct sip_pvt *p, struct sip_request *req)
16320 {
16321 char via[512];
16322 char *c, *maddr;
16323 struct ast_sockaddr tmp = { { 0, } };
16324 uint16_t port;
16325
16326 ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
16327
16328
16329 c = strchr(via, ',');
16330 if (c)
16331 *c = '\0';
16332
16333
16334 c = strstr(via, ";rport");
16335 if (c && (c[6] != '=')) {
16336 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16337 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16338 }
16339
16340
16341 maddr = strstr(via, "maddr=");
16342 if (maddr) {
16343 maddr += 6;
16344 c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16345 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16346 *c = '\0';
16347 }
16348
16349 c = strchr(via, ';');
16350 if (c)
16351 *c = '\0';
16352
16353 c = strchr(via, ' ');
16354 if (c) {
16355 *c = '\0';
16356 c = ast_skip_blanks(c+1);
16357 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16358 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16359 return;
16360 }
16361
16362 if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16363 p->sa = p->recv;
16364 }
16365
16366 ast_sockaddr_resolve_first(&tmp, c, 0);
16367 port = ast_sockaddr_port(&tmp);
16368 ast_sockaddr_set_port(&p->sa,
16369 port != 0 ? port : STANDARD_SIP_PORT);
16370
16371
16372
16373
16374
16375 if (ast_sockaddr_cmp(&tmp, &p->recv)) {
16376 char *tmp_str = ast_strdupa(ast_sockaddr_stringify(&tmp));
16377 ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify(&p->recv));
16378 p->natdetected = 1;
16379 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
16380 ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
16381 }
16382 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
16383 ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
16384 }
16385 } else {
16386 p->natdetected = 0;
16387 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
16388 ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
16389 }
16390 if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
16391 ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
16392 }
16393 }
16394
16395 if (sip_debug_test_pvt(p)) {
16396 ast_verbose("Sending to %s (%s)\n",
16397 ast_sockaddr_stringify(sip_real_dst(p)),
16398 sip_nat_mode(p));
16399 }
16400 }
16401 }
16402
16403
16404 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16405 struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16406 struct sip_peer **authpeer,
16407 enum xmittype reliable, char *calleridname, char *uri2)
16408 {
16409 enum check_auth_result res;
16410 int debug = sip_debug_test_addr(addr);
16411 struct sip_peer *peer;
16412
16413 if (sipmethod == SIP_SUBSCRIBE) {
16414
16415
16416
16417 peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16418 } else {
16419
16420 peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16421
16422
16423 if (!peer) {
16424 char *uri_tmp, *callback = NULL, *dummy;
16425 uri_tmp = ast_strdupa(uri2);
16426 parse_uri(uri_tmp, "sip:,sips:", &callback, &dummy, &dummy, &dummy);
16427 if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
16428 ;
16429 } else {
16430 peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16431 }
16432 }
16433 }
16434
16435 if (!peer) {
16436 if (debug) {
16437 ast_verbose("No matching peer for '%s' from '%s'\n",
16438 of, ast_sockaddr_stringify(&p->recv));
16439 }
16440 return AUTH_DONT_KNOW;
16441 }
16442
16443 if (!ast_apply_ha(peer->ha, addr)) {
16444 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16445 sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
16446 return AUTH_ACL_FAILED;
16447 }
16448 if (debug)
16449 ast_verbose("Found peer '%s' for '%s' from %s\n",
16450 peer->name, of, ast_sockaddr_stringify(&p->recv));
16451
16452
16453
16454 if (p->rtp) {
16455 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16456 p->autoframing = peer->autoframing;
16457 }
16458
16459
16460 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16461 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16462 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16463
16464 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16465 p->t38_maxdatagram = peer->t38_maxdatagram;
16466 set_t38_capabilities(p);
16467 }
16468
16469
16470
16471 if (p->sipoptions)
16472 peer->sipoptions = p->sipoptions;
16473
16474 do_setnat(p);
16475
16476 ast_string_field_set(p, peersecret, peer->secret);
16477 ast_string_field_set(p, peermd5secret, peer->md5secret);
16478 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16479 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16480 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16481 if (!ast_strlen_zero(peer->parkinglot)) {
16482 ast_string_field_set(p, parkinglot, peer->parkinglot);
16483 }
16484 ast_string_field_set(p, engine, peer->engine);
16485 p->disallowed_methods = peer->disallowed_methods;
16486 set_pvt_allowed_methods(p, req);
16487 ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16488 if (peer->callingpres)
16489 p->callingpres = peer->callingpres;
16490 if (peer->maxms && peer->lastms)
16491 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16492 else
16493 p->timer_t1 = peer->timer_t1;
16494
16495
16496 if (peer->timer_b)
16497 p->timer_b = peer->timer_b;
16498 else
16499 p->timer_b = 64 * p->timer_t1;
16500
16501 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16502
16503 ast_string_field_set(p, peersecret, NULL);
16504 ast_string_field_set(p, peermd5secret, NULL);
16505 }
16506 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16507 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16508 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16509 ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16510
16511 if (peer->call_limit)
16512 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16513 ast_string_field_set(p, peername, peer->name);
16514 ast_string_field_set(p, authname, peer->name);
16515
16516 if (sipmethod == SIP_INVITE) {
16517
16518 ast_variables_destroy(p->chanvars);
16519 p->chanvars = copy_vars(peer->chanvars);
16520 }
16521
16522 if (authpeer) {
16523 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16524 (*authpeer) = peer;
16525 }
16526
16527 if (!ast_strlen_zero(peer->username)) {
16528 ast_string_field_set(p, username, peer->username);
16529
16530
16531 ast_string_field_set(p, authname, peer->username);
16532 }
16533 if (!get_rpid(p, req)) {
16534 if (!ast_strlen_zero(peer->cid_num)) {
16535 char *tmp = ast_strdupa(peer->cid_num);
16536 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16537 ast_shrink_phone_number(tmp);
16538 ast_string_field_set(p, cid_num, tmp);
16539 }
16540 if (!ast_strlen_zero(peer->cid_name))
16541 ast_string_field_set(p, cid_name, peer->cid_name);
16542 if (!ast_strlen_zero(peer->cid_tag))
16543 ast_string_field_set(p, cid_tag, peer->cid_tag);
16544 if (peer->callingpres)
16545 p->callingpres = peer->callingpres;
16546 }
16547 ast_string_field_set(p, fullcontact, peer->fullcontact);
16548 if (!ast_strlen_zero(peer->context)) {
16549 ast_string_field_set(p, context, peer->context);
16550 }
16551 if (!ast_strlen_zero(peer->messagecontext)) {
16552 ast_string_field_set(p, messagecontext, peer->messagecontext);
16553 }
16554 if (!ast_strlen_zero(peer->mwi_from)) {
16555 ast_string_field_set(p, mwi_from, peer->mwi_from);
16556 }
16557 ast_string_field_set(p, peersecret, peer->secret);
16558 ast_string_field_set(p, peermd5secret, peer->md5secret);
16559 ast_string_field_set(p, language, peer->language);
16560 ast_string_field_set(p, accountcode, peer->accountcode);
16561 p->amaflags = peer->amaflags;
16562 p->callgroup = peer->callgroup;
16563 p->pickupgroup = peer->pickupgroup;
16564 ast_format_cap_copy(p->caps, peer->caps);
16565 ast_format_cap_copy(p->jointcaps, peer->caps);
16566 p->prefs = peer->prefs;
16567 ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
16568 if (peer->maxforwards > 0) {
16569 p->maxforwards = peer->maxforwards;
16570 }
16571 if (!(ast_format_cap_is_empty(p->peercaps))) {
16572 struct ast_format_cap *tmp = ast_format_cap_joint(p->jointcaps, p->peercaps);
16573 struct ast_format_cap *tmp2;
16574 if (tmp) {
16575 tmp2 = p->jointcaps;
16576 p->jointcaps = tmp;
16577 ast_format_cap_destroy(tmp2);
16578 }
16579 }
16580 p->maxcallbitrate = peer->maxcallbitrate;
16581 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16582 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16583 p->noncodeccapability |= AST_RTP_DTMF;
16584 else
16585 p->noncodeccapability &= ~AST_RTP_DTMF;
16586 p->jointnoncodeccapability = p->noncodeccapability;
16587 p->rtptimeout = peer->rtptimeout;
16588 p->rtpholdtimeout = peer->rtpholdtimeout;
16589 p->rtpkeepalive = peer->rtpkeepalive;
16590 if (!dialog_initialize_rtp(p)) {
16591 if (p->rtp) {
16592 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16593 p->autoframing = peer->autoframing;
16594 }
16595 } else {
16596 res = AUTH_RTP_FAILED;
16597 }
16598 }
16599 sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
16600 return res;
16601 }
16602
16603
16604
16605
16606
16607
16608
16609 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16610 int sipmethod, const char *uri, enum xmittype reliable,
16611 struct ast_sockaddr *addr, struct sip_peer **authpeer)
16612 {
16613 char from[256] = "", *of, *name, *unused_password, *domain;
16614 enum check_auth_result res = AUTH_DONT_KNOW;
16615 char calleridname[50];
16616 char *uri2 = ast_strdupa(uri);
16617
16618 terminate_uri(uri2);
16619
16620 ast_copy_string(from, sip_get_header(req, "From"), sizeof(from));
16621
16622
16623
16624 if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16625 ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16626 return res;
16627 }
16628
16629 if (calleridname[0]) {
16630 ast_string_field_set(p, cid_name, calleridname);
16631 }
16632
16633 if (ast_strlen_zero(p->exten)) {
16634 char *t = uri2;
16635 if (!strncasecmp(t, "sip:", 4))
16636 t+= 4;
16637 else if (!strncasecmp(t, "sips:", 5))
16638 t += 5;
16639 ast_string_field_set(p, exten, t);
16640 t = strchr(p->exten, '@');
16641 if (t)
16642 *t = '\0';
16643
16644 if (ast_strlen_zero(p->our_contact))
16645 build_contact(p);
16646 }
16647
16648 of = get_in_brackets(of);
16649
16650
16651 ast_string_field_set(p, from, of);
16652
16653 if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16654 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16655 }
16656
16657 SIP_PEDANTIC_DECODE(name);
16658 SIP_PEDANTIC_DECODE(domain);
16659
16660 extract_host_from_hostport(&domain);
16661
16662 if (ast_strlen_zero(domain)) {
16663
16664 ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16665 return res;
16666 }
16667
16668 if (ast_strlen_zero(name)) {
16669
16670
16671
16672 name = domain;
16673 } else {
16674
16675 char *tmp = ast_strdupa(name);
16676
16677
16678
16679 tmp = strsep(&tmp, ";");
16680 if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16681 ast_shrink_phone_number(tmp);
16682 }
16683 ast_string_field_set(p, cid_num, tmp);
16684 }
16685
16686 if (global_match_auth_username) {
16687
16688
16689
16690
16691
16692
16693
16694
16695 const char *hdr = sip_get_header(req, "Authorization");
16696 if (ast_strlen_zero(hdr)) {
16697 hdr = sip_get_header(req, "Proxy-Authorization");
16698 }
16699
16700 if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16701 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16702 name = from;
16703 name = strsep(&name, "\"");
16704 }
16705 }
16706
16707 res = check_peer_ok(p, name, req, sipmethod, addr,
16708 authpeer, reliable, calleridname, uri2);
16709 if (res != AUTH_DONT_KNOW) {
16710 return res;
16711 }
16712
16713
16714 if (sip_cfg.allowguest) {
16715 get_rpid(p, req);
16716 p->rtptimeout = global_rtptimeout;
16717 p->rtpholdtimeout = global_rtpholdtimeout;
16718 p->rtpkeepalive = global_rtpkeepalive;
16719 if (!dialog_initialize_rtp(p)) {
16720 res = AUTH_SUCCESSFUL;
16721 } else {
16722 res = AUTH_RTP_FAILED;
16723 }
16724 } else if (sip_cfg.alwaysauthreject) {
16725 res = AUTH_FAKE_AUTH;
16726 } else {
16727 res = AUTH_SECRET_FAILED;
16728 }
16729
16730 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16731 ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16732 }
16733
16734 return res;
16735 }
16736
16737
16738
16739
16740 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16741 {
16742 return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16743 }
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753 static int get_msg_text(char *buf, int len, struct sip_request *req)
16754 {
16755 int x;
16756 int linelen;
16757
16758 buf[0] = '\0';
16759 --len;
16760 for (x = 0; len && x < req->lines; ++x) {
16761 const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16762 strncat(buf, line, len);
16763 linelen = strlen(buf);
16764 buf += linelen;
16765 len -= linelen;
16766 if (len) {
16767 strcat(buf, "\n");
16768 ++buf;
16769 --len;
16770 }
16771 }
16772 return 0;
16773 }
16774
16775 static int get_msg_text2(struct ast_str **buf, struct sip_request *req)
16776 {
16777 int i, res = 0;
16778
16779 ast_str_reset(*buf);
16780
16781 for (i = 0; res >= 0 && i < req->lines; i++) {
16782 const char *line = REQ_OFFSET_TO_STR(req, line[i]);
16783
16784 res = ast_str_append(buf, 0, "%s\n", line);
16785 }
16786
16787 return res < 0 ? -1 : 0;
16788 }
16789
16790 static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
16791 {
16792 size_t x;
16793 char name_buf[1024];
16794 char val_buf[1024];
16795 const char *name;
16796 char *c;
16797 int res = 0;
16798
16799 for (x = 0; x < req->headers; x++) {
16800 const char *header = REQ_OFFSET_TO_STR(req, header[x]);
16801
16802 if ((c = strchr(header, ':'))) {
16803 ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
16804 ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
16805 ast_trim_blanks(name_buf);
16806
16807
16808 name = find_full_alias(name_buf, name_buf);
16809
16810 res = ast_msg_set_var(msg, name, val_buf);
16811 if (res) {
16812 break;
16813 }
16814 }
16815 }
16816 return res;
16817 }
16818
16819 AST_THREADSTORAGE(sip_msg_buf);
16820
16821
16822
16823
16824 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
16825 {
16826 struct ast_str *buf;
16827 char *cbuf;
16828 size_t len;
16829 struct ast_frame f;
16830 const char *content_type = sip_get_header(req, "Content-Type");
16831 struct ast_msg *msg;
16832 int res;
16833 char *from;
16834 char *to;
16835 char from_name[50];
16836
16837 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
16838 transmit_response(p, "415 Unsupported Media Type", req);
16839 if (!p->owner) {
16840 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16841 }
16842 return;
16843 }
16844
16845 if (!(buf = ast_str_thread_get(&sip_msg_buf, 128))) {
16846 transmit_response(p, "500 Internal Server Error", req);
16847 if (!p->owner) {
16848 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16849 }
16850 return;
16851 }
16852
16853 if (get_msg_text2(&buf, req)) {
16854 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16855 transmit_response(p, "500 Internal Server Error", req);
16856 if (!p->owner) {
16857 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16858 }
16859 return;
16860 }
16861
16862
16863
16864 cbuf = ast_str_buffer(buf);
16865 len = ast_str_strlen(buf);
16866 while (len > 0) {
16867 if (cbuf[--len] != '\n') {
16868 ++len;
16869 break;
16870 }
16871 }
16872 ast_str_truncate(buf, len);
16873
16874 if (p->owner) {
16875 if (sip_debug_test_pvt(p)) {
16876 ast_verbose("SIP Text message received: '%s'\n", ast_str_buffer(buf));
16877 }
16878 memset(&f, 0, sizeof(f));
16879 f.frametype = AST_FRAME_TEXT;
16880 f.subclass.integer = 0;
16881 f.offset = 0;
16882 f.data.ptr = ast_str_buffer(buf);
16883 f.datalen = ast_str_strlen(buf) + 1;
16884 ast_queue_frame(p->owner, &f);
16885 transmit_response(p, "202 Accepted", req);
16886 return;
16887 }
16888
16889
16890
16891
16892
16893
16894
16895
16896 if (!sip_cfg.accept_outofcall_message) {
16897
16898 ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
16899 transmit_response(p, "405 Method Not Allowed", req);
16900 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16901 return;
16902 }
16903
16904 copy_request(&p->initreq, req);
16905
16906 if (sip_cfg.auth_message_requests) {
16907 int res;
16908
16909 set_pvt_allowed_methods(p, req);
16910 res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
16911 if (res == AUTH_CHALLENGE_SENT) {
16912 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16913 return;
16914 }
16915 if (res < 0) {
16916 if (res == AUTH_FAKE_AUTH) {
16917 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", sip_get_header(req, "From"));
16918 transmit_fake_auth_response(p, SIP_MESSAGE, req, XMIT_UNRELIABLE);
16919 } else {
16920 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
16921 transmit_response(p, "403 Forbidden", req);
16922 }
16923 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16924 return;
16925 }
16926
16927 } else {
16928 struct sip_peer *peer;
16929
16930
16931
16932
16933
16934
16935
16936 peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
16937 if (peer) {
16938
16939 if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
16940 ast_string_field_set(p, context, peer->context);
16941 }
16942 if (!ast_strlen_zero(peer->messagecontext)) {
16943 ast_string_field_set(p, messagecontext, peer->messagecontext);
16944 }
16945 ast_string_field_set(p, peername, peer->name);
16946 peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
16947 }
16948 }
16949
16950
16951
16952
16953 if (!ast_strlen_zero(p->messagecontext)) {
16954 ast_string_field_set(p, context, p->messagecontext);
16955 } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
16956 ast_string_field_set(p, context, sip_cfg.messagecontext);
16957 }
16958
16959 get_destination(p, NULL, NULL);
16960
16961 if (!(msg = ast_msg_alloc())) {
16962 transmit_response(p, "500 Internal Server Error", req);
16963 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16964 return;
16965 }
16966
16967 to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlPart2));
16968 from = ast_strdupa(sip_get_header(req, "From"));
16969
16970 res = ast_msg_set_to(msg, "%s", to);
16971
16972
16973 from = (char *) get_calleridname(from, from_name, sizeof(from_name));
16974 from = get_in_brackets(from);
16975 if (from_name[0]) {
16976 res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_name, from);
16977 } else {
16978 res |= ast_msg_set_from(msg, "<%s>", from);
16979 }
16980
16981 res |= ast_msg_set_body(msg, "%s", ast_str_buffer(buf));
16982 res |= ast_msg_set_context(msg, "%s", p->context);
16983
16984 if (!ast_strlen_zero(p->peername)) {
16985 res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
16986 }
16987
16988 res |= ast_msg_set_exten(msg, "%s", p->exten);
16989 res |= set_message_vars_from_req(msg, req);
16990
16991 if (res) {
16992 ast_msg_destroy(msg);
16993 transmit_response(p, "500 Internal Server Error", req);
16994 } else {
16995 ast_msg_queue(msg);
16996 transmit_response(p, "202 Accepted", req);
16997 }
16998
16999 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17000 }
17001
17002
17003 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17004 {
17005 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
17006 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
17007 char ilimits[40];
17008 char iused[40];
17009 int showall = FALSE;
17010 struct ao2_iterator i;
17011 struct sip_peer *peer;
17012
17013 switch (cmd) {
17014 case CLI_INIT:
17015 e->command = "sip show inuse";
17016 e->usage =
17017 "Usage: sip show inuse [all]\n"
17018 " List all SIP devices usage counters and limits.\n"
17019 " Add option \"all\" to show all devices, not only those with a limit.\n";
17020 return NULL;
17021 case CLI_GENERATE:
17022 return NULL;
17023 }
17024
17025 if (a->argc < 3)
17026 return CLI_SHOWUSAGE;
17027
17028 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
17029 showall = TRUE;
17030
17031 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
17032
17033 i = ao2_iterator_init(peers, 0);
17034 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
17035 ao2_lock(peer);
17036 if (peer->call_limit)
17037 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
17038 else
17039 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
17040 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
17041 if (showall || peer->call_limit)
17042 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
17043 ao2_unlock(peer);
17044 sip_unref_peer(peer, "toss iterator pointer");
17045 }
17046 ao2_iterator_destroy(&i);
17047
17048 return CLI_SUCCESS;
17049 #undef FORMAT
17050 #undef FORMAT2
17051 }
17052
17053
17054
17055 static char *transfermode2str(enum transfermodes mode)
17056 {
17057 if (mode == TRANSFER_OPENFORALL)
17058 return "open";
17059 else if (mode == TRANSFER_CLOSED)
17060 return "closed";
17061 return "strict";
17062 }
17063
17064
17065
17066
17067
17068
17069
17070 static const struct _map_x_s stmodes[] = {
17071 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
17072 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
17073 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
17074 { -1, NULL},
17075 };
17076
17077 static const char *stmode2str(enum st_mode m)
17078 {
17079 return map_x_s(stmodes, m, "Unknown");
17080 }
17081
17082 static enum st_mode str2stmode(const char *s)
17083 {
17084 return map_s_x(stmodes, s, -1);
17085 }
17086
17087
17088 static const struct _map_x_s strefreshers[] = {
17089 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
17090 { SESSION_TIMER_REFRESHER_UAC, "uac"},
17091 { SESSION_TIMER_REFRESHER_UAS, "uas"},
17092 { -1, NULL},
17093 };
17094
17095 static const char *strefresher2str(enum st_refresher r)
17096 {
17097 return map_x_s(strefreshers, r, "Unknown");
17098 }
17099
17100 static enum st_refresher str2strefresher(const char *s)
17101 {
17102 return map_s_x(strefreshers, s, -1);
17103 }
17104
17105
17106 static struct _map_x_s autopeermodes[] = {
17107 { AUTOPEERS_DISABLED, "Off"},
17108 { AUTOPEERS_VOLATILE, "Volatile"},
17109 { AUTOPEERS_PERSIST, "Persisted"},
17110 { -1, NULL},
17111 };
17112
17113 static const char *autocreatepeer2str(enum autocreatepeer_mode r)
17114 {
17115 return map_x_s(autopeermodes, r, "Unknown");
17116 }
17117
17118 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
17119 {
17120 int res = 0;
17121 if (peer->maxms) {
17122 if (peer->lastms < 0) {
17123 ast_copy_string(status, "UNREACHABLE", statuslen);
17124 } else if (peer->lastms > peer->maxms) {
17125 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
17126 res = 1;
17127 } else if (peer->lastms) {
17128 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
17129 res = 1;
17130 } else {
17131 ast_copy_string(status, "UNKNOWN", statuslen);
17132 }
17133 } else {
17134 ast_copy_string(status, "Unmonitored", statuslen);
17135
17136 res = -1;
17137 }
17138 return res;
17139 }
17140
17141
17142 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17143 {
17144 struct sip_threadinfo *th;
17145 struct ao2_iterator i;
17146
17147 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
17148 #define FORMAT "%-47.47s %-9.9s %-6.6s\n"
17149
17150 switch (cmd) {
17151 case CLI_INIT:
17152 e->command = "sip show tcp";
17153 e->usage =
17154 "Usage: sip show tcp\n"
17155 " Lists all active TCP/TLS sessions.\n";
17156 return NULL;
17157 case CLI_GENERATE:
17158 return NULL;
17159 }
17160
17161 if (a->argc != 3)
17162 return CLI_SHOWUSAGE;
17163
17164 ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
17165
17166 i = ao2_iterator_init(threadt, 0);
17167 while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
17168 ast_cli(a->fd, FORMAT,
17169 ast_sockaddr_stringify(&th->tcptls_session->remote_address),
17170 sip_get_transport(th->type),
17171 (th->tcptls_session->client ? "Client" : "Server"));
17172 ao2_t_ref(th, -1, "decrement ref from iterator");
17173 }
17174 ao2_iterator_destroy(&i);
17175
17176 return CLI_SUCCESS;
17177 #undef FORMAT
17178 #undef FORMAT2
17179 }
17180
17181
17182 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17183 {
17184 regex_t regexbuf;
17185 int havepattern = FALSE;
17186 struct ao2_iterator user_iter;
17187 struct sip_peer *user;
17188
17189 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
17190
17191 switch (cmd) {
17192 case CLI_INIT:
17193 e->command = "sip show users";
17194 e->usage =
17195 "Usage: sip show users [like <pattern>]\n"
17196 " Lists all known SIP users.\n"
17197 " Optional regular expression pattern is used to filter the user list.\n";
17198 return NULL;
17199 case CLI_GENERATE:
17200 return NULL;
17201 }
17202
17203 switch (a->argc) {
17204 case 5:
17205 if (!strcasecmp(a->argv[3], "like")) {
17206 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
17207 return CLI_SHOWUSAGE;
17208 havepattern = TRUE;
17209 } else
17210 return CLI_SHOWUSAGE;
17211 case 3:
17212 break;
17213 default:
17214 return CLI_SHOWUSAGE;
17215 }
17216
17217 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
17218
17219 user_iter = ao2_iterator_init(peers, 0);
17220 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17221 ao2_lock(user);
17222 if (!(user->type & SIP_TYPE_USER)) {
17223 ao2_unlock(user);
17224 sip_unref_peer(user, "sip show users");
17225 continue;
17226 }
17227
17228 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
17229 ao2_unlock(user);
17230 sip_unref_peer(user, "sip show users");
17231 continue;
17232 }
17233
17234 ast_cli(a->fd, FORMAT, user->name,
17235 user->secret,
17236 user->accountcode,
17237 user->context,
17238 AST_CLI_YESNO(user->ha != NULL),
17239 AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
17240 ao2_unlock(user);
17241 sip_unref_peer(user, "sip show users");
17242 }
17243 ao2_iterator_destroy(&user_iter);
17244
17245 if (havepattern)
17246 regfree(®exbuf);
17247
17248 return CLI_SUCCESS;
17249 #undef FORMAT
17250 }
17251
17252
17253 static int manager_show_registry(struct mansession *s, const struct message *m)
17254 {
17255 const char *id = astman_get_header(m, "ActionID");
17256 char idtext[256] = "";
17257 int total = 0;
17258
17259 if (!ast_strlen_zero(id))
17260 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17261
17262 astman_send_listack(s, m, "Registrations will follow", "start");
17263
17264 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
17265 ASTOBJ_RDLOCK(iterator);
17266 astman_append(s,
17267 "Event: RegistryEntry\r\n"
17268 "%s"
17269 "Host: %s\r\n"
17270 "Port: %d\r\n"
17271 "Username: %s\r\n"
17272 "Domain: %s\r\n"
17273 "DomainPort: %d\r\n"
17274 "Refresh: %d\r\n"
17275 "State: %s\r\n"
17276 "RegistrationTime: %ld\r\n"
17277 "\r\n",
17278 idtext,
17279 iterator->hostname,
17280 iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
17281 iterator->username,
17282 S_OR(iterator->regdomain,iterator->hostname),
17283 iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
17284 iterator->refresh,
17285 regstate2str(iterator->regstate),
17286 (long) iterator->regtime.tv_sec);
17287 ASTOBJ_UNLOCK(iterator);
17288 total++;
17289 } while(0));
17290
17291 astman_append(s,
17292 "Event: RegistrationsComplete\r\n"
17293 "EventList: Complete\r\n"
17294 "ListItems: %d\r\n"
17295 "%s"
17296 "\r\n", total, idtext);
17297
17298 return 0;
17299 }
17300
17301
17302
17303 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
17304 {
17305 const char *id = astman_get_header(m, "ActionID");
17306 const char *a[] = {"sip", "show", "peers"};
17307 char idtext[256] = "";
17308 int total = 0;
17309
17310 if (!ast_strlen_zero(id))
17311 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17312
17313 astman_send_listack(s, m, "Peer status list will follow", "start");
17314
17315 _sip_show_peers(-1, &total, s, m, 3, a);
17316
17317 astman_append(s,
17318 "Event: PeerlistComplete\r\n"
17319 "EventList: Complete\r\n"
17320 "ListItems: %d\r\n"
17321 "%s"
17322 "\r\n", total, idtext);
17323 return 0;
17324 }
17325
17326
17327 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17328 {
17329 switch (cmd) {
17330 case CLI_INIT:
17331 e->command = "sip show peers";
17332 e->usage =
17333 "Usage: sip show peers [like <pattern>]\n"
17334 " Lists all known SIP peers.\n"
17335 " Optional regular expression pattern is used to filter the peer list.\n";
17336 return NULL;
17337 case CLI_GENERATE:
17338 return NULL;
17339 }
17340
17341 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
17342 }
17343
17344 int peercomparefunc(const void *a, const void *b);
17345
17346 int peercomparefunc(const void *a, const void *b)
17347 {
17348 struct sip_peer **ap = (struct sip_peer **)a;
17349 struct sip_peer **bp = (struct sip_peer **)b;
17350 return strcmp((*ap)->name, (*bp)->name);
17351 }
17352
17353
17354
17355 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
17356 {
17357 regex_t regexbuf;
17358 int havepattern = FALSE;
17359 struct sip_peer *peer;
17360 struct ao2_iterator i;
17361
17362
17363 #define FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
17364
17365 char name[256];
17366 int total_peers = 0;
17367 int peers_mon_online = 0;
17368 int peers_mon_offline = 0;
17369 int peers_unmon_offline = 0;
17370 int peers_unmon_online = 0;
17371 const char *id;
17372 char idtext[256] = "";
17373 int realtimepeers;
17374 int objcount = ao2_container_count(peers);
17375 struct sip_peer **peerarray;
17376 int k;
17377
17378 realtimepeers = ast_check_realtime("sippeers");
17379 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
17380
17381 if (s) {
17382 id = astman_get_header(m, "ActionID");
17383 if (!ast_strlen_zero(id))
17384 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17385 }
17386
17387 switch (argc) {
17388 case 5:
17389 if (!strcasecmp(argv[3], "like")) {
17390 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
17391 return CLI_SHOWUSAGE;
17392 havepattern = TRUE;
17393 } else
17394 return CLI_SHOWUSAGE;
17395 case 3:
17396 break;
17397 default:
17398 return CLI_SHOWUSAGE;
17399 }
17400
17401 if (!s)
17402 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", "Description", (realtimepeers ? "Realtime" : ""));
17403
17404 i = ao2_iterator_init(peers, 0);
17405 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17406 ao2_lock(peer);
17407
17408 if (!(peer->type & SIP_TYPE_PEER)) {
17409 ao2_unlock(peer);
17410 sip_unref_peer(peer, "unref peer because it's actually a user");
17411 continue;
17412 }
17413
17414 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
17415 objcount--;
17416 ao2_unlock(peer);
17417 sip_unref_peer(peer, "toss iterator peer ptr before continue");
17418 continue;
17419 }
17420
17421 peerarray[total_peers++] = peer;
17422 ao2_unlock(peer);
17423 }
17424 ao2_iterator_destroy(&i);
17425
17426 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
17427
17428 for(k=0; k < total_peers; k++) {
17429 char status[20] = "";
17430 char srch[2000];
17431 char pstatus;
17432
17433
17434
17435
17436
17437
17438 char *tmp_port;
17439 char *tmp_host;
17440
17441 peer = peerarray[k];
17442
17443 tmp_port = ast_sockaddr_isnull(&peer->addr) ?
17444 "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
17445
17446 tmp_host = ast_sockaddr_isnull(&peer->addr) ?
17447 "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
17448
17449 ao2_lock(peer);
17450 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
17451 ao2_unlock(peer);
17452 peer = peerarray[k] = sip_unref_peer(peer, "toss iterator peer ptr before continue");
17453 continue;
17454 }
17455
17456 if (!ast_strlen_zero(peer->username) && !s)
17457 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
17458 else
17459 ast_copy_string(name, peer->name, sizeof(name));
17460
17461 pstatus = peer_status(peer, status, sizeof(status));
17462 if (pstatus == 1)
17463 peers_mon_online++;
17464 else if (pstatus == 0)
17465 peers_mon_offline++;
17466 else {
17467 if (ast_sockaddr_isnull(&peer->addr) ||
17468 !ast_sockaddr_port(&peer->addr)) {
17469 peers_unmon_offline++;
17470 } else {
17471 peers_unmon_online++;
17472 }
17473 }
17474
17475 snprintf(srch, sizeof(srch), FORMAT2, name,
17476 tmp_host,
17477 peer->host_dynamic ? " D " : " ",
17478 ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
17479 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " A " : " a " :
17480 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
17481 peer->ha ? " A " : " ",
17482 tmp_port, status,
17483 peer->description ? peer->description : "",
17484 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17485
17486 if (!s) {
17487 ast_cli(fd, FORMAT2, name,
17488 tmp_host,
17489 peer->host_dynamic ? " D " : " ",
17490 ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
17491 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " A " : " a " :
17492 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : " ",
17493 peer->ha ? " A " : " ",
17494 tmp_port, status,
17495 peer->description ? peer->description : "",
17496 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17497 } else {
17498
17499 astman_append(s,
17500 "Event: PeerEntry\r\n%s"
17501 "Channeltype: SIP\r\n"
17502 "ObjectName: %s\r\n"
17503 "ChanObjectType: peer\r\n"
17504 "IPaddress: %s\r\n"
17505 "IPport: %s\r\n"
17506 "Dynamic: %s\r\n"
17507 "AutoForcerport: %s\r\n"
17508 "Forcerport: %s\r\n"
17509 "AutoComedia: %s\r\n"
17510 "Comedia: %s\r\n"
17511 "VideoSupport: %s\r\n"
17512 "TextSupport: %s\r\n"
17513 "ACL: %s\r\n"
17514 "Status: %s\r\n"
17515 "RealtimeDevice: %s\r\n"
17516 "Description: %s\r\n\r\n",
17517 idtext,
17518 peer->name,
17519 ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17520 ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17521 peer->host_dynamic ? "yes" : "no",
17522 ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
17523 ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
17524 ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
17525 ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
17526 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
17527 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
17528 peer->ha ? "yes" : "no",
17529 status,
17530 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no",
17531 peer->description);
17532 }
17533 ao2_unlock(peer);
17534 peer = peerarray[k] = sip_unref_peer(peer, "toss iterator peer ptr");
17535 }
17536
17537 if (!s)
17538 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17539 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
17540
17541 if (havepattern)
17542 regfree(®exbuf);
17543
17544 if (total)
17545 *total = total_peers;
17546
17547 ast_free(peerarray);
17548
17549 return CLI_SUCCESS;
17550 #undef FORMAT2
17551 }
17552
17553 static int peer_dump_func(void *userobj, void *arg, int flags)
17554 {
17555 struct sip_peer *peer = userobj;
17556 int refc = ao2_t_ref(userobj, 0, "");
17557 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17558
17559 ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17560 peer->name, 0, refc);
17561 return 0;
17562 }
17563
17564 static int dialog_dump_func(void *userobj, void *arg, int flags)
17565 {
17566 struct sip_pvt *pvt = userobj;
17567 int refc = ao2_t_ref(userobj, 0, "");
17568 struct ast_cli_args *a = (struct ast_cli_args *) arg;
17569
17570 ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17571 pvt->callid, 0, refc);
17572 return 0;
17573 }
17574
17575
17576
17577 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17578 {
17579 char tmp[256];
17580
17581 switch (cmd) {
17582 case CLI_INIT:
17583 e->command = "sip show objects";
17584 e->usage =
17585 "Usage: sip show objects\n"
17586 " Lists status of known SIP objects\n";
17587 return NULL;
17588 case CLI_GENERATE:
17589 return NULL;
17590 }
17591
17592 if (a->argc != 3)
17593 return CLI_SHOWUSAGE;
17594 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17595 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17596 ast_cli(a->fd, "-= Peer objects by IP =-\n\n");
17597 ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17598 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17599 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
17600 ast_cli(a->fd, "-= Dialog objects:\n\n");
17601 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17602 return CLI_SUCCESS;
17603 }
17604
17605 static void print_group(int fd, ast_group_t group, int crlf)
17606 {
17607 char buf[256];
17608 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17609 }
17610
17611
17612 static const struct _map_x_s dtmfstr[] = {
17613 { SIP_DTMF_RFC2833, "rfc2833" },
17614 { SIP_DTMF_INFO, "info" },
17615 { SIP_DTMF_SHORTINFO, "shortinfo" },
17616 { SIP_DTMF_INBAND, "inband" },
17617 { SIP_DTMF_AUTO, "auto" },
17618 { -1, NULL },
17619 };
17620
17621
17622 static const char *dtmfmode2str(int mode)
17623 {
17624 return map_x_s(dtmfstr, mode, "<error>");
17625 }
17626
17627
17628 static int str2dtmfmode(const char *str)
17629 {
17630 return map_s_x(dtmfstr, str, -1);
17631 }
17632
17633 static const struct _map_x_s insecurestr[] = {
17634 { SIP_INSECURE_PORT, "port" },
17635 { SIP_INSECURE_INVITE, "invite" },
17636 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17637 { 0, "no" },
17638 { -1, NULL },
17639 };
17640
17641
17642 static const char *insecure2str(int mode)
17643 {
17644 return map_x_s(insecurestr, mode, "<error>");
17645 }
17646
17647 static const struct _map_x_s allowoverlapstr[] = {
17648 { SIP_PAGE2_ALLOWOVERLAP_YES, "Yes" },
17649 { SIP_PAGE2_ALLOWOVERLAP_DTMF, "DTMF" },
17650 { SIP_PAGE2_ALLOWOVERLAP_NO, "No" },
17651 { -1, NULL },
17652 };
17653
17654
17655 static const char *allowoverlap2str(int mode)
17656 {
17657 return map_x_s(allowoverlapstr, mode, "<error>");
17658 }
17659
17660
17661
17662
17663 static void cleanup_stale_contexts(char *new, char *old)
17664 {
17665 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17666
17667 while ((oldcontext = strsep(&old, "&"))) {
17668 stalecontext = '\0';
17669 ast_copy_string(newlist, new, sizeof(newlist));
17670 stringp = newlist;
17671 while ((newcontext = strsep(&stringp, "&"))) {
17672 if (!strcmp(newcontext, oldcontext)) {
17673
17674 stalecontext = '\0';
17675 break;
17676 } else if (strcmp(newcontext, oldcontext)) {
17677 stalecontext = oldcontext;
17678 }
17679
17680 }
17681 if (stalecontext)
17682 ast_context_destroy(ast_context_find(stalecontext), "SIP");
17683 }
17684 }
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694 static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
17695 {
17696 struct sip_pvt *dialog = dialogobj;
17697 time_t *t = arg;
17698 int match_status;
17699
17700 if (sip_pvt_trylock(dialog)) {
17701 return 0;
17702 }
17703
17704 if (dialog->rtp || dialog->vrtp) {
17705 match_status = check_rtp_timeout(dialog, *t);
17706 } else {
17707
17708 match_status = CMP_MATCH;
17709 }
17710 sip_pvt_unlock(dialog);
17711
17712 return match_status;
17713 }
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17726 {
17727 struct sip_pvt *dialog = dialogobj;
17728
17729 if (sip_pvt_trylock(dialog)) {
17730
17731
17732 return 0;
17733 }
17734
17735
17736
17737
17738 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17739
17740 if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17741 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17742 sip_pvt_unlock(dialog);
17743 return 0;
17744 }
17745
17746 if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17747 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17748 sip_pvt_unlock(dialog);
17749 return 0;
17750 }
17751
17752 sip_pvt_unlock(dialog);
17753
17754
17755 dialog_unlink_all(dialog);
17756 return 0;
17757 }
17758
17759 sip_pvt_unlock(dialog);
17760
17761 return 0;
17762 }
17763
17764
17765
17766 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17767 {
17768 struct sip_peer *peer, *pi;
17769 int prunepeer = FALSE;
17770 int multi = FALSE;
17771 const char *name = NULL;
17772 regex_t regexbuf;
17773 int havepattern = 0;
17774 struct ao2_iterator i;
17775 static const char * const choices[] = { "all", "like", NULL };
17776 char *cmplt;
17777
17778 if (cmd == CLI_INIT) {
17779 e->command = "sip prune realtime [peer|all]";
17780 e->usage =
17781 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17782 " Prunes object(s) from the cache.\n"
17783 " Optional regular expression pattern is used to filter the objects.\n";
17784 return NULL;
17785 } else if (cmd == CLI_GENERATE) {
17786 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17787 cmplt = ast_cli_complete(a->word, choices, a->n);
17788 if (!cmplt)
17789 cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17790 return cmplt;
17791 }
17792 if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17793 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17794 return NULL;
17795 }
17796 switch (a->argc) {
17797 case 4:
17798 name = a->argv[3];
17799
17800 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17801 return CLI_SHOWUSAGE;
17802 prunepeer = TRUE;
17803 if (!strcasecmp(name, "all")) {
17804 multi = TRUE;
17805 name = NULL;
17806 }
17807
17808 break;
17809 case 5:
17810
17811 name = a->argv[4];
17812 if (!strcasecmp(a->argv[3], "peer"))
17813 prunepeer = TRUE;
17814 else if (!strcasecmp(a->argv[3], "like")) {
17815 prunepeer = TRUE;
17816 multi = TRUE;
17817 } else
17818 return CLI_SHOWUSAGE;
17819 if (!strcasecmp(name, "like"))
17820 return CLI_SHOWUSAGE;
17821 if (!multi && !strcasecmp(name, "all")) {
17822 multi = TRUE;
17823 name = NULL;
17824 }
17825 break;
17826 case 6:
17827 name = a->argv[5];
17828 multi = TRUE;
17829
17830 if (strcasecmp(a->argv[4], "like"))
17831 return CLI_SHOWUSAGE;
17832 if (!strcasecmp(a->argv[3], "peer")) {
17833 prunepeer = TRUE;
17834 } else
17835 return CLI_SHOWUSAGE;
17836 break;
17837 default:
17838 return CLI_SHOWUSAGE;
17839 }
17840
17841 if (multi && name) {
17842 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB)) {
17843 return CLI_SHOWUSAGE;
17844 }
17845 havepattern = 1;
17846 }
17847
17848 if (multi) {
17849 if (prunepeer) {
17850 int pruned = 0;
17851
17852 i = ao2_iterator_init(peers, 0);
17853 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17854 ao2_lock(pi);
17855 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
17856 ao2_unlock(pi);
17857 sip_unref_peer(pi, "toss iterator peer ptr before continue");
17858 continue;
17859 };
17860 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17861 pi->the_mark = 1;
17862 pruned++;
17863 }
17864 ao2_unlock(pi);
17865 sip_unref_peer(pi, "toss iterator peer ptr");
17866 }
17867 ao2_iterator_destroy(&i);
17868 if (pruned) {
17869 unlink_marked_peers_from_tables();
17870 ast_cli(a->fd, "%d peers pruned.\n", pruned);
17871 } else
17872 ast_cli(a->fd, "No peers found to prune.\n");
17873 }
17874 } else {
17875 if (prunepeer) {
17876 struct sip_peer tmp;
17877 ast_copy_string(tmp.name, name, sizeof(tmp.name));
17878 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17879 if (!ast_sockaddr_isnull(&peer->addr)) {
17880 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17881 }
17882 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17883 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17884
17885 ao2_t_link(peers, peer, "link peer into peer table");
17886 if (!ast_sockaddr_isnull(&peer->addr)) {
17887 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17888 }
17889 } else
17890 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17891 sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
17892 } else
17893 ast_cli(a->fd, "Peer '%s' not found.\n", name);
17894 }
17895 }
17896
17897 if (havepattern) {
17898 regfree(®exbuf);
17899 }
17900
17901 return CLI_SUCCESS;
17902 }
17903
17904
17905 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17906 {
17907 int x;
17908 struct ast_format codec;
17909
17910 for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
17911 if (!(ast_codec_pref_index(pref, x, &codec))) {
17912 break;
17913 }
17914 ast_cli(fd, "%s", ast_getformatname(&codec));
17915 ast_cli(fd, ":%d", pref->framing[x]);
17916 if (x < 31 && ast_codec_pref_index(pref, x + 1, &codec))
17917 ast_cli(fd, ",");
17918 }
17919 if (!x)
17920 ast_cli(fd, "none");
17921 }
17922
17923
17924 static const char *domain_mode_to_text(const enum domain_mode mode)
17925 {
17926 switch (mode) {
17927 case SIP_DOMAIN_AUTO:
17928 return "[Automatic]";
17929 case SIP_DOMAIN_CONFIG:
17930 return "[Configured]";
17931 }
17932
17933 return "";
17934 }
17935
17936
17937 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17938 {
17939 struct domain *d;
17940 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17941
17942 switch (cmd) {
17943 case CLI_INIT:
17944 e->command = "sip show domains";
17945 e->usage =
17946 "Usage: sip show domains\n"
17947 " Lists all configured SIP local domains.\n"
17948 " Asterisk only responds to SIP messages to local domains.\n";
17949 return NULL;
17950 case CLI_GENERATE:
17951 return NULL;
17952 }
17953
17954 if (AST_LIST_EMPTY(&domain_list)) {
17955 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17956 return CLI_SUCCESS;
17957 } else {
17958 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17959 AST_LIST_LOCK(&domain_list);
17960 AST_LIST_TRAVERSE(&domain_list, d, list)
17961 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17962 domain_mode_to_text(d->mode));
17963 AST_LIST_UNLOCK(&domain_list);
17964 ast_cli(a->fd, "\n");
17965 return CLI_SUCCESS;
17966 }
17967 }
17968 #undef FORMAT
17969
17970
17971 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17972 {
17973 const char *a[4];
17974 const char *peer;
17975
17976 peer = astman_get_header(m, "Peer");
17977 if (ast_strlen_zero(peer)) {
17978 astman_send_error(s, m, "Peer: <name> missing.");
17979 return 0;
17980 }
17981 a[0] = "sip";
17982 a[1] = "show";
17983 a[2] = "peer";
17984 a[3] = peer;
17985
17986 _sip_show_peer(1, -1, s, m, 4, a);
17987 astman_append(s, "\r\n" );
17988 return 0;
17989 }
17990
17991
17992 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17993 {
17994 switch (cmd) {
17995 case CLI_INIT:
17996 e->command = "sip show peer";
17997 e->usage =
17998 "Usage: sip show peer <name> [load]\n"
17999 " Shows all details on one SIP peer and the current status.\n"
18000 " Option \"load\" forces lookup of peer in realtime storage.\n";
18001 return NULL;
18002 case CLI_GENERATE:
18003 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18004 }
18005 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18006 }
18007
18008
18009 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18010 {
18011 struct sip_peer *peer;
18012 int load_realtime;
18013
18014 if (argc < 4)
18015 return CLI_SHOWUSAGE;
18016
18017 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18018 if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
18019 sip_poke_peer(peer, 1);
18020 sip_unref_peer(peer, "qualify: done with peer");
18021 } else if (type == 0) {
18022 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
18023 } else {
18024 astman_send_error(s, m, "Peer not found");
18025 }
18026 return CLI_SUCCESS;
18027 }
18028
18029
18030 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
18031 {
18032 const char *a[4];
18033 const char *peer;
18034
18035 peer = astman_get_header(m, "Peer");
18036 if (ast_strlen_zero(peer)) {
18037 astman_send_error(s, m, "Peer: <name> missing.");
18038 return 0;
18039 }
18040 a[0] = "sip";
18041 a[1] = "qualify";
18042 a[2] = "peer";
18043 a[3] = peer;
18044
18045 _sip_qualify_peer(1, -1, s, m, 4, a);
18046 astman_append(s, "\r\n\r\n" );
18047 return 0;
18048 }
18049
18050
18051 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18052 {
18053 switch (cmd) {
18054 case CLI_INIT:
18055 e->command = "sip qualify peer";
18056 e->usage =
18057 "Usage: sip qualify peer <name> [load]\n"
18058 " Requests a response from one SIP peer and the current status.\n"
18059 " Option \"load\" forces lookup of peer in realtime storage.\n";
18060 return NULL;
18061 case CLI_GENERATE:
18062 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18063 }
18064 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18065 }
18066
18067
18068 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
18069 {
18070 struct sip_mailbox *mailbox;
18071
18072 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
18073 ast_str_append(mailbox_str, 0, "%s%s%s%s",
18074 mailbox->mailbox,
18075 ast_strlen_zero(mailbox->context) ? "" : "@",
18076 S_OR(mailbox->context, ""),
18077 AST_LIST_NEXT(mailbox, entry) ? "," : "");
18078 }
18079 }
18080
18081 static struct _map_x_s faxecmodes[] = {
18082 { SIP_PAGE2_T38SUPPORT_UDPTL, "None"},
18083 { SIP_PAGE2_T38SUPPORT_UDPTL_FEC, "FEC"},
18084 { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY, "Redundancy"},
18085 { -1, NULL},
18086 };
18087
18088 static const char *faxec2str(int faxec)
18089 {
18090 return map_x_s(faxecmodes, faxec, "Unknown");
18091 }
18092
18093
18094 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18095 {
18096 char status[30] = "";
18097 char cbuf[256];
18098 struct sip_peer *peer;
18099 char codec_buf[512];
18100 struct ast_codec_pref *pref;
18101 struct ast_variable *v;
18102 int x = 0, load_realtime;
18103 struct ast_format codec;
18104 int realtimepeers;
18105
18106 realtimepeers = ast_check_realtime("sippeers");
18107
18108 if (argc < 4)
18109 return CLI_SHOWUSAGE;
18110
18111 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18112 peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
18113
18114 if (s) {
18115 if (peer) {
18116 const char *id = astman_get_header(m, "ActionID");
18117
18118 astman_append(s, "Response: Success\r\n");
18119 if (!ast_strlen_zero(id))
18120 astman_append(s, "ActionID: %s\r\n", id);
18121 } else {
18122 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
18123 astman_send_error(s, m, cbuf);
18124 return CLI_SUCCESS;
18125 }
18126 }
18127 if (peer && type==0 ) {
18128 struct ast_str *mailbox_str = ast_str_alloca(512);
18129 struct sip_auth_container *credentials;
18130
18131 ao2_lock(peer);
18132 credentials = peer->auth;
18133 if (credentials) {
18134 ao2_t_ref(credentials, +1, "Ref peer auth for show");
18135 }
18136 ao2_unlock(peer);
18137
18138 ast_cli(fd, "\n\n");
18139 ast_cli(fd, " * Name : %s\n", peer->name);
18140 ast_cli(fd, " Description : %s\n", peer->description);
18141 if (realtimepeers) {
18142 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
18143 }
18144 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
18145 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
18146 ast_cli(fd, " Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
18147 if (credentials) {
18148 struct sip_auth *auth;
18149
18150 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18151 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s %s\n",
18152 auth->realm,
18153 auth->username,
18154 !ast_strlen_zero(auth->secret)
18155 ? "<Secret set>"
18156 : (!ast_strlen_zero(auth->md5secret)
18157 ? "<MD5secret set>" : "<Not set>"));
18158 }
18159 ao2_t_ref(credentials, -1, "Unref peer auth for show");
18160 }
18161 ast_cli(fd, " Context : %s\n", peer->context);
18162 ast_cli(fd, " Record On feature : %s\n", peer->record_on_feature);
18163 ast_cli(fd, " Record Off feature : %s\n", peer->record_off_feature);
18164 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
18165 ast_cli(fd, " Language : %s\n", peer->language);
18166 ast_cli(fd, " Tonezone : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
18167 if (!ast_strlen_zero(peer->accountcode))
18168 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
18169 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
18170 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
18171 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
18172 if (!ast_strlen_zero(peer->fromuser))
18173 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
18174 if (!ast_strlen_zero(peer->fromdomain))
18175 ast_cli(fd, " FromDomain : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18176 ast_cli(fd, " Callgroup : ");
18177 print_group(fd, peer->callgroup, 0);
18178 ast_cli(fd, " Pickupgroup : ");
18179 print_group(fd, peer->pickupgroup, 0);
18180 peer_mailboxes_to_str(&mailbox_str, peer);
18181 ast_cli(fd, " MOH Suggest : %s\n", peer->mohsuggest);
18182 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
18183 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
18184 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
18185 ast_cli(fd, " Max forwards : %d\n", peer->maxforwards);
18186 if (peer->busy_level)
18187 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
18188 ast_cli(fd, " Dynamic : %s\n", AST_CLI_YESNO(peer->host_dynamic));
18189 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
18190 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
18191 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
18192 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18193 ast_cli(fd, " Force rport : %s\n", force_rport_string(peer->flags));
18194 ast_cli(fd, " Symmetric RTP: %s\n", comedia_string(peer->flags));
18195 ast_cli(fd, " ACL : %s\n", AST_CLI_YESNO(peer->ha != NULL));
18196 ast_cli(fd, " DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
18197 ast_cli(fd, " T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18198 ast_cli(fd, " T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18199 ast_cli(fd, " T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
18200 ast_cli(fd, " DirectMedia : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
18201 ast_cli(fd, " PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
18202 ast_cli(fd, " User=Phone : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
18203 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)));
18204 ast_cli(fd, " Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
18205 ast_cli(fd, " Ign SDP ver : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18206 ast_cli(fd, " Trust RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
18207 ast_cli(fd, " Send RPID : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
18208 ast_cli(fd, " Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18209 ast_cli(fd, " Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18210 if (peer->outboundproxy)
18211 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
18212 peer->outboundproxy->force ? "(forced)" : "");
18213
18214
18215 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18216 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
18217 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
18218 ast_cli(fd, " ToHost : %s\n", peer->tohost);
18219 ast_cli(fd, " Addr->IP : %s\n", ast_sockaddr_stringify(&peer->addr));
18220 ast_cli(fd, " Defaddr->IP : %s\n", ast_sockaddr_stringify(&peer->defaddr));
18221 ast_cli(fd, " Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
18222 ast_cli(fd, " Allowed.Trsp : %s\n", get_transport_list(peer->transports));
18223 if (!ast_strlen_zero(sip_cfg.regcontext))
18224 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
18225 ast_cli(fd, " Def. Username: %s\n", peer->username);
18226 ast_cli(fd, " SIP Options : ");
18227 if (peer->sipoptions) {
18228 int lastoption = -1;
18229 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18230 if (sip_options[x].id != lastoption) {
18231 if (peer->sipoptions & sip_options[x].id)
18232 ast_cli(fd, "%s ", sip_options[x].text);
18233 lastoption = x;
18234 }
18235 }
18236 } else
18237 ast_cli(fd, "(none)");
18238
18239 ast_cli(fd, "\n");
18240 ast_cli(fd, " Codecs : ");
18241 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
18242 ast_cli(fd, "%s\n", codec_buf);
18243 ast_cli(fd, " Codec Order : (");
18244 print_codec_to_cli(fd, &peer->prefs);
18245 ast_cli(fd, ")\n");
18246
18247 ast_cli(fd, " Auto-Framing : %s \n", AST_CLI_YESNO(peer->autoframing));
18248 ast_cli(fd, " Status : ");
18249 peer_status(peer, status, sizeof(status));
18250 ast_cli(fd, "%s\n", status);
18251 ast_cli(fd, " Useragent : %s\n", peer->useragent);
18252 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
18253 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
18254 if (peer->chanvars) {
18255 ast_cli(fd, " Variables :\n");
18256 for (v = peer->chanvars ; v ; v = v->next)
18257 ast_cli(fd, " %s = %s\n", v->name, v->value);
18258 }
18259
18260 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
18261 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
18262 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
18263 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
18264 ast_cli(fd, " RTP Engine : %s\n", peer->engine);
18265 ast_cli(fd, " Parkinglot : %s\n", peer->parkinglot);
18266 ast_cli(fd, " Use Reason : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
18267 ast_cli(fd, " Encryption : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
18268 ast_cli(fd, "\n");
18269 peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
18270 } else if (peer && type == 1) {
18271 char buffer[256];
18272 struct ast_str *mailbox_str = ast_str_alloca(512);
18273 astman_append(s, "Channeltype: SIP\r\n");
18274 astman_append(s, "ObjectName: %s\r\n", peer->name);
18275 astman_append(s, "ChanObjectType: peer\r\n");
18276 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
18277 astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
18278 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
18279 astman_append(s, "Context: %s\r\n", peer->context);
18280 astman_append(s, "Language: %s\r\n", peer->language);
18281 astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
18282 if (!ast_strlen_zero(peer->accountcode))
18283 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
18284 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
18285 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
18286 if (!ast_strlen_zero(peer->fromuser))
18287 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
18288 if (!ast_strlen_zero(peer->fromdomain))
18289 astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18290 astman_append(s, "Callgroup: ");
18291 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
18292 astman_append(s, "Pickupgroup: ");
18293 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
18294 astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
18295 peer_mailboxes_to_str(&mailbox_str, peer);
18296 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
18297 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
18298 astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
18299 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
18300 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
18301 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
18302 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
18303 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
18304 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
18305 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18306 astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
18307 (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
18308 (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
18309 astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
18310 (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
18311 (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
18312 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
18313 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18314 astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18315 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
18316 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
18317 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
18318 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
18319 astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
18320 astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18321 astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
18322 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
18323 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
18324 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
18325 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
18326 astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
18327 astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
18328
18329
18330 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18331 astman_append(s, "ToHost: %s\r\n", peer->tohost);
18332 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
18333 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));
18334 astman_append(s, "Default-Username: %s\r\n", peer->username);
18335 if (!ast_strlen_zero(sip_cfg.regcontext))
18336 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
18337 astman_append(s, "Codecs: ");
18338 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
18339 astman_append(s, "%s\r\n", codec_buf);
18340 astman_append(s, "CodecOrder: ");
18341 pref = &peer->prefs;
18342 for(x = 0; x < AST_CODEC_PREF_SIZE ; x++) {
18343 if (!(ast_codec_pref_index(pref, x, &codec))) {
18344 break;
18345 }
18346 astman_append(s, "%s", ast_getformatname(&codec));
18347 if ((x < (AST_CODEC_PREF_SIZE - 1)) && ast_codec_pref_index(pref, x+1, &codec))
18348 astman_append(s, ",");
18349 }
18350
18351 astman_append(s, "\r\n");
18352 astman_append(s, "Status: ");
18353 peer_status(peer, status, sizeof(status));
18354 astman_append(s, "%s\r\n", status);
18355 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
18356 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
18357 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
18358 astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
18359 if (peer->chanvars) {
18360 for (v = peer->chanvars ; v ; v = v->next) {
18361 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
18362 }
18363 }
18364 astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
18365 astman_append(s, "Description: %s\r\n", peer->description);
18366
18367 peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
18368
18369 } else {
18370 ast_cli(fd, "Peer %s not found.\n", argv[3]);
18371 ast_cli(fd, "\n");
18372 }
18373
18374 return CLI_SUCCESS;
18375 }
18376
18377
18378 static char *complete_sip_user(const char *word, int state)
18379 {
18380 char *result = NULL;
18381 int wordlen = strlen(word);
18382 int which = 0;
18383 struct ao2_iterator user_iter;
18384 struct sip_peer *user;
18385
18386 user_iter = ao2_iterator_init(peers, 0);
18387 while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18388 ao2_lock(user);
18389 if (!(user->type & SIP_TYPE_USER)) {
18390 ao2_unlock(user);
18391 sip_unref_peer(user, "complete sip user");
18392 continue;
18393 }
18394
18395 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
18396 result = ast_strdup(user->name);
18397 }
18398 ao2_unlock(user);
18399 sip_unref_peer(user, "complete sip user");
18400 if (result) {
18401 break;
18402 }
18403 }
18404 ao2_iterator_destroy(&user_iter);
18405 return result;
18406 }
18407
18408 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
18409 {
18410 if (pos == 3)
18411 return complete_sip_user(word, state);
18412
18413 return NULL;
18414 }
18415
18416
18417 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18418 {
18419 char cbuf[256];
18420 struct sip_peer *user;
18421 struct ast_variable *v;
18422 int load_realtime;
18423
18424 switch (cmd) {
18425 case CLI_INIT:
18426 e->command = "sip show user";
18427 e->usage =
18428 "Usage: sip show user <name> [load]\n"
18429 " Shows all details on one SIP user and the current status.\n"
18430 " Option \"load\" forces lookup of peer in realtime storage.\n";
18431 return NULL;
18432 case CLI_GENERATE:
18433 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
18434 }
18435
18436 if (a->argc < 4)
18437 return CLI_SHOWUSAGE;
18438
18439
18440 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
18441
18442 if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
18443 ao2_lock(user);
18444 ast_cli(a->fd, "\n\n");
18445 ast_cli(a->fd, " * Name : %s\n", user->name);
18446 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
18447 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
18448 ast_cli(a->fd, " Context : %s\n", user->context);
18449 ast_cli(a->fd, " Language : %s\n", user->language);
18450 if (!ast_strlen_zero(user->accountcode))
18451 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
18452 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
18453 ast_cli(a->fd, " Tonezone : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
18454 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
18455 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
18456 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
18457 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
18458 ast_cli(a->fd, " Callgroup : ");
18459 print_group(a->fd, user->callgroup, 0);
18460 ast_cli(a->fd, " Pickupgroup : ");
18461 print_group(a->fd, user->pickupgroup, 0);
18462 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
18463 ast_cli(a->fd, " ACL : %s\n", AST_CLI_YESNO(user->ha != NULL));
18464 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
18465 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
18466 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
18467 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
18468 ast_cli(a->fd, " RTP Engine : %s\n", user->engine);
18469
18470 ast_cli(a->fd, " Codec Order : (");
18471 print_codec_to_cli(a->fd, &user->prefs);
18472 ast_cli(a->fd, ")\n");
18473
18474 ast_cli(a->fd, " Auto-Framing: %s \n", AST_CLI_YESNO(user->autoframing));
18475 if (user->chanvars) {
18476 ast_cli(a->fd, " Variables :\n");
18477 for (v = user->chanvars ; v ; v = v->next)
18478 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
18479 }
18480
18481 ast_cli(a->fd, "\n");
18482
18483 ao2_unlock(user);
18484 sip_unref_peer(user, "sip show user");
18485 } else {
18486 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
18487 ast_cli(a->fd, "\n");
18488 }
18489
18490 return CLI_SUCCESS;
18491 }
18492
18493
18494 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18495 {
18496 struct ast_str *cbuf;
18497 struct ast_cb_names cbnames = {9, { "retrans_pkt",
18498 "__sip_autodestruct",
18499 "expire_register",
18500 "auto_congest",
18501 "sip_reg_timeout",
18502 "sip_poke_peer_s",
18503 "sip_poke_noanswer",
18504 "sip_reregister",
18505 "sip_reinvite_retry"},
18506 { retrans_pkt,
18507 __sip_autodestruct,
18508 expire_register,
18509 auto_congest,
18510 sip_reg_timeout,
18511 sip_poke_peer_s,
18512 sip_poke_noanswer,
18513 sip_reregister,
18514 sip_reinvite_retry}};
18515
18516 switch (cmd) {
18517 case CLI_INIT:
18518 e->command = "sip show sched";
18519 e->usage =
18520 "Usage: sip show sched\n"
18521 " Shows stats on what's in the sched queue at the moment\n";
18522 return NULL;
18523 case CLI_GENERATE:
18524 return NULL;
18525 }
18526
18527 cbuf = ast_str_alloca(2048);
18528
18529 ast_cli(a->fd, "\n");
18530 ast_sched_report(sched, &cbuf, &cbnames);
18531 ast_cli(a->fd, "%s", cbuf->str);
18532
18533 return CLI_SUCCESS;
18534 }
18535
18536
18537 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18538 {
18539 #define FORMAT2 "%-39.39s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
18540 #define FORMAT "%-39.39s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
18541 char host[80];
18542 char user[80];
18543 char tmpdat[256];
18544 struct ast_tm tm;
18545 int counter = 0;
18546
18547 switch (cmd) {
18548 case CLI_INIT:
18549 e->command = "sip show registry";
18550 e->usage =
18551 "Usage: sip show registry\n"
18552 " Lists all registration requests and status.\n";
18553 return NULL;
18554 case CLI_GENERATE:
18555 return NULL;
18556 }
18557
18558 if (a->argc != 3)
18559 return CLI_SHOWUSAGE;
18560 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18561
18562 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
18563 ASTOBJ_RDLOCK(iterator);
18564 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18565 snprintf(user, sizeof(user), "%s", iterator->username);
18566 if (!ast_strlen_zero(iterator->regdomain)) {
18567 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18568 snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18569 if (iterator->regdomainport) {
18570 snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18571 snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18572 if (iterator->regtime.tv_sec) {
18573 ast_localtime(&iterator->regtime, &tm, NULL);
18574 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18575 } else
18576 tmpdat[0] = '\0';
18577 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18578 ASTOBJ_UNLOCK(iterator);
18579 counter++;
18580 } while(0));
18581 ast_cli(a->fd, "%d SIP registrations.\n", counter);
18582 return CLI_SUCCESS;
18583 #undef FORMAT
18584 #undef FORMAT2
18585 }
18586
18587
18588
18589
18590
18591 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18592 {
18593 struct sip_peer *peer;
18594 int load_realtime = 0;
18595
18596 switch (cmd) {
18597 case CLI_INIT:
18598 e->command = "sip unregister";
18599 e->usage =
18600 "Usage: sip unregister <peer>\n"
18601 " Unregister (force expiration) a SIP peer from the registry\n";
18602 return NULL;
18603 case CLI_GENERATE:
18604 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18605 }
18606
18607 if (a->argc != 3)
18608 return CLI_SHOWUSAGE;
18609
18610 if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18611 if (peer->expire > 0) {
18612 AST_SCHED_DEL_UNREF(sched, peer->expire,
18613 sip_unref_peer(peer, "remove register expire ref"));
18614 expire_register(sip_ref_peer(peer, "ref for expire_register"));
18615 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18616 } else {
18617 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18618 }
18619 sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
18620 } else {
18621 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18622 }
18623
18624 return CLI_SUCCESS;
18625 }
18626
18627
18628 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18629 {
18630 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s ( %%) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
18631 #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"
18632 struct sip_pvt *cur = __cur;
18633 struct ast_rtp_instance_stats stats;
18634 char durbuf[10];
18635 int duration;
18636 int durh, durm, durs;
18637 struct ast_channel *c = cur->owner;
18638 struct __show_chan_arg *arg = __arg;
18639 int fd = arg->fd;
18640
18641
18642 if (cur->subscribed != NONE)
18643 return 0;
18644
18645 if (!cur->rtp) {
18646 if (sipdebug) {
18647 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n",
18648 ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18649 invitestate2string[cur->invitestate].desc,
18650 "-- No RTP active");
18651 }
18652 return 0;
18653 }
18654
18655 ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL);
18656
18657 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18658 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18659 durh = duration / 3600;
18660 durm = (duration % 3600) / 60;
18661 durs = duration % 60;
18662 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18663 } else {
18664 durbuf[0] = '\0';
18665 }
18666
18667 ast_cli(fd, FORMAT,
18668 ast_sockaddr_stringify_addr(&cur->sa),
18669 cur->callid,
18670 durbuf,
18671 stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18672 stats.rxcount > (unsigned int) 100000 ? "K":" ",
18673 stats.rxploss,
18674 (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18675 stats.rxjitter,
18676 stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18677 stats.txcount > (unsigned int) 100000 ? "K":" ",
18678 stats.txploss,
18679 stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18680 stats.txjitter
18681 );
18682 arg->numchans++;
18683
18684 return 0;
18685 }
18686
18687
18688 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18689 {
18690 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18691
18692 switch (cmd) {
18693 case CLI_INIT:
18694 e->command = "sip show channelstats";
18695 e->usage =
18696 "Usage: sip show channelstats\n"
18697 " Lists all currently active SIP channel's RTCP statistics.\n"
18698 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18699 return NULL;
18700 case CLI_GENERATE:
18701 return NULL;
18702 }
18703
18704 if (a->argc != 3)
18705 return CLI_SHOWUSAGE;
18706
18707 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18708
18709 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18710 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18711 return CLI_SUCCESS;
18712 }
18713 #undef FORMAT
18714 #undef FORMAT2
18715
18716
18717 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18718 {
18719 int realtimepeers;
18720 int realtimeregs;
18721 char codec_buf[SIPBUFSIZE];
18722 const char *msg;
18723 struct sip_auth_container *credentials;
18724
18725 switch (cmd) {
18726 case CLI_INIT:
18727 e->command = "sip show settings";
18728 e->usage =
18729 "Usage: sip show settings\n"
18730 " Provides detailed list of the configuration of the SIP channel.\n";
18731 return NULL;
18732 case CLI_GENERATE:
18733 return NULL;
18734 }
18735
18736 if (a->argc != 3)
18737 return CLI_SHOWUSAGE;
18738
18739 realtimepeers = ast_check_realtime("sippeers");
18740 realtimeregs = ast_check_realtime("sipregs");
18741
18742 ast_mutex_lock(&authl_lock);
18743 credentials = authl;
18744 if (credentials) {
18745 ao2_t_ref(credentials, +1, "Ref global auth for show");
18746 }
18747 ast_mutex_unlock(&authl_lock);
18748
18749 ast_cli(a->fd, "\n\nGlobal Settings:\n");
18750 ast_cli(a->fd, "----------------\n");
18751 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_sockaddr_stringify(&bindaddr));
18752 if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18753 ast_cli(a->fd, " ** Additional Info:\n");
18754 ast_cli(a->fd, " [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18755 }
18756 ast_cli(a->fd, " TCP SIP Bindaddress: %s\n",
18757 sip_cfg.tcp_enabled != FALSE ?
18758 ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18759 "Disabled");
18760 ast_cli(a->fd, " TLS SIP Bindaddress: %s\n",
18761 default_tls_cfg.enabled != FALSE ?
18762 ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18763 "Disabled");
18764 ast_cli(a->fd, " Videosupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18765 ast_cli(a->fd, " Textsupport: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18766 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18767 ast_cli(a->fd, " AutoCreate Peer: %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
18768 ast_cli(a->fd, " Match Auth Username: %s\n", AST_CLI_YESNO(global_match_auth_username));
18769 ast_cli(a->fd, " Allow unknown access: %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18770 ast_cli(a->fd, " Allow subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18771 ast_cli(a->fd, " Allow overlap dialing: %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18772 ast_cli(a->fd, " Allow promisc. redir: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18773 ast_cli(a->fd, " Enable call counters: %s\n", AST_CLI_YESNO(global_callcounter));
18774 ast_cli(a->fd, " SIP domain support: %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18775 ast_cli(a->fd, " Realm. auth: %s\n", AST_CLI_YESNO(credentials != NULL));
18776 if (credentials) {
18777 struct sip_auth *auth;
18778
18779 AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18780 ast_cli(a->fd, " Realm. auth entry: Realm %-15.15s User %-10.20s %s\n",
18781 auth->realm,
18782 auth->username,
18783 !ast_strlen_zero(auth->secret)
18784 ? "<Secret set>"
18785 : (!ast_strlen_zero(auth->md5secret)
18786 ? "<MD5secret set>" : "<Not set>"));
18787 }
18788 ao2_t_ref(credentials, -1, "Unref global auth for show");
18789 }
18790 ast_cli(a->fd, " Our auth realm %s\n", sip_cfg.realm);
18791 ast_cli(a->fd, " Use domains as realms: %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18792 ast_cli(a->fd, " Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18793 ast_cli(a->fd, " URI user is phone no: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18794 ast_cli(a->fd, " Always auth rejects: %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18795 ast_cli(a->fd, " Direct RTP setup: %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18796 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
18797 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18798 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18799 ast_cli(a->fd, " Reg. context: %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18800 ast_cli(a->fd, " Regexten on Qualify: %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18801 ast_cli(a->fd, " Trust RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
18802 ast_cli(a->fd, " Send RPID: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
18803 ast_cli(a->fd, " Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18804 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
18805 if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18806 ast_cli(a->fd, " From: Domain: %s:%d\n", default_fromdomain, default_fromdomainport);
18807 } else {
18808 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
18809 }
18810 ast_cli(a->fd, " Record SIP history: %s\n", AST_CLI_ONOFF(recordhistory));
18811 ast_cli(a->fd, " Call Events: %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18812 ast_cli(a->fd, " Auth. Failure Events: %s\n", AST_CLI_ONOFF(global_authfailureevents));
18813
18814 ast_cli(a->fd, " T.38 support: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18815 ast_cli(a->fd, " T.38 EC mode: %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18816 ast_cli(a->fd, " T.38 MaxDtgrm: %d\n", global_t38_maxdatagram);
18817 if (!realtimepeers && !realtimeregs)
18818 ast_cli(a->fd, " SIP realtime: Disabled\n" );
18819 else
18820 ast_cli(a->fd, " SIP realtime: Enabled\n" );
18821 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
18822 ast_cli(a->fd, " Q.850 Reason header: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18823 ast_cli(a->fd, " Store SIP_CAUSE: %s\n", AST_CLI_YESNO(global_store_sip_cause));
18824 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18825 ast_cli(a->fd, "---------------------------\n");
18826 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
18827 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
18828 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
18829 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
18830 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
18831 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
18832 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
18833 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
18834 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18835 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18836 ast_cli(a->fd, " Jitterbuffer forced: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18837 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
18838 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
18839 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
18840 if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18841 ast_cli(a->fd, " Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18842 }
18843 ast_cli(a->fd, " Jitterbuffer log: %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18844 }
18845
18846 ast_cli(a->fd, "\nNetwork Settings:\n");
18847 ast_cli(a->fd, "---------------------------\n");
18848
18849 if (localaddr == NULL)
18850 msg = "Disabled, no localnet list";
18851 else if (ast_sockaddr_isnull(&externaddr))
18852 msg = "Disabled";
18853 else if (!ast_strlen_zero(externhost))
18854 msg = "Enabled using externhost";
18855 else
18856 msg = "Enabled using externaddr";
18857 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
18858 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
18859 ast_cli(a->fd, " Externaddr: %s\n", ast_sockaddr_stringify(&externaddr));
18860 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
18861 {
18862 struct ast_ha *d;
18863 const char *prefix = "Localnet:";
18864
18865 for (d = localaddr; d ; prefix = "", d = d->next) {
18866 const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18867 const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18868 ast_cli(a->fd, " %-24s%s/%s\n", prefix, addr, mask);
18869 }
18870 }
18871 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18872 ast_cli(a->fd, "---------------------------\n");
18873 ast_cli(a->fd, " Codecs: ");
18874 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.caps);
18875 ast_cli(a->fd, "%s\n", codec_buf);
18876 ast_cli(a->fd, " Codec Order: ");
18877 print_codec_to_cli(a->fd, &default_prefs);
18878 ast_cli(a->fd, "\n");
18879 ast_cli(a->fd, " Relax DTMF: %s\n", AST_CLI_YESNO(global_relaxdtmf));
18880 ast_cli(a->fd, " RFC2833 Compensation: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18881 ast_cli(a->fd, " Symmetric RTP: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18882 ast_cli(a->fd, " Compact SIP headers: %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18883 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18884 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18885 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18886 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
18887 ast_cli(a->fd, " DNS SRV lookup: %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18888 ast_cli(a->fd, " Pedantic SIP support: %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18889 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
18890 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
18891 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
18892 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
18893 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
18894 ast_cli(a->fd, " Notify ringing state: %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18895 if (sip_cfg.notifyringing) {
18896 ast_cli(a->fd, " Include CID: %s%s\n",
18897 AST_CLI_YESNO(sip_cfg.notifycid),
18898 sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18899 }
18900 ast_cli(a->fd, " Notify hold state: %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18901 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(sip_cfg.allowtransfer));
18902 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
18903 ast_cli(a->fd, " Auto-Framing: %s\n", AST_CLI_YESNO(global_autoframing));
18904 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18905 sip_cfg.outboundproxy.force ? "(forced)" : "");
18906 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
18907 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
18908 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
18909 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
18910 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
18911 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
18912 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
18913 ast_cli(a->fd, " No premature media: %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18914 ast_cli(a->fd, " Max forwards: %d\n", sip_cfg.default_max_forwards);
18915
18916 ast_cli(a->fd, "\nDefault Settings:\n");
18917 ast_cli(a->fd, "-----------------\n");
18918 ast_cli(a->fd, " Allowed transports: %s\n", get_transport_list(default_transports));
18919 ast_cli(a->fd, " Outbound transport: %s\n", sip_get_transport(default_primary_transport));
18920 ast_cli(a->fd, " Context: %s\n", sip_cfg.default_context);
18921 ast_cli(a->fd, " Record on feature: %s\n", sip_cfg.default_record_on_feature);
18922 ast_cli(a->fd, " Record off feature: %s\n", sip_cfg.default_record_off_feature);
18923 ast_cli(a->fd, " Force rport: %s\n", force_rport_string(global_flags));
18924 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18925 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
18926 ast_cli(a->fd, " Use ClientCode: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18927 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)));
18928 ast_cli(a->fd, " Language: %s\n", default_language);
18929 ast_cli(a->fd, " Tone zone: %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
18930 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
18931 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
18932 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
18933
18934
18935 if (realtimepeers || realtimeregs) {
18936 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18937 ast_cli(a->fd, "----------------------\n");
18938 ast_cli(a->fd, " Realtime Peers: %s\n", AST_CLI_YESNO(realtimepeers));
18939 ast_cli(a->fd, " Realtime Regs: %s\n", AST_CLI_YESNO(realtimeregs));
18940 ast_cli(a->fd, " Cache Friends: %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18941 ast_cli(a->fd, " Update: %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18942 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18943 ast_cli(a->fd, " Save sys. name: %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18944 ast_cli(a->fd, " Auto Clear: %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18945 }
18946 ast_cli(a->fd, "\n----\n");
18947 return CLI_SUCCESS;
18948 }
18949
18950 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18951 {
18952 #define FORMAT "%-30.30s %-12.12s %-10.10s %-10.10s\n"
18953 char host[80];
18954
18955 switch (cmd) {
18956 case CLI_INIT:
18957 e->command = "sip show mwi";
18958 e->usage =
18959 "Usage: sip show mwi\n"
18960 " Provides a list of MWI subscriptions and status.\n";
18961 return NULL;
18962 case CLI_GENERATE:
18963 return NULL;
18964 }
18965
18966 ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18967
18968 ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18969 ASTOBJ_RDLOCK(iterator);
18970 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18971 ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18972 ASTOBJ_UNLOCK(iterator);
18973 } while(0));
18974
18975 return CLI_SUCCESS;
18976 #undef FORMAT
18977 }
18978
18979
18980
18981 static const char *subscription_type2str(enum subscriptiontype subtype)
18982 {
18983 int i;
18984
18985 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18986 if (subscription_types[i].type == subtype) {
18987 return subscription_types[i].text;
18988 }
18989 }
18990 return subscription_types[0].text;
18991 }
18992
18993
18994 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18995 {
18996 int i;
18997
18998 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18999 if (subscription_types[i].type == subtype) {
19000 return &subscription_types[i];
19001 }
19002 }
19003 return &subscription_types[0];
19004 }
19005
19006
19007
19008
19009
19010
19011
19012
19013 #define FORMAT4 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
19014 #define FORMAT3 "%-15.15s %-15.15s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
19015 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %-7.7s %-15.15s %-10.10s %-10.10s\n"
19016 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s %-10.10s\n"
19017
19018
19019 static int show_channels_cb(void *__cur, void *__arg, int flags)
19020 {
19021 struct sip_pvt *cur = __cur;
19022 struct __show_chan_arg *arg = __arg;
19023 const struct ast_sockaddr *dst = sip_real_dst(cur);
19024
19025
19026 if (cur->subscribed == NONE && !arg->subscriptions) {
19027
19028 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
19029 char formatbuf[SIPBUFSIZE/2];
19030
19031 ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
19032 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19033 cur->callid,
19034 cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner->nativeformats) : "(nothing)",
19035 AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
19036 cur->needdestroy ? "(d)" : "",
19037 cur->lastmsg ,
19038 referstatus,
19039 cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
19040 );
19041 arg->numchans++;
19042 }
19043 if (cur->subscribed != NONE && arg->subscriptions) {
19044 struct ast_str *mailbox_str = ast_str_alloca(512);
19045 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
19046 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
19047 ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
19048 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19049 cur->callid,
19050
19051 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
19052 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
19053 subscription_type2str(cur->subscribed),
19054 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
19055 cur->expiry
19056 );
19057 arg->numchans++;
19058 }
19059 return 0;
19060 }
19061
19062
19063
19064
19065
19066
19067 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19068 {
19069 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
19070
19071
19072 if (cmd == CLI_INIT) {
19073 e->command = "sip show {channels|subscriptions}";
19074 e->usage =
19075 "Usage: sip show channels\n"
19076 " Lists all currently active SIP calls (dialogs).\n"
19077 "Usage: sip show subscriptions\n"
19078 " Lists active SIP subscriptions.\n";
19079 return NULL;
19080 } else if (cmd == CLI_GENERATE)
19081 return NULL;
19082
19083 if (a->argc != e->args)
19084 return CLI_SHOWUSAGE;
19085 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
19086 if (!arg.subscriptions)
19087 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
19088 else
19089 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
19090
19091
19092 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
19093
19094
19095 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
19096 (arg.subscriptions ? "subscription" : "dialog"),
19097 ESS(arg.numchans));
19098 return CLI_SUCCESS;
19099 #undef FORMAT
19100 #undef FORMAT2
19101 #undef FORMAT3
19102 }
19103
19104
19105
19106
19107
19108
19109 static char *complete_sipch(const char *line, const char *word, int pos, int state)
19110 {
19111 int which=0;
19112 struct sip_pvt *cur;
19113 char *c = NULL;
19114 int wordlen = strlen(word);
19115 struct ao2_iterator i;
19116
19117 if (pos != 3) {
19118 return NULL;
19119 }
19120
19121 i = ao2_iterator_init(dialogs, 0);
19122 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19123 sip_pvt_lock(cur);
19124 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
19125 c = ast_strdup(cur->callid);
19126 sip_pvt_unlock(cur);
19127 dialog_unref(cur, "drop ref in iterator loop break");
19128 break;
19129 }
19130 sip_pvt_unlock(cur);
19131 dialog_unref(cur, "drop ref in iterator loop");
19132 }
19133 ao2_iterator_destroy(&i);
19134 return c;
19135 }
19136
19137
19138
19139 static char *complete_sip_peer(const char *word, int state, int flags2)
19140 {
19141 char *result = NULL;
19142 int wordlen = strlen(word);
19143 int which = 0;
19144 struct ao2_iterator i = ao2_iterator_init(peers, 0);
19145 struct sip_peer *peer;
19146
19147 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19148
19149 if (!strncasecmp(word, peer->name, wordlen) &&
19150 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19151 ++which > state)
19152 result = ast_strdup(peer->name);
19153 sip_unref_peer(peer, "toss iterator peer ptr before break");
19154 if (result) {
19155 break;
19156 }
19157 }
19158 ao2_iterator_destroy(&i);
19159 return result;
19160 }
19161
19162
19163 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
19164 {
19165 char *result = NULL;
19166 int wordlen = strlen(word);
19167 int which = 0;
19168 struct ao2_iterator i;
19169 struct sip_peer *peer;
19170
19171 i = ao2_iterator_init(peers, 0);
19172 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19173 if (!strncasecmp(word, peer->name, wordlen) &&
19174 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19175 ++which > state && peer->expire > 0)
19176 result = ast_strdup(peer->name);
19177 if (result) {
19178 sip_unref_peer(peer, "toss iterator peer ptr before break");
19179 break;
19180 }
19181 sip_unref_peer(peer, "toss iterator peer ptr");
19182 }
19183 ao2_iterator_destroy(&i);
19184 return result;
19185 }
19186
19187
19188 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
19189 {
19190 if (pos == 3)
19191 return complete_sipch(line, word, pos, state);
19192
19193 return NULL;
19194 }
19195
19196
19197 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
19198 {
19199 if (pos == 3) {
19200 return complete_sip_peer(word, state, 0);
19201 }
19202
19203 return NULL;
19204 }
19205
19206
19207 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
19208 {
19209 if (pos == 2)
19210 return complete_sip_registered_peer(word, state, 0);
19211
19212 return NULL;
19213 }
19214
19215
19216 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
19217 {
19218 char *c = NULL;
19219
19220 if (pos == 2) {
19221 int which = 0;
19222 char *cat = NULL;
19223 int wordlen = strlen(word);
19224
19225
19226
19227 if (!notify_types)
19228 return NULL;
19229
19230 while ( (cat = ast_category_browse(notify_types, cat)) ) {
19231 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
19232 c = ast_strdup(cat);
19233 break;
19234 }
19235 }
19236 return c;
19237 }
19238
19239 if (pos > 2)
19240 return complete_sip_peer(word, state, 0);
19241
19242 return NULL;
19243 }
19244
19245
19246 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19247 {
19248 struct sip_pvt *cur;
19249 size_t len;
19250 int found = 0;
19251 struct ao2_iterator i;
19252
19253 switch (cmd) {
19254 case CLI_INIT:
19255 e->command = "sip show channel";
19256 e->usage =
19257 "Usage: sip show channel <call-id>\n"
19258 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
19259 return NULL;
19260 case CLI_GENERATE:
19261 return complete_sipch(a->line, a->word, a->pos, a->n);
19262 }
19263
19264 if (a->argc != 4)
19265 return CLI_SHOWUSAGE;
19266 len = strlen(a->argv[3]);
19267
19268 i = ao2_iterator_init(dialogs, 0);
19269 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19270 sip_pvt_lock(cur);
19271
19272 if (!strncasecmp(cur->callid, a->argv[3], len)) {
19273 char formatbuf[SIPBUFSIZE/2];
19274 ast_cli(a->fd, "\n");
19275 if (cur->subscribed != NONE) {
19276 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
19277 } else {
19278 ast_cli(a->fd, " * SIP Call\n");
19279 }
19280 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
19281 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
19282 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
19283 ast_cli(a->fd, " Our Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->caps));
19284 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
19285 ast_cli(a->fd, " Their Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercaps));
19286 ast_cli(a->fd, " Joint Codec Capability: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcaps));
19287 ast_cli(a->fd, " Format: %s\n", cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner->nativeformats) : "(nothing)" );
19288 ast_cli(a->fd, " T.38 support %s\n", AST_CLI_YESNO(cur->udptl != NULL));
19289 ast_cli(a->fd, " Video support %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
19290 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
19291 ast_cli(a->fd, " Theoretical Address: %s\n", ast_sockaddr_stringify(&cur->sa));
19292 ast_cli(a->fd, " Received Address: %s\n", ast_sockaddr_stringify(&cur->recv));
19293 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
19294 ast_cli(a->fd, " Force rport: %s\n", force_rport_string(cur->flags));
19295 if (ast_sockaddr_isnull(&cur->redirip)) {
19296 ast_cli(a->fd,
19297 " Audio IP: %s (local)\n",
19298 ast_sockaddr_stringify_addr(&cur->ourip));
19299 } else {
19300 ast_cli(a->fd,
19301 " Audio IP: %s (Outside bridge)\n",
19302 ast_sockaddr_stringify_addr(&cur->redirip));
19303 }
19304 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
19305 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
19306 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
19307 if (!ast_strlen_zero(cur->username)) {
19308 ast_cli(a->fd, " Username: %s\n", cur->username);
19309 }
19310 if (!ast_strlen_zero(cur->peername)) {
19311 ast_cli(a->fd, " Peername: %s\n", cur->peername);
19312 }
19313 if (!ast_strlen_zero(cur->uri)) {
19314 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
19315 }
19316 if (!ast_strlen_zero(cur->cid_num)) {
19317 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
19318 }
19319 ast_cli(a->fd, " Need Destroy: %s\n", AST_CLI_YESNO(cur->needdestroy));
19320 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
19321 ast_cli(a->fd, " Promiscuous Redir: %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
19322 ast_cli(a->fd, " Route: ");
19323 if (cur->route) {
19324 struct sip_route *route;
19325 int first = 1;
19326
19327 for (route = cur->route; route; route = route->next) {
19328 ast_cli(a->fd, "%s<%s>", first ? "" : ", ", route->hop);
19329 first = 0;
19330 }
19331 ast_cli(a->fd, "\n");
19332 } else {
19333 ast_cli(a->fd, "N/A\n");
19334 }
19335 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
19336 ast_cli(a->fd, " SIP Options: ");
19337 if (cur->sipoptions) {
19338 int x;
19339 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
19340 if (cur->sipoptions & sip_options[x].id)
19341 ast_cli(a->fd, "%s ", sip_options[x].text);
19342 }
19343 ast_cli(a->fd, "\n");
19344 } else {
19345 ast_cli(a->fd, "(none)\n");
19346 }
19347
19348 if (!cur->stimer) {
19349 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
19350 } else {
19351 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
19352 if (cur->stimer->st_active == TRUE) {
19353 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
19354 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
19355 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
19356 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
19357 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
19358 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
19359 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
19360 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
19361 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
19362 }
19363 }
19364
19365 ast_cli(a->fd, "\n\n");
19366
19367 found++;
19368 }
19369
19370 sip_pvt_unlock(cur);
19371
19372 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
19373 }
19374 ao2_iterator_destroy(&i);
19375
19376 if (!found) {
19377 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19378 }
19379
19380 return CLI_SUCCESS;
19381 }
19382
19383
19384 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19385 {
19386 struct sip_pvt *cur;
19387 size_t len;
19388 int found = 0;
19389 struct ao2_iterator i;
19390
19391 switch (cmd) {
19392 case CLI_INIT:
19393 e->command = "sip show history";
19394 e->usage =
19395 "Usage: sip show history <call-id>\n"
19396 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
19397 return NULL;
19398 case CLI_GENERATE:
19399 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
19400 }
19401
19402 if (a->argc != 4) {
19403 return CLI_SHOWUSAGE;
19404 }
19405
19406 if (!recordhistory) {
19407 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
19408 }
19409
19410 len = strlen(a->argv[3]);
19411
19412 i = ao2_iterator_init(dialogs, 0);
19413 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19414 sip_pvt_lock(cur);
19415 if (!strncasecmp(cur->callid, a->argv[3], len)) {
19416 struct sip_history *hist;
19417 int x = 0;
19418
19419 ast_cli(a->fd, "\n");
19420 if (cur->subscribed != NONE) {
19421 ast_cli(a->fd, " * Subscription\n");
19422 } else {
19423 ast_cli(a->fd, " * SIP Call\n");
19424 }
19425 if (cur->history) {
19426 AST_LIST_TRAVERSE(cur->history, hist, list)
19427 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
19428 }
19429 if (x == 0) {
19430 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
19431 }
19432 found++;
19433 }
19434 sip_pvt_unlock(cur);
19435 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
19436 }
19437 ao2_iterator_destroy(&i);
19438
19439 if (!found) {
19440 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19441 }
19442
19443 return CLI_SUCCESS;
19444 }
19445
19446
19447 static void sip_dump_history(struct sip_pvt *dialog)
19448 {
19449 int x = 0;
19450 struct sip_history *hist;
19451 static int errmsg = 0;
19452
19453 if (!dialog) {
19454 return;
19455 }
19456
19457 if (!option_debug && !sipdebug) {
19458 if (!errmsg) {
19459 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
19460 errmsg = 1;
19461 }
19462 return;
19463 }
19464
19465 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
19466 if (dialog->subscribed) {
19467 ast_debug(1, " * Subscription\n");
19468 } else {
19469 ast_debug(1, " * SIP Call\n");
19470 }
19471 if (dialog->history) {
19472 AST_LIST_TRAVERSE(dialog->history, hist, list)
19473 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
19474 }
19475 if (!x) {
19476 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
19477 }
19478 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
19479 }
19480
19481
19482
19483 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
19484 {
19485 char buf[1024] = "";
19486 unsigned int event;
19487 const char *c = sip_get_header(req, "Content-Type");
19488
19489
19490 if (!strcasecmp(c, "application/dtmf-relay") ||
19491 !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
19492 !strcasecmp(c, "application/dtmf")) {
19493 unsigned int duration = 0;
19494
19495 if (!p->owner) {
19496 transmit_response(p, "481 Call leg/transaction does not exist", req);
19497 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19498 return;
19499 }
19500
19501
19502
19503 if (strcasecmp(c, "application/dtmf")) {
19504 const char *msg_body;
19505
19506 if ( ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
19507 && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
19508 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
19509 "call %s\n", p->callid);
19510 transmit_response(p, "200 OK", req);
19511 return;
19512 }
19513 ast_copy_string(buf, msg_body, sizeof(buf));
19514
19515 if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
19516 sscanf(msg_body, "%30u", &duration);
19517 }
19518 } else {
19519
19520 get_msg_text(buf, sizeof(buf), req);
19521 }
19522
19523
19524 if (ast_strlen_zero(buf)) {
19525 transmit_response(p, "200 OK", req);
19526 return;
19527 }
19528
19529 if (!duration) {
19530 duration = 100;
19531 }
19532
19533 if (buf[0] == '*') {
19534 event = 10;
19535 } else if (buf[0] == '#') {
19536 event = 11;
19537 } else if (buf[0] == '!') {
19538 event = 16;
19539 } else if ('A' <= buf[0] && buf[0] <= 'D') {
19540 event = 12 + buf[0] - 'A';
19541 } else if ('a' <= buf[0] && buf[0] <= 'd') {
19542 event = 12 + buf[0] - 'a';
19543 } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19544 ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19545 "value for INFO message on call %s\n", p->callid);
19546 transmit_response(p, "200 OK", req);
19547 return;
19548 }
19549
19550 if (event == 16) {
19551
19552 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19553 ast_queue_frame(p->owner, &f);
19554 if (sipdebug) {
19555 ast_verbose("* DTMF-relay event received: FLASH\n");
19556 }
19557 } else {
19558
19559 struct ast_frame f = { AST_FRAME_DTMF, };
19560 if (event < 10) {
19561 f.subclass.integer = '0' + event;
19562 } else if (event == 10) {
19563 f.subclass.integer = '*';
19564 } else if (event == 11) {
19565 f.subclass.integer = '#';
19566 } else {
19567 f.subclass.integer = 'A' + (event - 12);
19568 }
19569 f.len = duration;
19570 ast_queue_frame(p->owner, &f);
19571 if (sipdebug) {
19572 ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19573 }
19574 }
19575 transmit_response(p, "200 OK", req);
19576 return;
19577 } else if (!strcasecmp(c, "application/media_control+xml")) {
19578
19579 if (p->owner) {
19580 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19581 }
19582 transmit_response(p, "200 OK", req);
19583 return;
19584 } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
19585
19586 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19587 if (p->owner && p->owner->cdr) {
19588 ast_cdr_setuserfield(p->owner, c);
19589 }
19590 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr) {
19591 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19592 }
19593 transmit_response(p, "200 OK", req);
19594 } else {
19595 transmit_response(p, "403 Forbidden", req);
19596 }
19597 return;
19598 } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
19599
19600
19601
19602
19603 struct ast_call_feature *feat = NULL;
19604 int j;
19605 struct ast_frame f = { AST_FRAME_DTMF, };
19606 int suppress_warning = 0;
19607
19608 if (!p->owner) {
19609 transmit_response(p, "481 Call leg/transaction does not exist", req);
19610 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19611 return;
19612 }
19613
19614
19615 ast_rdlock_call_features();
19616 if (p->relatedpeer) {
19617 if (!strcasecmp(c, "on")) {
19618 if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
19619 suppress_warning = 1;
19620 } else {
19621 feat = ast_find_call_feature(p->relatedpeer->record_on_feature);
19622 }
19623 } else if (!strcasecmp(c, "off")) {
19624 if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
19625 suppress_warning = 1;
19626 } else {
19627 feat = ast_find_call_feature(p->relatedpeer->record_off_feature);
19628 }
19629 } else {
19630 ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
19631 }
19632 }
19633 if (!feat || ast_strlen_zero(feat->exten)) {
19634 if (!suppress_warning) {
19635 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19636 }
19637
19638 transmit_response(p, "403 Forbidden", req);
19639 ast_unlock_call_features();
19640 return;
19641 }
19642
19643 f.len = 100;
19644 for (j=0; j < strlen(feat->exten); j++) {
19645 f.subclass.integer = feat->exten[j];
19646 ast_queue_frame(p->owner, &f);
19647 if (sipdebug) {
19648 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19649 }
19650 }
19651 ast_unlock_call_features();
19652
19653 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19654 transmit_response(p, "200 OK", req);
19655 return;
19656 } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19657
19658 transmit_response(p, "200 OK", req);
19659 return;
19660 }
19661
19662
19663
19664
19665 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19666 transmit_response(p, "415 Unsupported media type", req);
19667 return;
19668 }
19669
19670
19671 static char *sip_do_debug_ip(int fd, const char *arg)
19672 {
19673 if (ast_sockaddr_resolve_first(&debugaddr, arg, 0)) {
19674 return CLI_SHOWUSAGE;
19675 }
19676
19677 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19678 sipdebug |= sip_debug_console;
19679
19680 return CLI_SUCCESS;
19681 }
19682
19683
19684 static char *sip_do_debug_peer(int fd, const char *arg)
19685 {
19686 struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19687 if (!peer) {
19688 ast_cli(fd, "No such peer '%s'\n", arg);
19689 } else if (ast_sockaddr_isnull(&peer->addr)) {
19690 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19691 } else {
19692 ast_sockaddr_copy(&debugaddr, &peer->addr);
19693 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19694 sipdebug |= sip_debug_console;
19695 }
19696 if (peer) {
19697 sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
19698 }
19699 return CLI_SUCCESS;
19700 }
19701
19702
19703 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19704 {
19705 int oldsipdebug = sipdebug & sip_debug_console;
19706 const char *what;
19707
19708 if (cmd == CLI_INIT) {
19709 e->command = "sip set debug {on|off|ip|peer}";
19710 e->usage =
19711 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19712 " Globally disables dumping of SIP packets,\n"
19713 " or enables it either globally or for a (single)\n"
19714 " IP address or registered peer.\n";
19715 return NULL;
19716 } else if (cmd == CLI_GENERATE) {
19717 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19718 return complete_sip_peer(a->word, a->n, 0);
19719 return NULL;
19720 }
19721
19722 what = a->argv[e->args-1];
19723 if (a->argc == e->args) {
19724 if (!strcasecmp(what, "on")) {
19725 sipdebug |= sip_debug_console;
19726 sipdebug_text = 1;
19727 memset(&debugaddr, 0, sizeof(debugaddr));
19728 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19729 return CLI_SUCCESS;
19730 } else if (!strcasecmp(what, "off")) {
19731 sipdebug &= ~sip_debug_console;
19732 sipdebug_text = 0;
19733 ast_cli(a->fd, "SIP Debugging Disabled\n");
19734 return CLI_SUCCESS;
19735 }
19736 } else if (a->argc == e->args +1) {
19737 if (!strcasecmp(what, "ip"))
19738 return sip_do_debug_ip(a->fd, a->argv[e->args]);
19739 else if (!strcasecmp(what, "peer"))
19740 return sip_do_debug_peer(a->fd, a->argv[e->args]);
19741 }
19742 return CLI_SHOWUSAGE;
19743 }
19744
19745
19746 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19747 {
19748 struct ast_variable *varlist;
19749 int i;
19750
19751 switch (cmd) {
19752 case CLI_INIT:
19753 e->command = "sip notify";
19754 e->usage =
19755 "Usage: sip notify <type> <peer> [<peer>...]\n"
19756 " Send a NOTIFY message to a SIP peer or peers\n"
19757 " Message types are defined in sip_notify.conf\n";
19758 return NULL;
19759 case CLI_GENERATE:
19760 return complete_sipnotify(a->line, a->word, a->pos, a->n);
19761 }
19762
19763 if (a->argc < 4)
19764 return CLI_SHOWUSAGE;
19765
19766 if (!notify_types) {
19767 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19768 return CLI_FAILURE;
19769 }
19770
19771 varlist = ast_variable_browse(notify_types, a->argv[2]);
19772
19773 if (!varlist) {
19774 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19775 return CLI_FAILURE;
19776 }
19777
19778 for (i = 3; i < a->argc; i++) {
19779 struct sip_pvt *p;
19780 char buf[512];
19781 struct ast_variable *header, *var;
19782
19783 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19784 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19785 return CLI_FAILURE;
19786 }
19787
19788 if (create_addr(p, a->argv[i], NULL, 1, NULL)) {
19789
19790 dialog_unlink_all(p);
19791 dialog_unref(p, "unref dialog inside for loop" );
19792
19793 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19794 continue;
19795 }
19796
19797
19798 ast_set_flag(&p->flags[0], SIP_OUTGOING);
19799 sip_notify_allocate(p);
19800 p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19801
19802 for (var = varlist; var; var = var->next) {
19803 ast_copy_string(buf, var->value, sizeof(buf));
19804 ast_unescape_semicolon(buf);
19805
19806 if (!strcasecmp(var->name, "Content")) {
19807 if (ast_str_strlen(p->notify->content))
19808 ast_str_append(&p->notify->content, 0, "\r\n");
19809 ast_str_append(&p->notify->content, 0, "%s", buf);
19810 } else if (!strcasecmp(var->name, "Content-Length")) {
19811 ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring");
19812 } else {
19813 header->next = ast_variable_new(var->name, buf, "");
19814 header = header->next;
19815 }
19816 }
19817
19818
19819 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19820 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19821 transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19822 dialog_unref(p, "bump down the count of p since we're done with it.");
19823 }
19824
19825 return CLI_SUCCESS;
19826 }
19827
19828
19829 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19830 {
19831 switch (cmd) {
19832 case CLI_INIT:
19833 e->command = "sip set history {on|off}";
19834 e->usage =
19835 "Usage: sip set history {on|off}\n"
19836 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19837 " Use 'sip show history' to view the history of a call number.\n";
19838 return NULL;
19839 case CLI_GENERATE:
19840 return NULL;
19841 }
19842
19843 if (a->argc != e->args)
19844 return CLI_SHOWUSAGE;
19845
19846 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19847 recordhistory = TRUE;
19848 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19849 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19850 recordhistory = FALSE;
19851 ast_cli(a->fd, "SIP History Recording Disabled\n");
19852 } else {
19853 return CLI_SHOWUSAGE;
19854 }
19855 return CLI_SUCCESS;
19856 }
19857
19858
19859 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19860 {
19861 char *header, *respheader;
19862 char digest[1024];
19863
19864 p->authtries++;
19865 sip_auth_headers(code, &header, &respheader);
19866 memset(digest, 0, sizeof(digest));
19867 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19868
19869
19870 if (sip_debug_test_pvt(p) && p->registry)
19871 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19872
19873 return -1;
19874 }
19875 if (p->do_history)
19876 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19877 if (sip_debug_test_pvt(p) && p->registry)
19878 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19879 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19880 }
19881
19882
19883 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19884 {
19885 char *header, *respheader;
19886 char digest[1024];
19887
19888 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19889 return -2;
19890
19891 p->authtries++;
19892 sip_auth_headers(code, &header, &respheader);
19893 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19894 memset(digest, 0, sizeof(digest));
19895 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19896
19897 return -1;
19898 }
19899
19900 p->options->auth = digest;
19901 p->options->authheader = respheader;
19902 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19903 }
19904
19905
19906
19907
19908
19909 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
19910 {
19911 char tmp[512];
19912 char *c;
19913 char oldnonce[256];
19914
19915
19916 const struct x {
19917 const char *key;
19918 const ast_string_field *field;
19919 } *i, keys[] = {
19920 { "realm=", &p->realm },
19921 { "nonce=", &p->nonce },
19922 { "opaque=", &p->opaque },
19923 { "qop=", &p->qop },
19924 { "domain=", &p->domain },
19925 { NULL, 0 },
19926 };
19927
19928 ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
19929 if (ast_strlen_zero(tmp))
19930 return -1;
19931 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19932 ast_log(LOG_WARNING, "missing Digest.\n");
19933 return -1;
19934 }
19935 c = tmp + strlen("Digest ");
19936 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19937 while (c && *(c = ast_skip_blanks(c))) {
19938 for (i = keys; i->key != NULL; i++) {
19939 char *src, *separator;
19940 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19941 continue;
19942
19943 c += strlen(i->key);
19944 if (*c == '"') {
19945 src = ++c;
19946 separator = "\"";
19947 } else {
19948 src = c;
19949 separator = ",";
19950 }
19951 strsep(&c, separator);
19952 ast_string_field_ptr_set(p, i->field, src);
19953 break;
19954 }
19955 if (i->key == NULL)
19956 strsep(&c, ",");
19957 }
19958
19959 if (strcmp(p->nonce, oldnonce))
19960 p->noncecount = 0;
19961
19962
19963 if (p->registry) {
19964 struct sip_registry *r = p->registry;
19965
19966 if (strcmp(r->nonce, p->nonce)) {
19967 ast_string_field_set(r, realm, p->realm);
19968 ast_string_field_set(r, nonce, p->nonce);
19969 ast_string_field_set(r, authdomain, p->domain);
19970 ast_string_field_set(r, opaque, p->opaque);
19971 ast_string_field_set(r, qop, p->qop);
19972 r->noncecount = 0;
19973 }
19974 }
19975 return build_reply_digest(p, sipmethod, digest, digest_len);
19976 }
19977
19978
19979
19980
19981
19982
19983 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19984 {
19985 char a1[256];
19986 char a2[256];
19987 char a1_hash[256];
19988 char a2_hash[256];
19989 char resp[256];
19990 char resp_hash[256];
19991 char uri[256];
19992 char opaque[256] = "";
19993 char cnonce[80];
19994 const char *username;
19995 const char *secret;
19996 const char *md5secret;
19997 struct sip_auth *auth;
19998 struct sip_auth_container *credentials;
19999
20000 if (!ast_strlen_zero(p->domain))
20001 snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
20002 else if (!ast_strlen_zero(p->uri))
20003 ast_copy_string(uri, p->uri, sizeof(uri));
20004 else
20005 snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
20006
20007 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
20008
20009
20010 ao2_lock(p);
20011 credentials = p->peerauth;
20012 if (credentials) {
20013 ao2_t_ref(credentials, +1, "Ref peer auth for digest");
20014 }
20015 ao2_unlock(p);
20016 auth = find_realm_authentication(credentials, p->realm);
20017 if (!auth) {
20018
20019 if (credentials) {
20020 ao2_t_ref(credentials, -1, "Unref peer auth for digest");
20021 }
20022 ast_mutex_lock(&authl_lock);
20023 credentials = authl;
20024 if (credentials) {
20025 ao2_t_ref(credentials, +1, "Ref global auth for digest");
20026 }
20027 ast_mutex_unlock(&authl_lock);
20028 auth = find_realm_authentication(credentials, p->realm);
20029 }
20030
20031 if (auth) {
20032 ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
20033 username = auth->username;
20034 secret = auth->secret;
20035 md5secret = auth->md5secret;
20036 if (sipdebug)
20037 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
20038 } else {
20039
20040 username = p->authname;
20041 secret = p->relatedpeer
20042 && !ast_strlen_zero(p->relatedpeer->remotesecret)
20043 ? p->relatedpeer->remotesecret : p->peersecret;
20044 md5secret = p->peermd5secret;
20045 }
20046 if (ast_strlen_zero(username)) {
20047
20048 if (credentials) {
20049 ao2_t_ref(credentials, -1, "Unref auth for digest");
20050 }
20051 return -1;
20052 }
20053
20054
20055 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
20056 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
20057 if (!ast_strlen_zero(md5secret))
20058 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
20059 else
20060