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 #include "asterisk.h"
00138
00139 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 227696 $")
00140
00141 #include <ctype.h>
00142 #include <sys/ioctl.h>
00143 #include <fcntl.h>
00144 #include <signal.h>
00145 #include <sys/signal.h>
00146 #include <regex.h>
00147 #include <time.h>
00148
00149 #include "asterisk/network.h"
00150 #include "asterisk/paths.h"
00151
00152 #include "asterisk/lock.h"
00153 #include "asterisk/channel.h"
00154 #include "asterisk/config.h"
00155 #include "asterisk/module.h"
00156 #include "asterisk/pbx.h"
00157 #include "asterisk/sched.h"
00158 #include "asterisk/io.h"
00159 #include "asterisk/rtp.h"
00160 #include "asterisk/udptl.h"
00161 #include "asterisk/acl.h"
00162 #include "asterisk/manager.h"
00163 #include "asterisk/callerid.h"
00164 #include "asterisk/cli.h"
00165 #include "asterisk/app.h"
00166 #include "asterisk/musiconhold.h"
00167 #include "asterisk/dsp.h"
00168 #include "asterisk/features.h"
00169 #include "asterisk/srv.h"
00170 #include "asterisk/astdb.h"
00171 #include "asterisk/causes.h"
00172 #include "asterisk/utils.h"
00173 #include "asterisk/file.h"
00174 #include "asterisk/astobj.h"
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187 #include "asterisk/astobj2.h"
00188 #include "asterisk/dnsmgr.h"
00189 #include "asterisk/devicestate.h"
00190 #include "asterisk/linkedlists.h"
00191 #include "asterisk/stringfields.h"
00192 #include "asterisk/monitor.h"
00193 #include "asterisk/netsock.h"
00194 #include "asterisk/localtime.h"
00195 #include "asterisk/abstract_jb.h"
00196 #include "asterisk/threadstorage.h"
00197 #include "asterisk/translate.h"
00198 #include "asterisk/ast_version.h"
00199 #include "asterisk/event.h"
00200 #include "asterisk/tcptls.h"
00201
00202 #ifndef FALSE
00203 #define FALSE 0
00204 #endif
00205
00206 #ifndef TRUE
00207 #define TRUE 1
00208 #endif
00209
00210 #define SIPBUFSIZE 512
00211
00212
00213 #define FINDUSERS (1 << 0)
00214 #define FINDPEERS (1 << 1)
00215 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00216
00217 #define XMIT_ERROR -2
00218
00219 #define SIP_RESERVED ";/?:@&=+$,# "
00220
00221
00222
00223 #define DEFAULT_DEFAULT_EXPIRY 120
00224 #define DEFAULT_MIN_EXPIRY 60
00225 #define DEFAULT_MAX_EXPIRY 3600
00226 #define DEFAULT_REGISTRATION_TIMEOUT 20
00227 #define DEFAULT_MAX_FORWARDS "70"
00228
00229
00230
00231 #define EXPIRY_GUARD_SECS 15
00232 #define EXPIRY_GUARD_LIMIT 30
00233
00234 #define EXPIRY_GUARD_MIN 500
00235
00236
00237
00238 #define EXPIRY_GUARD_PCT 0.20
00239
00240 #define DEFAULT_EXPIRY 900
00241
00242 static int min_expiry = DEFAULT_MIN_EXPIRY;
00243 static int max_expiry = DEFAULT_MAX_EXPIRY;
00244 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00245
00246 #ifndef MAX
00247 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00248 #endif
00249
00250 #define CALLERID_UNKNOWN "Anonymous"
00251 #define FROMDOMAIN_INVALID "anonymous.invalid"
00252
00253 #define DEFAULT_MAXMS 2000
00254 #define DEFAULT_QUALIFYFREQ 60 * 1000
00255 #define DEFAULT_FREQ_NOTOK 10 * 1000
00256
00257 #define DEFAULT_RETRANS 1000
00258 #define MAX_RETRANS 6
00259 #define SIP_TIMER_T1 500
00260 #define SIP_TRANS_TIMEOUT 64 * SIP_TIMER_T1
00261
00262
00263 #define DEFAULT_TRANS_TIMEOUT -1
00264 #define MAX_AUTHTRIES 3
00265
00266 #define SIP_MAX_HEADERS 64
00267 #define SIP_MAX_LINES 64
00268 #define SIP_MAX_PACKET 4096
00269 #define SIP_MIN_PACKET 1024
00270
00271 #define INITIAL_CSEQ 101
00272
00273 #define DEFAULT_MAX_SE 1800
00274 #define DEFAULT_MIN_SE 90
00275
00276 #define SDP_MAX_RTPMAP_CODECS 32
00277
00278
00279 static struct ast_jb_conf default_jbconf =
00280 {
00281 .flags = 0,
00282 .max_size = -1,
00283 .resync_threshold = -1,
00284 .impl = ""
00285 };
00286 static struct ast_jb_conf global_jbconf;
00287
00288 static const char config[] = "sip.conf";
00289 static const char notify_config[] = "sip_notify.conf";
00290
00291 #define RTP 1
00292 #define NO_RTP 0
00293
00294
00295
00296
00297 enum transfermodes {
00298 TRANSFER_OPENFORALL,
00299 TRANSFER_CLOSED,
00300 };
00301
00302
00303
00304 enum sip_result {
00305 AST_SUCCESS = 0,
00306 AST_FAILURE = -1,
00307 };
00308
00309
00310
00311
00312 enum invitestates {
00313 INV_NONE = 0,
00314 INV_CALLING = 1,
00315 INV_PROCEEDING = 2,
00316 INV_EARLY_MEDIA = 3,
00317 INV_COMPLETED = 4,
00318 INV_CONFIRMED = 5,
00319 INV_TERMINATED = 6,
00320
00321 INV_CANCELLED = 7,
00322 };
00323
00324
00325
00326 static const struct invstate2stringtable {
00327 const enum invitestates state;
00328 const char *desc;
00329 } invitestate2string[] = {
00330 {INV_NONE, "None" },
00331 {INV_CALLING, "Calling (Trying)"},
00332 {INV_PROCEEDING, "Proceeding "},
00333 {INV_EARLY_MEDIA, "Early media"},
00334 {INV_COMPLETED, "Completed (done)"},
00335 {INV_CONFIRMED, "Confirmed (up)"},
00336 {INV_TERMINATED, "Done"},
00337 {INV_CANCELLED, "Cancelled"}
00338 };
00339
00340
00341
00342
00343 enum xmittype {
00344 XMIT_CRITICAL = 2,
00345
00346 XMIT_RELIABLE = 1,
00347 XMIT_UNRELIABLE = 0,
00348 };
00349
00350 enum parse_register_result {
00351 PARSE_REGISTER_FAILED,
00352 PARSE_REGISTER_UPDATE,
00353 PARSE_REGISTER_QUERY,
00354 };
00355
00356
00357 enum subscriptiontype {
00358 NONE = 0,
00359 XPIDF_XML,
00360 DIALOG_INFO_XML,
00361 CPIM_PIDF_XML,
00362 PIDF_XML,
00363 MWI_NOTIFICATION
00364 };
00365
00366
00367
00368
00369
00370
00371 static const struct cfsubscription_types {
00372 enum subscriptiontype type;
00373 const char * const event;
00374 const char * const mediatype;
00375 const char * const text;
00376 } subscription_types[] = {
00377 { NONE, "-", "unknown", "unknown" },
00378
00379 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
00380 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" },
00381 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" },
00382 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" },
00383 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" }
00384 };
00385
00386
00387
00388
00389
00390
00391
00392 enum sip_auth_type {
00393 PROXY_AUTH = 407,
00394 WWW_AUTH = 401,
00395 };
00396
00397
00398 enum check_auth_result {
00399 AUTH_DONT_KNOW = -100,
00400
00401
00402 AUTH_SUCCESSFUL = 0,
00403 AUTH_CHALLENGE_SENT = 1,
00404 AUTH_SECRET_FAILED = -1,
00405 AUTH_USERNAME_MISMATCH = -2,
00406 AUTH_NOT_FOUND = -3,
00407 AUTH_FAKE_AUTH = -4,
00408 AUTH_UNKNOWN_DOMAIN = -5,
00409 AUTH_PEER_NOT_DYNAMIC = -6,
00410 AUTH_ACL_FAILED = -7,
00411 AUTH_BAD_TRANSPORT = -8,
00412 };
00413
00414
00415 enum sipregistrystate {
00416 REG_STATE_UNREGISTERED = 0,
00417
00418
00419
00420
00421 REG_STATE_REGSENT,
00422
00423
00424
00425
00426 REG_STATE_AUTHSENT,
00427
00428
00429
00430
00431 REG_STATE_REGISTERED,
00432
00433 REG_STATE_REJECTED,
00434
00435
00436
00437
00438
00439 REG_STATE_TIMEOUT,
00440
00441
00442 REG_STATE_NOAUTH,
00443
00444
00445 REG_STATE_FAILED,
00446
00447 };
00448
00449
00450 enum st_mode {
00451 SESSION_TIMER_MODE_INVALID = 0,
00452 SESSION_TIMER_MODE_ACCEPT,
00453 SESSION_TIMER_MODE_ORIGINATE,
00454 SESSION_TIMER_MODE_REFUSE
00455 };
00456
00457
00458 enum st_refresher {
00459 SESSION_TIMER_REFRESHER_AUTO,
00460 SESSION_TIMER_REFRESHER_UAC,
00461 SESSION_TIMER_REFRESHER_UAS
00462 };
00463
00464
00465
00466
00467 enum sip_transport {
00468 SIP_TRANSPORT_UDP = 1,
00469 SIP_TRANSPORT_TCP = 1 << 1,
00470 SIP_TRANSPORT_TLS = 1 << 2,
00471 };
00472
00473
00474
00475
00476
00477
00478
00479 struct sip_proxy {
00480 char name[MAXHOSTNAMELEN];
00481 struct sockaddr_in ip;
00482 time_t last_dnsupdate;
00483 enum sip_transport transport;
00484 int force;
00485
00486 };
00487
00488
00489 struct __show_chan_arg {
00490 int fd;
00491 int subscriptions;
00492 int numchans;
00493 };
00494
00495
00496
00497 enum can_create_dialog {
00498 CAN_NOT_CREATE_DIALOG,
00499 CAN_CREATE_DIALOG,
00500 CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00501 };
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511
00512
00513 enum sipmethod {
00514 SIP_UNKNOWN,
00515 SIP_RESPONSE,
00516 SIP_REGISTER,
00517 SIP_OPTIONS,
00518 SIP_NOTIFY,
00519 SIP_INVITE,
00520 SIP_ACK,
00521 SIP_PRACK,
00522 SIP_BYE,
00523 SIP_REFER,
00524 SIP_SUBSCRIBE,
00525 SIP_MESSAGE,
00526 SIP_UPDATE,
00527 SIP_INFO,
00528 SIP_CANCEL,
00529 SIP_PUBLISH,
00530 SIP_PING,
00531 };
00532
00533
00534
00535
00536
00537 static const struct cfsip_methods {
00538 enum sipmethod id;
00539 int need_rtp;
00540 char * const text;
00541 enum can_create_dialog can_create;
00542 } sip_methods[] = {
00543 { SIP_UNKNOWN, RTP, "-UNKNOWN-", CAN_CREATE_DIALOG },
00544 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
00545 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00546 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
00547 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
00548 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
00549 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
00550 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
00551 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
00552 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
00553 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", CAN_CREATE_DIALOG },
00554 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
00555 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
00556 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
00557 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
00558 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00559 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00560 };
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572 #define SUPPORTED 1
00573 #define NOT_SUPPORTED 0
00574
00575
00576 #define SIP_OPT_REPLACES (1 << 0)
00577 #define SIP_OPT_100REL (1 << 1)
00578 #define SIP_OPT_TIMER (1 << 2)
00579 #define SIP_OPT_EARLY_SESSION (1 << 3)
00580 #define SIP_OPT_JOIN (1 << 4)
00581 #define SIP_OPT_PATH (1 << 5)
00582 #define SIP_OPT_PREF (1 << 6)
00583 #define SIP_OPT_PRECONDITION (1 << 7)
00584 #define SIP_OPT_PRIVACY (1 << 8)
00585 #define SIP_OPT_SDP_ANAT (1 << 9)
00586 #define SIP_OPT_SEC_AGREE (1 << 10)
00587 #define SIP_OPT_EVENTLIST (1 << 11)
00588 #define SIP_OPT_GRUU (1 << 12)
00589 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00590 #define SIP_OPT_NOREFERSUB (1 << 14)
00591 #define SIP_OPT_HISTINFO (1 << 15)
00592 #define SIP_OPT_RESPRIORITY (1 << 16)
00593 #define SIP_OPT_FROMCHANGE (1 << 17)
00594 #define SIP_OPT_RECLISTINV (1 << 18)
00595 #define SIP_OPT_RECLISTSUB (1 << 19)
00596 #define SIP_OPT_UNKNOWN (1 << 20)
00597
00598
00599
00600
00601 static const struct cfsip_options {
00602 int id;
00603 int supported;
00604 char * const text;
00605 } sip_options[] = {
00606
00607 { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" },
00608
00609 { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
00610
00611 { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00612
00613 { SIP_OPT_FROMCHANGE, NOT_SUPPORTED, "from-change" },
00614
00615 { SIP_OPT_GRUU, NOT_SUPPORTED, "gruu" },
00616
00617 { SIP_OPT_HISTINFO, NOT_SUPPORTED, "histinfo" },
00618
00619 { SIP_OPT_JOIN, NOT_SUPPORTED, "join" },
00620
00621 { SIP_OPT_NOREFERSUB, NOT_SUPPORTED, "norefersub" },
00622
00623 { SIP_OPT_PATH, NOT_SUPPORTED, "path" },
00624
00625 { SIP_OPT_PREF, NOT_SUPPORTED, "pref" },
00626
00627 { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00628
00629 { SIP_OPT_PRIVACY, NOT_SUPPORTED, "privacy" },
00630
00631 { SIP_OPT_RECLISTINV, NOT_SUPPORTED, "recipient-list-invite" },
00632
00633 { SIP_OPT_RECLISTSUB, NOT_SUPPORTED, "recipient-list-subscribe" },
00634
00635 { SIP_OPT_REPLACES, SUPPORTED, "replaces" },
00636
00637 { SIP_OPT_REPLACES, SUPPORTED, "replace" },
00638
00639 { SIP_OPT_RESPRIORITY, NOT_SUPPORTED, "resource-priority" },
00640
00641 { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00642
00643 { SIP_OPT_SDP_ANAT, NOT_SUPPORTED, "sdp-anat" },
00644
00645 { SIP_OPT_TIMER, SUPPORTED, "timer" },
00646
00647 { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00648 };
00649
00650
00651
00652
00653
00654
00655 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00656
00657
00658
00659
00660
00661
00662 #define SUPPORTED_EXTENSIONS "replaces, timer"
00663
00664
00665 #define STANDARD_SIP_PORT 5060
00666
00667 #define STANDARD_TLS_PORT 5061
00668
00669
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683
00684
00685 #define DEFAULT_CONTEXT "default"
00686 #define DEFAULT_MOHINTERPRET "default"
00687 #define DEFAULT_MOHSUGGEST ""
00688 #define DEFAULT_VMEXTEN "asterisk"
00689 #define DEFAULT_CALLERID "asterisk"
00690 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
00691 #define DEFAULT_ALLOWGUEST TRUE
00692 #define DEFAULT_CALLCOUNTER FALSE
00693 #define DEFAULT_SRVLOOKUP TRUE
00694 #define DEFAULT_COMPACTHEADERS FALSE
00695 #define DEFAULT_TOS_SIP 0
00696 #define DEFAULT_TOS_AUDIO 0
00697 #define DEFAULT_TOS_VIDEO 0
00698 #define DEFAULT_TOS_TEXT 0
00699 #define DEFAULT_COS_SIP 4
00700 #define DEFAULT_COS_AUDIO 5
00701 #define DEFAULT_COS_VIDEO 6
00702 #define DEFAULT_COS_TEXT 5
00703 #define DEFAULT_ALLOW_EXT_DOM TRUE
00704 #define DEFAULT_REALM "asterisk"
00705 #define DEFAULT_NOTIFYRINGING TRUE
00706 #define DEFAULT_PEDANTIC FALSE
00707 #define DEFAULT_AUTOCREATEPEER FALSE
00708 #define DEFAULT_QUALIFY FALSE
00709 #define DEFAULT_REGEXTENONQUALIFY FALSE
00710 #define DEFAULT_T1MIN 100
00711 #define DEFAULT_MAX_CALL_BITRATE (384)
00712 #ifndef DEFAULT_USERAGENT
00713 #define DEFAULT_USERAGENT "Asterisk PBX"
00714 #define DEFAULT_SDPSESSION "Asterisk PBX"
00715 #define DEFAULT_SDPOWNER "root"
00716 #endif
00717
00718
00719
00720
00721
00722
00723
00724 static char default_context[AST_MAX_CONTEXT];
00725 static char default_subscribecontext[AST_MAX_CONTEXT];
00726 static char default_language[MAX_LANGUAGE];
00727 static char default_callerid[AST_MAX_EXTENSION];
00728 static char default_fromdomain[AST_MAX_EXTENSION];
00729 static char default_notifymime[AST_MAX_EXTENSION];
00730 static int default_qualify;
00731 static char default_vmexten[AST_MAX_EXTENSION];
00732 static char default_mohinterpret[MAX_MUSICCLASS];
00733 static char default_mohsuggest[MAX_MUSICCLASS];
00734
00735 static char default_parkinglot[AST_MAX_CONTEXT];
00736 static int default_maxcallbitrate;
00737 static struct ast_codec_pref default_prefs;
00738
00739
00740 struct sip_settings {
00741 int peer_rtupdate;
00742 int rtsave_sysname;
00743 int ignore_regexpire;
00744 };
00745
00746 static struct sip_settings sip_cfg;
00747
00748
00749
00750
00751
00752
00753
00754 static int global_directrtpsetup;
00755 static int global_rtautoclear;
00756 static int global_notifyringing;
00757 static int global_notifyhold;
00758 static int global_alwaysauthreject;
00759 static int global_srvlookup;
00760 static int pedanticsipchecking;
00761 static int autocreatepeer;
00762 static int global_match_auth_username;
00763 static int global_relaxdtmf;
00764 static int global_rtptimeout;
00765 static int global_rtpholdtimeout;
00766 static int global_rtpkeepalive;
00767 static int global_reg_timeout;
00768 static int global_regattempts_max;
00769 static int global_allowguest;
00770 static int global_callcounter;
00771
00772
00773 static int global_allowsubscribe;
00774
00775 static unsigned int global_tos_sip;
00776 static unsigned int global_tos_audio;
00777 static unsigned int global_tos_video;
00778 static unsigned int global_tos_text;
00779 static unsigned int global_cos_sip;
00780 static unsigned int global_cos_audio;
00781 static unsigned int global_cos_video;
00782 static unsigned int global_cos_text;
00783 static int compactheaders;
00784 static int recordhistory;
00785 static int dumphistory;
00786 static char global_realm[MAXHOSTNAMELEN];
00787 static char global_regcontext[AST_MAX_CONTEXT];
00788 static char global_useragent[AST_MAX_EXTENSION];
00789 static char global_sdpsession[AST_MAX_EXTENSION];
00790 static char global_sdpowner[AST_MAX_EXTENSION];
00791 static int allow_external_domains;
00792 static int global_callevents;
00793 static int global_authfailureevents;
00794 static int global_t1;
00795 static int global_t1min;
00796 static int global_timer_b;
00797 static int global_regextenonqualify;
00798 static int global_autoframing;
00799 static enum transfermodes global_allowtransfer;
00800 static struct sip_proxy global_outboundproxy;
00801 static int global_matchexterniplocally;
00802 static int global_qualifyfreq;
00803
00804
00805
00806 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00807
00808 static enum st_mode global_st_mode;
00809 static enum st_refresher global_st_refresher;
00810 static int global_min_se;
00811 static int global_max_se;
00812
00813
00814
00815
00816 static struct ast_ha *global_contact_ha = NULL;
00817 static int global_dynamic_exclude_static = 0;
00818
00819
00820
00821
00822 static int speerobjs = 0;
00823 static int rpeerobjs = 0;
00824 static int apeerobjs = 0;
00825 static int regobjs = 0;
00826
00827
00828 static struct ast_flags global_flags[2] = {{0}};
00829 static char used_context[AST_MAX_CONTEXT];
00830
00831
00832 AST_MUTEX_DEFINE_STATIC(netlock);
00833
00834
00835
00836 AST_MUTEX_DEFINE_STATIC(monlock);
00837
00838 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00839
00840
00841
00842 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00843
00844 static int sip_reloading = FALSE;
00845 static enum channelreloadreason sip_reloadreason;
00846
00847 static struct sched_context *sched;
00848 static struct io_context *io;
00849 static int *sipsock_read_id;
00850
00851 #define DEC_CALL_LIMIT 0
00852 #define INC_CALL_LIMIT 1
00853 #define DEC_CALL_RINGING 2
00854 #define INC_CALL_RINGING 3
00855
00856
00857 struct sip_socket {
00858 enum sip_transport type;
00859 int fd;
00860 uint16_t port;
00861 struct ast_tcptls_session_instance *tcptls_session;
00862 };
00863
00864
00865
00866
00867
00868
00869
00870
00871
00872
00873
00874
00875
00876
00877
00878
00879
00880
00881
00882
00883
00884
00885
00886
00887
00888 struct sip_request {
00889 ptrdiff_t rlPart1;
00890 ptrdiff_t rlPart2;
00891 int len;
00892 int headers;
00893 int method;
00894 int lines;
00895 unsigned int sdp_start;
00896 unsigned int sdp_end;
00897 char debug;
00898 char has_to_tag;
00899 char ignore;
00900
00901 ptrdiff_t header[SIP_MAX_HEADERS];
00902
00903 ptrdiff_t line[SIP_MAX_LINES];
00904 struct ast_str *data;
00905
00906 struct sip_socket socket;
00907 AST_LIST_ENTRY(sip_request) next;
00908 };
00909
00910
00911
00912
00913
00914
00915
00916
00917 #define REQ_OFFSET_TO_STR(req,offset) ((req)->data->str + ((req)->offset))
00918
00919
00920 struct sip_dual {
00921 struct ast_channel *chan1;
00922 struct ast_channel *chan2;
00923 struct sip_request req;
00924 int seqno;
00925 };
00926
00927 struct sip_pkt;
00928
00929
00930 struct sip_invite_param {
00931 int addsipheaders;
00932 const char *uri_options;
00933 const char *vxml_url;
00934 char *auth;
00935 char *authheader;
00936 enum sip_auth_type auth_type;
00937 const char *replaces;
00938 int transfer;
00939 };
00940
00941
00942 struct sip_route {
00943 struct sip_route *next;
00944 char hop[0];
00945 };
00946
00947
00948 enum domain_mode {
00949 SIP_DOMAIN_AUTO,
00950 SIP_DOMAIN_CONFIG,
00951 };
00952
00953
00954
00955
00956
00957 struct domain {
00958 char domain[MAXHOSTNAMELEN];
00959 char context[AST_MAX_EXTENSION];
00960 enum domain_mode mode;
00961 AST_LIST_ENTRY(domain) list;
00962 };
00963
00964 static AST_LIST_HEAD_STATIC(domain_list, domain);
00965
00966
00967
00968 struct sip_history {
00969 AST_LIST_ENTRY(sip_history) list;
00970 char event[0];
00971 };
00972
00973 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history);
00974
00975
00976 struct sip_auth {
00977 char realm[AST_MAX_EXTENSION];
00978 char username[256];
00979 char secret[256];
00980 char md5secret[256];
00981 struct sip_auth *next;
00982 };
00983
00984
00985
00986
00987
00988
00989
00990
00991
00992
00993
00994 #define SIP_OUTGOING (1 << 0)
00995 #define SIP_RINGING (1 << 2)
00996 #define SIP_PROGRESS_SENT (1 << 3)
00997 #define SIP_NEEDREINVITE (1 << 4)
00998 #define SIP_PENDINGBYE (1 << 5)
00999 #define SIP_GOTREFER (1 << 6)
01000 #define SIP_CALL_LIMIT (1 << 7)
01001 #define SIP_INC_COUNT (1 << 8)
01002 #define SIP_INC_RINGING (1 << 9)
01003 #define SIP_DEFER_BYE_ON_TRANSFER (1 << 10)
01004
01005 #define SIP_PROMISCREDIR (1 << 11)
01006 #define SIP_TRUSTRPID (1 << 12)
01007 #define SIP_USEREQPHONE (1 << 13)
01008 #define SIP_USECLIENTCODE (1 << 14)
01009
01010
01011 #define SIP_DTMF (7 << 15)
01012 #define SIP_DTMF_RFC2833 (0 << 15)
01013 #define SIP_DTMF_INBAND (1 << 15)
01014 #define SIP_DTMF_INFO (2 << 15)
01015 #define SIP_DTMF_AUTO (3 << 15)
01016 #define SIP_DTMF_SHORTINFO (4 << 15)
01017
01018
01019 #define SIP_NAT (3 << 18)
01020 #define SIP_NAT_NEVER (0 << 18)
01021 #define SIP_NAT_RFC3581 (1 << 18)
01022 #define SIP_NAT_ROUTE (2 << 18)
01023 #define SIP_NAT_ALWAYS (3 << 18)
01024
01025
01026 #define SIP_REINVITE (7 << 20)
01027 #define SIP_REINVITE_NONE (0 << 20)
01028 #define SIP_CAN_REINVITE (1 << 20)
01029 #define SIP_CAN_REINVITE_NAT (2 << 20)
01030 #define SIP_REINVITE_UPDATE (4 << 20)
01031
01032
01033 #define SIP_INSECURE (3 << 23)
01034 #define SIP_INSECURE_NONE (0 << 23)
01035 #define SIP_INSECURE_PORT (1 << 23)
01036 #define SIP_INSECURE_INVITE (1 << 24)
01037
01038
01039 #define SIP_PROG_INBAND (3 << 25)
01040 #define SIP_PROG_INBAND_NEVER (0 << 25)
01041 #define SIP_PROG_INBAND_NO (1 << 25)
01042 #define SIP_PROG_INBAND_YES (2 << 25)
01043
01044 #define SIP_SENDRPID (1 << 29)
01045 #define SIP_G726_NONSTANDARD (1 << 31)
01046
01047
01048 #define SIP_FLAGS_TO_COPY \
01049 (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01050 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01051 SIP_USEREQPHONE | SIP_INSECURE)
01052
01053
01054
01055
01056
01057
01058 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0)
01059 #define SIP_PAGE2_RTAUTOCLEAR (1 << 2)
01060
01061 #define SIP_PAGE2_STATECHANGEQUEUE (1 << 9)
01062
01063 #define SIP_PAGE2_RPORT_PRESENT (1 << 10)
01064 #define SIP_PAGE2_VIDEOSUPPORT (1 << 14)
01065 #define SIP_PAGE2_TEXTSUPPORT (1 << 15)
01066 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)
01067 #define SIP_PAGE2_ALLOWOVERLAP (1 << 17)
01068 #define SIP_PAGE2_SUBSCRIBEMWIONLY (1 << 18)
01069 #define SIP_PAGE2_IGNORESDPVERSION (1 << 19)
01070
01071 #define SIP_PAGE2_T38SUPPORT (7 << 20)
01072 #define SIP_PAGE2_T38SUPPORT_UDPTL (1 << 20)
01073 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC (2 << 20)
01074 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY (4 << 20)
01075
01076 #define SIP_PAGE2_CALL_ONHOLD (3 << 23)
01077 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE (1 << 23)
01078 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR (2 << 23)
01079 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)
01080
01081 #define SIP_PAGE2_RFC2833_COMPENSATE (1 << 25)
01082 #define SIP_PAGE2_BUGGY_MWI (1 << 26)
01083 #define SIP_PAGE2_DIALOG_ESTABLISHED (1 << 27)
01084 #define SIP_PAGE2_REGISTERTRYING (1 << 29)
01085 #define SIP_PAGE2_UDPTL_DESTINATION (1 << 30)
01086 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS (1 << 31)
01087
01088 #define SIP_PAGE2_FLAGS_TO_COPY \
01089 (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01090 SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01091 SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | \
01092 SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS)
01093
01094
01095
01096
01097
01098
01099
01100
01101
01102 enum sip_debug_e {
01103 sip_debug_none = 0,
01104 sip_debug_config = 1,
01105 sip_debug_console = 2,
01106 };
01107
01108 static enum sip_debug_e sipdebug;
01109
01110
01111
01112
01113
01114 static int sipdebug_text;
01115
01116
01117 enum t38state {
01118 T38_DISABLED = 0,
01119 T38_LOCAL_REINVITE,
01120 T38_PEER_REINVITE,
01121 T38_ENABLED
01122 };
01123
01124
01125 struct t38properties {
01126 enum t38state state;
01127 struct ast_control_t38_parameters our_parms;
01128 struct ast_control_t38_parameters their_parms;
01129 };
01130
01131
01132 enum referstatus {
01133 REFER_IDLE,
01134 REFER_SENT,
01135 REFER_RECEIVED,
01136 REFER_CONFIRMED,
01137 REFER_ACCEPTED,
01138 REFER_RINGING,
01139 REFER_200OK,
01140 REFER_FAILED,
01141 REFER_NOAUTH
01142 };
01143
01144
01145
01146
01147
01148
01149 struct _map_x_s {
01150 int x;
01151 const char *s;
01152 };
01153
01154 static const struct _map_x_s referstatusstrings[] = {
01155 { REFER_IDLE, "<none>" },
01156 { REFER_SENT, "Request sent" },
01157 { REFER_RECEIVED, "Request received" },
01158 { REFER_CONFIRMED, "Confirmed" },
01159 { REFER_ACCEPTED, "Accepted" },
01160 { REFER_RINGING, "Target ringing" },
01161 { REFER_200OK, "Done" },
01162 { REFER_FAILED, "Failed" },
01163 { REFER_NOAUTH, "Failed - auth failure" },
01164 { -1, NULL}
01165 };
01166
01167
01168
01169 struct sip_refer {
01170 char refer_to[AST_MAX_EXTENSION];
01171 char refer_to_domain[AST_MAX_EXTENSION];
01172 char refer_to_urioption[AST_MAX_EXTENSION];
01173 char refer_to_context[AST_MAX_EXTENSION];
01174 char referred_by[AST_MAX_EXTENSION];
01175 char referred_by_name[AST_MAX_EXTENSION];
01176 char refer_contact[AST_MAX_EXTENSION];
01177 char replaces_callid[SIPBUFSIZE];
01178 char replaces_callid_totag[SIPBUFSIZE/2];
01179 char replaces_callid_fromtag[SIPBUFSIZE/2];
01180 struct sip_pvt *refer_call;
01181
01182
01183
01184 int attendedtransfer;
01185 int localtransfer;
01186 enum referstatus status;
01187 };
01188
01189
01190
01191
01192
01193 struct sip_st_dlg {
01194 int st_active;
01195 int st_interval;
01196 int st_schedid;
01197 enum st_refresher st_ref;
01198 int st_expirys;
01199 int st_active_peer_ua;
01200 int st_cached_min_se;
01201 int st_cached_max_se;
01202 enum st_mode st_cached_mode;
01203 enum st_refresher st_cached_ref;
01204 };
01205
01206
01207
01208
01209
01210 struct sip_st_cfg {
01211 enum st_mode st_mode_oper;
01212 enum st_refresher st_ref;
01213 int st_min_se;
01214 int st_max_se;
01215 };
01216
01217 struct offered_media {
01218 int offered;
01219 char text[128];
01220 };
01221
01222
01223
01224
01225
01226 struct sip_pvt {
01227 struct sip_pvt *next;
01228 enum invitestates invitestate;
01229 int method;
01230 AST_DECLARE_STRING_FIELDS(
01231 AST_STRING_FIELD(callid);
01232 AST_STRING_FIELD(randdata);
01233 AST_STRING_FIELD(accountcode);
01234 AST_STRING_FIELD(realm);
01235 AST_STRING_FIELD(nonce);
01236 AST_STRING_FIELD(opaque);
01237 AST_STRING_FIELD(qop);
01238 AST_STRING_FIELD(domain);
01239 AST_STRING_FIELD(from);
01240 AST_STRING_FIELD(useragent);
01241 AST_STRING_FIELD(exten);
01242 AST_STRING_FIELD(context);
01243 AST_STRING_FIELD(subscribecontext);
01244 AST_STRING_FIELD(subscribeuri);
01245 AST_STRING_FIELD(fromdomain);
01246 AST_STRING_FIELD(fromuser);
01247 AST_STRING_FIELD(fromname);
01248 AST_STRING_FIELD(tohost);
01249 AST_STRING_FIELD(todnid);
01250 AST_STRING_FIELD(language);
01251 AST_STRING_FIELD(mohinterpret);
01252 AST_STRING_FIELD(mohsuggest);
01253 AST_STRING_FIELD(rdnis);
01254 AST_STRING_FIELD(redircause);
01255 AST_STRING_FIELD(theirtag);
01256 AST_STRING_FIELD(username);
01257 AST_STRING_FIELD(peername);
01258 AST_STRING_FIELD(authname);
01259 AST_STRING_FIELD(uri);
01260 AST_STRING_FIELD(okcontacturi);
01261 AST_STRING_FIELD(peersecret);
01262 AST_STRING_FIELD(peermd5secret);
01263 AST_STRING_FIELD(cid_num);
01264 AST_STRING_FIELD(cid_name);
01265 AST_STRING_FIELD(fullcontact);
01266
01267 AST_STRING_FIELD(our_contact);
01268 AST_STRING_FIELD(rpid);
01269 AST_STRING_FIELD(rpid_from);
01270 AST_STRING_FIELD(url);
01271 AST_STRING_FIELD(parkinglot);
01272 );
01273 char via[128];
01274 struct sip_socket socket;
01275 unsigned int ocseq;
01276 unsigned int icseq;
01277 ast_group_t callgroup;
01278 ast_group_t pickupgroup;
01279 int lastinvite;
01280 struct ast_flags flags[2];
01281
01282
01283 char do_history;
01284 char alreadygone;
01285 char needdestroy;
01286 char outgoing_call;
01287 char answered_elsewhere;
01288 char novideo;
01289 char notext;
01290
01291 int timer_t1;
01292 int timer_b;
01293 unsigned int sipoptions;
01294 unsigned int reqsipoptions;
01295 struct ast_codec_pref prefs;
01296 int capability;
01297 int jointcapability;
01298 int peercapability;
01299 int prefcodec;
01300 int noncodeccapability;
01301 int jointnoncodeccapability;
01302 int redircodecs;
01303 int maxcallbitrate;
01304 struct sip_proxy *outboundproxy;
01305 struct t38properties t38;
01306 struct sockaddr_in udptlredirip;
01307 struct ast_udptl *udptl;
01308 int callingpres;
01309 int authtries;
01310 int expiry;
01311 long branch;
01312 long invite_branch;
01313 char tag[11];
01314 int sessionid;
01315 int sessionversion;
01316 int64_t sessionversion_remote;
01317 int session_modify;
01318 struct sockaddr_in sa;
01319 struct sockaddr_in redirip;
01320 struct sockaddr_in vredirip;
01321 struct sockaddr_in tredirip;
01322 time_t lastrtprx;
01323 time_t lastrtptx;
01324 int rtptimeout;
01325 struct sockaddr_in recv;
01326 struct sockaddr_in ourip;
01327 struct ast_channel *owner;
01328 struct sip_route *route;
01329 int route_persistant;
01330 struct ast_variable *notify_headers;
01331 struct sip_auth *peerauth;
01332 int noncecount;
01333 unsigned int stalenonce:1;
01334 char lastmsg[256];
01335 int amaflags;
01336 int pendinginvite;
01337 int glareinvite;
01338
01339
01340 struct sip_request initreq;
01341
01342
01343
01344 int initid;
01345 int waitid;
01346 int autokillid;
01347 int t38id;
01348 enum transfermodes allowtransfer;
01349 struct sip_refer *refer;
01350 enum subscriptiontype subscribed;
01351 int stateid;
01352 int laststate;
01353 int dialogver;
01354
01355 struct ast_dsp *vad;
01356
01357 struct sip_peer *relatedpeer;
01358
01359 struct sip_registry *registry;
01360 struct ast_rtp *rtp;
01361 struct ast_rtp *vrtp;
01362 struct ast_rtp *trtp;
01363 struct sip_pkt *packets;
01364 struct sip_history_head *history;
01365 size_t history_entries;
01366 struct ast_variable *chanvars;
01367 AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue;
01368 int request_queue_sched_id;
01369 struct sip_invite_param *options;
01370 int autoframing;
01371
01372
01373
01374 struct sip_st_dlg *stimer;
01375 int red;
01376 int hangupcause;
01377
01378
01379
01380
01381
01382
01383
01384
01385
01386
01387
01388
01389
01390
01391 struct offered_media offered_media[4];
01392 };
01393
01394
01395 #define MAX_HISTORY_ENTRIES 50
01396
01397
01398
01399
01400
01401
01402
01403
01404
01405 struct ao2_container *dialogs;
01406
01407 #define sip_pvt_lock(x) ao2_lock(x)
01408 #define sip_pvt_trylock(x) ao2_trylock(x)
01409 #define sip_pvt_unlock(x) ao2_unlock(x)
01410
01411
01412
01413
01414
01415
01416 #ifdef REF_DEBUG
01417 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01418 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01419
01420 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01421 {
01422 if (p)
01423 _ao2_ref_debug(p, 1, tag, file, line, func);
01424 else
01425 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01426 return p;
01427 }
01428
01429 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01430 {
01431 if (p)
01432 _ao2_ref_debug(p, -1, tag, file, line, func);
01433 return NULL;
01434 }
01435 #else
01436 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01437 {
01438 if (p)
01439 ao2_ref(p, 1);
01440 else
01441 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01442 return p;
01443 }
01444
01445 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01446 {
01447 if (p)
01448 ao2_ref(p, -1);
01449 return NULL;
01450 }
01451 #endif
01452
01453
01454
01455
01456
01457
01458
01459 struct sip_pkt {
01460 struct sip_pkt *next;
01461 int retrans;
01462 int method;
01463 int seqno;
01464 char is_resp;
01465 char is_fatal;
01466 int response_code;
01467 struct sip_pvt *owner;
01468 int retransid;
01469 int timer_a;
01470 int timer_t1;
01471 int packetlen;
01472 struct ast_str *data;
01473 };
01474
01475
01476
01477
01478
01479
01480
01481 struct sip_mailbox {
01482 char *mailbox;
01483 char *context;
01484
01485 struct ast_event_sub *event_sub;
01486 AST_LIST_ENTRY(sip_mailbox) entry;
01487 };
01488
01489 enum sip_peer_type {
01490 SIP_TYPE_PEER = (1 << 0),
01491 SIP_TYPE_USER = (1 << 1),
01492 };
01493
01494
01495
01496
01497 struct sip_peer {
01498 char name[80];
01499 struct sip_socket socket;
01500 enum sip_transport default_outbound_transport;
01501 unsigned int transports:3;
01502 char secret[80];
01503 char md5secret[80];
01504 struct sip_auth *auth;
01505 char context[AST_MAX_CONTEXT];
01506 char subscribecontext[AST_MAX_CONTEXT];
01507 char username[80];
01508 char accountcode[AST_MAX_ACCOUNT_CODE];
01509 int amaflags;
01510 char tohost[MAXHOSTNAMELEN];
01511 char regexten[AST_MAX_EXTENSION];
01512 char fromuser[80];
01513 char fromdomain[MAXHOSTNAMELEN];
01514 char fullcontact[256];
01515 char cid_num[80];
01516 char cid_name[80];
01517 int callingpres;
01518 int inUse;
01519 int inRinging;
01520 int onHold;
01521 int call_limit;
01522 int busy_level;
01523 enum transfermodes allowtransfer;
01524 char vmexten[AST_MAX_EXTENSION];
01525 char language[MAX_LANGUAGE];
01526 char mohinterpret[MAX_MUSICCLASS];
01527 char mohsuggest[MAX_MUSICCLASS];
01528 char parkinglot[AST_MAX_CONTEXT];
01529 char useragent[256];
01530 struct ast_codec_pref prefs;
01531 int lastmsgssent;
01532 unsigned int sipoptions;
01533 struct ast_flags flags[2];
01534
01535
01536 AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01537
01538
01539 char is_realtime;
01540 char rt_fromcontact;
01541 char host_dynamic;
01542 char selfdestruct;
01543 char the_mark;
01544
01545 int expire;
01546 int capability;
01547 int rtptimeout;
01548 int rtpholdtimeout;
01549 int rtpkeepalive;
01550 ast_group_t callgroup;
01551 ast_group_t pickupgroup;
01552 struct sip_proxy *outboundproxy;
01553 struct ast_dnsmgr_entry *dnsmgr;
01554 struct sockaddr_in addr;
01555 int maxcallbitrate;
01556
01557
01558 struct sip_pvt *call;
01559 int pokeexpire;
01560 int lastms;
01561 int maxms;
01562 int qualifyfreq;
01563 struct timeval ps;
01564 struct sockaddr_in defaddr;
01565 struct ast_ha *ha;
01566 struct ast_ha *contactha;
01567 struct ast_variable *chanvars;
01568 struct sip_pvt *mwipvt;
01569 int autoframing;
01570 struct sip_st_cfg stimer;
01571 int timer_t1;
01572 int timer_b;
01573 int deprecated_username;
01574 enum sip_peer_type type;
01575 };
01576
01577
01578
01579
01580
01581
01582
01583
01584
01585
01586
01587
01588
01589
01590 struct sip_registry {
01591 ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01592 AST_DECLARE_STRING_FIELDS(
01593 AST_STRING_FIELD(callid);
01594 AST_STRING_FIELD(realm);
01595 AST_STRING_FIELD(nonce);
01596 AST_STRING_FIELD(opaque);
01597 AST_STRING_FIELD(qop);
01598 AST_STRING_FIELD(domain);
01599 AST_STRING_FIELD(username);
01600 AST_STRING_FIELD(authuser);
01601 AST_STRING_FIELD(hostname);
01602 AST_STRING_FIELD(secret);
01603 AST_STRING_FIELD(md5secret);
01604 AST_STRING_FIELD(callback);
01605 AST_STRING_FIELD(random);
01606 AST_STRING_FIELD(peername);
01607 );
01608 enum sip_transport transport;
01609 int portno;
01610 int expire;
01611 int expiry;
01612 int regattempts;
01613 int timeout;
01614 int refresh;
01615 struct sip_pvt *call;
01616 enum sipregistrystate regstate;
01617 struct timeval regtime;
01618 int callid_valid;
01619 unsigned int ocseq;
01620 struct ast_dnsmgr_entry *dnsmgr;
01621 struct sockaddr_in us;
01622 int noncecount;
01623 char lastmsg[256];
01624 };
01625
01626
01627 struct sip_threadinfo {
01628 int stop;
01629 pthread_t threadid;
01630 struct ast_tcptls_session_instance *tcptls_session;
01631 enum sip_transport type;
01632 AST_LIST_ENTRY(sip_threadinfo) list;
01633 };
01634
01635
01636
01637 #ifdef LOW_MEMORY
01638 static int hash_peer_size = 17;
01639 static int hash_dialog_size = 17;
01640 static int hash_user_size = 17;
01641 #else
01642 static int hash_peer_size = 563;
01643 static int hash_dialog_size = 563;
01644 static int hash_user_size = 563;
01645 #endif
01646
01647
01648 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
01649
01650
01651 struct ao2_container *peers;
01652 struct ao2_container *peers_by_ip;
01653
01654
01655 static struct ast_register_list {
01656 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01657 int recheck;
01658 } regl;
01659
01660
01661
01662
01663 static int peer_hash_cb(const void *obj, const int flags)
01664 {
01665 const struct sip_peer *peer = obj;
01666
01667 return ast_str_case_hash(peer->name);
01668 }
01669
01670
01671
01672
01673 static int peer_cmp_cb(void *obj, void *arg, int flags)
01674 {
01675 struct sip_peer *peer = obj, *peer2 = arg;
01676
01677 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01678 }
01679
01680
01681
01682
01683 static int peer_iphash_cb(const void *obj, const int flags)
01684 {
01685 const struct sip_peer *peer = obj;
01686 int ret1 = peer->addr.sin_addr.s_addr;
01687 if (ret1 < 0)
01688 ret1 = -ret1;
01689
01690 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT)) {
01691 return ret1;
01692 } else {
01693 return ret1 + peer->addr.sin_port;
01694 }
01695 }
01696
01697
01698
01699
01700 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
01701 {
01702 struct sip_peer *peer = obj, *peer2 = arg;
01703
01704 if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
01705 return 0;
01706 }
01707
01708 if (!ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) && !ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
01709 if (peer->addr.sin_port == peer2->addr.sin_port) {
01710 return CMP_MATCH | CMP_STOP;
01711 } else {
01712 return 0;
01713 }
01714 }
01715
01716 return CMP_MATCH | CMP_STOP;
01717 }
01718
01719
01720
01721
01722 static int dialog_hash_cb(const void *obj, const int flags)
01723 {
01724 const struct sip_pvt *pvt = obj;
01725
01726 return ast_str_case_hash(pvt->callid);
01727 }
01728
01729
01730
01731
01732 static int dialog_cmp_cb(void *obj, void *arg, int flags)
01733 {
01734 struct sip_pvt *pvt = obj, *pvt2 = arg;
01735
01736 return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
01737 }
01738
01739 static int temp_pvt_init(void *);
01740 static void temp_pvt_cleanup(void *);
01741
01742
01743 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01744
01745 #ifdef LOW_MEMORY
01746 static void ts_ast_rtp_destroy(void *);
01747
01748 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
01749 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
01750 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
01751 #endif
01752
01753
01754
01755 static struct sip_auth *authl = NULL;
01756
01757
01758
01759
01760
01761
01762
01763
01764
01765
01766
01767
01768
01769
01770
01771
01772
01773
01774 static int sipsock = -1;
01775
01776 static struct sockaddr_in bindaddr;
01777
01778
01779
01780
01781
01782
01783
01784 static struct sockaddr_in internip;
01785
01786
01787
01788
01789
01790
01791
01792
01793
01794
01795
01796
01797
01798
01799
01800
01801
01802
01803
01804 static struct sockaddr_in externip;
01805
01806 static char externhost[MAXHOSTNAMELEN];
01807 static time_t externexpire;
01808 static int externrefresh = 10;
01809 static struct sockaddr_in stunaddr;
01810
01811
01812
01813
01814
01815
01816
01817 static struct ast_ha *localaddr;
01818
01819 static int ourport_tcp;
01820 static int ourport_tls;
01821 static struct sockaddr_in debugaddr;
01822
01823 static struct ast_config *notify_types;
01824
01825
01826
01827 #define UNLINK(element, head, prev) do { \
01828 if (prev) \
01829 (prev)->next = (element)->next; \
01830 else \
01831 (head) = (element)->next; \
01832 } while (0)
01833
01834 enum t38_action_flag {
01835 SDP_T38_NONE = 0,
01836 SDP_T38_INITIATE,
01837 SDP_T38_ACCEPT,
01838 };
01839
01840
01841
01842
01843
01844
01845 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01846 static int sip_devicestate(void *data);
01847 static int sip_sendtext(struct ast_channel *ast, const char *text);
01848 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01849 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01850 static int sip_hangup(struct ast_channel *ast);
01851 static int sip_answer(struct ast_channel *ast);
01852 static struct ast_frame *sip_read(struct ast_channel *ast);
01853 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01854 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01855 static int sip_transfer(struct ast_channel *ast, const char *dest);
01856 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01857 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01858 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01859 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01860 static const char *sip_get_callid(struct ast_channel *chan);
01861
01862 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
01863 static int sip_standard_port(enum sip_transport type, int port);
01864 static int sip_prepare_socket(struct sip_pvt *p);
01865 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
01866
01867
01868 static int sipsock_read(int *id, int fd, short events, void *ignore);
01869 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
01870 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
01871 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01872 static int retrans_pkt(const void *data);
01873 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
01874 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01875 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01876 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01877 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
01878 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01879 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);
01880 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01881 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01882 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01883 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01884 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01885 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01886 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01887 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01888 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01889 static int transmit_refer(struct sip_pvt *p, const char *dest);
01890 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01891 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01892 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
01893 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01894 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01895 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01896 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01897 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01898 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01899 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
01900
01901
01902 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01903 int useglobal_nat, const int intended_method, struct sip_request *req);
01904 static int __sip_autodestruct(const void *data);
01905 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01906 static int sip_cancel_destroy(struct sip_pvt *p);
01907 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
01908 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
01909 static void *registry_unref(struct sip_registry *reg, char *tag);
01910 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
01911 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01912 static void __sip_pretend_ack(struct sip_pvt *p);
01913 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01914 static int auto_congest(const void *arg);
01915 static int update_call_counter(struct sip_pvt *fup, int event);
01916 static int hangup_sip2cause(int cause);
01917 static const char *hangup_cause2sip(int cause);
01918 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01919 static void free_old_route(struct sip_route *route);
01920 static void list_route(struct sip_route *route);
01921 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01922 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01923 struct sip_request *req, char *uri);
01924 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01925 static void check_pendings(struct sip_pvt *p);
01926 static void *sip_park_thread(void *stuff);
01927 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01928 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01929
01930
01931 static void try_suggested_sip_codec(struct sip_pvt *p);
01932 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01933 static const char *get_sdp(struct sip_request *req, const char *name);
01934 static int find_sdp(struct sip_request *req);
01935 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01936 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
01937 struct ast_str **m_buf, struct ast_str **a_buf,
01938 int debug, int *min_packet_size);
01939 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
01940 struct ast_str **m_buf, struct ast_str **a_buf,
01941 int debug);
01942 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01943 static void do_setnat(struct sip_pvt *p, int natflags);
01944 static void stop_media_flows(struct sip_pvt *p);
01945
01946
01947 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01948 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01949 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01950 const char *secret, const char *md5secret, int sipmethod,
01951 char *uri, enum xmittype reliable, int ignore);
01952 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01953 int sipmethod, char *uri, enum xmittype reliable,
01954 struct sockaddr_in *sin, struct sip_peer **authpeer);
01955 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
01956
01957
01958 static int check_sip_domain(const char *domain, char *context, size_t len);
01959 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01960 static void clear_sip_domains(void);
01961
01962
01963 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
01964 static int clear_realm_authentication(struct sip_auth *authlist);
01965 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
01966
01967
01968 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01969 static int sip_do_reload(enum channelreloadreason reason);
01970 static int reload_config(enum channelreloadreason reason);
01971 static int expire_register(const void *data);
01972 static void *do_monitor(void *data);
01973 static int restart_monitor(void);
01974 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01975
01976 static int sip_refer_allocate(struct sip_pvt *p);
01977 static void ast_quiet_chan(struct ast_channel *chan);
01978 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01979
01980
01981
01982
01983
01984
01985
01986 #define check_request_transport(peer, tmpl) ({ \
01987 int ret = 0; \
01988 if (peer->socket.type == tmpl->socket.type) \
01989 ; \
01990 else if (!(peer->transports & tmpl->socket.type)) {\
01991 ast_log(LOG_ERROR, \
01992 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
01993 get_transport(tmpl->socket.type), peer->name, get_transport_list(peer) \
01994 ); \
01995 ret = 1; \
01996 } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
01997 ast_log(LOG_WARNING, \
01998 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
01999 peer->name, get_transport(tmpl->socket.type) \
02000 ); \
02001 } else { \
02002 ast_debug(1, \
02003 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02004 peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02005 ); \
02006 }\
02007 (ret); \
02008 })
02009
02010
02011
02012 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02013 static int sip_devicestate(void *data);
02014 static int sip_poke_noanswer(const void *data);
02015 static int sip_poke_peer(struct sip_peer *peer, int force);
02016 static void sip_poke_all_peers(void);
02017 static void sip_peer_hold(struct sip_pvt *p, int hold);
02018 static void mwi_event_cb(const struct ast_event *, void *);
02019
02020
02021 static const char *sip_nat_mode(const struct sip_pvt *p);
02022 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02023 static char *transfermode2str(enum transfermodes mode) attribute_const;
02024 static const char *nat2str(int nat) attribute_const;
02025 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02026 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02027 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02028 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02029 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02030 static void print_group(int fd, ast_group_t group, int crlf);
02031 static const char *dtmfmode2str(int mode) attribute_const;
02032 static int str2dtmfmode(const char *str) attribute_unused;
02033 static const char *insecure2str(int mode) attribute_const;
02034 static void cleanup_stale_contexts(char *new, char *old);
02035 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02036 static const char *domain_mode_to_text(const enum domain_mode mode);
02037 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02038 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02039 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02040 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02041 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02042 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02043 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02044 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02045 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02046 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02047 static char *complete_sip_peer(const char *word, int state, int flags2);
02048 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02049 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02050 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02051 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02052 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02053 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02054 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02055 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02056 static char *sip_do_debug_ip(int fd, char *arg);
02057 static char *sip_do_debug_peer(int fd, char *arg);
02058 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02059 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02060 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02061 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02062 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02063 static int sip_addheader(struct ast_channel *chan, void *data);
02064 static int sip_do_reload(enum channelreloadreason reason);
02065 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02066 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02067
02068
02069
02070
02071
02072 static void sip_dump_history(struct sip_pvt *dialog);
02073 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02074 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02075
02076
02077
02078
02079 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
02080 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02081 static void sip_dump_history(struct sip_pvt *dialog);
02082
02083
02084 static struct sip_peer *temp_peer(const char *name);
02085 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
02086 static int update_call_counter(struct sip_pvt *fup, int event);
02087 static void sip_destroy_peer(struct sip_peer *peer);
02088 static void sip_destroy_peer_fn(void *peer);
02089 static void set_peer_defaults(struct sip_peer *peer);
02090 static struct sip_peer *temp_peer(const char *name);
02091 static void register_peer_exten(struct sip_peer *peer, int onoff);
02092 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only);
02093 static int sip_poke_peer_s(const void *data);
02094 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02095 static void reg_source_db(struct sip_peer *peer);
02096 static void destroy_association(struct sip_peer *peer);
02097 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02098 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02099 static void set_socket_transport(struct sip_socket *socket, int transport);
02100
02101
02102 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms);
02103 static void update_peer(struct sip_peer *p, int expire);
02104 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02105 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02106 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02107 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02108
02109
02110 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02111 static void sip_registry_destroy(struct sip_registry *reg);
02112 static int sip_register(const char *value, int lineno);
02113 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02114 static int sip_reregister(const void *data);
02115 static int __sip_do_register(struct sip_registry *r);
02116 static int sip_reg_timeout(const void *data);
02117 static void sip_send_all_registers(void);
02118 static int sip_reinvite_retry(const void *data);
02119
02120
02121 static void append_date(struct sip_request *req);
02122 static int determine_firstline_parts(struct sip_request *req);
02123 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02124 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02125 static int find_sip_method(const char *msg);
02126 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02127 static int parse_request(struct sip_request *req);
02128 static const char *get_header(const struct sip_request *req, const char *name);
02129 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02130 static int method_match(enum sipmethod id, const char *name);
02131 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02132 static char *get_in_brackets(char *tmp);
02133 static const char *find_alias(const char *name, const char *_default);
02134 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02135 static int lws2sws(char *msgbuf, int len);
02136 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02137 static char *remove_uri_parameters(char *uri);
02138 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02139 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02140 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02141 static int set_address_from_contact(struct sip_pvt *pvt);
02142 static void check_via(struct sip_pvt *p, struct sip_request *req);
02143 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02144 static int get_rpid_num(const char *input, char *output, int maxlen);
02145 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02146 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02147 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02148 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02149
02150
02151 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02152 static void *sip_tcp_worker_fn(void *);
02153
02154
02155 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02156 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02157 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02158 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02159 static int init_resp(struct sip_request *resp, const char *msg);
02160 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02161 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02162 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02163 static void build_via(struct sip_pvt *p);
02164 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02165 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02166 static char *generate_random_string(char *buf, size_t size);
02167 static void build_callid_pvt(struct sip_pvt *pvt);
02168 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02169 static void make_our_tag(char *tagbuf, size_t len);
02170 static int add_header(struct sip_request *req, const char *var, const char *value);
02171 static int add_header_contentLength(struct sip_request *req, int len);
02172 static int add_line(struct sip_request *req, const char *line);
02173 static int add_text(struct sip_request *req, const char *text);
02174 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02175 static int add_vidupdate(struct sip_request *req);
02176 static void add_route(struct sip_request *req, struct sip_route *route);
02177 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02178 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02179 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02180 static void set_destination(struct sip_pvt *p, char *uri);
02181 static void append_date(struct sip_request *req);
02182 static void build_contact(struct sip_pvt *p);
02183 static void build_rpid(struct sip_pvt *p);
02184
02185
02186 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02187 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
02188 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02189 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02190 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02191 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02192 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02193 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02194 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02195 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02196 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
02197 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02198 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02199
02200
02201 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02202 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02203 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02204 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02205 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02206
02207
02208 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
02209 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02210 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02211 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02212 static int sip_get_codec(struct ast_channel *chan);
02213 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02214
02215
02216 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02217 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02218 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02219 static void change_t38_state(struct sip_pvt *p, int state);
02220
02221
02222 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02223 static int proc_session_timer(const void *vp);
02224 static void stop_session_timer(struct sip_pvt *p);
02225 static void start_session_timer(struct sip_pvt *p);
02226 static void restart_session_timer(struct sip_pvt *p);
02227 static const char *strefresher2str(enum st_refresher r);
02228 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02229 static int parse_minse(const char *p_hdrval, int *const p_interval);
02230 static int st_get_se(struct sip_pvt *, int max);
02231 static enum st_refresher st_get_refresher(struct sip_pvt *);
02232 static enum st_mode st_get_mode(struct sip_pvt *);
02233 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02234
02235
02236
02237 static const struct ast_channel_tech sip_tech = {
02238 .type = "SIP",
02239 .description = "Session Initiation Protocol (SIP)",
02240 .capabilities = AST_FORMAT_AUDIO_MASK,
02241 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02242 .requester = sip_request_call,
02243 .devicestate = sip_devicestate,
02244 .call = sip_call,
02245 .send_html = sip_sendhtml,
02246 .hangup = sip_hangup,
02247 .answer = sip_answer,
02248 .read = sip_read,
02249 .write = sip_write,
02250 .write_video = sip_write,
02251 .write_text = sip_write,
02252 .indicate = sip_indicate,
02253 .transfer = sip_transfer,
02254 .fixup = sip_fixup,
02255 .send_digit_begin = sip_senddigit_begin,
02256 .send_digit_end = sip_senddigit_end,
02257 .bridge = ast_rtp_bridge,
02258 .early_bridge = ast_rtp_early_bridge,
02259 .send_text = sip_sendtext,
02260 .func_channel_read = acf_channel_read,
02261 .queryoption = sip_queryoption,
02262 .get_pvt_uniqueid = sip_get_callid,
02263 };
02264
02265
02266
02267
02268
02269
02270
02271 static struct ast_channel_tech sip_tech_info;
02272
02273
02274
02275 static struct ast_tls_config sip_tls_cfg;
02276
02277
02278 static struct ast_tls_config default_tls_cfg;
02279
02280
02281 static struct ast_tcptls_session_args sip_tcp_desc = {
02282 .accept_fd = -1,
02283 .master = AST_PTHREADT_NULL,
02284 .tls_cfg = NULL,
02285 .poll_timeout = -1,
02286 .name = "sip tcp server",
02287 .accept_fn = ast_tcptls_server_root,
02288 .worker_fn = sip_tcp_worker_fn,
02289 };
02290
02291
02292 static struct ast_tcptls_session_args sip_tls_desc = {
02293 .accept_fd = -1,
02294 .master = AST_PTHREADT_NULL,
02295 .tls_cfg = &sip_tls_cfg,
02296 .poll_timeout = -1,
02297 .name = "sip tls server",
02298 .accept_fn = ast_tcptls_server_root,
02299 .worker_fn = sip_tcp_worker_fn,
02300 };
02301
02302
02303 #define IS_SIP_TECH(t) ((t) == &sip_tech || (t) == &sip_tech_info)
02304
02305
02306
02307
02308 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02309 {
02310 const struct _map_x_s *cur;
02311
02312 for (cur = table; cur->s; cur++)
02313 if (cur->x == x)
02314 return cur->s;
02315 return errorstring;
02316 }
02317
02318
02319
02320
02321 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02322 {
02323 const struct _map_x_s *cur;
02324
02325 for (cur = table; cur->s; cur++)
02326 if (!strcasecmp(cur->s, s))
02327 return cur->x;
02328 return errorvalue;
02329 }
02330
02331
02332
02333 static struct ast_rtp_protocol sip_rtp = {
02334 .type = "SIP",
02335 .get_rtp_info = sip_get_rtp_peer,
02336 .get_vrtp_info = sip_get_vrtp_peer,
02337 .get_trtp_info = sip_get_trtp_peer,
02338 .set_rtp_peer = sip_set_rtp_peer,
02339 .get_codec = sip_get_codec,
02340 };
02341
02342
02343
02344 static void *sip_tcp_worker_fn(void *data)
02345 {
02346 struct ast_tcptls_session_instance *tcptls_session = data;
02347
02348 return _sip_tcp_helper_thread(NULL, tcptls_session);
02349 }
02350
02351
02352 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session)
02353 {
02354 int res, cl;
02355 struct sip_request req = { 0, } , reqcpy = { 0, };
02356 struct sip_threadinfo *me;
02357 char buf[1024] = "";
02358
02359 me = ast_calloc(1, sizeof(*me));
02360
02361 if (!me)
02362 goto cleanup2;
02363
02364 me->threadid = pthread_self();
02365 me->tcptls_session = tcptls_session;
02366 if (tcptls_session->ssl)
02367 me->type = SIP_TRANSPORT_TLS;
02368 else
02369 me->type = SIP_TRANSPORT_TCP;
02370
02371 ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02372
02373 AST_LIST_LOCK(&threadl);
02374 AST_LIST_INSERT_TAIL(&threadl, me, list);
02375 AST_LIST_UNLOCK(&threadl);
02376
02377 if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02378 goto cleanup;
02379 if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02380 goto cleanup;
02381
02382 for (;;) {
02383 struct ast_str *str_save;
02384
02385 str_save = req.data;
02386 memset(&req, 0, sizeof(req));
02387 req.data = str_save;
02388 ast_str_reset(req.data);
02389
02390 str_save = reqcpy.data;
02391 memset(&reqcpy, 0, sizeof(reqcpy));
02392 reqcpy.data = str_save;
02393 ast_str_reset(reqcpy.data);
02394
02395 memset(buf, 0, sizeof(buf));
02396
02397 if (tcptls_session->ssl) {
02398 set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02399 req.socket.port = htons(ourport_tls);
02400 } else {
02401 set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02402 req.socket.port = htons(ourport_tcp);
02403 }
02404 req.socket.fd = tcptls_session->fd;
02405 res = ast_wait_for_input(tcptls_session->fd, -1);
02406 if (res < 0) {
02407 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02408 goto cleanup;
02409 }
02410
02411
02412 while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02413 ast_mutex_lock(&tcptls_session->lock);
02414 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02415 ast_mutex_unlock(&tcptls_session->lock);
02416 goto cleanup;
02417 }
02418 ast_mutex_unlock(&tcptls_session->lock);
02419 if (me->stop)
02420 goto cleanup;
02421 ast_str_append(&req.data, 0, "%s", buf);
02422 req.len = req.data->used;
02423 }
02424 copy_request(&reqcpy, &req);
02425 parse_request(&reqcpy);
02426 if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02427 while (cl > 0) {
02428 ast_mutex_lock(&tcptls_session->lock);
02429 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, tcptls_session->f)) {
02430 ast_mutex_unlock(&tcptls_session->lock);
02431 goto cleanup;
02432 }
02433 ast_mutex_unlock(&tcptls_session->lock);
02434 if (me->stop)
02435 goto cleanup;
02436 cl -= strlen(buf);
02437 ast_str_append(&req.data, 0, "%s", buf);
02438 req.len = req.data->used;
02439 }
02440 }
02441 req.socket.tcptls_session = tcptls_session;
02442 handle_request_do(&req, &tcptls_session->remote_address);
02443 }
02444
02445 cleanup:
02446 AST_LIST_LOCK(&threadl);
02447 AST_LIST_REMOVE(&threadl, me, list);
02448 AST_LIST_UNLOCK(&threadl);
02449 ast_free(me);
02450 cleanup2:
02451 fclose(tcptls_session->f);
02452 tcptls_session->f = NULL;
02453 tcptls_session->fd = -1;
02454 if (reqcpy.data) {
02455 ast_free(reqcpy.data);
02456 }
02457
02458 if (req.data) {
02459 ast_free(req.data);
02460 req.data = NULL;
02461 }
02462
02463 ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02464
02465 ao2_ref(tcptls_session, -1);
02466 tcptls_session = NULL;
02467
02468 return NULL;
02469 }
02470
02471
02472
02473
02474
02475
02476
02477 static void *unref_peer(struct sip_peer *peer, char *tag)
02478 {
02479 ao2_t_ref(peer, -1, tag);
02480 return NULL;
02481 }
02482
02483 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02484 {
02485 ao2_t_ref(peer, 1, tag);
02486 return peer;
02487 }
02488
02489
02490
02491
02492
02493
02494
02495
02496
02497
02498
02499
02500 static struct sip_proxy *ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02501 {
02502 struct sip_proxy *old_obproxy = pvt->outboundproxy;
02503
02504 if (proxy && proxy != &global_outboundproxy) {
02505 ao2_ref(proxy, +1);
02506 }
02507 pvt->outboundproxy = proxy;
02508 if (old_obproxy && old_obproxy != &global_outboundproxy) {
02509 ao2_ref(old_obproxy, -1);
02510 }
02511 return proxy;
02512 }
02513
02514
02515
02516
02517
02518
02519
02520
02521 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
02522 {
02523 struct sip_pkt *cp;
02524
02525 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02526
02527 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02528
02529
02530 if (dialog->owner) {
02531 if (lockowner)
02532 ast_channel_lock(dialog->owner);
02533 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
02534 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02535 if (lockowner)
02536 ast_channel_unlock(dialog->owner);
02537 }
02538 if (dialog->registry) {
02539 if (dialog->registry->call == dialog)
02540 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02541 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02542 }
02543 if (dialog->stateid > -1) {
02544 ast_extension_state_del(dialog->stateid, NULL);
02545 dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
02546 dialog->stateid = -1;
02547 }
02548
02549 if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
02550 dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02551 if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
02552 dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02553
02554
02555 while((cp = dialog->packets)) {
02556 dialog->packets = dialog->packets->next;
02557 AST_SCHED_DEL(sched, cp->retransid);
02558 dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02559 if (cp->data) {
02560 ast_free(cp->data);
02561 }
02562 ast_free(cp);
02563 }
02564
02565 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"));
02566
02567 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"));
02568
02569 if (dialog->autokillid > -1)
02570 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"));
02571
02572 if (dialog->request_queue_sched_id > -1) {
02573 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"));
02574 }
02575
02576 if (dialog->t38id > -1) {
02577 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"));
02578 }
02579
02580 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
02581 return NULL;
02582 }
02583
02584 static void *registry_unref(struct sip_registry *reg, char *tag)
02585 {
02586 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
02587 ASTOBJ_UNREF(reg, sip_registry_destroy);
02588 return NULL;
02589 }
02590
02591
02592 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
02593 {
02594 ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
02595 return ASTOBJ_REF(reg);
02596 }
02597
02598
02599 static struct ast_udptl_protocol sip_udptl = {
02600 type: "SIP",
02601 get_udptl_info: sip_get_udptl_peer,
02602 set_udptl_peer: sip_set_udptl_peer,
02603 };
02604
02605 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
02606 __attribute__((format(printf, 2, 3)));
02607
02608
02609
02610 static const char *referstatus2str(enum referstatus rstatus)
02611 {
02612 return map_x_s(referstatusstrings, rstatus, "");
02613 }
02614
02615
02616
02617
02618 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
02619 {
02620 if (p->initreq.headers)
02621 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
02622 else
02623 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
02624
02625 copy_request(&p->initreq, req);
02626 parse_request(&p->initreq);
02627 if (req->debug)
02628 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
02629 }
02630
02631
02632 static void sip_alreadygone(struct sip_pvt *dialog)
02633 {
02634 ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
02635 dialog->alreadygone = 1;
02636 }
02637
02638
02639 static int proxy_update(struct sip_proxy *proxy)
02640 {
02641
02642
02643 if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
02644
02645
02646 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
02647 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
02648 return FALSE;
02649 }
02650 }
02651 proxy->last_dnsupdate = time(NULL);
02652 return TRUE;
02653 }
02654
02655
02656 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
02657 {
02658 struct sip_proxy *proxy;
02659
02660 if (ast_strlen_zero(name)) {
02661 return NULL;
02662 }
02663
02664 proxy = ao2_alloc(sizeof(*proxy), NULL);
02665 if (!proxy)
02666 return NULL;
02667 proxy->force = force;
02668 ast_copy_string(proxy->name, name, sizeof(proxy->name));
02669 proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
02670 proxy_update(proxy);
02671 return proxy;
02672 }
02673
02674
02675 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
02676 {
02677 if (peer && peer->outboundproxy) {
02678 if (sipdebug)
02679 ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
02680 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
02681 return peer->outboundproxy;
02682 }
02683 if (global_outboundproxy.name[0]) {
02684 if (sipdebug)
02685 ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
02686 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
02687 return &global_outboundproxy;
02688 }
02689 if (sipdebug)
02690 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
02691 return NULL;
02692 }
02693
02694
02695
02696
02697
02698
02699
02700 static int method_match(enum sipmethod id, const char *name)
02701 {
02702 int len = strlen(sip_methods[id].text);
02703 int l_name = name ? strlen(name) : 0;
02704
02705 return (l_name >= len && name[len] < 33 &&
02706 !strncasecmp(sip_methods[id].text, name, len));
02707 }
02708
02709
02710 static int find_sip_method(const char *msg)
02711 {
02712 int i, res = 0;
02713
02714 if (ast_strlen_zero(msg))
02715 return 0;
02716 for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
02717 if (method_match(i, msg))
02718 res = sip_methods[i].id;
02719 }
02720 return res;
02721 }
02722
02723
02724 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
02725 {
02726 char *next, *sep;
02727 char *temp;
02728 unsigned int profile = 0;
02729 int i, found;
02730
02731 if (ast_strlen_zero(supported) )
02732 return 0;
02733 temp = ast_strdupa(supported);
02734
02735 if (sipdebug)
02736 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
02737
02738 for (next = temp; next; next = sep) {
02739 found = FALSE;
02740 if ( (sep = strchr(next, ',')) != NULL)
02741 *sep++ = '\0';
02742 next = ast_skip_blanks(next);
02743 if (sipdebug)
02744 ast_debug(3, "Found SIP option: -%s-\n", next);
02745 for (i = 0; i < ARRAY_LEN(sip_options); i++) {
02746 if (!strcasecmp(next, sip_options[i].text)) {
02747 profile |= sip_options[i].id;
02748 found = TRUE;
02749 if (sipdebug)
02750 ast_debug(3, "Matched SIP option: %s\n", next);
02751 break;
02752 }
02753 }
02754
02755
02756
02757
02758
02759 if (!found)
02760 profile |= SIP_OPT_UNKNOWN;
02761
02762 if (!found && sipdebug) {
02763 if (!strncasecmp(next, "x-", 2))
02764 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
02765 else
02766 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
02767 }
02768 }
02769
02770 if (pvt)
02771 pvt->sipoptions = profile;
02772 return profile;
02773 }
02774
02775
02776 static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
02777 {
02778 if (!sipdebug)
02779 return 0;
02780 if (debugaddr.sin_addr.s_addr) {
02781 if (((ntohs(debugaddr.sin_port) != 0)
02782 && (debugaddr.sin_port != addr->sin_port))
02783 || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
02784 return 0;
02785 }
02786 return 1;
02787 }
02788
02789
02790 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
02791 {
02792 if (p->outboundproxy)
02793 return &p->outboundproxy->ip;
02794
02795 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
02796 }
02797
02798
02799 static const char *sip_nat_mode(const struct sip_pvt *p)
02800 {
02801 return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
02802 }
02803
02804
02805 static inline int sip_debug_test_pvt(struct sip_pvt *p)
02806 {
02807 if (!sipdebug)
02808 return 0;
02809 return sip_debug_test_addr(sip_real_dst(p));
02810 }
02811
02812 static int get_transport_str2enum(const char *transport)
02813 {
02814 int res = 0;
02815
02816 if (ast_strlen_zero(transport)) {
02817 return res;
02818 }
02819
02820 if (!strcasecmp(transport, "udp")) {
02821 res |= SIP_TRANSPORT_UDP;
02822 }
02823 if (!strcasecmp(transport, "tcp")) {
02824 res |= SIP_TRANSPORT_TCP;
02825 }
02826 if (!strcasecmp(transport, "tls")) {
02827 res |= SIP_TRANSPORT_TLS;
02828 }
02829
02830 return res;
02831 }
02832
02833 static inline const char *get_transport_list(struct sip_peer *peer) {
02834 switch (peer->transports) {
02835 case SIP_TRANSPORT_UDP:
02836 return "UDP";
02837 case SIP_TRANSPORT_TCP:
02838 return "TCP";
02839 case SIP_TRANSPORT_TLS:
02840 return "TLS";
02841 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
02842 return "TCP,UDP";
02843 case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
02844 return "TLS,UDP";
02845 case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
02846 return "TLS,TCP";
02847 default:
02848 return peer->transports ?
02849 "TLS,TCP,UDP" : "UNKNOWN";
02850 }
02851 }
02852
02853 static inline const char *get_transport(enum sip_transport t)
02854 {
02855 switch (t) {
02856 case SIP_TRANSPORT_UDP:
02857 return "UDP";
02858 case SIP_TRANSPORT_TCP:
02859 return "TCP";
02860 case SIP_TRANSPORT_TLS:
02861 return "TLS";
02862 }
02863
02864 return "UNKNOWN";
02865 }
02866
02867 static inline const char *get_transport_pvt(struct sip_pvt *p)
02868 {
02869 if (p->outboundproxy && p->outboundproxy->transport) {
02870 set_socket_transport(&p->socket, p->outboundproxy->transport);
02871 }
02872
02873 return get_transport(p->socket.type);
02874 }
02875
02876
02877
02878
02879
02880
02881 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
02882 {
02883 int res = 0;
02884 const struct sockaddr_in *dst = sip_real_dst(p);
02885
02886 ast_debug(1, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
02887
02888 if (sip_prepare_socket(p) < 0)
02889 return XMIT_ERROR;
02890
02891 if (p->socket.tcptls_session)
02892 ast_mutex_lock(&p->socket.tcptls_session->lock);
02893
02894 if (p->socket.type & SIP_TRANSPORT_UDP) {
02895 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
02896 } else if (p->socket.tcptls_session) {
02897 if (p->socket.tcptls_session->f) {
02898 res = ast_tcptls_server_write(p->socket.tcptls_session, data->str, len);
02899 } else {
02900 ast_debug(2, "No p->socket.tcptls_session->f len=%d\n", len);
02901 }
02902 } else {
02903 ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
02904 return XMIT_ERROR;
02905 }
02906
02907 if (p->socket.tcptls_session)
02908 ast_mutex_unlock(&p->socket.tcptls_session->lock);
02909
02910 if (res == -1) {
02911 switch (errno) {
02912 case EBADF:
02913 case EHOSTUNREACH:
02914 case ENETDOWN:
02915 case ENETUNREACH:
02916 case ECONNREFUSED:
02917 res = XMIT_ERROR;
02918 }
02919 }
02920 if (res != len)
02921 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
02922
02923 return res;
02924 }
02925
02926
02927 static void build_via(struct sip_pvt *p)
02928 {
02929
02930 const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
02931
02932
02933 snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
02934 get_transport_pvt(p),
02935 ast_inet_ntoa(p->ourip.sin_addr),
02936 ntohs(p->ourip.sin_port), (int) p->branch, rport);
02937 }
02938
02939
02940
02941
02942
02943
02944
02945
02946 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
02947 {
02948 struct sockaddr_in theirs;
02949
02950
02951
02952
02953
02954
02955
02956
02957
02958
02959
02960
02961 int want_remap;
02962
02963 *us = internip;
02964
02965 ast_ouraddrfor(them, &us->sin_addr);
02966 theirs.sin_addr = *them;
02967
02968 want_remap = localaddr &&
02969 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
02970 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
02971
02972 if (want_remap &&
02973 (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
02974
02975 if (externexpire && time(NULL) >= externexpire) {
02976 if (stunaddr.sin_addr.s_addr) {
02977 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
02978 } else {
02979 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
02980 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
02981 }
02982 externexpire = time(NULL) + externrefresh;
02983 }
02984 if (externip.sin_addr.s_addr)
02985 *us = externip;
02986 else
02987 ast_log(LOG_WARNING, "stun failed\n");
02988 ast_debug(1, "Target address %s is not local, substituting externip\n",
02989 ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
02990 } else if (p) {
02991
02992 switch (p->socket.type) {
02993 case SIP_TRANSPORT_TCP:
02994 if (sip_tcp_desc.local_address.sin_addr.s_addr) {
02995 *us = sip_tcp_desc.local_address;
02996 } else {
02997 us->sin_port = sip_tcp_desc.local_address.sin_port;
02998 }
02999 break;
03000 case SIP_TRANSPORT_TLS:
03001 if (sip_tls_desc.local_address.sin_addr.s_addr) {
03002 *us = sip_tls_desc.local_address;
03003 } else {
03004 us->sin_port = sip_tls_desc.local_address.sin_port;
03005 }
03006 break;
03007 case SIP_TRANSPORT_UDP:
03008
03009 default:
03010 if (bindaddr.sin_addr.s_addr) {
03011 *us = bindaddr;
03012 }
03013 }
03014 } else if (bindaddr.sin_addr.s_addr) {
03015 *us = bindaddr;
03016 }
03017 ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
03018 }
03019
03020
03021 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03022 {
03023 char buf[80], *c = buf;
03024 struct sip_history *hist;
03025 int l;
03026
03027 vsnprintf(buf, sizeof(buf), fmt, ap);
03028 strsep(&c, "\r\n");
03029 l = strlen(buf) + 1;
03030 if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03031 return;
03032 if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03033 ast_free(hist);
03034 return;
03035 }
03036 memcpy(hist->event, buf, l);
03037 if (p->history_entries == MAX_HISTORY_ENTRIES) {
03038 struct sip_history *oldest;
03039 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03040 p->history_entries--;
03041 ast_free(oldest);
03042 }
03043 AST_LIST_INSERT_TAIL(p->history, hist, list);
03044 p->history_entries++;
03045 }
03046
03047
03048 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03049 {
03050 va_list ap;
03051
03052 if (!p)
03053 return;
03054
03055 if (!p->do_history && !recordhistory && !dumphistory)
03056 return;
03057
03058 va_start(ap, fmt);
03059 append_history_va(p, fmt, ap);
03060 va_end(ap);
03061
03062 return;
03063 }
03064
03065
03066 static int retrans_pkt(const void *data)
03067 {
03068 struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03069 int reschedule = DEFAULT_RETRANS;
03070 int xmitres = 0;
03071
03072
03073 sip_pvt_lock(pkt->owner);
03074
03075 if (pkt->retrans < MAX_RETRANS) {
03076 pkt->retrans++;
03077 if (!pkt->timer_t1) {
03078 if (sipdebug)
03079 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
03080 } else {
03081 int siptimer_a;
03082
03083 if (sipdebug)
03084 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03085 if (!pkt->timer_a)
03086 pkt->timer_a = 2 ;
03087 else
03088 pkt->timer_a = 2 * pkt->timer_a;
03089
03090
03091 siptimer_a = pkt->timer_t1 * pkt->timer_a;
03092 if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03093 siptimer_a = 4000;
03094
03095
03096 reschedule = siptimer_a;
03097 ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
03098 }
03099
03100 if (sip_debug_test_pvt(pkt->owner)) {
03101 const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03102 ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03103 pkt->retrans, sip_nat_mode(pkt->owner),
03104 ast_inet_ntoa(dst->sin_addr),
03105 ntohs(dst->sin_port), pkt->data->str);
03106 }
03107
03108 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03109 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03110 sip_pvt_unlock(pkt->owner);
03111 if (xmitres == XMIT_ERROR)
03112 ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03113 else
03114 return reschedule;
03115 }
03116
03117 if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03118 if (pkt->is_fatal || sipdebug)
03119 ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03120 pkt->owner->callid, pkt->seqno,
03121 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03122 } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03123 ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03124
03125 }
03126 if (xmitres == XMIT_ERROR) {
03127 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03128 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03129 } else
03130 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03131
03132 pkt->retransid = -1;
03133
03134 if (pkt->is_fatal) {
03135 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03136 sip_pvt_unlock(pkt->owner);
03137 usleep(1);
03138 sip_pvt_lock(pkt->owner);
03139 }
03140
03141 if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
03142 pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03143
03144 if (pkt->owner->owner) {
03145 sip_alreadygone(pkt->owner);
03146 ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03147 ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03148 ast_channel_unlock(pkt->owner->owner);
03149 } else {
03150
03151
03152
03153 if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03154 pkt->owner->needdestroy = 1;
03155 sip_alreadygone(pkt->owner);
03156 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03157 }
03158 }
03159 }
03160
03161 if (pkt->method == SIP_BYE) {
03162
03163 if (pkt->owner->owner)
03164 ast_channel_unlock(pkt->owner->owner);
03165 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03166 pkt->owner->needdestroy = 1;
03167 }
03168
03169
03170 for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03171 if (cur == pkt) {
03172 UNLINK(cur, pkt->owner->packets, prev);
03173 sip_pvt_unlock(pkt->owner);
03174 if (pkt->owner)
03175 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03176 if (pkt->data)
03177 ast_free(pkt->data);
03178 pkt->data = NULL;
03179 ast_free(pkt);
03180 return 0;
03181 }
03182 }
03183
03184 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03185 sip_pvt_unlock(pkt->owner);
03186 return 0;
03187 }
03188
03189
03190
03191
03192 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
03193 {
03194 struct sip_pkt *pkt = NULL;
03195 int siptimer_a = DEFAULT_RETRANS;
03196 int xmitres = 0;
03197 int respid;
03198
03199 if (sipmethod == SIP_INVITE) {
03200
03201 p->pendinginvite = seqno;
03202 }
03203
03204
03205
03206
03207 if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03208 xmitres = __sip_xmit(p, data, len);
03209 if (xmitres == XMIT_ERROR) {
03210 append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03211 return AST_FAILURE;
03212 } else
03213 return AST_SUCCESS;
03214 }
03215
03216 if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03217 return AST_FAILURE;
03218
03219 if (!(pkt->data = ast_str_create(len))) {
03220 ast_free(pkt);
03221 return AST_FAILURE;
03222 }
03223 ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03224 pkt->packetlen = len;
03225
03226 pkt->method = sipmethod;
03227 pkt->seqno = seqno;
03228 pkt->is_resp = resp;
03229 pkt->is_fatal = fatal;
03230 pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03231 pkt->next = p->packets;
03232 p->packets = pkt;
03233 if (resp) {
03234
03235 if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30d", &respid) == 1) {
03236 pkt->response_code = respid;
03237 }
03238 }
03239 pkt->timer_t1 = p->timer_t1;
03240 pkt->retransid = -1;
03241 if (pkt->timer_t1)
03242 siptimer_a = pkt->timer_t1 * 2;
03243
03244
03245 AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03246 if (sipdebug)
03247 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
03248
03249 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03250
03251 if (xmitres == XMIT_ERROR) {
03252 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03253 ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03254 AST_SCHED_DEL(sched, pkt->retransid);
03255 p->packets = pkt->next;
03256 pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03257 ast_free(pkt->data);
03258 ast_free(pkt);
03259 return AST_FAILURE;
03260 } else {
03261 return AST_SUCCESS;
03262 }
03263 }
03264
03265
03266
03267
03268
03269
03270 static int __sip_autodestruct(const void *data)
03271 {
03272 struct sip_pvt *p = (struct sip_pvt *)data;
03273
03274
03275 if (p->subscribed) {
03276 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);
03277 p->subscribed = NONE;
03278 append_history(p, "Subscribestatus", "timeout");
03279 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03280 return 10000;
03281 }
03282
03283
03284 if (p->packets) {
03285 if (!p->needdestroy) {
03286 char method_str[31];
03287 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03288 append_history(p, "ReliableXmit", "timeout");
03289 if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03290 if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03291 p->needdestroy = 1;
03292 }
03293 }
03294 return 10000;
03295 } else {
03296
03297 __sip_pretend_ack(p);
03298 }
03299 }
03300
03301 if (p->subscribed == MWI_NOTIFICATION)
03302 if (p->relatedpeer)
03303 p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");
03304
03305
03306 p->autokillid = -1;
03307
03308 if (p->owner) {
03309 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03310 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03311 } else if (p->refer && !p->alreadygone) {
03312 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03313 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03314 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03315 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03316 } else {
03317 append_history(p, "AutoDestroy", "%s", p->callid);
03318 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03319 dialog_unlink_all(p, TRUE, TRUE);
03320
03321
03322
03323 }
03324 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03325 return 0;
03326 }
03327
03328
03329 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03330 {
03331 if (ms < 0) {
03332 if (p->timer_t1 == 0) {
03333 p->timer_t1 = global_t1;
03334 p->timer_b = global_timer_b;
03335 }
03336 ms = p->timer_t1 * 64;
03337 }
03338 if (sip_debug_test_pvt(p))
03339 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03340 if (sip_cancel_destroy(p))
03341 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
03342
03343 if (p->do_history)
03344 append_history(p, "SchedDestroy", "%d ms", ms);
03345 p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03346
03347 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
03348 stop_session_timer(p);
03349 }
03350
03351
03352
03353
03354
03355 static int sip_cancel_destroy(struct sip_pvt *p)
03356 {
03357 int res = 0;
03358 if (p->autokillid > -1) {
03359 int res3;
03360
03361 if (!(res3 = ast_sched_del(sched, p->autokillid))) {
03362 append_history(p, "CancelDestroy", "");
03363 p->autokillid = -1;
03364 dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
03365 }
03366 }
03367 return res;
03368 }
03369
03370
03371
03372 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03373 {
03374 struct sip_pkt *cur, *prev = NULL;
03375 const char *msg = "Not Found";
03376 int res = FALSE;
03377
03378
03379
03380
03381
03382
03383 if (p->outboundproxy && !p->outboundproxy->force){
03384 ref_proxy(p, NULL);
03385 }
03386
03387 for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03388 if (cur->seqno != seqno || cur->is_resp != resp)
03389 continue;
03390 if (cur->is_resp || cur->method == sipmethod) {
03391 res = TRUE;
03392 msg = "Found";
03393 if (!resp && (seqno == p->pendinginvite)) {
03394 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03395 p->pendinginvite = 0;
03396 }
03397 if (cur->retransid > -1) {
03398 if (sipdebug)
03399 ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03400 }
03401
03402
03403
03404
03405
03406
03407
03408
03409
03410
03411
03412
03413
03414
03415
03416
03417 while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03418 sip_pvt_unlock(p);
03419 usleep(1);
03420 sip_pvt_lock(p);
03421 }
03422 UNLINK(cur, p->packets, prev);
03423 dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
03424 if (cur->data)
03425 ast_free(cur->data);
03426 ast_free(cur);
03427 break;
03428 }
03429 }
03430 ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
03431 p->callid, resp ? "Response" : "Request", seqno, msg);
03432 return res;
03433 }
03434
03435
03436
03437 static void __sip_pretend_ack(struct sip_pvt *p)
03438 {
03439 struct sip_pkt *cur = NULL;
03440
03441 while (p->packets) {
03442 int method;
03443 if (cur == p->packets) {
03444 ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
03445 return;
03446 }
03447 cur = p->packets;
03448 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
03449 __sip_ack(p, cur->seqno, cur->is_resp, method);
03450 }
03451 }
03452
03453
03454 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03455 {
03456 struct sip_pkt *cur;
03457 int res = FALSE;
03458
03459 for (cur = p->packets; cur; cur = cur->next) {
03460 if (cur->seqno == seqno && cur->is_resp == resp &&
03461 (cur->is_resp || method_match(sipmethod, cur->data->str))) {
03462
03463 if (cur->retransid > -1) {
03464 if (sipdebug)
03465 ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
03466 }
03467 AST_SCHED_DEL(sched, cur->retransid);
03468 res = TRUE;
03469 break;
03470 }
03471 }
03472 ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
03473 return res;
03474 }
03475
03476
03477
03478 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
03479 {
03480 copy_request(dst, src);
03481 parse_request(dst);
03482 }
03483
03484
03485 static void add_blank(struct sip_request *req)
03486 {
03487 if (!req->lines) {
03488
03489 ast_str_append(&req->data, 0, "\r\n");
03490 req->len = req->data->used;
03491 }
03492 }
03493
03494
03495 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03496 {
03497 int res;
03498
03499 add_blank(req);
03500 if (sip_debug_test_pvt(p)) {
03501 const struct sockaddr_in *dst = sip_real_dst(p);
03502
03503 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
03504 reliable ? "Reliably " : "", sip_nat_mode(p),
03505 ast_inet_ntoa(dst->sin_addr),
03506 ntohs(dst->sin_port), req->data->str);
03507 }
03508 if (p->do_history) {
03509 struct sip_request tmp = { .rlPart1 = 0, };
03510 parse_copy(&tmp, req);
03511 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
03512 (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
03513 ast_free(tmp.data);
03514 }
03515 res = (reliable) ?
03516 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03517 __sip_xmit(p, req->data, req->len);
03518 ast_free(req->data);
03519 req->data = NULL;
03520 if (res > 0)
03521 return 0;
03522 return res;
03523 }
03524
03525
03526 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03527 {
03528 int res;
03529
03530
03531
03532
03533 if (p->outboundproxy) {
03534 p->sa = p->outboundproxy->ip;
03535 }
03536
03537 add_blank(req);
03538 if (sip_debug_test_pvt(p)) {
03539 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
03540 ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
03541 else
03542 ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
03543 }
03544 if (p->do_history) {
03545 struct sip_request tmp = { .rlPart1 = 0, };
03546 parse_copy(&tmp, req);
03547 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
03548 ast_free(tmp.data);
03549 }
03550 res = (reliable) ?
03551 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03552 __sip_xmit(p, req->data, req->len);
03553 if (req->data) {
03554 ast_free(req->data);
03555 req->data = NULL;
03556 }
03557 return res;
03558 }
03559
03560
03561 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
03562 {
03563 int res = -1;
03564 enum ast_t38_state state = T38_STATE_UNAVAILABLE;
03565 struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
03566
03567 switch (option) {
03568 case AST_OPTION_T38_STATE:
03569
03570 if (*datalen != sizeof(enum ast_t38_state)) {
03571 ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
03572 return -1;
03573 }
03574
03575 sip_pvt_lock(p);
03576
03577
03578 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
03579 switch (p->t38.state) {
03580 case T38_LOCAL_REINVITE:
03581 case T38_PEER_REINVITE:
03582 state = T38_STATE_NEGOTIATING;
03583 break;
03584 case T38_ENABLED:
03585 state = T38_STATE_NEGOTIATED;
03586 break;
03587 default:
03588 state = T38_STATE_UNKNOWN;
03589 }
03590 }
03591
03592 sip_pvt_unlock(p);
03593
03594 *((enum ast_t38_state *) data) = state;
03595 res = 0;
03596
03597 break;
03598 default:
03599 break;
03600 }
03601
03602 return res;
03603 }
03604
03605
03606
03607
03608
03609 static const char *find_closing_quote(const char *start, const char *lim)
03610 {
03611 char last_char = '\0';
03612 const char *s;
03613 for (s = start; *s && s != lim; last_char = *s++) {
03614 if (*s == '"' && last_char != '\\')
03615 break;
03616 }
03617 return s;
03618 }
03619
03620
03621
03622
03623
03624
03625
03626
03627
03628
03629
03630
03631
03632 static char *get_in_brackets(char *tmp)
03633 {
03634 const char *parse = tmp;
03635 char *first_bracket;
03636
03637
03638
03639
03640
03641 while ( (first_bracket = strchr(parse, '<')) ) {
03642 char *first_quote = strchr(parse, '"');
03643
03644 if (!first_quote || first_quote > first_bracket)
03645 break;
03646
03647 parse = find_closing_quote(first_quote + 1, NULL);
03648 if (!*parse) {
03649
03650 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
03651 break;
03652 }
03653 parse++;
03654 }
03655 if (first_bracket) {
03656 char *second_bracket = strchr(first_bracket + 1, '>');
03657 if (second_bracket) {
03658 *second_bracket = '\0';
03659 tmp = first_bracket + 1;
03660 } else {
03661 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
03662 }
03663 }
03664
03665 return tmp;
03666 }
03667
03668
03669
03670
03671
03672
03673
03674
03675
03676
03677
03678
03679
03680
03681
03682
03683
03684
03685 static int parse_uri(char *uri, char *scheme,
03686 char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
03687 {
03688 char *name = NULL;
03689 int error = 0;
03690
03691
03692 if (pass)
03693 *pass = "";
03694 if (port)
03695 *port = "";
03696 if (scheme) {
03697 int l = strlen(scheme);
03698 if (!strncasecmp(uri, scheme, l))
03699 uri += l;
03700 else {
03701 ast_debug(1, "Missing scheme '%s' in '%s'\n", scheme, uri);
03702 error = -1;
03703 }
03704 }
03705 if (transport) {
03706 char *t, *type = "";
03707 *transport = "";
03708 if ((t = strstr(uri, "transport="))) {
03709 strsep(&t, "=");
03710 if ((type = strsep(&t, ";"))) {
03711 *transport = type;
03712 }
03713 }
03714 }
03715
03716 if (!domain) {
03717
03718
03719
03720 } else {
03721
03722
03723
03724 char *c, *dom = "";
03725
03726 if ((c = strchr(uri, '@')) == NULL) {
03727
03728 dom = uri;
03729 name = "";
03730 } else {
03731 *c++ = '\0';
03732 dom = c;
03733 name = uri;
03734 }
03735
03736
03737 dom = strsep(&dom, ";");
03738 name = strsep(&name, ";");
03739
03740 if (port && (c = strchr(dom, ':'))) {
03741 *c++ = '\0';
03742 *port = c;
03743 }
03744 if (pass && (c = strchr(name, ':'))) {
03745 *c++ = '\0';
03746 *pass = c;
03747 }
03748 *domain = dom;
03749 }
03750 if (ret_name)
03751 *ret_name = name;
03752 if (options)
03753 *options = uri ? uri : "";
03754
03755 return error;
03756 }
03757
03758
03759 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
03760 {
03761 struct sip_pvt *p = chan->tech_pvt;
03762
03763 if (subclass != AST_HTML_URL)
03764 return -1;
03765
03766 ast_string_field_build(p, url, "<%s>;mode=active", data);
03767
03768 if (sip_debug_test_pvt(p))
03769 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
03770
03771 switch (chan->_state) {
03772 case AST_STATE_RING:
03773 transmit_response(p, "100 Trying", &p->initreq);
03774 break;
03775 case AST_STATE_RINGING:
03776 transmit_response(p, "180 Ringing", &p->initreq);
03777 break;
03778 case AST_STATE_UP:
03779 if (!p->pendinginvite) {
03780 transmit_reinvite_with_sdp(p, FALSE, FALSE);
03781 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
03782 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
03783 }
03784 break;
03785 default:
03786 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
03787 }
03788
03789 return 0;
03790 }
03791
03792
03793 static const char *sip_get_callid(struct ast_channel *chan)
03794 {
03795 return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
03796 }
03797
03798
03799
03800 static int sip_sendtext(struct ast_channel *ast, const char *text)
03801 {
03802 struct sip_pvt *p = ast->tech_pvt;
03803 int debug = sip_debug_test_pvt(p);
03804
03805 if (debug)
03806 ast_verbose("Sending text %s on %s\n", text, ast->name);
03807 if (!p)
03808 return -1;
03809
03810
03811 if (!text)
03812 return 0;
03813 if (debug)
03814 ast_verbose("Really sending text %s on %s\n", text, ast->name);
03815 transmit_message_with_text(p, text);
03816 return 0;
03817 }
03818
03819
03820
03821
03822
03823
03824 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms)
03825 {
03826 char port[10];
03827 char ipaddr[INET_ADDRSTRLEN];
03828 char regseconds[20];
03829 char *tablename = NULL;
03830 char str_lastms[20];
03831
03832 const char *sysname = ast_config_AST_SYSTEM_NAME;
03833 char *syslabel = NULL;
03834
03835 time_t nowtime = time(NULL) + expirey;
03836 const char *fc = fullcontact ? "fullcontact" : NULL;
03837
03838 int realtimeregs = ast_check_realtime("sipregs");
03839
03840 tablename = realtimeregs ? "sipregs" : "sippeers";
03841
03842
03843 snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
03844 snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
03845 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
03846 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
03847
03848 if (ast_strlen_zero(sysname))
03849 sysname = NULL;
03850 else if (sip_cfg.rtsave_sysname)
03851 syslabel = "regserver";
03852
03853 if (fc) {
03854 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
03855 "port", port, "regseconds", regseconds,
03856 deprecated_username ? "username" : "defaultuser", defaultuser,
03857 "useragent", useragent, "lastms", str_lastms,
03858 fc, fullcontact, syslabel, sysname, SENTINEL);
03859 } else {
03860 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
03861 "port", port, "regseconds", regseconds,
03862 "useragent", useragent, "lastms", str_lastms,
03863 deprecated_username ? "username" : "defaultuser", defaultuser,
03864 syslabel, sysname, SENTINEL);
03865 }
03866 }
03867
03868
03869 static void register_peer_exten(struct sip_peer *peer, int onoff)
03870 {
03871 char multi[256];
03872 char *stringp, *ext, *context;
03873 struct pbx_find_info q = { .stacklen = 0 };
03874
03875
03876
03877
03878
03879 if (ast_strlen_zero(global_regcontext))
03880 return;
03881
03882 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
03883 stringp = multi;
03884 while ((ext = strsep(&stringp, "&"))) {
03885 if ((context = strchr(ext, '@'))) {
03886 *context++ = '\0';
03887 if (!ast_context_find(context)) {
03888 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
03889 continue;
03890 }
03891 } else {
03892 context = global_regcontext;
03893 }
03894 if (onoff) {
03895 if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
03896 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
03897 ast_strdup(peer->name), ast_free_ptr, "SIP");
03898 }
03899 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
03900 ast_context_remove_extension(context, ext, 1, NULL);
03901 }
03902 }
03903 }
03904
03905
03906 static void destroy_mailbox(struct sip_mailbox *mailbox)
03907 {
03908 if (mailbox->mailbox)
03909 ast_free(mailbox->mailbox);
03910 if (mailbox->context)
03911 ast_free(mailbox->context);
03912 if (mailbox->event_sub)
03913 ast_event_unsubscribe(mailbox->event_sub);
03914 ast_free(mailbox);
03915 }
03916
03917
03918 static void clear_peer_mailboxes(struct sip_peer *peer)
03919 {
03920 struct sip_mailbox *mailbox;
03921
03922 while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
03923 destroy_mailbox(mailbox);
03924 }
03925
03926 static void sip_destroy_peer_fn(void *peer)
03927 {
03928 sip_destroy_peer(peer);
03929 }
03930
03931
03932 static void sip_destroy_peer(struct sip_peer *peer)
03933 {
03934 ast_debug(3, "Destroying SIP peer %s\n", peer->name);
03935 if (peer->outboundproxy)
03936 ao2_ref(peer->outboundproxy, -1);
03937 peer->outboundproxy = NULL;
03938
03939
03940 if (peer->call) {
03941 dialog_unlink_all(peer->call, TRUE, TRUE);
03942 peer->call = dialog_unref(peer->call, "peer->call is being unset");
03943 }
03944
03945
03946 if (peer->mwipvt) {
03947 dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
03948 peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
03949 }
03950
03951 if (peer->chanvars) {
03952 ast_variables_destroy(peer->chanvars);
03953 peer->chanvars = NULL;
03954 }
03955
03956 register_peer_exten(peer, FALSE);
03957 ast_free_ha(peer->ha);
03958 if (peer->selfdestruct)
03959 ast_atomic_fetchadd_int(&apeerobjs, -1);
03960 else if (peer->is_realtime) {
03961 ast_atomic_fetchadd_int(&rpeerobjs, -1);
03962 ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
03963 } else
03964 ast_atomic_fetchadd_int(&speerobjs, -1);
03965 clear_realm_authentication(peer->auth);
03966 peer->auth = NULL;
03967 if (peer->dnsmgr)
03968 ast_dnsmgr_release(peer->dnsmgr);
03969 clear_peer_mailboxes(peer);
03970
03971 if (peer->socket.tcptls_session) {
03972 ao2_ref(peer->socket.tcptls_session, -1);
03973 peer->socket.tcptls_session = NULL;
03974 }
03975 }
03976
03977
03978 static void update_peer(struct sip_peer *p, int expire)
03979 {
03980 int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
03981 if (sip_cfg.peer_rtupdate &&
03982 (p->is_realtime || rtcachefriends)) {
03983 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
03984 }
03985 }
03986
03987 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
03988 {
03989 struct ast_variable *var = NULL;
03990 struct ast_flags flags = {0};
03991 char *cat = NULL;
03992 const char *insecure;
03993 while ((cat = ast_category_browse(cfg, cat))) {
03994 insecure = ast_variable_retrieve(cfg, cat, "insecure");
03995 set_insecure_flags(&flags, insecure, -1);
03996 if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
03997 var = ast_category_root(cfg, cat);
03998 break;
03999 }
04000 }
04001 return var;
04002 }
04003
04004 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04005 {
04006 struct ast_variable *tmp;
04007 for (tmp = var; tmp; tmp = tmp->next) {
04008 if (!newpeername && !strcasecmp(tmp->name, "name"))
04009 newpeername = tmp->value;
04010 }
04011 return newpeername;
04012 }
04013
04014
04015
04016
04017
04018
04019
04020 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04021 {
04022 struct sip_peer *peer;
04023 struct ast_variable *var = NULL;
04024 struct ast_variable *varregs = NULL;
04025 struct ast_variable *tmp;
04026 struct ast_config *peerlist = NULL;
04027 char ipaddr[INET_ADDRSTRLEN];
04028 char portstring[6];
04029 char *cat = NULL;
04030 unsigned short portnum;
04031 int realtimeregs = ast_check_realtime("sipregs");
04032
04033
04034 if (newpeername) {
04035 if (realtimeregs)
04036 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04037
04038 var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04039 if (!var && sin)
04040 var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04041 if (!var) {
04042 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04043
04044
04045
04046
04047
04048
04049 if (var && sin) {
04050 for (tmp = var; tmp; tmp = tmp->next) {
04051 if (!strcasecmp(tmp->name, "host")) {
04052 struct hostent *hp;
04053 struct ast_hostent ahp;
04054 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04055
04056 ast_variables_destroy(var);
04057 var = NULL;
04058 }
04059 break;
04060 }
04061 }
04062 }
04063 }
04064 }
04065
04066 if (!var && sin) {
04067 ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04068 portnum = ntohs(sin->sin_port);
04069 sprintf(portstring, "%u", portnum);
04070 var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);
04071 if (var) {
04072 if (realtimeregs) {
04073 newpeername = get_name_from_variable(var, newpeername);
04074 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04075 }
04076 } else {
04077 if (realtimeregs)
04078 varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04079 else
04080 var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL);
04081 if (varregs) {
04082 newpeername = get_name_from_variable(varregs, newpeername);
04083 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04084 }
04085 }
04086 if (!var) {
04087 peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04088 if (peerlist) {
04089 var = get_insecure_variable_from_config(peerlist);
04090 if(var) {
04091 if (realtimeregs) {
04092 newpeername = get_name_from_variable(var, newpeername);
04093 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04094 }
04095 } else {
04096 peerlist = NULL;
04097 cat = NULL;
04098 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04099 if(peerlist) {
04100 var = get_insecure_variable_from_config(peerlist);
04101 if(var) {
04102 if (realtimeregs) {
04103 newpeername = get_name_from_variable(var, newpeername);
04104 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04105 }
04106 }
04107 }
04108 }
04109 } else {
04110 if (realtimeregs) {
04111 peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04112 if (peerlist) {
04113 varregs = get_insecure_variable_from_config(peerlist);
04114 if (varregs) {
04115 newpeername = get_name_from_variable(varregs, newpeername);
04116 var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04117 }
04118 }
04119 } else {
04120 peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04121 if (peerlist) {
04122 var = get_insecure_variable_from_config(peerlist);
04123 if (var) {
04124 newpeername = get_name_from_variable(var, newpeername);
04125 varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04126 }
04127 }
04128 }
04129 }
04130 }
04131 }
04132
04133 if (!var) {
04134 if (peerlist)
04135 ast_config_destroy(peerlist);
04136 return NULL;
04137 }
04138
04139 for (tmp = var; tmp; tmp = tmp->next) {
04140
04141 if (!strcasecmp(tmp->name, "type") &&
04142 !strcasecmp(tmp->value, "user")) {
04143 if(peerlist)
04144 ast_config_destroy(peerlist);
04145 else {
04146 ast_variables_destroy(var);
04147 ast_variables_destroy(varregs);
04148 }
04149 return NULL;
04150 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04151 newpeername = tmp->value;
04152 }
04153 }
04154
04155 if (!newpeername) {
04156 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04157 if(peerlist)
04158 ast_config_destroy(peerlist);
04159 else
04160 ast_variables_destroy(var);
04161 return NULL;
04162 }
04163
04164
04165
04166 peer = build_peer(newpeername, var, varregs, TRUE);
04167 if (!peer) {
04168 if(peerlist)
04169 ast_config_destroy(peerlist);
04170 else {
04171 ast_variables_destroy(var);
04172 ast_variables_destroy(varregs);
04173 }
04174 return NULL;
04175 }
04176
04177 ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04178
04179 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04180
04181 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04182 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04183 AST_SCHED_REPLACE_UNREF(peer->expire, sched, global_rtautoclear * 1000, expire_register, peer,
04184 unref_peer(_data, "remove registration ref"),
04185 unref_peer(peer, "remove registration ref"),
04186 ref_peer(peer, "add registration ref"));
04187 }
04188 ao2_t_link(peers, peer, "link peer into peers table");
04189 if (peer->addr.sin_addr.s_addr) {
04190 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04191 }
04192 }
04193 peer->is_realtime = 1;
04194 if (peerlist)
04195 ast_config_destroy(peerlist);
04196 else {
04197 ast_variables_destroy(var);
04198 ast_variables_destroy(varregs);
04199 }
04200
04201 return peer;
04202 }
04203
04204
04205
04206
04207
04208
04209 struct peer_finding_info {
04210 struct sip_peer tmp_peer;
04211 int which_objects;
04212 };
04213
04214
04215 static int find_by_name(void *obj, void *arg, int flags)
04216 {
04217 struct sip_peer *search = obj;
04218 struct peer_finding_info *pfi = arg;
04219
04220
04221 if (strcmp(search->name, pfi->tmp_peer.name)) {
04222 return 0;
04223 }
04224
04225 switch (pfi->which_objects) {
04226 case FINDUSERS:
04227 if (!(search->type & SIP_TYPE_USER)) {
04228 return 0;
04229 }
04230 break;
04231 case FINDPEERS:
04232 if (!(search->type & SIP_TYPE_PEER)) {
04233 return 0;
04234 }
04235 break;
04236 case FINDALLDEVICES:
04237 break;
04238 }
04239
04240 return CMP_MATCH | CMP_STOP;
04241 }
04242
04243
04244
04245
04246
04247
04248
04249
04250
04251
04252
04253
04254
04255
04256 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only)
04257 {
04258 struct sip_peer *p = NULL;
04259
04260 if (peer) {
04261 struct peer_finding_info pfi = {
04262 .which_objects = which_objects,
04263 };
04264 ast_copy_string(pfi.tmp_peer.name, peer, sizeof(pfi.tmp_peer.name));
04265 p = ao2_t_callback(peers, OBJ_POINTER, find_by_name, &pfi, "ao2_callback in peers table");
04266 } else if (sin) {
04267 struct sip_peer tmp_peer;
04268 tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04269 tmp_peer.addr.sin_port = sin->sin_port;
04270 tmp_peer.flags[0].flags = 0;
04271 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table");
04272 if (!p) {
04273 ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04274 p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2");
04275 if (p) {
04276 return p;
04277 }
04278 }
04279 }
04280
04281 if (!p && (realtime || devstate_only))
04282 p = realtime_peer(peer, sin, devstate_only);
04283
04284 return p;
04285 }
04286
04287
04288 static void do_setnat(struct sip_pvt *p, int natflags)
04289 {
04290 const char *mode = natflags ? "On" : "Off";
04291
04292 if (p->rtp) {
04293 ast_debug(1, "Setting NAT on RTP to %s\n", mode);
04294 ast_rtp_setnat(p->rtp, natflags);
04295 }
04296 if (p->vrtp) {
04297 ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
04298 ast_rtp_setnat(p->vrtp, natflags);
04299 }
04300 if (p->udptl) {
04301 ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
04302 ast_udptl_setnat(p->udptl, natflags);
04303 }
04304 if (p->trtp) {
04305 ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
04306 ast_rtp_setnat(p->trtp, natflags);
04307 }
04308 }
04309
04310
04311 static void change_t38_state(struct sip_pvt *p, int state)
04312 {
04313 int old = p->t38.state;
04314 struct ast_channel *chan = p->owner;
04315 struct ast_control_t38_parameters parameters = { .request_response = 0 };
04316
04317
04318 if (old == state)
04319 return;
04320
04321 p->t38.state = state;
04322 ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
04323
04324
04325 if (!chan)
04326 return;
04327
04328
04329 if (state == T38_PEER_REINVITE) {
04330 parameters = p->t38.their_parms;
04331 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04332 parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
04333 } else if (state == T38_ENABLED) {
04334 parameters = p->t38.their_parms;
04335 parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04336 parameters.request_response = AST_T38_NEGOTIATED;
04337 } else if (state == T38_DISABLED && old == T38_ENABLED)
04338 parameters.request_response = AST_T38_TERMINATED;
04339 else if (state == T38_DISABLED && old == T38_LOCAL_REINVITE)
04340 parameters.request_response = AST_T38_REFUSED;
04341
04342
04343 if (parameters.request_response)
04344 ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, ¶meters, sizeof(parameters));
04345 }
04346
04347
04348 static void set_t38_capabilities(struct sip_pvt *p)
04349 {
04350 if (p->udptl) {
04351 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
04352 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
04353 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
04354 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
04355 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
04356 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
04357 }
04358 }
04359 }
04360
04361 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
04362 {
04363 if (to_sock->tcptls_session) {
04364 ao2_ref(to_sock->tcptls_session, -1);
04365 to_sock->tcptls_session = NULL;
04366 }
04367
04368 if (from_sock->tcptls_session) {
04369 ao2_ref(from_sock->tcptls_session, +1);
04370 }
04371
04372 *to_sock = *from_sock;
04373 }
04374
04375
04376
04377
04378
04379
04380
04381
04382 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
04383 {
04384
04385
04386
04387 if (dialog->socket.type && check_request_transport(peer, dialog))
04388 return -1;
04389 copy_socket_data(&dialog->socket, &peer->socket);
04390
04391 if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
04392 (!peer->maxms || ((peer->lastms >= 0) && (peer->lastms <= peer->maxms)))) {
04393 dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
04394 dialog->recv = dialog->sa;
04395 } else
04396 return -1;
04397
04398 ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
04399 ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04400 dialog->capability = peer->capability;
04401 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
04402 (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
04403 !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
04404 dialog->vrtp) {
04405 ast_rtp_destroy(dialog->vrtp);
04406 dialog->vrtp = NULL;
04407 }
04408 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
04409 ast_rtp_destroy(dialog->trtp);
04410 dialog->trtp = NULL;
04411 }
04412 dialog->prefs = peer->prefs;
04413 if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
04414 if (!dialog->udptl) {
04415
04416 dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04417 }
04418 set_t38_capabilities(dialog);
04419 } else if (dialog->udptl) {
04420 ast_udptl_destroy(dialog->udptl);
04421 dialog->udptl = NULL;
04422 }
04423 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04424
04425 if (dialog->rtp) {
04426 ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04427 ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04428 ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
04429 ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
04430 ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
04431
04432 ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
04433 dialog->autoframing = peer->autoframing;
04434 }
04435 if (dialog->vrtp) {
04436 ast_rtp_setdtmf(dialog->vrtp, 0);
04437 ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
04438 ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
04439 ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
04440 ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
04441 }
04442 if (dialog->trtp) {
04443 ast_rtp_setdtmf(dialog->trtp, 0);
04444 ast_rtp_setdtmfcompensate(dialog->trtp, 0);
04445 ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
04446 ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
04447 ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
04448 }
04449
04450 ast_string_field_set(dialog, peername, peer->name);
04451 ast_string_field_set(dialog, authname, peer->username);
04452 ast_string_field_set(dialog, username, peer->username);
04453 ast_string_field_set(dialog, peersecret, peer->secret);
04454 ast_string_field_set(dialog, peermd5secret, peer->md5secret);
04455 ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
04456 ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
04457 ast_string_field_set(dialog, tohost, peer->tohost);
04458 ast_string_field_set(dialog, fullcontact, peer->fullcontact);
04459 ast_string_field_set(dialog, context, peer->context);
04460 ast_string_field_set(dialog, parkinglot, peer->parkinglot);
04461 ref_proxy(dialog, obproxy_get(dialog, peer));
04462 dialog->callgroup = peer->callgroup;
04463 dialog->pickupgroup = peer->pickupgroup;
04464 dialog->allowtransfer = peer->allowtransfer;
04465 dialog->jointnoncodeccapability = dialog->noncodeccapability;
04466 dialog->rtptimeout = peer->rtptimeout;
04467 dialog->peerauth = peer->auth;
04468 dialog->maxcallbitrate = peer->maxcallbitrate;
04469 if (ast_strlen_zero(dialog->tohost))
04470 ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
04471 if (!ast_strlen_zero(peer->fromdomain)) {
04472 ast_string_field_set(dialog, fromdomain, peer->fromdomain);
04473 if (!dialog->initreq.headers) {
04474 char *c;
04475 char *tmpcall = ast_strdupa(dialog->callid);
04476
04477 c = strchr(tmpcall, '@');
04478 if (c) {
04479 *c = '\0';
04480 ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
04481 ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
04482 ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
04483 }
04484 }
04485 }
04486 if (!ast_strlen_zero(peer->fromuser))
04487 ast_string_field_set(dialog, fromuser, peer->fromuser);
04488 if (!ast_strlen_zero(peer->language))
04489 ast_string_field_set(dialog, language, peer->language);
04490
04491
04492
04493
04494 if (peer->maxms && peer->lastms)
04495 dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
04496 else
04497 dialog->timer_t1 = peer->timer_t1;
04498
04499
04500
04501 if (peer->timer_b)
04502 dialog->timer_b = peer->timer_b;
04503 else
04504 dialog->timer_b = 64 * dialog->timer_t1;
04505
04506 if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04507 (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04508 dialog->noncodeccapability |= AST_RTP_DTMF;
04509 else
04510 dialog->noncodeccapability &= ~AST_RTP_DTMF;
04511 if (peer->call_limit)
04512 ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
04513
04514 return 0;
04515 }
04516
04517
04518
04519
04520 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
04521 {
04522 struct hostent *hp;
04523 struct ast_hostent ahp;
04524 struct sip_peer *peer;
04525 char *port;
04526 int portno = 0;
04527 char host[MAXHOSTNAMELEN], *hostn;
04528 char peername[256];
04529 int srv_ret = 0;
04530
04531 ast_copy_string(peername, opeer, sizeof(peername));
04532 port = strchr(peername, ':');
04533 if (port)
04534 *port++ = '\0';
04535 dialog->sa.sin_family = AF_INET;
04536 dialog->timer_t1 = global_t1;
04537 dialog->timer_b = global_timer_b;
04538 peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE);
04539
04540 if (peer) {
04541 int res;
04542 if (newdialog) {
04543 set_socket_transport(&dialog->socket, 0);
04544 }
04545 res = create_addr_from_peer(dialog, peer);
04546 if (!ast_strlen_zero(port)) {
04547 if ((portno = atoi(port))) {
04548 dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
04549 }
04550 }
04551 unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
04552 return res;
04553 }
04554
04555 do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04556
04557 ast_string_field_set(dialog, tohost, peername);
04558
04559
04560 ref_proxy(dialog, obproxy_get(dialog, NULL));
04561
04562 if (sin) {
04563
04564 memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
04565 if (!sin->sin_port) {
04566 if (ast_strlen_zero(port) || sscanf(port, "%5u", &portno) != 1) {
04567 portno = (dialog->socket.type & SIP_TRANSPORT_TLS) ?
04568 STANDARD_TLS_PORT : STANDARD_SIP_PORT;
04569 }
04570 } else {
04571 portno = ntohs(sin->sin_port);
04572 }
04573 } else {
04574
04575
04576
04577
04578
04579
04580 hostn = peername;
04581
04582
04583
04584 if (!port && global_srvlookup) {
04585 char service[MAXHOSTNAMELEN];
04586 int tportno;
04587
04588 snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
04589 srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
04590 if (srv_ret > 0) {
04591 hostn = host;
04592 portno = tportno;
04593 }
04594 }
04595 if (!portno)
04596 portno = port ? atoi(port) : (dialog->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
04597 hp = ast_gethostbyname(hostn, &ahp);
04598 if (!hp) {
04599 ast_log(LOG_WARNING, "No such host: %s\n", peername);
04600 return -1;
04601 }
04602 memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
04603 }
04604
04605 if (!dialog->socket.type)
04606 set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
04607 if (!dialog->socket.port)
04608 dialog->socket.port = bindaddr.sin_port;
04609 dialog->sa.sin_port = htons(portno);
04610 dialog->recv = dialog->sa;
04611 return 0;
04612 }
04613
04614
04615
04616
04617 static int auto_congest(const void *arg)
04618 {
04619 struct sip_pvt *p = (struct sip_pvt *)arg;
04620
04621 sip_pvt_lock(p);
04622 p->initid = -1;
04623 if (p->owner) {
04624
04625 if (!ast_channel_trylock(p->owner)) {
04626 append_history(p, "Cong", "Auto-congesting (timer)");
04627 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
04628 ast_channel_unlock(p->owner);
04629 }
04630 }
04631 sip_pvt_unlock(p);
04632 dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
04633 return 0;
04634 }
04635
04636
04637
04638
04639 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
04640 {
04641 int res;
04642 struct sip_pvt *p = ast->tech_pvt;
04643 struct varshead *headp;
04644 struct ast_var_t *current;
04645 const char *referer = NULL;
04646
04647 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
04648 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
04649 return -1;
04650 }
04651
04652
04653 headp=&ast->varshead;
04654 AST_LIST_TRAVERSE(headp, current, entries) {
04655
04656 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
04657 p->options->vxml_url = ast_var_value(current);
04658 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
04659 p->options->uri_options = ast_var_value(current);
04660 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
04661
04662 p->options->addsipheaders = 1;
04663 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
04664
04665 p->options->transfer = 1;
04666 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
04667
04668 referer = ast_var_value(current);
04669 } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
04670
04671 p->options->replaces = ast_var_value(current);
04672 }
04673 }
04674
04675 res = 0;
04676 ast_set_flag(&p->flags[0], SIP_OUTGOING);
04677
04678 if (p->options->transfer) {
04679 char buf[SIPBUFSIZE/2];
04680
04681 if (referer) {
04682 if (sipdebug)
04683 ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
04684 snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
04685 } else
04686 snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
04687 ast_string_field_set(p, cid_name, buf);
04688 }
04689 ast_debug(1, "Outgoing Call for %s\n", p->username);
04690
04691 res = update_call_counter(p, INC_CALL_RINGING);
04692
04693 if (res == -1) {
04694 ast->hangupcause = AST_CAUSE_USER_BUSY;
04695 return res;
04696 }
04697 p->callingpres = ast->cid.cid_pres;
04698 p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
04699 p->jointnoncodeccapability = p->noncodeccapability;
04700
04701
04702 if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
04703 ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
04704 res = -1;
04705 } else {
04706 int xmitres;
04707
04708 xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
04709 if (xmitres == XMIT_ERROR)
04710 return -1;
04711 p->invitestate = INV_CALLING;
04712
04713
04714 AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
04715 dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
04716 dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
04717 dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
04718 }
04719 return res;
04720 }
04721
04722
04723
04724 static void sip_registry_destroy(struct sip_registry *reg)
04725 {
04726
04727 ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
04728
04729 if (reg->call) {
04730
04731
04732 reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
04733 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
04734 dialog_unlink_all(reg->call, TRUE, TRUE);
04735 reg->call = dialog_unref(reg->call, "unref reg->call");
04736
04737 }
04738 AST_SCHED_DEL(sched, reg->expire);
04739 AST_SCHED_DEL(sched, reg->timeout);
04740
04741 ast_string_field_free_memory(reg);
04742 ast_atomic_fetchadd_int(®objs, -1);
04743 ast_dnsmgr_release(reg->dnsmgr);
04744 ast_free(reg);
04745 }
04746
04747
04748 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
04749 {
04750 struct sip_request *req;
04751
04752 if (sip_debug_test_pvt(p))
04753 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
04754
04755 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
04756 update_call_counter(p, DEC_CALL_LIMIT);
04757 ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
04758 }
04759
04760
04761 if (p->owner) {
04762 if (lockowner)
04763 ast_channel_lock(p->owner);
04764 if (option_debug)
04765 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
04766 p->owner->tech_pvt = NULL;
04767
04768 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04769 if (lockowner)
04770 ast_channel_unlock(p->owner);
04771
04772 usleep(1);
04773 }
04774
04775
04776 if (p->relatedpeer && p->relatedpeer->mwipvt)
04777 p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
04778 if (p->relatedpeer && p->relatedpeer->call == p)
04779 p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
04780
04781 if (p->relatedpeer)
04782 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
04783
04784 if (p->registry) {
04785 if (p->registry->call == p)
04786 p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
04787 p->registry = registry_unref(p->registry, "delete p->registry");
04788 }
04789
04790 if (dumphistory)
04791 sip_dump_history(p);
04792
04793 if (p->options)
04794 ast_free(p->options);
04795
04796 if (p->notify_headers) {
04797 ast_variables_destroy(p->notify_headers);
04798 p->notify_headers = NULL;
04799 }
04800 if (p->rtp) {
04801 ast_rtp_destroy(p->rtp);
04802 }
04803 if (p->vrtp) {
04804 ast_rtp_destroy(p->vrtp);
04805 }
04806 if (p->trtp) {
04807 while (ast_rtp_get_bridged(p->trtp))
04808 usleep(1);
04809 ast_rtp_destroy(p->trtp);
04810 }
04811 if (p->udptl)
04812 ast_udptl_destroy(p->udptl);
04813 if (p->refer)
04814 ast_free(p->refer);
04815 if (p->route) {
04816 free_old_route(p->route);
04817 p->route = NULL;
04818 }
04819 if (p->initreq.data)
04820 ast_free(p->initreq.data);
04821
04822
04823 if (p->stimer) {
04824 if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
04825 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
04826 dialog_unref(p, "removing session timer ref"));
04827 }
04828 ast_free(p->stimer);
04829 p->stimer = NULL;
04830 }
04831
04832
04833 if (p->history) {
04834 struct sip_history *hist;
04835 while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
04836 ast_free(hist);
04837 p->history_entries--;
04838 }
04839 ast_free(p->history);
04840 p->history = NULL;
04841 }
04842
04843 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
04844 ast_free(req);
04845 }
04846
04847 if (p->chanvars) {
04848 ast_variables_destroy(p->chanvars);
04849 p->chanvars = NULL;
04850 }
04851
04852 ast_string_field_free_memory(p);
04853
04854 if (p->socket.tcptls_session) {
04855 ao2_ref(p->socket.tcptls_session, -1);
04856 p->socket.tcptls_session = NULL;
04857 }
04858 }
04859
04860
04861
04862
04863
04864
04865
04866
04867
04868
04869
04870
04871
04872
04873
04874 static int update_call_counter(struct sip_pvt *fup, int event)
04875 {
04876 char name[256];
04877 int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
04878 int outgoing = fup->outgoing_call;
04879 struct sip_peer *p = NULL;
04880
04881 ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
04882
04883
04884
04885
04886 if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
04887 return 0;
04888
04889 ast_copy_string(name, fup->username, sizeof(name));
04890
04891
04892 if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE) ) ) {
04893 inuse = &p->inUse;
04894 call_limit = &p->call_limit;
04895 inringing = &p->inRinging;
04896 ast_copy_string(name, fup->peername, sizeof(name));
04897 }
04898 if (!p) {
04899 ast_debug(2, "%s is not a local device, no call limit\n", name);
04900 return 0;
04901 }
04902
04903 switch(event) {
04904
04905 case DEC_CALL_LIMIT:
04906
04907 if (inuse) {
04908 sip_pvt_lock(fup);
04909 ao2_lock(p);
04910 if (*inuse > 0) {
04911 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
04912 (*inuse)--;
04913 ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
04914 }
04915 } else {
04916 *inuse = 0;
04917 }
04918 ao2_unlock(p);
04919 sip_pvt_unlock(fup);
04920 }
04921
04922
04923 if (inringing) {
04924 sip_pvt_lock(fup);
04925 ao2_lock(p);
04926 if (*inringing > 0) {
04927 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
04928 (*inringing)--;
04929 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
04930 }
04931 } else {
04932 *inringing = 0;
04933 }
04934 ao2_unlock(p);
04935 sip_pvt_unlock(fup);
04936 }
04937
04938
04939 sip_pvt_lock(fup);
04940 ao2_lock(p);
04941 if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
04942 ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
04943 ao2_unlock(p);
04944 sip_pvt_unlock(fup);
04945 sip_peer_hold(fup, FALSE);
04946 } else {
04947 ao2_unlock(p);
04948 sip_pvt_unlock(fup);
04949 }
04950 if (sipdebug)
04951 ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
04952 break;
04953
04954 case INC_CALL_RINGING:
04955 case INC_CALL_LIMIT:
04956
04957 if (*call_limit > 0 ) {
04958 if (*inuse >= *call_limit) {
04959 ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
04960 unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
04961 return -1;
04962 }
04963 }
04964 if (inringing && (event == INC_CALL_RINGING)) {
04965 sip_pvt_lock(fup);
04966 ao2_lock(p);
04967 if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
04968 (*inringing)++;
04969 ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
04970 }
04971 ao2_unlock(p);
04972 sip_pvt_unlock(fup);
04973 }
04974 if (inuse) {
04975 sip_pvt_lock(fup);
04976 ao2_lock(p);
04977 if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
04978 (*inuse)++;
04979 ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
04980 }
04981 ao2_unlock(p);
04982 sip_pvt_unlock(fup);
04983 }
04984 if (sipdebug) {
04985 ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
04986 }
04987 break;
04988
04989 case DEC_CALL_RINGING:
04990 if (inringing) {
04991 sip_pvt_lock(fup);
04992 ao2_lock(p);
04993 if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
04994 if (*inringing > 0) {
04995 (*inringing)--;
04996 }
04997 ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
04998 }
04999 ao2_unlock(p);
05000 sip_pvt_unlock(fup);
05001 }
05002 break;
05003
05004 default:
05005 ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05006 }
05007
05008 if (p) {
05009 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05010 unref_peer(p, "update_call_counter: unref_peer from call counter");
05011 }
05012 return 0;
05013 }
05014
05015
05016 static void sip_destroy_fn(void *p)
05017 {
05018 sip_destroy(p);
05019 }
05020
05021
05022
05023
05024
05025
05026 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05027 {
05028 ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05029 __sip_destroy(p, TRUE, TRUE);
05030 return NULL;
05031 }
05032
05033
05034 static int hangup_sip2cause(int cause)
05035 {
05036
05037
05038 switch(cause) {
05039 case 401:
05040 return AST_CAUSE_CALL_REJECTED;
05041 case 403:
05042 return AST_CAUSE_CALL_REJECTED;
05043 case 404:
05044 return AST_CAUSE_UNALLOCATED;
05045 case 405:
05046 return AST_CAUSE_INTERWORKING;
05047 case 407:
05048 return AST_CAUSE_CALL_REJECTED;
05049 case 408:
05050 return AST_CAUSE_NO_USER_RESPONSE;
05051 case 409:
05052 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05053 case 410:
05054 return AST_CAUSE_NUMBER_CHANGED;
05055 case 411:
05056 return AST_CAUSE_INTERWORKING;
05057 case 413:
05058 return AST_CAUSE_INTERWORKING;
05059 case 414:
05060 return AST_CAUSE_INTERWORKING;
05061 case 415:
05062 return AST_CAUSE_INTERWORKING;
05063 case 420:
05064 return AST_CAUSE_NO_ROUTE_DESTINATION;
05065 case 480:
05066 return AST_CAUSE_NO_ANSWER;
05067 case 481:
05068 return AST_CAUSE_INTERWORKING;
05069 case 482:
05070 return AST_CAUSE_INTERWORKING;
05071 case 483:
05072 return AST_CAUSE_NO_ANSWER;
05073 case 484:
05074 return AST_CAUSE_INVALID_NUMBER_FORMAT;
05075 case 485:
05076 return AST_CAUSE_UNALLOCATED;
05077 case 486:
05078 return AST_CAUSE_BUSY;
05079 case 487:
05080 return AST_CAUSE_INTERWORKING;
05081 case 488:
05082 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05083 case 491:
05084 return AST_CAUSE_INTERWORKING;
05085 case 493:
05086 return AST_CAUSE_INTERWORKING;
05087 case 500:
05088 return AST_CAUSE_FAILURE;
05089 case 501:
05090 return AST_CAUSE_FACILITY_REJECTED;
05091 case 502:
05092 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05093 case 503:
05094 return AST_CAUSE_CONGESTION;
05095 case 504:
05096 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05097 case 505:
05098 return AST_CAUSE_INTERWORKING;
05099 case 600:
05100 return AST_CAUSE_USER_BUSY;
05101 case 603:
05102 return AST_CAUSE_CALL_REJECTED;
05103 case 604:
05104 return AST_CAUSE_UNALLOCATED;
05105 case 606:
05106 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05107 default:
05108 return AST_CAUSE_NORMAL;
05109 }
05110
05111 return 0;
05112 }
05113
05114
05115
05116
05117
05118
05119
05120
05121
05122
05123
05124
05125
05126
05127
05128
05129
05130
05131
05132
05133
05134
05135
05136
05137
05138
05139
05140
05141
05142
05143
05144
05145
05146 static const char *hangup_cause2sip(int cause)
05147 {
05148 switch (cause) {
05149 case AST_CAUSE_UNALLOCATED:
05150 case AST_CAUSE_NO_ROUTE_DESTINATION:
05151 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:
05152 return "404 Not Found";
05153 case AST_CAUSE_CONGESTION:
05154 case AST_CAUSE_SWITCH_CONGESTION:
05155 return "503 Service Unavailable";
05156 case AST_CAUSE_NO_USER_RESPONSE:
05157 return "408 Request Timeout";
05158 case AST_CAUSE_NO_ANSWER:
05159 case AST_CAUSE_UNREGISTERED:
05160 return "480 Temporarily unavailable";
05161 case AST_CAUSE_CALL_REJECTED:
05162 return "403 Forbidden";
05163 case AST_CAUSE_NUMBER_CHANGED:
05164 return "410 Gone";
05165 case AST_CAUSE_NORMAL_UNSPECIFIED:
05166 return "480 Temporarily unavailable";
05167 case AST_CAUSE_INVALID_NUMBER_FORMAT:
05168 return "484 Address incomplete";
05169 case AST_CAUSE_USER_BUSY:
05170 return "486 Busy here";
05171 case AST_CAUSE_FAILURE:
05172 return "500 Server internal failure";
05173 case AST_CAUSE_FACILITY_REJECTED:
05174 return "501 Not Implemented";
05175 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05176 return "503 Service Unavailable";
05177
05178 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05179 return "502 Bad Gateway";
05180 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:
05181 return "488 Not Acceptable Here";
05182
05183 case AST_CAUSE_NOTDEFINED:
05184 default:
05185 ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05186 return NULL;
05187 }
05188
05189
05190 return 0;
05191 }
05192
05193
05194
05195
05196 static int sip_hangup(struct ast_channel *ast)
05197 {
05198 struct sip_pvt *p = ast->tech_pvt;
05199 int needcancel = FALSE;
05200 int needdestroy = 0;
05201 struct ast_channel *oldowner = ast;
05202
05203 if (!p) {
05204 ast_debug(1, "Asked to hangup channel that was not connected\n");
05205 return 0;
05206 }
05207 if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
05208 ast_debug(1, "This call was answered elsewhere");
05209 append_history(p, "Cancel", "Call answered elsewhere");
05210 p->answered_elsewhere = TRUE;
05211 }
05212
05213
05214 if (p->owner)
05215 p->hangupcause = p->owner->hangupcause;
05216
05217 if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05218 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05219 if (sipdebug)
05220 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05221 update_call_counter(p, DEC_CALL_LIMIT);
05222 }
05223 ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05224 if (p->autokillid > -1 && sip_cancel_destroy(p))
05225 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
05226 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05227 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
05228 p->needdestroy = 0;
05229 p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05230 sip_pvt_lock(p);
05231 p->owner = NULL;
05232 sip_pvt_unlock(p);
05233 return 0;
05234 }
05235
05236 if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
05237 if (p->refer)
05238 ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
05239 else
05240 ast_debug(1, "Hanging up zombie call. Be scared.\n");
05241 } else
05242 ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
05243
05244 sip_pvt_lock(p);
05245 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05246 if (sipdebug)
05247 ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05248 update_call_counter(p, DEC_CALL_LIMIT);
05249 }
05250
05251
05252 if (p->owner != ast) {
05253 ast_log(LOG_WARNING, "Huh? We aren't the owner? Can't hangup call.\n");
05254 sip_pvt_unlock(p);
05255 return 0;
05256 }
05257
05258
05259 if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
05260 needcancel = TRUE;
05261 ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
05262 }
05263
05264 stop_media_flows(p);
05265
05266 append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
05267
05268
05269 if (p->vad)
05270 ast_dsp_free(p->vad);
05271
05272 p->owner = NULL;
05273 ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
05274
05275 ast_module_unref(ast_module_info->self);
05276
05277
05278
05279
05280
05281
05282 if (p->alreadygone)
05283 needdestroy = 1;
05284 else if (p->invitestate != INV_CALLING)
05285 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05286
05287
05288 if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
05289 if (needcancel) {
05290 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05291
05292 struct sip_pkt *cur;
05293 for (cur = p->packets; cur; cur = cur->next) {
05294 __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
05295 }
05296
05297
05298 if (p->invitestate == INV_CALLING) {
05299
05300 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05301
05302 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05303 append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
05304 } else {
05305 p->invitestate = INV_CANCELLED;
05306
05307 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
05308
05309
05310 needdestroy = 0;
05311 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05312 }
05313 } else {
05314 const char *res;
05315 if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
05316 transmit_response_reliable(p, res, &p->initreq);
05317 else
05318 transmit_response_reliable(p, "603 Declined", &p->initreq);
05319 p->invitestate = INV_TERMINATED;
05320 }
05321 } else {
05322 if (p->stimer->st_active == TRUE) {
05323 stop_session_timer(p);
05324 }
05325
05326 if (!p->pendinginvite) {
05327 struct ast_channel *bridge = ast_bridged_channel(oldowner);
05328 char *audioqos = "";
05329 char *videoqos = "";
05330 char *textqos = "";
05331
05332
05333
05334
05335 while (bridge && ast_channel_trylock(bridge)) {
05336 struct ast_channel *chan = p->owner;
05337 sip_pvt_unlock(p);
05338 do {
05339
05340
05341
05342 CHANNEL_DEADLOCK_AVOIDANCE(chan);
05343 } while (sip_pvt_trylock(p));
05344 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
05345 }
05346
05347 if (p->rtp)
05348 ast_rtp_set_vars(oldowner, p->rtp);
05349
05350 if (bridge) {
05351 struct sip_pvt *q = bridge->tech_pvt;
05352
05353 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
05354 ast_rtp_set_vars(bridge, q->rtp);
05355 ast_channel_unlock(bridge);
05356 }
05357
05358 if (p->vrtp)
05359 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
05360 if (p->trtp)
05361 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
05362
05363 if (oldowner->_state == AST_STATE_UP) {
05364 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
05365 }
05366
05367
05368 if (p->do_history) {
05369 if (p->rtp)
05370 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
05371 if (p->vrtp)
05372 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
05373 if (p->trtp)
05374 append_history(p, "RTCPtext", "Quality:%s", textqos);
05375 }
05376 if (p->rtp && oldowner)
05377 pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
05378 if (p->vrtp && oldowner)
05379 pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
05380 if (p->trtp && oldowner)
05381 pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
05382 } else {
05383
05384
05385 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05386 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
05387 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"));
05388 if (sip_cancel_destroy(p))
05389 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
05390 }
05391 }
05392 }
05393 if (needdestroy)
05394 p->needdestroy = 1;
05395 sip_pvt_unlock(p);
05396 return 0;
05397 }
05398
05399
05400 static void try_suggested_sip_codec(struct sip_pvt *p)
05401 {
05402 int fmt;
05403 const char *codec;
05404
05405 while (p->owner && ast_channel_trylock(p->owner)) {
05406 sip_pvt_unlock(p);
05407 sched_yield();
05408 sip_pvt_lock(p);
05409 }
05410
05411 if (!p->owner)
05412 return;
05413
05414 codec = ast_strdupa(S_OR(pbx_builtin_getvar_helper(p->owner, "SIP_CODEC"), ""));
05415
05416 ast_channel_unlock(p->owner);
05417
05418 if (ast_strlen_zero(codec))
05419 return;
05420
05421 fmt = ast_getformatbyname(codec);
05422 if (fmt) {
05423 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
05424 if (p->jointcapability & fmt) {
05425 p->jointcapability &= fmt;
05426 p->capability &= fmt;
05427 } else
05428 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
05429 } else
05430 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
05431 return;
05432 }
05433
05434
05435
05436 static int sip_answer(struct ast_channel *ast)
05437 {
05438 int res = 0;
05439 struct sip_pvt *p = ast->tech_pvt;
05440
05441 sip_pvt_lock(p);
05442 if (ast->_state != AST_STATE_UP) {
05443 try_suggested_sip_codec(p);
05444
05445 ast_setstate(ast, AST_STATE_UP);
05446 ast_debug(1, "SIP answering channel: %s\n", ast->name);
05447 ast_rtp_new_source(p->rtp);
05448 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
05449 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
05450 }
05451 sip_pvt_unlock(p);
05452 return res;
05453 }
05454
05455
05456 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
05457 {
05458 struct sip_pvt *p = ast->tech_pvt;
05459 int res = 0;
05460
05461 switch (frame->frametype) {
05462 case AST_FRAME_VOICE:
05463 if (!(frame->subclass & ast->nativeformats)) {
05464 char s1[512], s2[512], s3[512];
05465 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
05466 frame->subclass,
05467 ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
05468 ast->nativeformats & AST_FORMAT_AUDIO_MASK,
05469 ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
05470 ast->readformat,
05471 ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
05472 ast->writeformat);
05473 return 0;
05474 }
05475 if (p) {
05476 sip_pvt_lock(p);
05477 if (p->rtp) {
05478
05479 if ((ast->_state != AST_STATE_UP) &&
05480 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05481 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05482 ast_rtp_new_source(p->rtp);
05483 p->invitestate = INV_EARLY_MEDIA;
05484 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05485 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05486 } else if (p->t38.state == T38_ENABLED) {
05487 change_t38_state(p, T38_DISABLED);
05488 transmit_reinvite_with_sdp(p, FALSE, FALSE);
05489 } else {
05490 p->lastrtptx = time(NULL);
05491 res = ast_rtp_write(p->rtp, frame);
05492 }
05493 }
05494 sip_pvt_unlock(p);
05495 }
05496 break;
05497 case AST_FRAME_VIDEO:
05498 if (p) {
05499 sip_pvt_lock(p);
05500 if (p->vrtp) {
05501
05502 if ((ast->_state != AST_STATE_UP) &&
05503 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05504 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05505 p->invitestate = INV_EARLY_MEDIA;
05506 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05507 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05508 }
05509 p->lastrtptx = time(NULL);
05510 res = ast_rtp_write(p->vrtp, frame);
05511 }
05512 sip_pvt_unlock(p);
05513 }
05514 break;
05515 case AST_FRAME_TEXT:
05516 if (p) {
05517 sip_pvt_lock(p);
05518 if (p->red) {
05519 red_buffer_t140(p->trtp, frame);
05520 } else {
05521 if (p->trtp) {
05522
05523 if ((ast->_state != AST_STATE_UP) &&
05524 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05525 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05526 p->invitestate = INV_EARLY_MEDIA;
05527 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05528 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05529 }
05530 p->lastrtptx = time(NULL);
05531 res = ast_rtp_write(p->trtp, frame);
05532 }
05533 }
05534 sip_pvt_unlock(p);
05535 }
05536 break;
05537 case AST_FRAME_IMAGE:
05538 return 0;
05539 break;
05540 case AST_FRAME_MODEM:
05541 if (p) {
05542 sip_pvt_lock(p);
05543
05544
05545
05546
05547 if ((ast->_state == AST_STATE_UP) &&
05548 p->udptl &&
05549 (p->t38.state == T38_ENABLED)) {
05550 res = ast_udptl_write(p->udptl, frame);
05551 }
05552 sip_pvt_unlock(p);
05553 }
05554 break;
05555 default:
05556 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
05557 return 0;
05558 }
05559
05560 return res;
05561 }
05562
05563
05564
05565 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
05566 {
05567 int ret = -1;
05568 struct sip_pvt *p;
05569
05570 if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
05571 ast_debug(1, "New channel is zombie\n");
05572 if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
05573 ast_debug(1, "Old channel is zombie\n");
05574
05575 if (!newchan || !newchan->tech_pvt) {
05576 if (!newchan)
05577 ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
05578 else
05579 ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
05580 return -1;
05581 }
05582 p = newchan->tech_pvt;
05583
05584 sip_pvt_lock(p);
05585 append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
05586 append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
05587 if (p->owner != oldchan)
05588 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
05589 else {
05590 p->owner = newchan;
05591
05592
05593
05594
05595
05596
05597 sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
05598 ret = 0;
05599 }
05600 ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
05601
05602 sip_pvt_unlock(p);
05603 return ret;
05604 }
05605
05606 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
05607 {
05608 struct sip_pvt *p = ast->tech_pvt;
05609 int res = 0;
05610
05611 sip_pvt_lock(p);
05612 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05613 case SIP_DTMF_INBAND:
05614 res = -1;
05615 break;
05616 case SIP_DTMF_RFC2833:
05617 if (p->rtp)
05618 ast_rtp_senddigit_begin(p->rtp, digit);
05619 break;
05620 default:
05621 break;
05622 }
05623 sip_pvt_unlock(p);
05624
05625 return res;
05626 }
05627
05628
05629
05630 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
05631 {
05632 struct sip_pvt *p = ast->tech_pvt;
05633 int res = 0;
05634
05635 sip_pvt_lock(p);
05636 switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05637 case SIP_DTMF_INFO:
05638 case SIP_DTMF_SHORTINFO:
05639 transmit_info_with_digit(p, digit, duration);
05640 break;
05641 case SIP_DTMF_RFC2833:
05642 if (p->rtp)
05643 ast_rtp_senddigit_end(p->rtp, digit);
05644 break;
05645 case SIP_DTMF_INBAND:
05646 res = -1;
05647 break;
05648 }
05649 sip_pvt_unlock(p);
05650
05651 return res;
05652 }
05653
05654
05655 static int sip_transfer(struct ast_channel *ast, const char *dest)
05656 {
05657 struct sip_pvt *p = ast->tech_pvt;
05658 int res;
05659
05660 if (dest == NULL)
05661 dest = "";
05662 sip_pvt_lock(p);
05663 if (ast->_state == AST_STATE_RING)
05664 res = sip_sipredirect(p, dest);
05665 else
05666 res = transmit_refer(p, dest);
05667 sip_pvt_unlock(p);
05668 return res;
05669 }
05670
05671
05672 static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
05673 {
05674 switch (parameters->request_response) {
05675 case AST_T38_NEGOTIATED:
05676 case AST_T38_REQUEST_NEGOTIATE:
05677 if (p->t38.state == T38_PEER_REINVITE) {
05678 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"));
05679 p->t38.our_parms = *parameters;
05680
05681
05682
05683 if (!p->t38.their_parms.fill_bit_removal) {
05684 p->t38.our_parms.fill_bit_removal = FALSE;
05685 }
05686 if (!p->t38.their_parms.transcoding_mmr) {
05687 p->t38.our_parms.transcoding_mmr = FALSE;
05688 }
05689 if (!p->t38.their_parms.transcoding_jbig) {
05690 p->t38.our_parms.transcoding_jbig = FALSE;
05691 }
05692 p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
05693 p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
05694 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
05695 change_t38_state(p, T38_ENABLED);
05696 transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
05697 } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->t38.state != T38_ENABLED) {
05698 p->t38.our_parms = *parameters;
05699 ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
05700 change_t38_state(p, T38_LOCAL_REINVITE);
05701 if (!p->pendinginvite) {
05702 transmit_reinvite_with_sdp(p, TRUE, FALSE);
05703 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
05704 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
05705 }
05706 }
05707 break;
05708 case AST_T38_TERMINATED:
05709 case AST_T38_REFUSED:
05710 case AST_T38_REQUEST_TERMINATE:
05711 if (p->t38.state == T38_PEER_REINVITE) {
05712 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"));
05713 change_t38_state(p, T38_DISABLED);
05714 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
05715 } else if (p->t38.state == T38_ENABLED)
05716 transmit_reinvite_with_sdp(p, FALSE, FALSE);
05717 break;
05718 default:
05719 break;
05720 }
05721 }
05722
05723
05724
05725
05726
05727
05728 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
05729 {
05730 struct sip_pvt *p = ast->tech_pvt;
05731 int res = 0;
05732
05733 sip_pvt_lock(p);
05734 switch(condition) {
05735 case AST_CONTROL_RINGING:
05736 if (ast->_state == AST_STATE_RING) {
05737 p->invitestate = INV_EARLY_MEDIA;
05738 if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
05739 (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
05740
05741 transmit_response(p, "180 Ringing", &p->initreq);
05742 ast_set_flag(&p->flags[0], SIP_RINGING);
05743 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
05744 break;
05745 } else {
05746
05747 }
05748 }
05749 res = -1;
05750 break;
05751 case AST_CONTROL_BUSY:
05752 if (ast->_state != AST_STATE_UP) {
05753 transmit_response_reliable(p, "486 Busy Here", &p->initreq);
05754 p->invitestate = INV_COMPLETED;
05755 sip_alreadygone(p);
05756 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
05757 break;
05758 }
05759 res = -1;
05760 break;
05761 case AST_CONTROL_CONGESTION:
05762 if (ast->_state != AST_STATE_UP) {
05763 transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
05764 p->invitestate = INV_COMPLETED;
05765 sip_alreadygone(p);
05766 ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
05767 break;
05768 }
05769 res = -1;
05770 break;
05771 case AST_CONTROL_PROCEEDING:
05772 if ((ast->_state != AST_STATE_UP) &&
05773 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05774 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05775 transmit_response(p, "100 Trying", &p->initreq);
05776 p->invitestate = INV_PROCEEDING;
05777 break;
05778 }
05779 res = -1;
05780 break;
05781 case AST_CONTROL_PROGRESS:
05782 if ((ast->_state != AST_STATE_UP) &&
05783 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05784 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05785 p->invitestate = INV_EARLY_MEDIA;
05786 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE, FALSE);
05787 ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05788 break;
05789 }
05790 res = -1;
05791 break;
05792 case AST_CONTROL_HOLD:
05793 ast_rtp_new_source(p->rtp);
05794 ast_moh_start(ast, data, p->mohinterpret);
05795 break;
05796 case AST_CONTROL_UNHOLD:
05797 ast_rtp_new_source(p->rtp);
05798 ast_moh_stop(ast);
05799 break;
05800 case AST_CONTROL_VIDUPDATE:
05801 if (p->vrtp && !p->novideo) {
05802 transmit_info_with_vidupdate(p);
05803
05804 } else
05805 res = -1;
05806 break;
05807 case AST_CONTROL_T38_PARAMETERS:
05808 if (datalen != sizeof(struct ast_control_t38_parameters)) {
05809 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);
05810 } else {
05811 const struct ast_control_t38_parameters *parameters = data;
05812 interpret_t38_parameters(p, parameters);
05813 }
05814 break;
05815 case AST_CONTROL_SRCUPDATE:
05816 ast_rtp_new_source(p->rtp);
05817 break;
05818 case -1:
05819 res = -1;
05820 break;
05821 default:
05822 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
05823 res = -1;
05824 break;
05825 }
05826 sip_pvt_unlock(p);
05827 return res;
05828 }
05829
05830
05831
05832
05833
05834
05835
05836 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
05837 {
05838 struct ast_channel *tmp;
05839 struct ast_variable *v = NULL;
05840 int fmt;
05841 int what;
05842 int video;
05843 int text;
05844 int needvideo = 0;
05845 int needtext = 0;
05846 char buf[SIPBUFSIZE];
05847 char *decoded_exten;
05848
05849 {
05850 const char *my_name;
05851
05852 if (title)
05853 my_name = title;
05854 else if ( (my_name = strchr(i->fromdomain, ':')) )
05855 my_name++;
05856 else
05857 my_name = i->fromdomain;
05858
05859 sip_pvt_unlock(i);
05860
05861 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, (int)(long) i);
05862
05863 }
05864 if (!tmp) {
05865 ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
05866 sip_pvt_lock(i);
05867 return NULL;
05868 }
05869 sip_pvt_lock(i);
05870
05871 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;
05872
05873
05874
05875 if (i->jointcapability) {
05876 what = i->jointcapability;
05877 video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
05878 text = i->jointcapability & AST_FORMAT_TEXT_MASK;
05879 } else if (i->capability) {
05880 what = i->capability;
05881 video = i->capability & AST_FORMAT_VIDEO_MASK;
05882 text = i->capability & AST_FORMAT_TEXT_MASK;
05883 } else {
05884 what = global_capability;
05885 video = global_capability & AST_FORMAT_VIDEO_MASK;
05886 text = global_capability & AST_FORMAT_TEXT_MASK;
05887 }
05888
05889
05890 tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
05891 ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
05892 ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
05893 ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
05894 ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
05895 if (i->prefcodec)
05896 ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
05897
05898
05899 fmt = ast_best_codec(tmp->nativeformats);
05900
05901
05902
05903
05904
05905 if (i->vrtp) {
05906 if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
05907 needvideo = AST_FORMAT_VIDEO_MASK;
05908 else if (i->prefcodec)
05909 needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;
05910 else
05911 needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;
05912 }
05913
05914 if (i->trtp) {
05915 if (i->prefcodec)
05916 needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;
05917 else
05918 needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;
05919 }
05920
05921 if (needvideo)
05922 ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
05923 else
05924 ast_debug(3, "This channel will not be able to handle video.\n");
05925
05926 if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
05927 i->vad = ast_dsp_new();
05928 ast_dsp_set_features(i->vad, DSP_FEATURE_DIGIT_DETECT);
05929 if (global_relaxdtmf)
05930 ast_dsp_set_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
05931 }
05932
05933
05934 if (i->rtp) {
05935 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
05936 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
05937 }
05938 if (needvideo && i->vrtp) {
05939 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
05940 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
05941 }
05942 if (needtext && i->trtp)
05943 ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
05944 if (i->udptl)
05945 ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
05946
05947 if (state == AST_STATE_RING)
05948 tmp->rings = 1;
05949 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05950 tmp->writeformat = fmt;
05951 tmp->rawwriteformat = fmt;
05952 tmp->readformat = fmt;
05953 tmp->rawreadformat = fmt;
05954 tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
05955
05956 tmp->callgroup = i->callgroup;
05957 tmp->pickupgroup = i->pickupgroup;
05958 tmp->cid.cid_pres = i->callingpres;
05959 if (!ast_strlen_zero(i->accountcode))
05960 ast_string_field_set(tmp, accountcode, i->accountcode);
05961 if (i->amaflags)
05962 tmp->amaflags = i->amaflags;
05963 if (!ast_strlen_zero(i->language))
05964 ast_string_field_set(tmp, language, i->language);
05965 i->owner = tmp;
05966 ast_module_ref(ast_module_info->self);
05967 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05968
05969
05970
05971
05972 decoded_exten = ast_strdupa(i->exten);
05973 ast_uri_decode(decoded_exten);
05974 ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
05975
05976
05977
05978 tmp->cid.cid_ani = ast_strdup(i->cid_num);
05979 if (!ast_strlen_zero(i->rdnis))
05980 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
05981
05982 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
05983 tmp->cid.cid_dnid = ast_strdup(i->exten);
05984
05985 tmp->priority = 1;
05986 if (!ast_strlen_zero(i->uri))
05987 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
05988 if (!ast_strlen_zero(i->domain))
05989 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
05990 if (!ast_strlen_zero(i->callid))
05991 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
05992 if (i->rtp)
05993 ast_jb_configure(tmp, &global_jbconf);
05994
05995
05996 for (v = i->chanvars ; v ; v = v->next)
05997 pbx_builtin_setvar_helper(tmp, v->name, v->value);
05998
05999 if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06000 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06001 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06002 ast_hangup(tmp);
06003 tmp = NULL;
06004 }
06005
06006 if (i->do_history)
06007 append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06008
06009
06010 if (global_callevents)
06011 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06012 "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06013 tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06014
06015 return tmp;
06016 }
06017
06018
06019 static char *get_body_by_line(const char *line, const char *name, int nameLen)
06020 {
06021 if (!strncasecmp(line, name, nameLen) && line[nameLen] == '=')
06022 return ast_skip_blanks(line + nameLen + 1);
06023
06024 return "";
06025 }
06026
06027
06028
06029
06030
06031 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06032 {
06033 int len = strlen(name);
06034
06035 while (*start < req->sdp_end) {
06036 const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len);
06037 if (r[0] != '\0')
06038 return r;
06039 }
06040
06041 return "";
06042 }
06043
06044
06045 static const char *get_sdp(struct sip_request *req, const char *name)
06046 {
06047 int dummy = 0;
06048
06049 return get_sdp_iterate(&dummy, req, name);
06050 }
06051
06052
06053 static char *get_body(struct sip_request *req, char *name)
06054 {
06055 int x;
06056 int len = strlen(name);
06057 char *r;
06058
06059 for (x = 0; x < req->lines; x++) {
06060 r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len);
06061 if (r[0] != '\0')
06062 return r;
06063 }
06064
06065 return "";
06066 }
06067
06068
06069 static const char *find_alias(const char *name, const char *_default)
06070 {
06071
06072 static const struct cfalias {
06073 char * const fullname;
06074 char * const shortname;
06075 } aliases[] = {
06076 { "Content-Type", "c" },
06077 { "Content-Encoding", "e" },
06078 { "From", "f" },
06079 { "Call-ID", "i" },
06080 { "Contact", "m" },
06081 { "Content-Length", "l" },
06082 { "Subject", "s" },
06083 { "To", "t" },
06084 { "Supported", "k" },
06085 { "Refer-To", "r" },
06086 { "Referred-By", "b" },
06087 { "Allow-Events", "u" },
06088 { "Event", "o" },
06089 { "Via", "v" },
06090 { "Accept-Contact", "a" },
06091 { "Reject-Contact", "j" },
06092 { "Request-Disposition", "d" },
06093 { "Session-Expires", "x" },
06094 { "Identity", "y" },
06095 { "Identity-Info", "n" },
06096 };
06097 int x;
06098
06099 for (x = 0; x < ARRAY_LEN(aliases); x++) {
06100 if (!strcasecmp(aliases[x].fullname, name))
06101 return aliases[x].shortname;
06102 }
06103
06104 return _default;
06105 }
06106
06107 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06108 {
06109 int pass;
06110
06111
06112
06113
06114
06115
06116
06117
06118
06119
06120 for (pass = 0; name && pass < 2;pass++) {
06121 int x, len = strlen(name);
06122 for (x = *start; x < req->headers; x++) {
06123 char *header = REQ_OFFSET_TO_STR(req, header[x]);
06124 if (!strncasecmp(header, name, len)) {
06125 char *r = header + len;
06126 if (pedanticsipchecking)
06127 r = ast_skip_blanks(r);
06128
06129 if (*r == ':') {
06130 *start = x+1;
06131 return ast_skip_blanks(r+1);
06132 }
06133 }
06134 }
06135 if (pass == 0)
06136 name = find_alias(name, NULL);
06137 }
06138
06139
06140 return "";
06141 }
06142
06143
06144
06145
06146 static const char *get_header(const struct sip_request *req, const char *name)
06147 {
06148 int start = 0;
06149 return __get_header(req, name, &start);
06150 }
06151
06152
06153 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06154 {
06155
06156 struct ast_frame *f;
06157
06158 if (!p->rtp) {
06159
06160 return &ast_null_frame;
06161 }
06162
06163 switch(ast->fdno) {
06164 case 0:
06165 f = ast_rtp_read(p->rtp);
06166 break;
06167 case 1:
06168 f = ast_rtcp_read(p->rtp);
06169 break;
06170 case 2:
06171 f = ast_rtp_read(p->vrtp);
06172 break;
06173 case 3:
06174 f = ast_rtcp_read(p->vrtp);
06175 break;
06176 case 4:
06177 f = ast_rtp_read(p->trtp);
06178 if (sipdebug_text) {
06179 int i;
06180 unsigned char* arr = f->data.ptr;
06181 for (i=0; i < f->datalen; i++)
06182 ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
06183 ast_verbose(" -> ");
06184 for (i=0; i < f->datalen; i++)
06185 ast_verbose("%02X ", arr[i]);
06186 ast_verbose("\n");
06187 }
06188 break;
06189 case 5:
06190 f = ast_udptl_read(p->udptl);
06191 break;
06192 default:
06193 f = &ast_null_frame;
06194 }
06195
06196 if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
06197 (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
06198 ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
06199 return &ast_null_frame;
06200 }
06201
06202
06203 if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
06204 return f;
06205
06206 if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
06207 if (!(f->subclass & p->jointcapability)) {
06208 ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
06209 ast_getformatname(f->subclass), p->owner->name);
06210 return &ast_null_frame;
06211 }
06212 ast_debug(1, "Oooh, format changed to %d %s\n",
06213 f->subclass, ast_getformatname(f->subclass));
06214 p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
06215 ast_set_read_format(p->owner, p->owner->readformat);
06216 ast_set_write_format(p->owner, p->owner->writeformat);
06217 }
06218
06219 if (f && (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
06220 f = ast_dsp_process(p->owner, p->vad, f);
06221 if (f && f->frametype == AST_FRAME_DTMF) {
06222 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && f->subclass == 'f') {
06223 ast_debug(1, "Fax CNG detected on %s\n", ast->name);
06224 *faxdetect = 1;
06225 } else {
06226 ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
06227 }
06228 }
06229 }
06230
06231 return f;
06232 }
06233
06234
06235 static struct ast_frame *sip_read(struct ast_channel *ast)
06236 {
06237 struct ast_frame *fr;
06238 struct sip_pvt *p = ast->tech_pvt;
06239 int faxdetected = FALSE;
06240
06241 sip_pvt_lock(p);
06242 fr = sip_rtp_read(ast, p, &faxdetected);
06243 p->lastrtprx = time(NULL);
06244
06245
06246
06247 if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && (p->t38.state == T38_DISABLED) && !(ast_bridged_channel(ast))) {
06248 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
06249 if (!p->pendinginvite) {
06250 ast_debug(3, "Sending reinvite on SIP (%s) for T.38 negotiation.\n", ast->name);
06251 change_t38_state(p, T38_LOCAL_REINVITE);
06252 transmit_reinvite_with_sdp(p, TRUE, FALSE);
06253 }
06254 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06255 ast_debug(3, "Deferring reinvite on SIP (%s) - it will be re-negotiated for T.38\n", ast->name);
06256 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06257 }
06258 }
06259
06260
06261 if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
06262 fr = &ast_null_frame;
06263 }
06264
06265 sip_pvt_unlock(p);
06266
06267 return fr;
06268 }
06269
06270
06271
06272 static char *generate_random_string(char *buf, size_t size)
06273 {
06274 long val[4];
06275 int x;
06276
06277 for (x=0; x<4; x++)
06278 val[x] = ast_random();
06279 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
06280
06281 return buf;
06282 }
06283
06284
06285 static void build_callid_pvt(struct sip_pvt *pvt)
06286 {
06287 char buf[33];
06288
06289 const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
06290
06291 ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06292
06293 }
06294
06295
06296 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
06297 {
06298 char buf[33];
06299
06300 const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
06301
06302 ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06303 }
06304
06305
06306 static void make_our_tag(char *tagbuf, size_t len)
06307 {
06308 snprintf(tagbuf, len, "as%08lx", ast_random());
06309 }
06310
06311
06312 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
06313 {
06314 struct sip_st_dlg *stp;
06315
06316 if (p->stimer) {
06317 ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
06318 return p->stimer;
06319 }
06320
06321 if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
06322 return NULL;
06323
06324 p->stimer = stp;
06325
06326 stp->st_schedid = -1;
06327
06328 return p->stimer;
06329 }
06330
06331
06332
06333
06334
06335 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
06336 int useglobal_nat, const int intended_method, struct sip_request *req)
06337 {
06338 struct sip_pvt *p;
06339
06340 if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
06341 return NULL;
06342
06343 if (ast_string_field_init(p, 512)) {
06344 ao2_t_ref(p, -1, "failed to string_field_init, drop p");
06345 return NULL;
06346 }
06347
06348 if (req) {
06349 set_socket_transport(&p->socket, req->socket.type);
06350 } else {
06351 set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
06352 }
06353
06354 p->socket.fd = -1;
06355 p->method = intended_method;
06356 p->initid = -1;
06357 p->waitid = -1;
06358 p->autokillid = -1;
06359 p->request_queue_sched_id = -1;
06360 p->t38id = -1;
06361 p->subscribed = NONE;
06362 p->stateid = -1;
06363 p->sessionversion_remote = -1;
06364 p->session_modify = TRUE;
06365 p->stimer = NULL;
06366 p->prefs = default_prefs;
06367
06368 if (intended_method != SIP_OPTIONS) {
06369 p->timer_t1 = global_t1;
06370 p->timer_b = global_timer_b;
06371 }
06372
06373 if (!sin)
06374 p->ourip = internip;
06375 else {
06376 p->sa = *sin;
06377 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
06378 }
06379
06380
06381 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
06382 ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
06383
06384 p->do_history = recordhistory;
06385
06386 p->branch = ast_random();
06387 make_our_tag(p->tag, sizeof(p->tag));
06388 p->ocseq = INITIAL_CSEQ;
06389
06390 if (sip_methods[intended_method].need_rtp) {
06391 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06392
06393 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06394 p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06395 if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
06396 p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06397 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
06398 p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
06399 if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)
06400 || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
06401 ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
06402 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
06403 ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
06404 if (p->chanvars) {
06405 ast_variables_destroy(p->chanvars);
06406 p->chanvars = NULL;
06407 }
06408 ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
06409 return NULL;
06410 }
06411 ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
06412 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
06413 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06414 ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
06415 ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
06416 ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
06417 if (p->vrtp) {
06418 ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
06419 ast_rtp_setdtmf(p->vrtp, 0);
06420 ast_rtp_setdtmfcompensate(p->vrtp, 0);
06421 ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
06422 ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
06423 ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
06424 }
06425 if (p->trtp) {
06426 ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
06427 ast_rtp_setdtmf(p->trtp, 0);
06428 ast_rtp_setdtmfcompensate(p->trtp, 0);
06429 }
06430 if (p->udptl)
06431 ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06432 p->maxcallbitrate = default_maxcallbitrate;
06433 p->autoframing = global_autoframing;
06434 ast_rtp_codec_setpref(p->rtp, &p->prefs);
06435 }
06436
06437 if (useglobal_nat && sin) {
06438
06439 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
06440 p->recv = *sin;
06441 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
06442 }
06443
06444 if (p->method != SIP_REGISTER)
06445 ast_string_field_set(p, fromdomain, default_fromdomain);
06446 build_via(p);
06447 if (!callid)
06448 build_callid_pvt(p);
06449 else
06450 ast_string_field_set(p, callid, callid);
06451
06452 ast_string_field_set(p, mohinterpret, default_mohinterpret);
06453 ast_string_field_set(p, mohsuggest, default_mohsuggest);
06454 p->capability = global_capability;
06455 p->allowtransfer = global_allowtransfer;
06456 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06457 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06458 p->noncodeccapability |= AST_RTP_DTMF;
06459 if (p->udptl) {
06460 set_t38_capabilities(p);
06461 }
06462 ast_string_field_set(p, context, default_context);
06463 ast_string_field_set(p, parkinglot, default_parkinglot);
06464
06465 AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
06466
06467
06468
06469 ao2_t_link(dialogs, p, "link pvt into dialogs table");
06470
06471 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");
06472 return p;
06473 }
06474
06475
06476 struct find_call_cb_arg {
06477 enum sipmethod method;
06478 const char *callid;
06479 const char *fromtag;
06480 const char *totag;
06481 const char *tag;
06482 };
06483
06484
06485
06486
06487
06488 static int find_call_cb(void *__pvt, void *__arg, int flags)
06489 {
06490 struct sip_pvt *p = __pvt;
06491 struct find_call_cb_arg *arg = __arg;
06492
06493 int found = FALSE;
06494
06495 if (!ast_strlen_zero(p->callid)) {
06496 if (arg->method == SIP_REGISTER)
06497 found = (!strcmp(p->callid, arg->callid));
06498 else {
06499 found = !strcmp(p->callid, arg->callid);
06500 if (pedanticsipchecking && found) {
06501 found = ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, arg->tag);
06502 }
06503 }
06504
06505 ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
06506
06507
06508 if (pedanticsipchecking && found && arg->method != SIP_RESPONSE) {
06509 if (p->tag[0] == '\0' && arg->totag[0]) {
06510
06511 found = FALSE;
06512 } else if (arg->totag[0]) {
06513 if (strcmp(arg->totag, p->tag)) {
06514 found = FALSE;
06515 }
06516 }
06517 if (!found)
06518 ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, arg->totag, sip_methods[arg->method].text);
06519 }
06520 }
06521 return found;
06522 }
06523
06524
06525
06526
06527
06528
06529 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
06530 {
06531 struct sip_pvt *p = NULL;
06532 char *tag = "";
06533 char totag[128];
06534 char fromtag[128];
06535 struct find_call_cb_arg arg;
06536 const char *callid = get_header(req, "Call-ID");
06537 const char *from = get_header(req, "From");
06538 const char *to = get_header(req, "To");
06539 const char *cseq = get_header(req, "Cseq");
06540 struct sip_pvt *sip_pvt_ptr;
06541
06542
06543
06544 if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
06545 ast_strlen_zero(from) || ast_strlen_zero(cseq))
06546 return NULL;
06547
06548 arg.method = req->method;
06549 arg.callid = callid;
06550 arg.fromtag = fromtag;
06551 arg.totag = totag;
06552 arg.tag = "";
06553
06554 if (pedanticsipchecking) {
06555
06556
06557
06558
06559
06560
06561 if (gettag(req, "To", totag, sizeof(totag)))
06562 req->has_to_tag = 1;
06563 gettag(req, "From", fromtag, sizeof(fromtag));
06564
06565 tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
06566
06567 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);
06568
06569
06570 if (ast_strlen_zero(fromtag)) {
06571 ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06572 return NULL;
06573 }
06574
06575 if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
06576 ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06577 return NULL;
06578 }
06579 }
06580
06581 restartsearch:
06582 if (!pedanticsipchecking) {
06583 struct sip_pvt tmp_dialog = {
06584 .callid = callid,
06585 };
06586 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
06587 if (sip_pvt_ptr) {
06588
06589 sip_pvt_lock(sip_pvt_ptr);
06590 return sip_pvt_ptr;
06591 }
06592 } else {
06593 ao2_lock(dialogs);
06594 p = ao2_t_callback(dialogs, 0 , find_call_cb, &arg, "pedantic linear search for dialog");
06595 if (p) {
06596 if (sip_pvt_trylock(p)) {
06597 ao2_unlock(dialogs);
06598 usleep(1);
06599 goto restartsearch;
06600 }
06601 ao2_unlock(dialogs);
06602 return p;
06603 }
06604 ao2_unlock(dialogs);
06605 }
06606
06607
06608 if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
06609 if (intended_method == SIP_REFER) {
06610
06611 transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
06612 } else if (intended_method == SIP_NOTIFY) {
06613
06614
06615 transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
06616 } else {
06617
06618 if ((p = sip_alloc(callid, sin, 1, intended_method, req))) {
06619
06620 sip_pvt_lock(p);
06621 } else {
06622
06623
06624
06625
06626
06627
06628
06629
06630 transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
06631 ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
06632 }
06633 }
06634 return p;
06635 } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
06636
06637 transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
06638 ast_debug(2, "Got a request with unsupported SIP method.\n");
06639 } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
06640
06641 transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
06642 ast_debug(2, "That's odd... Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
06643 }
06644
06645
06646 if (intended_method == SIP_RESPONSE)
06647 ast_debug(2, "That's odd... Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
06648
06649 return NULL;
06650 }
06651
06652
06653 static int sip_register(const char *value, int lineno)
06654 {
06655 struct sip_registry *reg;
06656 int portnum = 0;
06657 enum sip_transport transport = SIP_TRANSPORT_UDP;
06658 char buf[256] = "";
06659 char *username = NULL;
06660 char *hostname=NULL, *secret=NULL, *authuser=NULL, *expire=NULL, *tmp=NULL;
06661 char *callback=NULL, *peername=NULL;
06662
06663 if (!value)
06664 return -1;
06665 ast_copy_string(buf, value, sizeof(buf));
06666 tmp = strrchr(buf, '@');
06667
06668
06669 expire = strchr(tmp, '~');
06670 if (expire)
06671 *expire++ = '\0';
06672 callback = strrchr(tmp, '/');
06673 if (callback)
06674 *callback++ = '\0';
06675 if (ast_strlen_zero(callback))
06676 callback = "s";
06677
06678
06679 tmp = strchr(buf, '?');
06680 if (tmp) {
06681 *tmp++ = '\0';
06682 peername = buf;
06683 } else {
06684 tmp = buf;
06685 }
06686
06687 sip_parse_host(tmp, lineno, &username, &portnum, &transport);
06688
06689
06690 hostname = strrchr(username, '@');
06691 if (hostname)
06692 *hostname++ = '\0';
06693 if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
06694 ast_log(LOG_WARNING, "Format for registration is [transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
06695 return -1;
06696 }
06697
06698 secret = strchr(username, ':');
06699 if (secret) {
06700 *secret++ = '\0';
06701 authuser = strchr(secret, ':');
06702 if (authuser)
06703 *authuser++ = '\0';
06704 }
06705
06706 if (!(reg = ast_calloc(1, sizeof(*reg)))) {
06707 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
06708 return -1;
06709 }
06710
06711 if (ast_string_field_init(reg, 256)) {
06712 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
06713 ast_free(reg);
06714 return -1;
06715 }
06716
06717 ast_atomic_fetchadd_int(®objs, 1);
06718 ASTOBJ_INIT(reg);
06719 ast_string_field_set(reg, callback, callback);
06720 if (!ast_strlen_zero(username))
06721 ast_string_field_set(reg, username, username);
06722 if (hostname)
06723 ast_string_field_set(reg, hostname, hostname);
06724 if (authuser)
06725 ast_string_field_set(reg, authuser, authuser);
06726 if (secret)
06727 ast_string_field_set(reg, secret, secret);
06728 if (peername) {
06729 ast_string_field_set(reg, peername, peername);
06730 }
06731 reg->transport = transport;
06732 reg->expire = -1;
06733 reg->expiry = (expire ? atoi(expire) : default_expiry);
06734 reg->timeout = -1;
06735 reg->refresh = reg->expiry;
06736 reg->portno = portnum;
06737 reg->callid_valid = FALSE;
06738 reg->ocseq = INITIAL_CSEQ;
06739 ASTOBJ_CONTAINER_LINK(®l, reg);
06740 registry_unref(reg, "unref the reg pointer");
06741 return 0;
06742 }
06743
06744
06745
06746 static int lws2sws(char *msgbuf, int len)
06747 {
06748 int h = 0, t = 0;
06749 int lws = 0;
06750
06751 for (; h < len;) {
06752
06753 if (msgbuf[h] == '\r') {
06754 h++;
06755 continue;
06756 }
06757
06758 if (msgbuf[h] == '\n') {
06759
06760 if (h + 1 == len)
06761 break;
06762
06763 if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
06764
06765 h++;
06766 continue;
06767 }
06768
06769 msgbuf[t++] = msgbuf[h++];
06770 lws = 0;
06771 continue;
06772 }
06773 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
06774 if (lws) {
06775 h++;
06776 continue;
06777 }
06778 msgbuf[t++] = msgbuf[h++];
06779 lws = 1;
06780 continue;
06781 }
06782 msgbuf[t++] = msgbuf[h++];
06783 if (lws)
06784 lws = 0;
06785 }
06786 msgbuf[t] = '\0';
06787 return t;
06788 }
06789
06790
06791
06792
06793 static int parse_request(struct sip_request *req)
06794 {
06795 char *c = req->data->str;
06796 ptrdiff_t *dst = req->header;
06797 int i = 0, lim = SIP_MAX_HEADERS - 1;
06798 unsigned int skipping_headers = 0;
06799 ptrdiff_t current_header_offset = 0;
06800 char *previous_header = "";
06801
06802 req->header[0] = 0;
06803 req->headers = -1;
06804 for (; *c; c++) {
06805 if (*c == '\r') {
06806 *c = '\0';
06807 } else if (*c == '\n') {
06808 *c = '\0';
06809 current_header_offset = (c + 1) - req->data->str;
06810 previous_header = req->data->str + dst[i];
06811 if (skipping_headers) {
06812
06813
06814
06815 if (ast_strlen_zero(previous_header)) {
06816 skipping_headers = 0;
06817 }
06818 dst[i] = current_header_offset;
06819 continue;
06820 }
06821 if (sipdebug) {
06822 ast_debug(4, "%7s %2d [%3d]: %s\n",
06823 req->headers < 0 ? "Header" : "Body",
06824 i, (int) strlen(previous_header), previous_header);
06825 }
06826 if (ast_strlen_zero(previous_header) && req->headers < 0) {
06827 req->headers = i;
06828 dst = req->line;
06829 i = 0;
06830 lim = SIP_MAX_LINES - 1;
06831 } else {
06832 if (i++ == lim) {
06833
06834
06835
06836 if (req->headers != -1) {
06837 break;
06838 } else {
06839 req->headers = i;
06840 dst = req->line;
06841 i = 0;
06842 lim = SIP_MAX_LINES - 1;
06843 skipping_headers = 1;
06844 }
06845 }
06846 }
06847 dst[i] = current_header_offset;
06848 }
06849 }
06850
06851
06852
06853
06854
06855
06856 previous_header = req->data->str + dst[i];
06857 if ((i < lim) && !ast_strlen_zero(previous_header)) {
06858 if (sipdebug) {
06859 ast_debug(4, "%7s %2d [%3d]: %s\n",
06860 req->headers < 0 ? "Header" : "Body",
06861 i, (int) strlen(previous_header), previous_header );
06862 }
06863 i++;
06864 }
06865
06866
06867 if (req->headers >= 0) {
06868 req->lines = i;
06869 } else {
06870 req->headers = i;
06871 req->lines = 0;
06872
06873 req->line[0] = req->data->used;
06874 }
06875
06876 if (*c) {
06877 ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
06878 }
06879
06880
06881 return determine_firstline_parts(req);
06882 }
06883
06884
06885
06886
06887
06888
06889
06890
06891
06892 static int find_sdp(struct sip_request *req)
06893 {
06894 const char *content_type;
06895 const char *content_length;
06896 const char *search;
06897 char *boundary;
06898 unsigned int x;
06899 int boundaryisquoted = FALSE;
06900 int found_application_sdp = FALSE;
06901 int found_end_of_headers = FALSE;
06902
06903 content_length = get_header(req, "Content-Length");
06904
06905 if (!ast_strlen_zero(content_length)) {
06906 if (sscanf(content_length, "%30u", &x) != 1) {
06907 ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
06908 return 0;
06909 }
06910
06911
06912
06913 if (x == 0)
06914 return 0;
06915 }
06916
06917 content_type = get_header(req, "Content-Type");
06918
06919
06920 if (!strncasecmp(content_type, "application/sdp", 15)) {
06921 req->sdp_start = 0;
06922 req->sdp_end = req->lines;
06923 return req->lines ? 1 : 0;
06924 }
06925
06926
06927 if (strncasecmp(content_type, "multipart/mixed", 15))
06928 return 0;
06929
06930
06931 if ((search = strcasestr(content_type, ";boundary=")))
06932 search += 10;
06933 else if ((search = strcasestr(content_type, "; boundary=")))
06934 search += 11;
06935 else
06936 return 0;
06937
06938 if (ast_strlen_zero(search))
06939 return 0;
06940
06941
06942 if (*search == '\"') {
06943 search++;
06944 boundaryisquoted = TRUE;
06945 }
06946
06947
06948
06949 boundary = ast_strdupa(search - 2);
06950 boundary[0] = boundary[1] = '-';
06951
06952 if (boundaryisquoted)
06953 boundary[strlen(boundary) - 1] = '\0';
06954
06955
06956
06957
06958 for (x = 0; x < (req->lines); x++) {
06959 char *line = REQ_OFFSET_TO_STR(req, line[x]);
06960 if (!strncasecmp(line, boundary, strlen(boundary))){
06961 if (found_application_sdp && found_end_of_headers) {
06962 req->sdp_end = x-1;
06963 return 1;
06964 }
06965 found_application_sdp = FALSE;
06966 }
06967 if (!strcasecmp(line, "Content-Type: application/sdp"))
06968 found_application_sdp = TRUE;
06969
06970 if (ast_strlen_zero(line)) {
06971 if (found_application_sdp && !found_end_of_headers){
06972 req->sdp_start = x;
06973 found_end_of_headers = TRUE;
06974 }
06975 }
06976 }
06977 if (found_application_sdp && found_end_of_headers) {
06978 req->sdp_end = x;
06979 return TRUE;
06980 }
06981 return FALSE;
06982 }
06983
06984 enum media_type {
06985 SDP_AUDIO,
06986 SDP_VIDEO,
06987 SDP_IMAGE,
06988 SDP_TEXT,
06989 };
06990
06991 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
06992 {
06993 const char *m;
06994 const char *c;
06995 int miterator = req->sdp_start;
06996 int citerator = req->sdp_start;
06997 int x = 0;
06998 int numberofports;
06999 int len;
07000 char host[258] = "";
07001 struct ast_hostent audiohp;
07002 struct hostent *hp;
07003
07004 c = get_sdp_iterate(&citerator, req, "c");
07005 if (sscanf(c, "IN IP4 %256s", host) != 1) {
07006 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07007
07008 }
07009
07010 for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
07011 if ((media == SDP_AUDIO && ((sscanf(m, "audio %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07012 (sscanf(m, "audio %30d RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
07013 (media == SDP_VIDEO && ((sscanf(m, "video %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07014 (sscanf(m, "video %30d RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
07015
07016
07017
07018
07019 c = get_sdp_iterate(&citerator, req, "c");
07020 if (!ast_strlen_zero(c)) {
07021 sscanf(c, "IN IP4 %256s", host);
07022 }
07023 break;
07024 }
07025 }
07026
07027 if (ast_strlen_zero(host) || x == 0) {
07028 ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
07029 return -1;
07030 }
07031
07032 hp = ast_gethostbyname(host, &audiohp);
07033 if (!hp) {
07034 ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
07035 return -1;
07036 }
07037
07038 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
07039 sin->sin_port = htons(x);
07040 return 0;
07041 }
07042
07043
07044
07045
07046
07047
07048 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
07049 {
07050 const char *m;
07051 const char *c;
07052 const char *a;
07053 const char *o;
07054 char *o_copy;
07055 char *token;
07056 char host[258];
07057 int len = -1;
07058 int portno = -1;
07059 int vportno = -1;
07060 int tportno = -1;
07061 int udptlportno = -1;
07062 char s[256];
07063 int old = 0;
07064
07065
07066 int peercapability = 0, peernoncodeccapability = 0;
07067 int vpeercapability = 0, vpeernoncodeccapability = 0;
07068 int tpeercapability = 0, tpeernoncodeccapability = 0;
07069 struct sockaddr_in sin;
07070 struct sockaddr_in vsin;
07071 struct sockaddr_in tsin;
07072
07073 const char *codecs;
07074 struct hostent *hp;
07075 struct hostent *vhp = NULL;
07076 struct hostent *thp = NULL;
07077 struct ast_hostent audiohp;
07078 struct ast_hostent videohp;
07079 struct ast_hostent texthp;
07080 int codec;
07081 int destiterator = 0;
07082 int iterator;
07083 int sendonly = -1;
07084 int numberofports;
07085 struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
07086 int newjointcapability;
07087 int newpeercapability;
07088 int newnoncodeccapability;
07089 int numberofmediastreams = 0;
07090 int debug = sip_debug_test_pvt(p);
07091
07092 int found_rtpmap_codecs[SDP_MAX_RTPMAP_CODECS];
07093 int last_rtpmap_codec=0;
07094
07095 char buf[SIPBUFSIZE];
07096 int64_t rua_version;
07097
07098 int red_data_pt[10];
07099 int red_num_gen = 0;
07100 int red_pt = 0;
07101
07102 char *red_cp;
07103 char red_fmtp[100] = "empty";
07104
07105 if (!p->rtp) {
07106 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
07107 return -1;
07108 }
07109
07110
07111 #ifdef LOW_MEMORY
07112 newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
07113 #else
07114 newaudiortp = alloca(ast_rtp_alloc_size());
07115 #endif
07116 memset(newaudiortp, 0, ast_rtp_alloc_size());
07117 ast_rtp_new_init(newaudiortp);
07118 ast_rtp_pt_clear(newaudiortp);
07119
07120 #ifdef LOW_MEMORY
07121 newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
07122 #else
07123 newvideortp = alloca(ast_rtp_alloc_size());
07124 #endif
07125 memset(newvideortp, 0, ast_rtp_alloc_size());
07126 ast_rtp_new_init(newvideortp);
07127 ast_rtp_pt_clear(newvideortp);
07128
07129 #ifdef LOW_MEMORY
07130 newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
07131 #else
07132 newtextrtp = alloca(ast_rtp_alloc_size());
07133 #endif
07134 memset(newtextrtp, 0, ast_rtp_alloc_size());
07135 ast_rtp_new_init(newtextrtp);
07136 ast_rtp_pt_clear(newtextrtp);
07137
07138
07139 p->lastrtprx = p->lastrtptx = time(NULL);
07140
07141 memset(p->offered_media, 0, sizeof(p->offered_media));
07142
07143
07144
07145
07146
07147
07148
07149
07150
07151
07152 o = get_sdp(req, "o");
07153 if (ast_strlen_zero(o)) {
07154 ast_log(LOG_WARNING, "SDP sytax error. SDP without an o= line\n");
07155 return -1;
07156 }
07157
07158 o_copy = ast_strdupa(o);
07159 token = strsep(&o_copy, " ");
07160 if (!o_copy) {
07161 ast_log(LOG_WARNING, "SDP sytax error in o= line username\n");
07162 return -1;
07163 }
07164 token = strsep(&o_copy, " ");
07165 if (!o_copy) {
07166 ast_log(LOG_WARNING, "SDP sytax error in o= line session-id\n");
07167 return -1;
07168 }
07169 token = strsep(&o_copy, " ");
07170 if (!o_copy) {
07171 ast_log(LOG_WARNING, "SDP sytax error in o= line\n");
07172 return -1;
07173 }
07174 if (!sscanf(token, "%30" SCNd64, &rua_version)) {
07175 ast_log(LOG_WARNING, "SDP sytax error in o= line version\n");
07176 return -1;
07177 }
07178
07179
07180
07181
07182
07183
07184
07185
07186
07187
07188
07189
07190
07191
07192
07193
07194
07195
07196
07197 if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
07198 (p->sessionversion_remote < 0) ||
07199 (p->sessionversion_remote < rua_version)) {
07200 p->sessionversion_remote = rua_version;
07201 p->session_modify = TRUE;
07202 } else {
07203 if (p->t38.state == T38_LOCAL_REINVITE) {
07204 p->sessionversion_remote = rua_version;
07205 p->session_modify = TRUE;
07206 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);
07207 } else {
07208 p->session_modify = FALSE;
07209 ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
07210 return 0;
07211 }
07212 }
07213
07214
07215 m = get_sdp(req, "m");
07216 destiterator = req->sdp_start;
07217 c = get_sdp_iterate(&destiterator, req, "c");
07218 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
07219 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
07220 return -1;
07221 }
07222
07223
07224 if (sscanf(c, "IN IP4 %256s", host) != 1) {
07225 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07226 return -1;
07227 }
07228
07229
07230 hp = ast_gethostbyname(host, &audiohp);
07231 if (!hp) {
07232 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
07233 return -1;
07234 }
07235 vhp = hp;
07236 thp = hp;
07237
07238 iterator = req->sdp_start;
07239
07240 p->novideo = TRUE;
07241 p->notext = TRUE;
07242
07243 if (p->vrtp)
07244 ast_rtp_pt_clear(newvideortp);
07245
07246 if (p->trtp)
07247 ast_rtp_pt_clear(newtextrtp);
07248
07249
07250 while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
07251 int x;
07252 int audio = FALSE;
07253 int video = FALSE;
07254 int text = FALSE;
07255
07256 numberofports = 1;
07257 len = -1;
07258 if ((sscanf(m, "audio %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07259 (sscanf(m, "audio %30d RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07260 audio = TRUE;
07261 p->offered_media[SDP_AUDIO].offered = TRUE;
07262 numberofmediastreams++;
07263
07264 portno = x;
07265
07266 codecs = m + len;
07267 ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
07268 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07269 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
07270 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07271 return -1;
07272 }
07273 if (debug)
07274 ast_verbose("Found RTP audio format %d\n", codec);
07275 ast_rtp_set_m_type(newaudiortp, codec);
07276 }
07277 } else if ((sscanf(m, "video %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07278 (sscanf(m, "video %30d RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
07279 video = TRUE;
07280 p->novideo = FALSE;
07281 p->offered_media[SDP_VIDEO].offered = TRUE;
07282 numberofmediastreams++;
07283 vportno = x;
07284
07285 codecs = m + len;
07286 ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
07287 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07288 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
07289 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07290 return -1;
07291 }
07292 if (debug)
07293 ast_verbose("Found RTP video format %d\n", codec);
07294 ast_rtp_set_m_type(newvideortp, codec);
07295 }
07296 } else if ((sscanf(m, "text %30d/%30d RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07297 (sscanf(m, "text %30d RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07298 text = TRUE;
07299 p->offered_media[SDP_TEXT].offered = TRUE;
07300 p->notext = FALSE;
07301 numberofmediastreams++;
07302 tportno = x;
07303
07304 codecs = m + len;
07305 ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
07306 for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07307 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
07308 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07309 return -1;
07310 }
07311 if (debug)
07312 ast_verbose("Found RTP text format %d\n", codec);
07313 ast_rtp_set_m_type(newtextrtp, codec);
07314 }
07315 } else if (p->udptl && ( (sscanf(m, "image %30d udptl t38%n", &x, &len) == 1 && len > 0) ||
07316 (sscanf(m, "image %30d UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
07317 if (debug)
07318 ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
07319 p->offered_media[SDP_IMAGE].offered = TRUE;
07320 udptlportno = x;
07321 numberofmediastreams++;
07322 } else
07323 ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
07324 if (numberofports > 1)
07325 ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
07326
07327
07328
07329 c = get_sdp_iterate(&destiterator, req, "c");
07330 if (!ast_strlen_zero(c)) {
07331 if (sscanf(c, "IN IP4 %256s", host) != 1) {
07332 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
07333 } else {
07334
07335 if (audio) {
07336 if ( !(hp = ast_gethostbyname(host, &audiohp))) {
07337 ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in secondary c= line, '%s'\n", c);
07338 return -2;
07339 }
07340 } else if (video) {
07341 if (!(vhp = ast_gethostbyname(host, &videohp))) {
07342 ast_log(LOG_WARNING, "Unable to lookup RTP video host in secondary c= line, '%s'\n", c);
07343 return -2;
07344 }
07345 } else if (text) {
07346 if (!(thp = ast_gethostbyname(host, &texthp))) {
07347 ast_log(LOG_WARNING, "Unable to lookup RTP text host in secondary c= line, '%s'\n", c);
07348 return -2;
07349 }
07350 }
07351 }
07352
07353 }
07354 }
07355 if (portno == -1 && vportno == -1 && udptlportno == -1 && tportno == -1)
07356
07357
07358 return -2;
07359
07360 if (numberofmediastreams > 3)
07361
07362 return -3;
07363
07364
07365 sin.sin_family = AF_INET;
07366 vsin.sin_family = AF_INET;
07367 tsin.sin_family = AF_INET;
07368 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
07369 if (vhp)
07370 memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
07371 if (thp)
07372 memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
07373
07374
07375 if (p->udptl) {
07376 if (udptlportno > 0) {
07377 sin.sin_port = htons(udptlportno);
07378 if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
07379 struct sockaddr_in peer;
07380 ast_rtp_get_peer(p->rtp, &peer);
07381 if (peer.sin_addr.s_addr) {
07382 memcpy(&sin.sin_addr, &peer.sin_addr, sizeof(sin.sin_addr));
07383 if (debug) {
07384 ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(sin.sin_addr));
07385 }
07386 }
07387 }
07388 ast_udptl_set_peer(p->udptl, &sin);
07389 if (debug)
07390 ast_debug(1, "Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07391 } else {
07392 ast_udptl_stop(p->udptl);
07393 if (debug)
07394 ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
07395 }
07396 }
07397
07398
07399 if (p->rtp) {
07400 if (portno > 0) {
07401 sin.sin_port = htons(portno);
07402 ast_rtp_set_peer(p->rtp, &sin);
07403 if (debug)
07404 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07405 } else {
07406 if (udptlportno > 0) {
07407 if (debug)
07408 ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session. Callid %s\n", p->callid);
07409 } else {
07410 ast_rtp_stop(p->rtp);
07411 if (debug)
07412 ast_verbose("Peer doesn't provide audio. Callid %s\n", p->callid);
07413 }
07414 }
07415 }
07416
07417 if (vportno != -1)
07418 vsin.sin_port = htons(vportno);
07419
07420
07421 if (tportno != -1)
07422 tsin.sin_port = htons(tportno);
07423
07424
07425
07426
07427
07428 iterator = req->sdp_start;
07429 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
07430 char mimeSubtype[128];
07431 if (option_debug > 1) {
07432 int breakout = FALSE;
07433
07434
07435 if (!strncasecmp(a, "rtcp:", (size_t) 5)) {
07436 if (debug)
07437 ast_verbose("Got unsupported a:rtcp in SDP offer \n");
07438 breakout = TRUE;
07439 } else if (!strncasecmp(a, "fmtp:", (size_t) 5)) {
07440
07441
07442
07443
07444 if (debug)
07445 ast_verbose("Got unsupported a:fmtp in SDP offer \n");
07446 breakout = TRUE;
07447 } else if (!strncasecmp(a, "framerate:", (size_t) 10)) {
07448
07449 if (debug)
07450 ast_verbose("Got unsupported a:framerate in SDP offer \n");
07451 breakout = TRUE;
07452 } else if (!strncasecmp(a, "maxprate:", (size_t) 9)) {
07453
07454 if (debug)
07455 ast_verbose("Got unsupported a:maxprate in SDP offer \n");
07456 breakout = TRUE;
07457 } else if (!strncasecmp(a, "crypto:", (size_t) 7)) {
07458
07459 if (debug)
07460 ast_verbose("Got unsupported a:crypto in SDP offer \n");
07461 breakout = TRUE;
07462 }
07463 if (breakout)
07464 continue;
07465 }
07466 if (!strcasecmp(a, "sendonly")) {
07467 if (sendonly == -1)
07468 sendonly = 1;
07469 continue;
07470 } else if (!strcasecmp(a, "inactive")) {
07471 if (sendonly == -1)
07472 sendonly = 2;
07473 continue;
07474 } else if (!strcasecmp(a, "sendrecv")) {
07475 if (sendonly == -1)
07476 sendonly = 0;
07477 continue;
07478 } else if (strlen(a) > 5 && !strncasecmp(a, "ptime", 5)) {
07479 char *tmp = strrchr(a, ':');
07480 long int framing = 0;
07481 if (tmp) {
07482 tmp++;
07483 framing = strtol(tmp, NULL, 10);
07484 if (framing == LONG_MIN || framing == LONG_MAX) {
07485 framing = 0;
07486 ast_debug(1, "Can't read framing from SDP: %s\n", a);
07487 }
07488 }
07489 if (framing && p->autoframing) {
07490 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
07491 int codec_n;
07492 int format = 0;
07493 for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
07494 format = ast_rtp_codec_getformat(codec_n);
07495 if (!format)
07496 continue;
07497 if (option_debug)
07498 ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
07499 ast_codec_pref_setsize(pref, format, framing);
07500 }
07501 ast_rtp_codec_setpref(p->rtp, pref);
07502 }
07503 continue;
07504
07505 } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
07506
07507 red_cp = &red_fmtp[strlen(red_fmtp)];
07508 strncpy(red_fmtp, a, 100);
07509
07510 sscanf(red_cp, "%30u", &red_data_pt[red_num_gen]);
07511 red_cp = strtok(red_cp, "/");
07512 while (red_cp && red_num_gen++ < RED_MAX_GENERATION) {
07513 sscanf(red_cp, "%30u", &red_data_pt[red_num_gen]);
07514 red_cp = strtok(NULL, "/");
07515 }
07516 red_cp = red_fmtp;
07517
07518 } else if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
07519
07520
07521 if (last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
07522
07523
07524 if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
07525 if(ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
07526 if (debug)
07527 ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
07528 found_rtpmap_codecs[last_rtpmap_codec] = codec;
07529 last_rtpmap_codec++;
07530 } else {
07531 ast_rtp_unset_m_type(newvideortp, codec);
07532 if (debug)
07533 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
07534 }
07535 } else if (!strncasecmp(mimeSubtype, "T140", 4)) {
07536 if (p->trtp) {
07537
07538 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
07539 }
07540 } else if (!strncasecmp(mimeSubtype, "RED", 3)) {
07541 if (p->trtp) {
07542 ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
07543 red_pt = codec;
07544 sprintf(red_fmtp, "fmtp:%d ", red_pt);
07545
07546 if (debug)
07547 ast_verbose("Red submimetype has payload type: %d\n", red_pt);
07548 }
07549 } else {
07550 if(ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
07551 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
07552 if (debug)
07553 ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
07554 found_rtpmap_codecs[last_rtpmap_codec] = codec;
07555 last_rtpmap_codec++;
07556 } else {
07557 ast_rtp_unset_m_type(newaudiortp, codec);
07558 if (debug)
07559 ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
07560 }
07561 }
07562 } else {
07563 if (debug)
07564 ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
07565 }
07566
07567 }
07568 }
07569
07570 if (udptlportno != -1) {
07571 if (p->t38.state != T38_ENABLED) {
07572 int found = 0, x;
07573
07574 old = 0;
07575 memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
07576
07577
07578 iterator = req->sdp_start;
07579 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
07580 if ((sscanf(a, "T38FaxMaxBuffer:%30d", &x) == 1)) {
07581 found = 1;
07582 ast_debug(3, "MaxBufferSize:%d\n", x);
07583 } else if ((sscanf(a, "T38MaxBitRate:%30d", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30d", &x) == 1)) {
07584 found = 1;
07585 ast_debug(3, "T38MaxBitRate: %d\n", x);
07586 switch (x) {
07587 case 14400:
07588 p->t38.their_parms.rate = AST_T38_RATE_14400;
07589 break;
07590 case 12000:
07591 p->t38.their_parms.rate = AST_T38_RATE_12000;
07592 break;
07593 case 9600:
07594 p->t38.their_parms.rate = AST_T38_RATE_9600;
07595 break;
07596 case 7200:
07597 p->t38.their_parms.rate = AST_T38_RATE_7200;
07598 break;
07599 case 4800:
07600 p->t38.their_parms.rate = AST_T38_RATE_4800;
07601 break;
07602 case 2400:
07603 p->t38.their_parms.rate = AST_T38_RATE_2400;
07604 break;
07605 }
07606 } else if ((sscanf(a, "T38FaxVersion:%30d", &x) == 1)) {
07607 found = 1;
07608 ast_debug(3, "FaxVersion: %d\n", x);
07609 p->t38.their_parms.version = x;
07610 } else if ((sscanf(a, "T38FaxMaxDatagram:%30d", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30d", &x) == 1)) {
07611 found = 1;
07612 ast_debug(3, "FaxMaxDatagram: %d\n", x);
07613 ast_udptl_set_far_max_datagram(p->udptl, x);
07614 } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
07615 found = 1;
07616 if (sscanf(a, "T38FaxFillBitRemoval:%30d", &x) == 1) {
07617 ast_debug(3, "FillBitRemoval: %d\n", x);
07618 if (x == 1) {
07619 p->t38.their_parms.fill_bit_removal = TRUE;
07620 }
07621 } else {
07622 ast_debug(3, "FillBitRemoval\n");
07623 p->t38.their_parms.fill_bit_removal = TRUE;
07624 }
07625 } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
07626 found = 1;
07627 if (sscanf(a, "T38FaxTranscodingMMR:%30d", &x) == 1) {
07628 ast_debug(3, "Transcoding MMR: %d\n", x);
07629 if (x == 1) {
07630 p->t38.their_parms.transcoding_mmr = TRUE;
07631 }
07632 } else {
07633 ast_debug(3, "Transcoding MMR\n");
07634 p->t38.their_parms.transcoding_mmr = TRUE;
07635 }
07636 } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
07637 found = 1;
07638 if (sscanf(a, "T38FaxTranscodingJBIG:%30d", &x) == 1) {
07639 ast_debug(3, "Transcoding JBIG: %d\n", x);
07640 if (x == 1) {
07641 p->t38.their_parms.transcoding_jbig = TRUE;
07642 }
07643 } else {
07644 ast_debug(3, "Transcoding JBIG\n");
07645 p->t38.their_parms.transcoding_jbig = TRUE;
07646 }
07647 } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
07648 found = 1;
07649 ast_debug(3, "RateManagement: %s\n", s);
07650 if (!strcasecmp(s, "localTCF"))
07651 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
07652 else if (!strcasecmp(s, "transferredTCF"))
07653 p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
07654 } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
07655 found = 1;
07656 ast_debug(3, "UDP EC: %s\n", s);
07657 if (!strcasecmp(s, "t38UDPRedundancy")) {
07658 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
07659 } else if (!strcasecmp(s, "t38UDPFEC")) {
07660 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
07661 } else {
07662 ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
07663 }
07664 }
07665 }
07666
07667
07668 if ((t38action == SDP_T38_ACCEPT) &&
07669 (p->t38.state == T38_LOCAL_REINVITE)) {
07670 change_t38_state(p, T38_ENABLED);
07671 } else if ((t38action == SDP_T38_INITIATE) &&
07672 p->owner && p->lastinvite) {
07673 change_t38_state(p, T38_PEER_REINVITE);
07674 }
07675 }
07676 } else {
07677 change_t38_state(p, T38_DISABLED);
07678 }
07679
07680
07681 ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
07682 ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
07683 ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
07684
07685 newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
07686 newpeercapability = (peercapability | vpeercapability | tpeercapability);
07687 newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
07688
07689
07690 if (debug) {
07691
07692 char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
07693
07694 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
07695 ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
07696 ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
07697 ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
07698 ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
07699 ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
07700
07701 ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
07702 ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
07703 ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
07704 ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
07705 }
07706 if (!newjointcapability) {
07707
07708 if ((p->t38.state == T38_DISABLED) || !udptlportno) {
07709 ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
07710
07711 return -1;
07712 } else {
07713 ast_debug(3, "Have T.38 but no audio codecs, accepting offer anyway\n");
07714 return 0;
07715 }
07716 }
07717
07718
07719
07720 p->jointcapability = newjointcapability;
07721 p->peercapability = newpeercapability;
07722 p->jointnoncodeccapability = newnoncodeccapability;
07723
07724 if (p->trtp && (p->jointcapability & AST_FORMAT_T140RED)) {
07725 p->red = 1;
07726 rtp_red_init(p->trtp, 300, red_data_pt, 2);
07727 } else {
07728 p->red = 0;
07729 }
07730
07731 ast_rtp_pt_copy(p->rtp, newaudiortp);
07732 if (p->vrtp)
07733 ast_rtp_pt_copy(p->vrtp, newvideortp);
07734 if (p->trtp)
07735 ast_rtp_pt_copy(p->trtp, newtextrtp);
07736
07737 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
07738 ast_clear_flag(&p->flags[0], SIP_DTMF);
07739 if (newnoncodeccapability & AST_RTP_DTMF) {
07740
07741 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
07742
07743 ast_rtp_setdtmf(p->rtp, 1);
07744 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07745 } else {
07746 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
07747 }
07748 }
07749
07750
07751 if (p->rtp && sin.sin_port) {
07752 ast_rtp_set_peer(p->rtp, &sin);
07753 if (debug)
07754 ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07755 }
07756
07757
07758 if (p->vrtp && vsin.sin_port) {
07759 ast_rtp_set_peer(p->vrtp, &vsin);
07760 if (debug)
07761 ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
07762 }
07763
07764
07765 if (p->trtp && tsin.sin_port) {
07766 ast_rtp_set_peer(p->trtp, &tsin);
07767 if (debug)
07768 ast_verbose("Peer text RTP is at port %s:%d\n", ast_inet_ntoa(tsin.sin_addr), ntohs(tsin.sin_port));
07769 }
07770
07771
07772 ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
07773
07774 if (!p->owner)
07775 return 0;
07776
07777 ast_debug(4, "We have an owner, now see if we need to change this call\n");
07778
07779 if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
07780 if (debug) {
07781 char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
07782 ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
07783 ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
07784 ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
07785 }
07786 p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
07787 ast_set_read_format(p->owner, p->owner->readformat);
07788 ast_set_write_format(p->owner, p->owner->writeformat);
07789 }
07790
07791 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
07792 ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
07793
07794 ast_queue_frame(p->owner, &ast_null_frame);
07795
07796 append_history(p, "Unhold", "%s", req->data->str);
07797 if (global_callevents)
07798 manager_event(EVENT_FLAG_CALL, "Hold",
07799 "Status: Off\r\n"
07800 "Channel: %s\r\n"
07801 "Uniqueid: %s\r\n",
07802 p->owner->name,
07803 p->owner->uniqueid);
07804 if (global_notifyhold)
07805 sip_peer_hold(p, FALSE);
07806 ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
07807 } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
07808 int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
07809 ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
07810 S_OR(p->mohsuggest, NULL),
07811 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
07812 if (sendonly)
07813 ast_rtp_stop(p->rtp);
07814
07815
07816 ast_queue_frame(p->owner, &ast_null_frame);
07817
07818 append_history(p, "Hold", "%s", req->data->str);
07819 if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07820 manager_event(EVENT_FLAG_CALL, "Hold",
07821 "Status: On\r\n"
07822 "Channel: %s\r\n"
07823 "Uniqueid: %s\r\n",
07824 p->owner->name,
07825 p->owner->uniqueid);
07826 }
07827 if (sendonly == 1)
07828 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
07829 else if (sendonly == 2)
07830 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
07831 else
07832 ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
07833 if (global_notifyhold && !already_on_hold)
07834 sip_peer_hold(p, TRUE);
07835 }
07836
07837 return 0;
07838 }
07839
07840 #ifdef LOW_MEMORY
07841 static void ts_ast_rtp_destroy(void *data)
07842 {
07843 struct ast_rtp *tmp = data;
07844 ast_rtp_destroy(tmp);
07845 }
07846 #endif
07847
07848
07849 static int add_header(struct sip_request *req, const char *var, const char *value)
07850 {
07851 if (req->headers == SIP_MAX_HEADERS) {
07852 ast_log(LOG_WARNING, "Out of SIP header space\n");
07853 return -1;
07854 }
07855
07856 if (req->lines) {
07857 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
07858 return -1;
07859 }
07860
07861 if (compactheaders)
07862 var = find_alias(var, var);
07863
07864 ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
07865 req->header[req->headers] = req->len;
07866
07867 req->len = req->data->used;
07868 req->headers++;
07869
07870 return 0;
07871 }
07872
07873
07874 static int add_header_contentLength(struct sip_request *req, int len)
07875 {
07876 char clen[10];
07877
07878 snprintf(clen, sizeof(clen), "%d", len);
07879 return add_header(req, "Content-Length", clen);
07880 }
07881
07882
07883 static int add_line(struct sip_request *req, const char *line)
07884 {
07885 if (req->lines == SIP_MAX_LINES) {
07886 ast_log(LOG_WARNING, "Out of SIP line space\n");
07887 return -1;
07888 }
07889 if (!req->lines)
07890
07891 req->len += ast_str_append(&req->data, 0, "\r\n");
07892 req->line[req->lines] = req->len;
07893 ast_str_append(&req->data, 0, "%s", line);
07894 req->len = req->data->used;
07895 req->lines++;
07896 return 0;
07897 }
07898
07899
07900 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
07901 {
07902 const char *tmp = get_header(orig, field);
07903
07904 if (!ast_strlen_zero(tmp))
07905 return add_header(req, field, tmp);
07906 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
07907 return -1;
07908 }
07909
07910
07911 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
07912 {
07913 int start = 0;
07914 int copied = 0;
07915 for (;;) {
07916 const char *tmp = __get_header(orig, field, &start);
07917
07918 if (ast_strlen_zero(tmp))
07919 break;
07920
07921 add_header(req, field, tmp);
07922 copied++;
07923 }
07924 return copied ? 0 : -1;
07925 }
07926
07927
07928
07929
07930
07931
07932
07933
07934
07935 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
07936 {
07937 int copied = 0;
07938 int start = 0;
07939
07940 for (;;) {
07941 char new[512];
07942 const char *oh = __get_header(orig, field, &start);
07943
07944 if (ast_strlen_zero(oh))
07945 break;
07946
07947 if (!copied) {
07948 char leftmost[512], *others, *rport;
07949
07950
07951 ast_copy_string(leftmost, oh, sizeof(leftmost));
07952 others = strchr(leftmost, ',');
07953 if (others)
07954 *others++ = '\0';
07955
07956
07957 rport = strstr(leftmost, ";rport");
07958 if (rport && *(rport+6) == '=')
07959 rport = NULL;
07960
07961
07962 if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
07963
07964 char *end;
07965
07966 rport = strstr(leftmost, ";rport");
07967
07968 if (rport) {
07969 end = strchr(rport + 1, ';');
07970 if (end)
07971 memmove(rport, end, strlen(end) + 1);
07972 else
07973 *rport = '\0';
07974 }
07975
07976
07977 snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
07978 leftmost, ast_inet_ntoa(p->recv.sin_addr),
07979 ntohs(p->recv.sin_port),
07980 others ? "," : "", others ? others : "");
07981 } else {
07982
07983 snprintf(new, sizeof(new), "%s;received=%s%s%s",
07984 leftmost, ast_inet_ntoa(p->recv.sin_addr),
07985 others ? "," : "", others ? others : "");
07986 }
07987 oh = new;
07988 }
07989 add_header(req, field, oh);
07990 copied++;
07991 }
07992 if (!copied) {
07993 ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
07994 return -1;
07995 }
07996 return 0;
07997 }
07998
07999
08000 static void add_route(struct sip_request *req, struct sip_route *route)
08001 {
08002 char r[SIPBUFSIZE*2], *p;
08003 int n, rem = sizeof(r);
08004
08005 if (!route)
08006 return;
08007
08008 p = r;
08009 for (;route ; route = route->next) {
08010 n = strlen(route->hop);
08011 if (rem < n+3)
08012 break;
08013 if (p != r) {
08014 *p++ = ',';
08015 --rem;
08016 }
08017 *p++ = '<';
08018 ast_copy_string(p, route->hop, rem);
08019 p += n;
08020 *p++ = '>';
08021 rem -= (n+2);
08022 }
08023 *p = '\0';
08024 add_header(req, "Route", r);
08025 }
08026
08027
08028 static void set_destination(struct sip_pvt *p, char *uri)
08029 {
08030 char *h, *maddr, hostname[256];
08031 int port, hn;
08032 struct hostent *hp;
08033 struct ast_hostent ahp;
08034 int debug=sip_debug_test_pvt(p);
08035
08036
08037
08038
08039 if (debug)
08040 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
08041
08042
08043 h = strchr(uri, '@');
08044 if (h)
08045 ++h;
08046 else {
08047 h = uri;
08048 if (!strncasecmp(h, "sip:", 4))
08049 h += 4;
08050 else if (!strncasecmp(h, "sips:", 5))
08051 h += 5;
08052 }
08053 hn = strcspn(h, ":;>") + 1;
08054 if (hn > sizeof(hostname))
08055 hn = sizeof(hostname);
08056 ast_copy_string(hostname, h, hn);
08057
08058 h += hn - 1;
08059
08060
08061 if (*h == ':') {
08062
08063 ++h;
08064 port = strtol(h, &h, 10);
08065 }
08066 else
08067 port = STANDARD_SIP_PORT;
08068
08069
08070 maddr = strstr(h, "maddr=");
08071 if (maddr) {
08072 maddr += 6;
08073 hn = strspn(maddr, "0123456789.") + 1;
08074 if (hn > sizeof(hostname))
08075 hn = sizeof(hostname);
08076 ast_copy_string(hostname, maddr, hn);
08077 }
08078
08079 hp = ast_gethostbyname(hostname, &ahp);
08080 if (hp == NULL) {
08081 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
08082 return;
08083 }
08084 p->sa.sin_family = AF_INET;
08085 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
08086 p->sa.sin_port = htons(port);
08087 if (debug)
08088 ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
08089 }
08090
08091
08092 static int init_resp(struct sip_request *resp, const char *msg)
08093 {
08094
08095 memset(resp, 0, sizeof(*resp));
08096 resp->method = SIP_RESPONSE;
08097 if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
08098 return -1;
08099 resp->header[0] = 0;
08100 ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
08101 resp->len = resp->data->used;
08102 resp->headers++;
08103 return 0;
08104 }
08105
08106
08107 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
08108 {
08109
08110 memset(req, 0, sizeof(*req));
08111 if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
08112 return -1;
08113 req->method = sipmethod;
08114 req->header[0] = 0;
08115 ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
08116 req->len = req->data->used;
08117 req->headers++;
08118 return 0;
08119 }
08120
08121
08122 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
08123
08124
08125
08126
08127
08128
08129
08130
08131
08132
08133
08134
08135
08136
08137
08138 switch (method) {
08139
08140 case SIP_INVITE:
08141 case SIP_UPDATE:
08142 case SIP_SUBSCRIBE:
08143 case SIP_NOTIFY:
08144 if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
08145 return 1;
08146 break;
08147
08148
08149 case SIP_REGISTER:
08150 case SIP_OPTIONS:
08151 if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
08152 return 1;
08153 break;
08154
08155
08156 case SIP_BYE:
08157 case SIP_PRACK:
08158 case SIP_MESSAGE:
08159 case SIP_PUBLISH:
08160 if (msg[0] == '3' || !strncmp(msg, "485", 3))
08161 return 1;
08162 break;
08163
08164
08165 case SIP_REFER:
08166 if (msg[0] >= '2' && msg[0] <= '6')
08167 return 1;
08168 break;
08169
08170
08171 case SIP_ACK:
08172 case SIP_CANCEL:
08173 case SIP_INFO:
08174 case SIP_PING:
08175 default:
08176 return 0;
08177 }
08178 return 0;
08179 }
08180
08181
08182 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
08183 {
08184 char newto[256];
08185 const char *ot;
08186
08187 init_resp(resp, msg);
08188 copy_via_headers(p, resp, req, "Via");
08189 if (msg[0] == '1' || msg[0] == '2')
08190 copy_all_header(resp, req, "Record-Route");
08191 copy_header(resp, req, "From");
08192 ot = get_header(req, "To");
08193 if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
08194
08195
08196 if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
08197 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08198 else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
08199 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08200 else
08201 ast_copy_string(newto, ot, sizeof(newto));
08202 ot = newto;
08203 }
08204 add_header(resp, "To", ot);
08205 copy_header(resp, req, "Call-ID");
08206 copy_header(resp, req, "CSeq");
08207 if (!ast_strlen_zero(global_useragent))
08208 add_header(resp, "Server", global_useragent);
08209 add_header(resp, "Allow", ALLOWED_METHODS);
08210 add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
08211
08212
08213 if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
08214 char se_hdr[256];
08215 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
08216 strefresher2str(p->stimer->st_ref));
08217 add_header(resp, "Require", "timer");
08218 add_header(resp, "Session-Expires", se_hdr);
08219 }
08220
08221 if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
08222
08223
08224 char tmp[256];
08225
08226 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
08227 add_header(resp, "Expires", tmp);
08228 if (p->expiry) {
08229 char contact[SIPBUFSIZE];
08230 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
08231 add_header(resp, "Contact", contact);
08232 }
08233 } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
08234 add_header(resp, "Contact", p->our_contact);
08235 }
08236
08237 if (!ast_strlen_zero(p->url)) {
08238 add_header(resp, "Access-URL", p->url);
08239 ast_string_field_set(p, url, NULL);
08240 }
08241
08242 return 0;
08243 }
08244
08245
08246 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
08247 {
08248 struct sip_request *orig = &p->initreq;
08249 char stripped[80];
08250 char tmp[80];
08251 char newto[256];
08252 const char *c;
08253 const char *ot, *of;
08254 int is_strict = FALSE;
08255 int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);
08256
08257 memset(req, 0, sizeof(struct sip_request));
08258
08259 snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
08260
08261 if (!seqno) {
08262 p->ocseq++;
08263 seqno = p->ocseq;
08264 }
08265
08266
08267
08268
08269
08270 if (sipmethod == SIP_CANCEL || (sipmethod == SIP_INVITE && p->options && !ast_strlen_zero(p->options->auth))) {
08271 p->branch = p->invite_branch;
08272 build_via(p);
08273 } else if (newbranch) {
08274 p->branch ^= ast_random();
08275 build_via(p);
08276 }
08277
08278
08279 if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
08280 is_strict = TRUE;
08281 if (sipdebug)
08282 ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
08283 }
08284
08285 if (sipmethod == SIP_CANCEL)
08286 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
08287 else if (sipmethod == SIP_ACK) {
08288
08289
08290 if (!ast_strlen_zero(p->okcontacturi))
08291 c = is_strict ? p->route->hop : p->okcontacturi;
08292 else
08293 c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
08294 } else if (!ast_strlen_zero(p->okcontacturi))
08295 c = is_strict ? p->route->hop : p->okcontacturi;
08296 else if (!ast_strlen_zero(p->uri))
08297 c = p->uri;
08298 else {
08299 char *n;
08300
08301 ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
08302 sizeof(stripped));
08303 n = get_in_brackets(stripped);
08304 c = remove_uri_parameters(n);
08305 }
08306 init_req(req, sipmethod, c);
08307
08308 snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
08309
08310 add_header(req, "Via", p->via);
08311 if (p->route) {
08312 set_destination(p, p->route->hop);
08313 add_route(req, is_strict ? p->route->next : p->route);
08314 }
08315 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
08316
08317 ot = get_header(orig, "To");
08318 of = get_header(orig, "From");
08319
08320
08321
08322 if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
08323
08324
08325 if (is_outbound && !ast_strlen_zero(p->theirtag))
08326 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08327 else if (!is_outbound)
08328 snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08329 else
08330 snprintf(newto, sizeof(newto), "%s", ot);
08331 ot = newto;
08332 }
08333
08334 if (is_outbound) {
08335 add_header(req, "From", of);
08336 add_header(req, "To", ot);
08337 } else {
08338 add_header(req, "From", ot);
08339 add_header(req, "To", of);
08340 }
08341
08342 if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
08343 add_header(req, "Contact", p->our_contact);
08344
08345 copy_header(req, orig, "Call-ID");
08346 add_header(req, "CSeq", tmp);
08347
08348 if (!ast_strlen_zero(global_useragent))
08349 add_header(req, "User-Agent", global_useragent);
08350
08351 if (!ast_strlen_zero(p->rpid))
08352 add_header(req, "Remote-Party-ID", p->rpid);
08353
08354 if (!ast_strlen_zero(p->url)) {
08355 add_header(req, "Access-URL", p->url);
08356 ast_string_field_set(p, url, NULL);
08357 }
08358
08359
08360
08361
08362
08363
08364
08365
08366 if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
08367 && sipmethod == SIP_INVITE) {
08368 char se_hdr[256];
08369 snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
08370 strefresher2str(p->stimer->st_ref));
08371 add_header(req, "Require", "timer");
08372 add_header(req, "Session-Expires", se_hdr);
08373 snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
08374 add_header(req, "Min-SE", se_hdr);
08375 }
08376
08377 return 0;
08378 }
08379
08380
08381 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
08382 {
08383 struct sip_request resp;
08384 int seqno = 0;
08385
08386 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
08387 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
08388 return -1;
08389 }
08390 respprep(&resp, p, msg, req);
08391 add_header_contentLength(&resp, 0);
08392
08393
08394 if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
08395 char buf[10];
08396
08397 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
08398 snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
08399 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
08400 }
08401 return send_response(p, &resp, reliable, seqno);
08402 }
08403
08404 static int temp_pvt_init(void *data)
08405 {
08406 struct sip_pvt *p = data;
08407
08408 p->do_history = 0;
08409 return ast_string_field_init(p, 512);
08410 }
08411
08412 static void temp_pvt_cleanup(void *data)
08413 {
08414 struct sip_pvt *p = data;
08415
08416 ast_string_field_free_memory(p);
08417
08418 ast_free(data);
08419 }
08420
08421
08422 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
08423 {
08424 struct sip_pvt *p = NULL;
08425
08426 if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
08427 ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
08428 return -1;
08429 }
08430
08431
08432
08433
08434
08435
08436
08437
08438
08439 p->method = intended_method;
08440
08441 if (!sin)
08442 p->ourip = internip;
08443 else {
08444 p->sa = *sin;
08445 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
08446 }
08447
08448 p->branch = ast_random();
08449 make_our_tag(p->tag, sizeof(p->tag));
08450 p->ocseq = INITIAL_CSEQ;
08451
08452 if (useglobal_nat && sin) {
08453 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
08454 p->recv = *sin;
08455 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
08456 }
08457
08458 ast_string_field_set(p, fromdomain, default_fromdomain);
08459 build_via(p);
08460 ast_string_field_set(p, callid, callid);
08461
08462 copy_socket_data(&p->socket, &req->socket);
08463
08464
08465 __transmit_response(p, msg, req, XMIT_UNRELIABLE);
08466
08467
08468 ast_string_field_init(p, 0);
08469
08470 return 0;
08471 }
08472
08473
08474 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
08475 {
08476 return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
08477 }
08478
08479
08480 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
08481 {
08482 struct sip_request resp;
08483 respprep(&resp, p, msg, req);
08484 append_date(&resp);
08485 add_header(&resp, "Unsupported", unsupported);
08486 add_header_contentLength(&resp, 0);
08487 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
08488 }
08489
08490
08491 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
08492 {
08493 struct sip_request resp;
08494 char minse_str[20];
08495
08496 respprep(&resp, p, msg, req);
08497 append_date(&resp);
08498
08499 snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
08500 add_header(&resp, "Min-SE", minse_str);
08501
08502 add_header_contentLength(&resp, 0);
08503 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
08504 }
08505
08506
08507
08508
08509
08510 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
08511 {
08512 return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
08513 }
08514
08515
08516 static void append_date(struct sip_request *req)
08517 {
08518 char tmpdat[256];
08519 struct tm tm;
08520 time_t t = time(NULL);
08521
08522 gmtime_r(&t, &tm);
08523 strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
08524 add_header(req, "Date", tmpdat);
08525 }
08526
08527
08528 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
08529 {
08530 struct sip_request resp;
08531 respprep(&resp, p, msg, req);
08532 append_date(&resp);
08533 add_header_contentLength(&resp, 0);
08534 return send_response(p, &resp, XMIT_UNRELIABLE, 0);
08535 }
08536
08537
08538 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
08539 {
08540 struct sip_request resp;
08541 respprep(&resp, p, msg, req);
08542 add_header(&resp, "Accept", "application/sdp");
08543 add_header_contentLength(&resp, 0);
08544 return send_response(p, &resp, reliable, 0);
08545 }
08546
08547
08548 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)
08549 {
08550 struct sip_request resp;
08551 char tmp[512];
08552 int seqno = 0;
08553
08554 if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
08555 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
08556 return -1;
08557 }
08558
08559
08560 snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
08561 respprep(&resp, p, msg, req);
08562 add_header(&resp, header, tmp);
08563 add_header_contentLength(&resp, 0);
08564 append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
08565 return send_response(p, &resp, reliable, seqno);
08566 }
08567
08568
08569 static int add_text(struct sip_request *req, const char *text)
08570 {
08571
08572 add_header(req, "Content-Type", "text/plain;charset=UTF-8");
08573 add_header_contentLength(req, strlen(text));
08574 add_line(req, text);
08575 return 0;
08576 }
08577
08578
08579
08580
08581
08582 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
08583 {
08584 char tmp[256];
08585 int event;
08586 if (mode) {
08587
08588 if (digit == '*')
08589 event = 10;
08590 else if (digit == '#')
08591 event = 11;
08592 else if ((digit >= 'A') && (digit <= 'D'))
08593 event = 12 + digit - 'A';
08594 else
08595 event = atoi(&digit);
08596 snprintf(tmp, sizeof(tmp), "%d\r\n", event);
08597 add_header(req, "Content-Type", "application/dtmf");
08598 add_header_contentLength(req, strlen(tmp));
08599 add_line(req, tmp);
08600 } else {
08601
08602 snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
08603 add_header(req, "Content-Type", "application/dtmf-relay");
08604 add_header_contentLength(req, strlen(tmp));
08605 add_line(req, tmp);
08606 }
08607 return 0;
08608 }
08609
08610
08611
08612 static int add_vidupdate(struct sip_request *req)
08613 {
08614 const char *xml_is_a_huge_waste_of_space =
08615 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
08616 " <media_control>\r\n"
08617 " <vc_primitive>\r\n"
08618 " <to_encoder>\r\n"
08619 " <picture_fast_update>\r\n"
08620 " </picture_fast_update>\r\n"
08621 " </to_encoder>\r\n"
08622 " </vc_primitive>\r\n"
08623 " </media_control>\r\n";
08624 add_header(req, "Content-Type", "application/media_control+xml");
08625 add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
08626 add_line(req, xml_is_a_huge_waste_of_space);
08627 return 0;
08628 }
08629
08630
08631 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
08632 struct ast_str **m_buf, struct ast_str **a_buf,
08633 int debug, int *min_packet_size)
08634 {
08635 int rtp_code;
08636 struct ast_format_list fmt;
08637
08638
08639 if (debug)
08640 ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
08641 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
08642 return;
08643
08644 if (p->rtp) {
08645 struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08646 fmt = ast_codec_pref_getsize(pref, codec);
08647 } else
08648 return;
08649 ast_str_append(m_buf, 0, " %d", rtp_code);
08650 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08651 ast_rtp_lookup_mime_subtype(1, codec,
08652 ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
08653 sample_rate);
08654 if (codec == AST_FORMAT_G729A) {
08655
08656 ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
08657 } else if (codec == AST_FORMAT_G723_1) {
08658
08659 ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
08660 } else if (codec == AST_FORMAT_ILBC) {
08661
08662 ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
08663 }
08664
08665 if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
08666 *min_packet_size = fmt.cur_ms;
08667
08668
08669 if ((*min_packet_size)==0 && fmt.cur_ms)
08670 *min_packet_size = fmt.cur_ms;
08671 }
08672
08673
08674
08675 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
08676 struct ast_str **m_buf, struct ast_str **a_buf,
08677 int debug, int *min_packet_size)
08678 {
08679 int rtp_code;
08680
08681 if (!p->vrtp)
08682 return;
08683
08684 if (debug)
08685 ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
08686
08687 if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
08688 return;
08689
08690 ast_str_append(m_buf, 0, " %d", rtp_code);
08691 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08692 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
08693
08694 }
08695
08696
08697 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
08698 struct ast_str **m_buf, struct ast_str **a_buf,
08699 int debug, int *min_packet_size)
08700 {
08701 int rtp_code;
08702
08703 if (!p->trtp)
08704 return;
08705
08706 if (debug)
08707 ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
08708
08709 if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
08710 return;
08711
08712 ast_str_append(m_buf, 0, " %d", rtp_code);
08713 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08714 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
08715
08716
08717 if (codec == AST_FORMAT_T140RED) {
08718 ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
08719 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
08720 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
08721 ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
08722
08723 }
08724 }
08725
08726
08727
08728 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
08729 {
08730 switch (rate) {
08731 case AST_T38_RATE_2400:
08732 return 2400;
08733 case AST_T38_RATE_4800:
08734 return 4800;
08735 case AST_T38_RATE_7200:
08736 return 7200;
08737 case AST_T38_RATE_9600:
08738 return 9600;
08739 case AST_T38_RATE_12000:
08740 return 12000;
08741 case AST_T38_RATE_14400:
08742 return 14400;
08743 default:
08744 return 0;
08745 }
08746 }
08747
08748
08749 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
08750 struct ast_str **m_buf, struct ast_str **a_buf,
08751 int debug)
08752 {
08753 int rtp_code;
08754
08755 if (debug)
08756 ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
08757 if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
08758 return;
08759
08760 ast_str_append(m_buf, 0, " %d", rtp_code);
08761 ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
08762 ast_rtp_lookup_mime_subtype(0, format, 0),
08763 sample_rate);
08764 if (format == AST_RTP_DTMF)
08765 ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
08766 }
08767
08768
08769
08770
08771 static void get_our_media_address(struct sip_pvt *p, int needvideo,
08772 struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
08773 struct sockaddr_in *dest, struct sockaddr_in *vdest)
08774 {
08775
08776 ast_rtp_get_us(p->rtp, sin);
08777 if (p->vrtp)
08778 ast_rtp_get_us(p->vrtp, vsin);
08779 if (p->trtp)
08780 ast_rtp_get_us(p->trtp, tsin);
08781
08782
08783
08784 if (p->redirip.sin_addr.s_addr) {
08785 dest->sin_port = p->redirip.sin_port;
08786 dest->sin_addr = p->redirip.sin_addr;
08787 } else {
08788 dest->sin_addr = p->ourip.sin_addr;
08789 dest->sin_port = sin->sin_port;
08790 }
08791 if (needvideo) {
08792
08793 if (p->vredirip.sin_addr.s_addr) {
08794 vdest->sin_addr = p->vredirip.sin_addr;
08795 vdest->sin_port = p->vredirip.sin_port;
08796 } else {
08797 vdest->sin_addr = p->ourip.sin_addr;
08798 vdest->sin_port = vsin->sin_port;
08799 }
08800 }
08801
08802 }
08803
08804
08805
08806
08807
08808
08809 #define SDP_SAMPLE_RATE(x) 8000
08810
08811
08812
08813
08814
08815
08816
08817 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
08818 {
08819 int len = 0;
08820 int alreadysent = 0;
08821
08822 struct sockaddr_in sin;
08823 struct sockaddr_in vsin;
08824 struct sockaddr_in tsin;
08825 struct sockaddr_in dest;
08826 struct sockaddr_in udptlsin;
08827 struct sockaddr_in vdest = { 0, };
08828 struct sockaddr_in tdest = { 0, };
08829 struct sockaddr_in udptldest = { 0, };
08830
08831
08832 char *version = "v=0\r\n";
08833 char subject[256];
08834 char owner[256];
08835 char connection[256];
08836 char *session_time = "t=0 0\r\n";
08837 char bandwidth[256] = "";
08838 char *hold = "";
08839 struct ast_str *m_audio = ast_str_alloca(256);
08840 struct ast_str *m_video = ast_str_alloca(256);
08841 struct ast_str *m_text = ast_str_alloca(256);
08842 struct ast_str *m_modem = ast_str_alloca(256);
08843 struct ast_str *a_audio = ast_str_alloca(1024);
08844 struct ast_str *a_video = ast_str_alloca(1024);
08845 struct ast_str *a_text = ast_str_alloca(1024);
08846 struct ast_str *a_modem = ast_str_alloca(1024);
08847
08848 int x;
08849 int capability = 0;
08850 int needaudio = FALSE;
08851 int needvideo = FALSE;
08852 int needtext = FALSE;
08853 int debug = sip_debug_test_pvt(p);
08854 int min_audio_packet_size = 0;
08855 int min_video_packet_size = 0;
08856 int min_text_packet_size = 0;
08857
08858 char codecbuf[SIPBUFSIZE];
08859 char buf[SIPBUFSIZE];
08860 char dummy_answer[256];
08861
08862
08863 snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
08864
08865 if (!p->rtp) {
08866 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
08867 return AST_FAILURE;
08868 }
08869
08870
08871
08872
08873 if (!p->sessionid) {
08874 p->sessionid = (int)ast_random();
08875 p->sessionversion = p->sessionid;
08876 } else {
08877 if (oldsdp == FALSE)
08878 p->sessionversion++;
08879 }
08880
08881
08882 if (add_audio && (capability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
08883 if (p->vrtp) {
08884 needvideo = TRUE;
08885 ast_debug(2, "This call needs video offers!\n");
08886 } else
08887 ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
08888 }
08889
08890 get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
08891
08892 snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
08893 snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
08894
08895 if (add_audio) {
08896 capability = p->jointcapability;
08897
08898
08899 ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
08900 p->novideo ? "True" : "False", p->notext ? "True" : "False");
08901 ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
08902
08903
08904 if (capability & AST_FORMAT_AUDIO_MASK)
08905 needaudio = TRUE;
08906
08907 if (debug)
08908 ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));
08909
08910
08911
08912 if (needvideo) {
08913 ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
08914
08915
08916 if (p->maxcallbitrate)
08917 snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
08918 if (debug)
08919 ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));
08920 }
08921
08922
08923 if((capability & AST_FORMAT_TEXT_MASK) && !p->notext) {
08924 if (sipdebug_text)
08925 ast_verbose("We think we can do text\n");
08926 if (p->trtp) {
08927 if (sipdebug_text)
08928 ast_verbose("And we have a text rtp object\n");
08929 needtext = TRUE;
08930 ast_debug(2, "This call needs text offers! \n");
08931 } else
08932 ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
08933 }
08934
08935
08936
08937 if (needtext) {
08938 if (sipdebug_text)
08939 ast_verbose("Lets set up the text sdp\n");
08940
08941 if (p->tredirip.sin_addr.s_addr) {
08942 tdest.sin_addr = p->tredirip.sin_addr;
08943 tdest.sin_port = p->tredirip.sin_port;
08944 } else {
08945 tdest.sin_addr = p->ourip.sin_addr;
08946 tdest.sin_port = tsin.sin_port;
08947 }
08948 ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
08949
08950 if (debug)
08951 ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));
08952
08953 }
08954
08955
08956
08957
08958
08959
08960 ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
08961
08962 if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
08963 hold = "a=recvonly\r\n";
08964 else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
08965 hold = "a=inactive\r\n";
08966 else
08967 hold = "a=sendrecv\r\n";
08968
08969
08970
08971
08972
08973
08974
08975
08976
08977
08978 if (capability & p->prefcodec) {
08979 int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
08980
08981 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
08982 &m_audio, &a_audio,
08983 debug, &min_audio_packet_size);
08984 alreadysent |= codec;
08985 }
08986
08987
08988 for (x = 0; x < 32; x++) {
08989 int codec;
08990
08991 if (!(codec = ast_codec_pref_index(&p->prefs, x)))
08992 break;
08993
08994 if (!(capability & codec))
08995 continue;
08996
08997 if (alreadysent & codec)
08998 continue;
08999
09000 add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
09001 &m_audio, &a_audio,
09002 debug, &min_audio_packet_size);
09003 alreadysent |= codec;
09004 }
09005
09006
09007 for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
09008 if (!(capability & x))
09009 continue;
09010
09011 if (alreadysent & x)
09012 continue;
09013
09014 if (x & AST_FORMAT_AUDIO_MASK)
09015 add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
09016 &m_audio, &a_audio, debug, &min_audio_packet_size);
09017 else if (x & AST_FORMAT_VIDEO_MASK)
09018 add_vcodec_to_sdp(p, x, 90000,
09019 &m_video, &a_video, debug, &min_video_packet_size);
09020 else if (x & AST_FORMAT_TEXT_MASK)
09021 add_tcodec_to_sdp(p, x, 1000,
09022 &m_text, &a_text, debug, &min_text_packet_size);
09023 }
09024
09025
09026 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
09027 if (!(p->jointnoncodeccapability & x))
09028 continue;
09029
09030 add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
09031 }
09032
09033 ast_debug(3, "-- Done with adding codecs to SDP\n");
09034
09035 if (!p->owner || !ast_internal_timing_enabled(p->owner))
09036 ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
09037
09038 if (min_audio_packet_size)
09039 ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
09040
09041
09042 if (min_video_packet_size)
09043 ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
09044
09045
09046 if (min_text_packet_size)
09047 ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
09048 }
09049
09050 if (add_t38) {
09051 ast_udptl_get_us(p->udptl, &udptlsin);
09052
09053
09054 if (p->udptlredirip.sin_addr.s_addr) {
09055 udptldest.sin_port = p->udptlredirip.sin_port;
09056 udptldest.sin_addr = p->udptlredirip.sin_addr;
09057 } else {
09058 udptldest.sin_addr = p->ourip.sin_addr;
09059 udptldest.sin_port = udptlsin.sin_port;
09060 }
09061
09062 if (debug)
09063 ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
09064
09065
09066
09067
09068 ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
09069
09070 ast_str_append(&a_modem, 0, "a=T38Faxversion:%d\r\n", p->t38.our_parms.version);
09071 ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
09072 if (p->t38.our_parms.fill_bit_removal) {
09073 ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
09074 }
09075 if (p->t38.our_parms.transcoding_mmr) {
09076 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
09077 }
09078 if (p->t38.our_parms.transcoding_jbig) {
09079 ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
09080 }
09081 switch (p->t38.our_parms.rate_management) {
09082 case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
09083 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
09084 break;
09085 case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
09086 ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
09087 break;
09088 }
09089 ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%d\r\n", ast_udptl_get_local_max_datagram(p->udptl));
09090 switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
09091 case UDPTL_ERROR_CORRECTION_NONE:
09092 break;
09093 case UDPTL_ERROR_CORRECTION_FEC:
09094 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
09095 break;
09096 case UDPTL_ERROR_CORRECTION_REDUNDANCY:
09097 ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
09098 break;
09099 }
09100 }
09101
09102 if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
09103 m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
09104 a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
09105 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
09106
09107 if (needaudio)
09108 ast_str_append(&m_audio, 0, "\r\n");
09109 if (needvideo)
09110 ast_str_append(&m_video, 0, "\r\n");
09111 if (needtext)
09112 ast_str_append(&m_text, 0, "\r\n");
09113
09114 len = strlen(version) + strlen(subject) + strlen(owner) +
09115 strlen(connection) + strlen(session_time);
09116 if (needaudio)
09117 len += m_audio->used + a_audio->used + strlen(hold);
09118 if (needvideo)
09119 len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
09120 if (needtext)
09121 len += m_text->used + a_text->used + strlen(hold);
09122 if (add_t38)
09123 len += m_modem->used + a_modem->used;
09124
09125 add_header(resp, "Content-Type", "application/sdp");
09126 add_header_contentLength(resp, len);
09127 add_line(resp, version);
09128 add_line(resp, owner);
09129 add_line(resp, subject);
09130 add_line(resp, connection);
09131 if (needvideo)
09132 add_line(resp, bandwidth);
09133 add_line(resp, session_time);
09134 if (needaudio) {
09135 add_line(resp, m_audio->str);
09136 add_line(resp, a_audio->str);
09137 add_line(resp, hold);
09138 } else if (p->offered_media[SDP_AUDIO].offered) {
09139 snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
09140 add_line(resp, dummy_answer);
09141 }
09142 if (needvideo) {
09143 add_line(resp, m_video->str);
09144 add_line(resp, a_video->str);
09145 add_line(resp, hold);
09146 } else if (p->offered_media[SDP_VIDEO].offered) {
09147 snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
09148 add_line(resp, dummy_answer);
09149 }
09150 if (needtext) {
09151 add_line(resp, m_text->str);
09152 add_line(resp, a_text->str);
09153 add_line(resp, hold);
09154 } else if (p->offered_media[SDP_TEXT].offered) {
09155 snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
09156 add_line(resp, dummy_answer);
09157 }
09158 if (add_t38) {
09159 add_line(resp, m_modem->str);
09160 add_line(resp, a_modem->str);
09161 } else if (p->offered_media[SDP_IMAGE].offered) {
09162 add_line(resp, "m=image 0 udptl t38\r\n");
09163 }
09164
09165
09166 p->lastrtprx = p->lastrtptx = time(NULL);
09167
09168 ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
09169
09170 return AST_SUCCESS;
09171 }
09172
09173
09174 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
09175 {
09176 struct sip_request resp;
09177 int seqno;
09178
09179 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09180 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09181 return -1;
09182 }
09183 respprep(&resp, p, msg, req);
09184 if (p->udptl) {
09185 add_sdp(&resp, p, 0, 0, 1);
09186 } else
09187 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
09188 if (retrans && !p->pendinginvite)
09189 p->pendinginvite = seqno;
09190 return send_response(p, &resp, retrans, seqno);
09191 }
09192
09193
09194 static void copy_request(struct sip_request *dst, const struct sip_request *src)
09195 {
09196 struct ast_str *duplicate = dst->data;
09197
09198
09199 memcpy(dst, src, sizeof(*dst));
09200 dst->data = duplicate;
09201
09202
09203
09204
09205
09206
09207
09208 if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
09209 return;
09210 else if (dst->data->len < src->data->used + 1)
09211 ast_str_make_space(&dst->data, src->data->used + 1);
09212
09213 memcpy(dst->data->str, src->data->str, src->data->used + 1);
09214 dst->data->used = src->data->used;
09215 }
09216
09217
09218
09219
09220 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
09221 {
09222 struct sip_request resp;
09223 int seqno;
09224 if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09225 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09226 return -1;
09227 }
09228 respprep(&resp, p, msg, req);
09229 if (p->rtp) {
09230 if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
09231 ast_debug(1, "Setting framing from config on incoming call\n");
09232 ast_rtp_codec_setpref(p->rtp, &p->prefs);
09233 }
09234 try_suggested_sip_codec(p);
09235 if (p->t38.state == T38_ENABLED) {
09236 add_sdp(&resp, p, oldsdp, TRUE, TRUE);
09237 } else {
09238 add_sdp(&resp, p, oldsdp, TRUE, FALSE);
09239 }
09240 } else
09241 ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
09242 if (reliable && !p->pendinginvite)
09243 p->pendinginvite = seqno;
09244 return send_response(p, &resp, reliable, seqno);
09245 }
09246
09247
09248 static int determine_firstline_parts(struct sip_request *req)
09249 {
09250 char *e = ast_skip_blanks(req->data->str);
09251 char *local_rlPart1;
09252
09253 if (!*e)
09254 return -1;
09255 req->rlPart1 = e - req->data->str;
09256 local_rlPart1 = e;
09257 e = ast_skip_nonblanks(e);
09258 if (*e)
09259 *e++ = '\0';
09260
09261 e = ast_skip_blanks(e);
09262 if ( !*e )
09263 return -1;
09264 ast_trim_blanks(e);
09265
09266 if (!strcasecmp(local_rlPart1, "SIP/2.0") ) {
09267 if (strlen(e) < 3)
09268 return -1;
09269 req->rlPart2 = e - req->data->str;
09270 } else {
09271 if ( *e == '<' ) {
09272 ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
09273 e++;
09274 if (!*e)
09275 return -1;
09276 }
09277 req->rlPart2 = e - req->data->str;
09278 e = ast_skip_nonblanks(e);
09279 if (*e)
09280 *e++ = '\0';
09281 e = ast_skip_blanks(e);
09282 if (strcasecmp(e, "SIP/2.0") ) {
09283 ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
09284 return -1;
09285 }
09286 }
09287 return 1;
09288 }
09289
09290
09291
09292
09293
09294
09295
09296
09297
09298
09299
09300
09301
09302
09303 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
09304 {
09305 struct sip_request req;
09306
09307 reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
09308
09309 add_header(&req, "Allow", ALLOWED_METHODS);
09310 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09311 if (sipdebug) {
09312 if (oldsdp == TRUE)
09313 add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
09314 else
09315 add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
09316 }
09317
09318 if (p->do_history)
09319 append_history(p, "ReInv", "Re-invite sent");
09320 memset(p->offered_media, 0, sizeof(p->offered_media));
09321
09322 if (t38version)
09323 add_sdp(&req, p, oldsdp, FALSE, TRUE);
09324 else
09325 add_sdp(&req, p, oldsdp, TRUE, FALSE);
09326
09327
09328 initialize_initreq(p, &req);
09329 p->lastinvite = p->ocseq;
09330 ast_set_flag(&p->flags[0], SIP_OUTGOING);
09331
09332 return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
09333 }
09334
09335
09336 static char *remove_uri_parameters(char *uri)
09337 {
09338 char *atsign;
09339 atsign = strchr(uri, '@');
09340 if (!atsign)
09341 atsign = uri;
09342 atsign = strchr(atsign, ';');
09343 if (atsign)
09344 *atsign = '\0';
09345 return uri;
09346 }
09347
09348
09349 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
09350 {
09351 char stripped[SIPBUFSIZE];
09352 char *c;
09353
09354 ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
09355 c = get_in_brackets(stripped);
09356
09357 c = remove_uri_parameters(c);
09358 if (!ast_strlen_zero(c))
09359 ast_string_field_set(p, uri, c);
09360
09361 }
09362
09363
09364 static void build_contact(struct sip_pvt *p)
09365 {
09366 int ourport = ntohs(p->ourip.sin_port);
09367
09368 if (!sip_standard_port(p->socket.type, ourport)) {
09369 if (p->socket.type == SIP_TRANSPORT_UDP)
09370 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
09371 else
09372 ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
09373 } else {
09374 if (p->socket.type == SIP_TRANSPORT_UDP)
09375 ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
09376 else
09377 ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
09378 }
09379 }
09380
09381
09382 static void build_rpid(struct sip_pvt *p)
09383 {
09384 int send_pres_tags = TRUE;
09385 const char *privacy=NULL;
09386 const char *screen=NULL;
09387 char buf[256];
09388 const char *clid = default_callerid;
09389 const char *clin = NULL;
09390 const char *fromdomain;
09391
09392 if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))
09393 return;
09394
09395 if (p->owner && p->owner->cid.cid_num)
09396 clid = p->owner->cid.cid_num;
09397 if (p->owner && p->owner->cid.cid_name)
09398 clin = p->owner->cid.cid_name;
09399 if (ast_strlen_zero(clin))
09400 clin = clid;
09401
09402 switch (p->callingpres) {
09403 case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
09404 privacy = "off";
09405 screen = "no";
09406 break;
09407 case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
09408 privacy = "off";
09409 screen = "yes";
09410 break;
09411 case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
09412 privacy = "off";
09413 screen = "no";
09414 break;
09415 case AST_PRES_ALLOWED_NETWORK_NUMBER:
09416 privacy = "off";
09417 screen = "yes";
09418 break;
09419 case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
09420 privacy = "full";
09421 screen = "no";
09422 break;
09423 case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
09424 privacy = "full";
09425 screen = "yes";
09426 break;
09427 case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
09428 privacy = "full";
09429 screen = "no";
09430 break;
09431 case AST_PRES_PROHIB_NETWORK_NUMBER:
09432 privacy = "full";
09433 screen = "yes";
09434 break;
09435 case AST_PRES_NUMBER_NOT_AVAILABLE:
09436 send_pres_tags = FALSE;
09437 break;
09438 default:
09439 ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
09440 if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
09441 privacy = "full";
09442 else
09443 privacy = "off";
09444 screen = "no";
09445 break;
09446 }
09447
09448 fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
09449
09450 snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
09451 if (send_pres_tags)
09452 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
09453 ast_string_field_set(p, rpid, buf);
09454
09455 ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
09456 S_OR(p->fromuser, clid),
09457 fromdomain, p->tag);
09458 }
09459
09460
09461 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
09462 {
09463 struct ast_str *invite = ast_str_alloca(256);
09464 char from[256];
09465 char to[256];
09466 char tmp_n[SIPBUFSIZE/2];
09467 char tmp_l[SIPBUFSIZE/2];
09468 const char *l = NULL;
09469 const char *n = NULL;
09470 const char *d = NULL;
09471 const char *urioptions = "";
09472 int ourport;
09473
09474 if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
09475 const char *s = p->username;
09476
09477
09478
09479
09480
09481
09482 if (*s == '+')
09483 s++;
09484 for (; *s; s++) {
09485 if (!strchr(AST_DIGIT_ANYNUM, *s) )
09486 break;
09487 }
09488
09489 if (!*s)
09490 urioptions = ";user=phone";
09491 }
09492
09493
09494 snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
09495
09496 d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
09497 if (p->owner) {
09498 l = p->owner->cid.cid_num;
09499 n = p->owner->cid.cid_name;
09500 }
09501
09502 if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
09503 ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
09504 l = CALLERID_UNKNOWN;
09505 n = l;
09506 d = FROMDOMAIN_INVALID;
09507 }
09508 if (ast_strlen_zero(l))
09509 l = default_callerid;
09510 if (ast_strlen_zero(n))
09511 n = l;
09512
09513 if (!ast_strlen_zero(p->fromuser))
09514 l = p->fromuser;
09515 else
09516 ast_string_field_set(p, fromuser, l);
09517
09518
09519 if (!ast_strlen_zero(p->fromname))
09520 n = p->fromname;
09521 else
09522 ast_string_field_set(p, fromname, n);
09523
09524 if (pedanticsipchecking) {
09525 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
09526 n = tmp_n;
09527 ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
09528 l = tmp_l;
09529 }
09530
09531 ourport = ntohs(p->ourip.sin_port);
09532 if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
09533 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
09534 else
09535 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
09536
09537
09538 if (!ast_strlen_zero(p->fullcontact)) {
09539
09540 ast_str_append(&invite, 0, "%s", p->fullcontact);
09541 } else {
09542
09543 ast_str_append(&invite, 0, "sip:");
09544 if (!ast_strlen_zero(p->username)) {
09545 n = p->username;
09546 if (pedanticsipchecking) {
09547 ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
09548 n = tmp_n;
09549 }
09550 ast_str_append(&invite, 0, "%s@", n);
09551 }
09552 ast_str_append(&invite, 0, "%s", p->tohost);
09553 if (ntohs(p->sa.sin_port) != STANDARD_SIP_PORT)
09554 ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
09555 ast_str_append(&invite, 0, "%s", urioptions);
09556 }
09557
09558
09559 if (p->options && !ast_strlen_zero(p->options->uri_options))
09560 ast_str_append(&invite, 0, ";%s", p->options->uri_options);
09561
09562
09563
09564
09565 ast_string_field_set(p, uri, invite->str);
09566
09567 if (!ast_strlen_zero(p->todnid)) {
09568
09569 if (!strchr(p->todnid, '@')) {
09570
09571 snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
09572 } else {
09573 snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
09574 }
09575 } else {
09576 if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
09577
09578 snprintf(to, sizeof(to), "<%s%s>;tag=%s", (!strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
09579 } else if (p->options && p->options->vxml_url) {
09580
09581 snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
09582 } else
09583 snprintf(to, sizeof(to), "<%s>", p->uri);
09584 }
09585
09586 init_req(req, sipmethod, p->uri);
09587
09588 snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
09589
09590 add_header(req, "Via", p->via);
09591 add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09592
09593
09594
09595
09596 add_route(req, p->route);
09597
09598
09599 if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
09600 build_rpid(p);
09601 add_header(req, "From", p->rpid_from);
09602 } else
09603 add_header(req, "From", from);
09604 add_header(req, "To", to);
09605 ast_string_field_set(p, exten, l);
09606 build_contact(p);
09607 add_header(req, "Contact", p->our_contact);
09608 add_header(req, "Call-ID", p->callid);
09609 add_header(req, "CSeq", tmp_n);
09610 if (!ast_strlen_zero(global_useragent))
09611 add_header(req, "User-Agent", global_useragent);
09612 if (!ast_strlen_zero(p->rpid))
09613 add_header(req, "Remote-Party-ID", p->rpid);
09614 }
09615
09616
09617
09618
09619
09620
09621
09622
09623 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
09624 {
09625 struct sip_request req;
09626 struct ast_variable *var;
09627
09628 req.method = sipmethod;
09629 if (init) {
09630 p->branch ^= ast_random();
09631 p->invite_branch = p->branch;
09632 build_via(p);
09633 }
09634 if (init > 1)
09635 initreqprep(&req, p, sipmethod);
09636 else
09637
09638 reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
09639
09640 if (p->options && p->options->auth)
09641 add_header(&req, p->options->authheader, p->options->auth);
09642 append_date(&req);
09643 if (sipmethod == SIP_REFER) {
09644 if (p->refer) {
09645 char buf[SIPBUFSIZE];
09646 if (!ast_strlen_zero(p->refer->refer_to))
09647 add_header(&req, "Refer-To", p->refer->refer_to);
09648 if (!ast_strlen_zero(p->refer->referred_by)) {
09649 snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
09650 add_header(&req, "Referred-By", buf);
09651 }
09652 }
09653 }
09654
09655
09656 if (p->options && !ast_strlen_zero(p->options->replaces)) {
09657 add_header(&req, "Replaces", p->options->replaces);
09658 add_header(&req, "Require", "replaces");
09659 }
09660
09661
09662 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
09663 char i2astr[10];
09664
09665 if (!p->stimer->st_interval)
09666 p->stimer->st_interval = st_get_se(p, TRUE);
09667
09668 p->stimer->st_active = TRUE;
09669
09670 snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
09671 add_header(&req, "Session-Expires", i2astr);
09672 snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
09673 add_header(&req, "Min-SE", i2astr);
09674 }
09675
09676 add_header(&req, "Allow", ALLOWED_METHODS);
09677 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09678
09679 if(p->notify_headers) {
09680 char buf[512];
09681 for (var = p->notify_headers; var; var = var->next) {
09682 ast_copy_string(buf, var->value, sizeof(buf));
09683 add_header(&req, var->name, ast_unescape_semicolon(buf));
09684 }
09685 }
09686 if (p->options && p->options->addsipheaders && p->owner) {
09687 struct ast_channel *chan = p->owner;
09688 struct varshead *headp;
09689
09690 ast_channel_lock(chan);
09691
09692 headp = &chan->varshead;
09693
09694 if (!headp)
09695 ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
09696 else {
09697 const struct ast_var_t *current;
09698 AST_LIST_TRAVERSE(headp, current, entries) {
09699
09700 if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
09701 char *content, *end;
09702 const char *header = ast_var_value(current);
09703 char *headdup = ast_strdupa(header);
09704
09705
09706 if (*headdup == '"')
09707 headdup++;
09708 if ((content = strchr(headdup, ':'))) {
09709 *content++ = '\0';
09710 content = ast_skip_blanks(content);
09711
09712 end = content + strlen(content) -1;
09713 if (*end == '"')
09714 *end = '\0';
09715
09716 add_header(&req, headdup, content);
09717 if (sipdebug)
09718 ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
09719 }
09720 }
09721 }
09722 }
09723
09724 ast_channel_unlock(chan);
09725 }
09726 if (sdp) {
09727 memset(p->offered_media, 0, sizeof(p->offered_media));
09728 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
09729 ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
09730 add_sdp(&req, p, FALSE, FALSE, TRUE);
09731 } else if (p->rtp)
09732 add_sdp(&req, p, FALSE, TRUE, FALSE);
09733 } else {
09734 if (!p->notify_headers) {
09735 add_header_contentLength(&req, 0);
09736 }
09737 }
09738
09739 if (!p->initreq.headers || init > 2)
09740 initialize_initreq(p, &req);
09741 p->lastinvite = p->ocseq;
09742 return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
09743 }
09744
09745
09746 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
09747 {
09748 struct ast_str *tmp = ast_str_alloca(4000);
09749 char from[256], to[256];
09750 char *c, *mfrom, *mto;
09751 struct sip_request req;
09752 char hint[AST_MAX_EXTENSION];
09753 char *statestring = "terminated";
09754 const struct cfsubscription_types *subscriptiontype;
09755 enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
09756 char *pidfstate = "--";
09757 char *pidfnote= "Ready";
09758
09759 memset(from, 0, sizeof(from));
09760 memset(to, 0, sizeof(to));
09761
09762 switch (state) {
09763 case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
09764 statestring = (global_notifyringing) ? "early" : "confirmed";
09765 local_state = NOTIFY_INUSE;
09766 pidfstate = "busy";
09767 pidfnote = "Ringing";
09768 break;
09769 case AST_EXTENSION_RINGING:
09770 statestring = "early";
09771 local_state = NOTIFY_INUSE;
09772 pidfstate = "busy";
09773 pidfnote = "Ringing";
09774 break;
09775 case AST_EXTENSION_INUSE:
09776 statestring = "confirmed";
09777 local_state = NOTIFY_INUSE;
09778 pidfstate = "busy";
09779 pidfnote = "On the phone";
09780 break;
09781 case AST_EXTENSION_BUSY:
09782 statestring = "confirmed";
09783 local_state = NOTIFY_CLOSED;
09784 pidfstate = "busy";
09785 pidfnote = "On the phone";
09786 break;
09787 case AST_EXTENSION_UNAVAILABLE:
09788 statestring = "terminated";
09789 local_state = NOTIFY_CLOSED;
09790 pidfstate = "away";
09791 pidfnote = "Unavailable";
09792 break;
09793 case AST_EXTENSION_ONHOLD:
09794 statestring = "confirmed";
09795 local_state = NOTIFY_CLOSED;
09796 pidfstate = "busy";
09797 pidfnote = "On hold";
09798 break;
09799 case AST_EXTENSION_NOT_INUSE:
09800 default:
09801
09802 break;
09803 }
09804
09805 subscriptiontype = find_subscription_type(p->subscribed);
09806
09807
09808 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
09809 char *hint2 = hint, *individual_hint = NULL;
09810 int hint_count = 0, unavailable_count = 0;
09811
09812 while ((individual_hint = strsep(&hint2, "&"))) {
09813 hint_count++;
09814
09815 if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
09816 unavailable_count++;
09817 }
09818
09819
09820
09821
09822 if (hint_count > 0 && hint_count == unavailable_count) {
09823 local_state = NOTIFY_CLOSED;
09824 pidfstate = "away";
09825 pidfnote = "Not online";
09826 }
09827 }
09828
09829 ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
09830 c = get_in_brackets(from);
09831 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
09832 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
09833 return -1;
09834 }
09835
09836 mfrom = remove_uri_parameters(c);
09837
09838 ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
09839 c = get_in_brackets(to);
09840 if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
09841 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", c);
09842 return -1;
09843 }
09844 mto = remove_uri_parameters(c);
09845
09846 reqprep(&req, p, SIP_NOTIFY, 0, 1);
09847
09848
09849 add_header(&req, "Event", subscriptiontype->event);
09850 add_header(&req, "Content-Type", subscriptiontype->mediatype);
09851 switch(state) {
09852 case AST_EXTENSION_DEACTIVATED:
09853 if (timeout)
09854 add_header(&req, "Subscription-State", "terminated;reason=timeout");
09855 else {
09856 add_header(&req, "Subscription-State", "terminated;reason=probation");
09857 add_header(&req, "Retry-After", "60");
09858 }
09859 break;
09860 case AST_EXTENSION_REMOVED:
09861 add_header(&req, "Subscription-State", "terminated;reason=noresource");
09862 break;
09863 default:
09864 if (p->expiry)
09865 add_header(&req, "Subscription-State", "active");
09866 else
09867 add_header(&req, "Subscription-State", "terminated;reason=timeout");
09868 }
09869 switch (p->subscribed) {
09870 case XPIDF_XML:
09871 case CPIM_PIDF_XML:
09872 ast_str_append(&tmp, 0,
09873 "<?xml version=\"1.0\"?>\n"
09874 "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
09875 "<presence>\n");
09876 ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
09877 ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
09878 ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
09879 ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
09880 ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
09881 ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
09882 break;
09883 case PIDF_XML:
09884 ast_str_append(&tmp, 0,
09885 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
09886 "<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);
09887 ast_str_append(&tmp, 0, "<pp:person><status>\n");
09888 if (pidfstate[0] != '-')
09889 ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
09890 ast_str_append(&tmp, 0, "</status></pp:person>\n");
09891 ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote);
09892 ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten);
09893 ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
09894 if (pidfstate[0] == 'b')
09895 ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
09896 else
09897 ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
09898 ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
09899 break;
09900 case DIALOG_INFO_XML:
09901 ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
09902 ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
09903 if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
09904 ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
09905 else
09906 ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
09907 ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
09908 if (state == AST_EXTENSION_ONHOLD) {
09909 ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
09910 "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
09911 "</target>\n</local>\n", mto);
09912 }
09913 ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
09914 break;
09915 case NONE:
09916 default:
09917 break;
09918 }
09919
09920 add_header_contentLength(&req, tmp->used);
09921 add_line(&req, tmp->str);
09922
09923 p->pendinginvite = p->ocseq;
09924
09925 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
09926 }
09927
09928
09929
09930
09931
09932
09933
09934 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
09935 {
09936 struct sip_request req;
09937 struct ast_str *out = ast_str_alloca(500);
09938 int ourport = ntohs(p->ourip.sin_port);
09939 const char *exten = S_OR(vmexten, default_vmexten);
09940
09941 initreqprep(&req, p, SIP_NOTIFY);
09942 add_header(&req, "Event", "message-summary");
09943 add_header(&req, "Content-Type", default_notifymime);
09944 ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
09945
09946 if (!ast_strlen_zero(p->fromdomain)) {
09947 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
09948 } else if (!sip_standard_port(p->socket.type, ourport)) {
09949 if (p->socket.type == SIP_TRANSPORT_UDP) {
09950 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
09951 } else {
09952 ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
09953 }
09954 } else {
09955 if (p->socket.type == SIP_TRANSPORT_UDP) {
09956 ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
09957 } else {
09958 ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
09959 }
09960 }
09961
09962
09963
09964 ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
09965 newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
09966
09967 if (p->subscribed) {
09968 if (p->expiry)
09969 add_header(&req, "Subscription-State", "active");
09970 else
09971 add_header(&req, "Subscription-State", "terminated;reason=timeout");
09972 }
09973
09974 add_header_contentLength(&req, out->used);
09975 add_line(&req, out->str);
09976
09977 if (!p->initreq.headers)
09978 initialize_initreq(p, &req);
09979 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
09980 }
09981
09982
09983 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
09984 {
09985 struct sip_request req;
09986 char tmp[SIPBUFSIZE/2];
09987
09988 reqprep(&req, p, SIP_NOTIFY, 0, 1);
09989 snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
09990 add_header(&req, "Event", tmp);
09991 add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
09992 add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
09993 add_header(&req, "Allow", ALLOWED_METHODS);
09994 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09995
09996 snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
09997 add_header_contentLength(&req, strlen(tmp));
09998 add_line(&req, tmp);
09999
10000 if (!p->initreq.headers)
10001 initialize_initreq(p, &req);
10002
10003 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10004 }
10005
10006
10007 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
10008 struct sip_request req;
10009 struct ast_variable *var, *newvar;
10010
10011 initreqprep(&req, p, SIP_NOTIFY);
10012
10013
10014 p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
10015 add_header(&req, newvar->name, newvar->value);
10016 for (var = vars; var; var = var->next) {
10017 char buf[512];
10018 ast_debug(2, " Adding pair %s=%s\n", var->name, var->value);
10019 ast_copy_string(buf, var->value, sizeof(buf));
10020 add_header(&req, var->name, ast_unescape_semicolon(buf));
10021 newvar->next = ast_variable_new(var->name, var->value, "");
10022 newvar = newvar->next;
10023 }
10024
10025 if (!p->initreq.headers) {
10026 initialize_initreq(p, &req);
10027 }
10028
10029 return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
10030 }
10031
10032 static int manager_sipnotify(struct mansession *s, const struct message *m)
10033 {
10034 const char *channame = astman_get_header(m, "Channel");
10035 struct ast_variable *vars = astman_get_variables(m);
10036 struct sip_pvt *p;
10037
10038 if (ast_strlen_zero(channame)) {
10039 astman_send_error(s, m, "SIPNotify requires a channel name");
10040 return 0;
10041 }
10042
10043 if (!strncasecmp(channame, "sip/", 4)) {
10044 channame += 4;
10045 }
10046
10047 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
10048 astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
10049 return 0;
10050 }
10051
10052 if (create_addr(p, channame, NULL, 0)) {
10053
10054 dialog_unlink_all(p, TRUE, TRUE);
10055 dialog_unref(p, "unref dialog inside for loop" );
10056
10057 astman_send_error(s, m, "Could not create address");
10058 return 0;
10059 }
10060
10061
10062 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10063
10064
10065 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10066 build_via(p);
10067 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
10068 build_callid_pvt(p);
10069 ao2_t_link(dialogs, p, "Linking in new name");
10070 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
10071 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
10072
10073 if (!transmit_notify_custom(p, vars)) {
10074 astman_send_ack(s, m, "Notify Sent");
10075 } else {
10076 astman_send_error(s, m, "Unable to send notify");
10077 }
10078 ast_variables_destroy(vars);
10079 return 0;
10080 }
10081
10082 static char mandescr_sipnotify[] =
10083 "Description: Sends a SIP Notify event\n"
10084 "All parameters for this event must be specified in the body of this request\n"
10085 "via multiple Variable: name=value sequences.\n"
10086 "Variables: \n"
10087 " *Channel: <peername> Peer to receive the notify. Required.\n"
10088 " *Variable: <name>=<value> At least one variable pair must be specified.\n"
10089 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
10090
10091 static const struct _map_x_s regstatestrings[] = {
10092 { REG_STATE_FAILED, "Failed" },
10093 { REG_STATE_UNREGISTERED, "Unregistered"},
10094 { REG_STATE_REGSENT, "Request Sent"},
10095 { REG_STATE_AUTHSENT, "Auth. Sent"},
10096 { REG_STATE_REGISTERED, "Registered"},
10097 { REG_STATE_REJECTED, "Rejected"},
10098 { REG_STATE_TIMEOUT, "Timeout"},
10099 { REG_STATE_NOAUTH, "No Authentication"},
10100 { -1, NULL }
10101 };
10102
10103
10104 static const char *regstate2str(enum sipregistrystate regstate)
10105 {
10106 return map_x_s(regstatestrings, regstate, "Unknown");
10107 }
10108
10109
10110
10111
10112
10113
10114
10115 static int sip_reregister(const void *data)
10116 {
10117
10118 struct sip_registry *r= (struct sip_registry *) data;
10119
10120
10121 if (!r)
10122 return 0;
10123
10124 if (r->call && r->call->do_history)
10125 append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
10126
10127
10128 if (sipdebug)
10129 ast_log(LOG_NOTICE, " -- Re-registration for %s@%s\n", r->username, r->hostname);
10130
10131 r->expire = -1;
10132 __sip_do_register(r);
10133 registry_unref(r, "unref the re-register scheduled event");
10134 return 0;
10135 }
10136
10137
10138 static int __sip_do_register(struct sip_registry *r)
10139 {
10140 int res;
10141
10142 res = transmit_register(r, SIP_REGISTER, NULL, NULL);
10143 return res;
10144 }
10145
10146
10147
10148
10149
10150
10151
10152 static int sip_reg_timeout(const void *data)
10153 {
10154
10155
10156 struct sip_registry *r = (struct sip_registry *)data;
10157 struct sip_pvt *p;
10158 int res;
10159
10160
10161 if (!r)
10162 return 0;
10163
10164 if (r->dnsmgr) {
10165
10166 ast_dnsmgr_refresh(r->dnsmgr);
10167 }
10168
10169 ast_log(LOG_NOTICE, " -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
10170
10171
10172
10173
10174 if (r->call) {
10175
10176
10177 p = r->call;
10178 sip_pvt_lock(p);
10179 p->needdestroy = 1;
10180
10181 __sip_pretend_ack(p);
10182 sip_pvt_unlock(p);
10183
10184
10185
10186 if (p->registry)
10187 p->registry = registry_unref(p->registry, "p->registry unreffed");
10188 r->call = dialog_unref(r->call, "unrefing r->call");
10189 }
10190
10191 if (global_regattempts_max && r->regattempts > global_regattempts_max) {
10192
10193
10194
10195 ast_log(LOG_NOTICE, " -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
10196 r->regstate = REG_STATE_FAILED;
10197 } else {
10198 r->regstate = REG_STATE_UNREGISTERED;
10199 r->timeout = -1;
10200 res=transmit_register(r, SIP_REGISTER, NULL, NULL);
10201 }
10202 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));
10203 registry_unref(r, "unreffing registry_unref r");
10204 return 0;
10205 }
10206
10207
10208
10209
10210 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
10211 {
10212 struct sip_request req;
10213 char from[256];
10214 char to[256];
10215 char tmp[80];
10216 char addr[80];
10217 struct sip_pvt *p;
10218 struct sip_peer *peer;
10219 int res;
10220 char *fromdomain;
10221
10222
10223 if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
10224 if (r) {
10225 ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
10226 }
10227 return 0;
10228 }
10229
10230 if (r->dnsmgr == NULL) {
10231 char transport[MAXHOSTNAMELEN];
10232 peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE);
10233 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport));
10234 ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, global_srvlookup ? transport : NULL);
10235 if (peer) {
10236 unref_peer(peer, "removing peer ref for dnsmgr_lookup");
10237 }
10238 }
10239
10240 if (r->call) {
10241 if (!auth) {
10242 ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
10243 return 0;
10244 } else {
10245 p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
10246 make_our_tag(p->tag, sizeof(p->tag));
10247 ast_string_field_set(p, theirtag, NULL);
10248 }
10249 } else {
10250
10251 struct sip_peer *peer = NULL;
10252
10253 if (!r->callid_valid) {
10254 build_callid_registry(r, internip.sin_addr, default_fromdomain);
10255 r->callid_valid = TRUE;
10256 }
10257
10258 if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
10259 ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
10260 return 0;
10261 }
10262
10263 if (p->do_history)
10264 append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
10265
10266 if (!ast_strlen_zero(r->peername)) {
10267 if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE))) {
10268 ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
10269 }
10270 }
10271 ref_proxy(p, obproxy_get(p, peer));
10272 if (peer) {
10273 unref_peer(peer, "transmit_registration: from find_peer operation");
10274 }
10275
10276 if (!r->us.sin_port && r->portno)
10277 r->us.sin_port = htons(r->portno);
10278
10279
10280 if (create_addr(p, r->hostname, &r->us, 0)) {
10281
10282
10283 dialog_unlink_all(p, TRUE, TRUE);
10284 p = dialog_unref(p, "unref dialog after unlink_all");
10285 if (r->timeout > -1) {
10286 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10287 registry_unref(_data, "del for REPLACE of registry ptr"),
10288 registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
10289 registry_addref(r,"add for REPLACE registry ptr"));
10290 ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
10291 } else {
10292 r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
10293 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);
10294 }
10295 r->regattempts++;
10296 return 0;
10297 }
10298
10299
10300 ast_string_field_set(r, callid, p->callid);
10301 if (!r->dnsmgr && r->portno) {
10302 p->sa.sin_port = htons(r->portno);
10303 p->recv.sin_port = htons(r->portno);
10304 } else {
10305 r->portno = ntohs(p->sa.sin_port);
10306 }
10307 ast_set_flag(&p->flags[0], SIP_OUTGOING);
10308 r->call = dialog_ref(p, "copying dialog into registry r->call");
10309 p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register");
10310 if (!ast_strlen_zero(r->secret))
10311 ast_string_field_set(p, peersecret, r->secret);
10312 if (!ast_strlen_zero(r->md5secret))
10313 ast_string_field_set(p, peermd5secret, r->md5secret);
10314
10315
10316 if (!ast_strlen_zero(r->authuser)) {
10317 ast_string_field_set(p, peername, r->authuser);
10318 ast_string_field_set(p, authname, r->authuser);
10319 } else if (!ast_strlen_zero(r->username)) {
10320 ast_string_field_set(p, peername, r->username);
10321 ast_string_field_set(p, authname, r->username);
10322 ast_string_field_set(p, fromuser, r->username);
10323 }
10324 if (!ast_strlen_zero(r->username))
10325 ast_string_field_set(p, username, r->username);
10326
10327 if (!ast_strlen_zero(r->callback))
10328 ast_string_field_set(p, exten, r->callback);
10329
10330
10331 set_socket_transport(&p->socket, r->transport);
10332 if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
10333 p->socket.port = sip_tcp_desc.local_address.sin_port;
10334 }
10335
10336
10337
10338
10339
10340
10341 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10342 build_contact(p);
10343 }
10344
10345
10346 if (auth == NULL) {
10347 if (r->timeout > -1)
10348 ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
10349 AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10350 registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
10351 registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
10352 registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
10353 ast_debug(1, "Scheduled a registration timeout for %s id #%d \n", r->hostname, r->timeout);
10354 }
10355
10356 if ((fromdomain = strchr(r->username, '@'))) {
10357
10358 fromdomain++ ;
10359
10360 snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
10361 if (!ast_strlen_zero(p->theirtag))
10362 snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
10363 else
10364 snprintf(to, sizeof(to), "<sip:%s>", r->username);
10365
10366
10367
10368 if (ast_strlen_zero(p->fromdomain)) {
10369 ast_string_field_set(p, fromdomain, fromdomain);
10370 }
10371 } else {
10372 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
10373 if (!ast_strlen_zero(p->theirtag))
10374 snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
10375 else
10376 snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
10377 }
10378
10379
10380
10381 if (!ast_strlen_zero(p->fromdomain)) {
10382 if (r->portno && r->portno != STANDARD_SIP_PORT)
10383 snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
10384 else
10385 snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
10386 } else {
10387 if (r->portno && r->portno != STANDARD_SIP_PORT)
10388 snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
10389 else
10390 snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
10391 }
10392 ast_string_field_set(p, uri, addr);
10393
10394 p->branch ^= ast_random();
10395
10396 init_req(&req, sipmethod, addr);
10397
10398
10399 snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
10400 p->ocseq = r->ocseq;
10401
10402 build_via(p);
10403 add_header(&req, "Via", p->via);
10404 add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10405 add_header(&req, "From", from);
10406 add_header(&req, "To", to);
10407 add_header(&req, "Call-ID", p->callid);
10408 add_header(&req, "CSeq", tmp);
10409 if (!ast_strlen_zero(global_useragent))
10410 add_header(&req, "User-Agent", global_useragent);
10411
10412
10413 if (auth)
10414 add_header(&req, authheader, auth);
10415 else if (!ast_strlen_zero(r->nonce)) {
10416 char digest[1024];
10417
10418
10419
10420
10421
10422
10423 if (sipdebug)
10424 ast_debug(1, " >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
10425 ast_string_field_set(p, realm, r->realm);
10426 ast_string_field_set(p, nonce, r->nonce);
10427 ast_string_field_set(p, domain, r->domain);
10428 ast_string_field_set(p, opaque, r->opaque);
10429 ast_string_field_set(p, qop, r->qop);
10430 p->noncecount = ++r->noncecount;
10431
10432 memset(digest, 0, sizeof(digest));
10433 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
10434 add_header(&req, "Authorization", digest);
10435 else
10436 ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
10437
10438 }
10439
10440 snprintf(tmp, sizeof(tmp), "%d", r->expiry);
10441 add_header(&req, "Expires", tmp);
10442 add_header(&req, "Contact", p->our_contact);
10443 add_header_contentLength(&req, 0);
10444
10445 initialize_initreq(p, &req);
10446 if (sip_debug_test_pvt(p)) {
10447 ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
10448 }
10449 r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
10450 r->regattempts++;
10451 ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
10452 res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10453 dialog_unref(p, "p is finished here at the end of transmit_register");
10454 return res;
10455 }
10456
10457
10458 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
10459 {
10460 struct sip_request req;
10461
10462 reqprep(&req, p, SIP_MESSAGE, 0, 1);
10463 add_text(&req, text);
10464 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10465 }
10466
10467
10468 static int sip_refer_allocate(struct sip_pvt *p)
10469 {
10470 p->refer = ast_calloc(1, sizeof(struct sip_refer));
10471 return p->refer ? 1 : 0;
10472 }
10473
10474
10475
10476
10477
10478
10479 static int transmit_refer(struct sip_pvt *p, const char *dest)
10480 {
10481 struct sip_request req = {
10482 .headers = 0,
10483 };
10484 char from[256];
10485 const char *of;
10486 char *c;
10487 char referto[256];
10488 char *ttag, *ftag;
10489 char *theirtag = ast_strdupa(p->theirtag);
10490
10491 if (sipdebug)
10492 ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
10493
10494
10495 if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10496 of = get_header(&p->initreq, "To");
10497 ttag = theirtag;
10498 ftag = p->tag;
10499 } else {
10500 of = get_header(&p->initreq, "From");
10501 ftag = theirtag;
10502 ttag = p->tag;
10503 }
10504
10505 ast_copy_string(from, of, sizeof(from));
10506 of = get_in_brackets(from);
10507 ast_string_field_set(p, from, of);
10508 if (!strncasecmp(of, "sip:", 4))
10509 of += 4;
10510 else if (!strncasecmp(of, "sips:", 5))
10511 of += 5;
10512 else
10513 ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
10514
10515 if ((c = strchr(dest, '@')))
10516 c = NULL;
10517 else if ((c = strchr(of, '@')))
10518 *c++ = '\0';
10519 if (c)
10520 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
10521 else
10522 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
10523
10524
10525 sip_refer_allocate(p);
10526 ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
10527 ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
10528 p->refer->status = REFER_SENT;
10529
10530 reqprep(&req, p, SIP_REFER, 0, 1);
10531
10532 add_header(&req, "Refer-To", referto);
10533 add_header(&req, "Allow", ALLOWED_METHODS);
10534 add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10535 if (!ast_strlen_zero(p->our_contact))
10536 add_header(&req, "Referred-By", p->our_contact);
10537
10538 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548 }
10549
10550
10551
10552 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
10553 {
10554 struct sip_request req;
10555
10556 reqprep(&req, p, SIP_INFO, 0, 1);
10557 add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
10558 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10559 }
10560
10561
10562 static int transmit_info_with_vidupdate(struct sip_pvt *p)
10563 {
10564 struct sip_request req;
10565
10566 reqprep(&req, p, SIP_INFO, 0, 1);
10567 add_vidupdate(&req);
10568 return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10569 }
10570
10571
10572
10573
10574 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
10575 {
10576 struct sip_request resp;
10577
10578 if (sipmethod == SIP_ACK)
10579 p->invitestate = INV_CONFIRMED;
10580
10581 reqprep(&resp, p, sipmethod, seqno, newbranch);
10582 if (sipmethod == SIP_CANCEL && p->answered_elsewhere)
10583 add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
10584
10585 add_header_contentLength(&resp, 0);
10586 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
10587 }
10588
10589
10590 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
10591 {
10592 if (code == WWW_AUTH) {
10593 *header = "WWW-Authenticate";
10594 *respheader = "Authorization";
10595 } else if (code == PROXY_AUTH) {
10596 *header = "Proxy-Authenticate";
10597 *respheader = "Proxy-Authorization";
10598 } else {
10599 ast_verbose("-- wrong response code %d\n", code);
10600 *header = *respheader = "Invalid";
10601 }
10602 }
10603
10604
10605 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
10606 {
10607 struct sip_request resp;
10608
10609 reqprep(&resp, p, sipmethod, seqno, newbranch);
10610 if (!ast_strlen_zero(p->realm)) {
10611 char digest[1024];
10612
10613 memset(digest, 0, sizeof(digest));
10614 if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
10615 char *dummy, *response;
10616 enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH;
10617 auth_headers(code, &dummy, &response);
10618 add_header(&resp, response, digest);
10619 } else
10620 ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
10621 }
10622
10623
10624 if (sipmethod == SIP_BYE) {
10625 char buf[10];
10626
10627 add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
10628 snprintf(buf, sizeof(buf), "%d", p->hangupcause);
10629 add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10630 }
10631
10632 add_header_contentLength(&resp, 0);
10633 return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
10634 }
10635
10636
10637 static void destroy_association(struct sip_peer *peer)
10638 {
10639 int realtimeregs = ast_check_realtime("sipregs");
10640 char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
10641
10642 if (!sip_cfg.ignore_regexpire) {
10643 if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
10644 ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
10645 } else {
10646 ast_db_del("SIP/Registry", peer->name);
10647 }
10648 }
10649 }
10650
10651 static void set_socket_transport(struct sip_socket *socket, int transport)
10652 {
10653
10654 if (socket->type != transport) {
10655 socket->fd = -1;
10656 socket->type = transport;
10657 if (socket->tcptls_session) {
10658 ao2_ref(socket->tcptls_session, -1);
10659 socket->tcptls_session = NULL;
10660 }
10661 }
10662 }
10663
10664
10665 static int expire_register(const void *data)
10666 {
10667 struct sip_peer *peer = (struct sip_peer *)data;
10668
10669 if (!peer)
10670 return 0;
10671
10672 peer->expire = -1;
10673 memset(&peer->addr, 0, sizeof(peer->addr));
10674
10675 destroy_association(peer);
10676 set_socket_transport(&peer->socket, peer->default_outbound_transport);
10677
10678 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
10679 register_peer_exten(peer, FALSE);
10680 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
10681
10682
10683
10684
10685 if (peer->is_realtime)
10686 ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
10687
10688 if (peer->selfdestruct ||
10689 ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
10690 ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
10691 if (peer->addr.sin_addr.s_addr) {
10692 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
10693 }
10694 }
10695
10696 unref_peer(peer, "removing peer ref for expire_register");
10697
10698 return 0;
10699 }
10700
10701
10702 static int sip_poke_peer_s(const void *data)
10703 {
10704 struct sip_peer *peer = (struct sip_peer *)data;
10705
10706 peer->pokeexpire = -1;
10707
10708 sip_poke_peer(peer, 0);
10709
10710 unref_peer(peer, "removing poke peer ref");
10711
10712 return 0;
10713 }
10714
10715
10716 static void reg_source_db(struct sip_peer *peer)
10717 {
10718 char data[256];
10719 struct in_addr in;
10720 int expire;
10721 int port;
10722 char *scan, *addr, *port_str, *expiry_str, *username, *contact;
10723
10724 if (peer->rt_fromcontact)
10725 return;
10726 if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
10727 return;
10728
10729 scan = data;
10730 addr = strsep(&scan, ":");
10731 port_str = strsep(&scan, ":");
10732 expiry_str = strsep(&scan, ":");
10733 username = strsep(&scan, ":");
10734 contact = scan;
10735
10736 if (!inet_aton(addr, &in))
10737 return;
10738
10739 if (port_str)
10740 port = atoi(port_str);
10741 else
10742 return;
10743
10744 if (expiry_str)
10745 expire = atoi(expiry_str);
10746 else
10747 return;
10748
10749 if (username)
10750 ast_copy_string(peer->username, username, sizeof(peer->username));
10751 if (contact)
10752 ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
10753
10754 ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
10755 peer->name, peer->username, ast_inet_ntoa(in), port, expire);
10756
10757 memset(&peer->addr, 0, sizeof(peer->addr));
10758 peer->addr.sin_family = AF_INET;
10759 peer->addr.sin_addr = in;
10760 peer->addr.sin_port = htons(port);
10761 if (sipsock < 0) {
10762
10763 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
10764 unref_peer(_data, "removing poke peer ref"),
10765 unref_peer(peer, "removing poke peer ref"),
10766 ref_peer(peer, "adding poke peer ref"));
10767 } else {
10768 sip_poke_peer(peer, 0);
10769 }
10770 AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
10771 unref_peer(_data, "remove registration ref"),
10772 unref_peer(peer, "remove registration ref"),
10773 ref_peer(peer, "add registration ref"));
10774 register_peer_exten(peer, TRUE);
10775 }
10776
10777
10778 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
10779 {
10780 char contact[SIPBUFSIZE];
10781 char *c;
10782
10783
10784 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10785 c = get_in_brackets(contact);
10786
10787
10788 ast_string_field_set(pvt, fullcontact, c);
10789
10790
10791 ast_string_field_set(pvt, okcontacturi, c);
10792
10793
10794
10795 return TRUE;
10796 }
10797
10798 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
10799 {
10800 struct hostent *hp;
10801 struct ast_hostent ahp;
10802 int port;
10803 char *host, *pt;
10804 char contact_buf[256];
10805 char contact2_buf[256];
10806 char *contact, *contact2;
10807
10808
10809 ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
10810 ast_copy_string(contact2_buf, fullcontact, sizeof(contact2_buf));
10811 contact = contact_buf;
10812 contact2 = contact2_buf;
10813
10814
10815 if (tcp) {
10816 if (parse_uri(contact, "sips:", &contact, NULL, &host, &pt, NULL, NULL)) {
10817 if (parse_uri(contact2, "sip:", &contact, NULL, &host, &pt, NULL, NULL))
10818 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10819 }
10820 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10821 } else {
10822 if (parse_uri(contact, "sip:", &contact, NULL, &host, &pt, NULL, NULL))
10823 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", contact);
10824 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10825 }
10826
10827
10828
10829 hp = ast_gethostbyname(host, &ahp);
10830 if (!hp) {
10831 ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
10832 return -1;
10833 }
10834 sin->sin_family = AF_INET;
10835 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
10836 sin->sin_port = htons(port);
10837
10838 return 0;
10839 }
10840
10841
10842 static int set_address_from_contact(struct sip_pvt *pvt)
10843 {
10844 if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
10845
10846
10847 pvt->sa = pvt->recv;
10848 return 0;
10849 }
10850
10851 return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
10852 }
10853
10854
10855 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
10856 {
10857 char contact[SIPBUFSIZE];
10858 char data[SIPBUFSIZE];
10859 const char *expires = get_header(req, "Expires");
10860 int expire = atoi(expires);
10861 char *curi, *host, *pt, *curi2, *transport;
10862 int port;
10863 int transport_type;
10864 const char *useragent;
10865 struct hostent *hp;
10866 struct ast_hostent ahp;
10867 struct sockaddr_in oldsin, testsin;
10868
10869
10870 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
10871
10872 if (ast_strlen_zero(expires)) {
10873 char *s = strcasestr(contact, ";expires=");
10874 if (s) {
10875 expires = strsep(&s, ";");
10876 if (sscanf(expires + 9, "%30d", &expire) != 1)
10877 expire = default_expiry;
10878 } else {
10879
10880 expire = default_expiry;
10881 }
10882 }
10883
10884 copy_socket_data(&pvt->socket, &req->socket);
10885
10886
10887 curi = contact;
10888 if (strchr(contact, '<') == NULL)
10889 strsep(&curi, ";");
10890 curi = get_in_brackets(contact);
10891 curi2 = ast_strdupa(curi);
10892
10893
10894
10895
10896
10897 if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
10898
10899 if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
10900 pvt->expiry = ast_sched_when(sched, peer->expire);
10901 return PARSE_REGISTER_QUERY;
10902 } else if (!strcasecmp(curi, "*") || !expire) {
10903
10904 memset(&peer->addr, 0, sizeof(peer->addr));
10905 set_socket_transport(&peer->socket, peer->default_outbound_transport);
10906
10907 AST_SCHED_DEL_UNREF(sched, peer->expire,
10908 unref_peer(peer, "remove register expire ref"));
10909
10910 destroy_association(peer);
10911
10912 register_peer_exten(peer, FALSE);
10913 peer->fullcontact[0] = '\0';
10914 peer->useragent[0] = '\0';
10915 peer->sipoptions = 0;
10916 peer->lastms = 0;
10917 pvt->expiry = 0;
10918
10919 ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
10920
10921 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
10922 return PARSE_REGISTER_UPDATE;
10923 }
10924
10925
10926 ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
10927
10928
10929 ast_string_field_build(pvt, our_contact, "<%s>", curi);
10930
10931
10932 if (pvt->socket.type == SIP_TRANSPORT_TLS) {
10933 if (parse_uri(curi, "sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
10934 if (parse_uri(curi2, "sip:", &curi, NULL, &host, &pt, NULL, &transport))
10935 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10936 }
10937 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_TLS_PORT;
10938 } else {
10939 if (parse_uri(curi, "sip:", &curi, NULL, &host, &pt, NULL, &transport))
10940 ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
10941 port = !ast_strlen_zero(pt) ? atoi(pt) : STANDARD_SIP_PORT;
10942 }
10943
10944
10945 if ((transport_type = get_transport_str2enum(transport))) {
10946
10947
10948
10949 if (ast_strlen_zero(pt)) {
10950 port = (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
10951 }
10952 } else {
10953 transport_type = pvt->socket.type;
10954 }
10955
10956
10957
10958
10959 if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
10960 set_socket_transport(&peer->socket, transport_type);
10961 }
10962
10963 oldsin = peer->addr;
10964
10965
10966 if (peer->addr.sin_addr.s_addr) {
10967 ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
10968 }
10969
10970
10971
10972 hp = ast_gethostbyname(host, &ahp);
10973 if (!hp) {
10974 ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
10975 *peer->fullcontact = '\0';
10976 ast_string_field_set(pvt, our_contact, "");
10977 return PARSE_REGISTER_FAILED;
10978 }
10979 memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
10980 if ( ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
10981 ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
10982 ast_log(LOG_WARNING, "Host '%s' disallowed by rule\n", host);
10983 *peer->fullcontact = '\0';
10984 ast_string_field_set(pvt, our_contact, "");
10985 return PARSE_REGISTER_FAILED;
10986 }
10987
10988 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
10989 peer->addr.sin_family = AF_INET;
10990 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
10991 peer->addr.sin_port = htons(port);
10992 } else {
10993
10994
10995 peer->addr = pvt->recv;
10996 }
10997
10998
10999
11000
11001 if ((peer->socket.type == pvt->socket.type) &&
11002 (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
11003 (peer->addr.sin_port == pvt->recv.sin_port)){
11004
11005 copy_socket_data(&peer->socket, &pvt->socket);
11006 }
11007
11008
11009 ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
11010
11011
11012 peer->sipoptions = pvt->sipoptions;
11013
11014 if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
11015 ast_copy_string(peer->username, curi, sizeof(peer->username));
11016
11017 AST_SCHED_DEL_UNREF(sched, peer->expire,
11018 unref_peer(peer, "remove register expire ref"));
11019
11020 if (expire > max_expiry)
11021 expire = max_expiry;
11022 if (expire < min_expiry)
11023 expire = min_expiry;
11024 if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
11025 peer->expire = -1;
11026 } else {
11027 peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
11028 ref_peer(peer, "add registration ref"));
11029 if (peer->expire == -1) {
11030 unref_peer(peer, "remote registration ref");
11031 }
11032 }
11033 pvt->expiry = expire;
11034 snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expire, peer->username, peer->fullcontact);
11035
11036
11037
11038
11039 if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
11040 ast_db_put("SIP/Registry", peer->name, data);
11041 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
11042
11043
11044 if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
11045 ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
11046 }
11047 sip_poke_peer(peer, 0);
11048 register_peer_exten(peer, 1);
11049
11050
11051 useragent = get_header(req, "User-Agent");
11052 if (strcasecmp(useragent, peer->useragent)) {
11053 ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
11054 ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
11055 }
11056 return PARSE_REGISTER_UPDATE;
11057 }
11058
11059
11060 static void free_old_route(struct sip_route *route)
11061 {
11062 struct sip_route *next;
11063
11064 while (route) {
11065 next = route->next;
11066 ast_free(route);
11067 route = next;
11068 }
11069 }
11070
11071
11072 static void list_route(struct sip_route *route)
11073 {
11074 if (!route)
11075 ast_verbose("list_route: no route\n");
11076 else {
11077 for (;route; route = route->next)
11078 ast_verbose("list_route: hop: <%s>\n", route->hop);
11079 }
11080 }
11081
11082
11083 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
11084 {
11085 struct sip_route *thishop, *head, *tail;
11086 int start = 0;
11087 int len;
11088 const char *rr, *contact, *c;
11089
11090
11091 if (p->route && p->route_persistant) {
11092 ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
11093 return;
11094 }
11095
11096 if (p->route) {
11097 free_old_route(p->route);
11098 p->route = NULL;
11099 }
11100
11101
11102 p->route_persistant = 1;
11103
11104
11105
11106
11107
11108
11109 head = NULL;
11110 tail = head;
11111
11112 for (;;) {
11113
11114 rr = __get_header(req, "Record-Route", &start);
11115 if (*rr == '\0')
11116 break;
11117 for (; (rr = strchr(rr, '<')) ; rr += len) {
11118 ++rr;
11119 len = strcspn(rr, ">") + 1;
11120
11121 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11122
11123 ast_copy_string(thishop->hop, rr, len);
11124 ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
11125
11126 if (backwards) {
11127
11128 thishop->next = head;
11129 head = thishop;
11130
11131 if (!tail)
11132 tail = thishop;
11133 } else {
11134 thishop->next = NULL;
11135
11136 if (tail)
11137 tail->next = thishop;
11138 else
11139 head = thishop;
11140 tail = thishop;
11141 }
11142 }
11143 }
11144 }
11145
11146
11147 if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
11148
11149
11150 contact = get_header(req, "Contact");
11151 if (!ast_strlen_zero(contact)) {
11152 ast_debug(2, "build_route: Contact hop: %s\n", contact);
11153
11154 c = strchr(contact, '<');
11155 if (c) {
11156
11157 ++c;
11158 len = strcspn(c, ">") + 1;
11159 } else {
11160
11161 c = contact;
11162 len = strlen(contact) + 1;
11163 }
11164 if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11165
11166 ast_copy_string(thishop->hop, c, len);
11167 thishop->next = NULL;
11168
11169 if (tail)
11170 tail->next = thishop;
11171 else
11172 head = thishop;
11173 }
11174 }
11175 }
11176
11177
11178 p->route = head;
11179
11180
11181 if (sip_debug_test_pvt(p))
11182 list_route(p->route);
11183 }
11184
11185
11186
11187
11188
11189
11190
11191 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
11192 {
11193 if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
11194 ast_string_field_build(p, randdata, "%08lx", ast_random());
11195 p->stalenonce = 0;
11196 }
11197 }
11198
11199 AST_THREADSTORAGE(check_auth_buf);
11200 #define CHECK_AUTH_BUF_INITLEN 256
11201
11202
11203
11204
11205
11206
11207 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
11208 const char *secret, const char *md5secret, int sipmethod,
11209 char *uri, enum xmittype reliable, int ignore)
11210 {
11211 const char *response;
11212 char *reqheader, *respheader;
11213 const char *authtoken;
11214 char a1_hash[256];
11215 char resp_hash[256]="";
11216 char *c;
11217 int wrongnonce = FALSE;
11218 int good_response;
11219 const char *usednonce = p->randdata;
11220 struct ast_str *buf;
11221 int res;
11222
11223
11224 enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
11225 struct x {
11226 const char *key;
11227 const char *s;
11228 } *i, keys[] = {
11229 [K_RESP] = { "response=", "" },
11230 [K_URI] = { "uri=", "" },
11231 [K_USER] = { "username=", "" },
11232 [K_NONCE] = { "nonce=", "" },
11233 [K_LAST] = { NULL, NULL}
11234 };
11235
11236
11237 if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
11238 return AUTH_SUCCESSFUL;
11239
11240
11241
11242 response = "401 Unauthorized";
11243
11244
11245
11246
11247
11248 auth_headers(WWW_AUTH, &respheader, &reqheader);
11249
11250 authtoken = get_header(req, reqheader);
11251 if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
11252
11253
11254 if (!reliable) {
11255
11256
11257 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11258
11259 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11260 }
11261 return AUTH_CHALLENGE_SENT;
11262 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
11263
11264 set_nonce_randdata(p, 1);
11265 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11266
11267 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11268 return AUTH_CHALLENGE_SENT;
11269 }
11270
11271
11272
11273
11274
11275
11276 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
11277 return AUTH_SECRET_FAILED;
11278
11279
11280 res = ast_str_set(&buf, 0, "%s", authtoken);
11281
11282 if (res == AST_DYNSTR_BUILD_FAILED)
11283 return AUTH_SECRET_FAILED;
11284
11285 c = buf->str;
11286
11287 while(c && *(c = ast_skip_blanks(c)) ) {
11288 for (i = keys; i->key != NULL; i++) {
11289 const char *separator = ",";
11290
11291 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11292 continue;
11293
11294 c += strlen(i->key);
11295 if (*c == '"') {
11296 c++;
11297 separator = "\"";
11298 }
11299 i->s = c;
11300 strsep(&c, separator);
11301 break;
11302 }
11303 if (i->key == NULL)
11304 strsep(&c, " ,");
11305 }
11306
11307
11308 if (strcmp(username, keys[K_USER].s)) {
11309 ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
11310 username, keys[K_USER].s);
11311
11312 return AUTH_USERNAME_MISMATCH;
11313 }
11314
11315
11316
11317 if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) {
11318 wrongnonce = TRUE;
11319 usednonce = keys[K_NONCE].s;
11320 } else {
11321 p->stalenonce = 1;
11322 }
11323
11324 if (!ast_strlen_zero(md5secret))
11325 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11326 else {
11327 char a1[256];
11328 snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
11329 ast_md5_hash(a1_hash, a1);
11330 }
11331
11332
11333 {
11334 char a2[256];
11335 char a2_hash[256];
11336 char resp[256];
11337
11338 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
11339 S_OR(keys[K_URI].s, uri));
11340 ast_md5_hash(a2_hash, a2);
11341 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
11342 ast_md5_hash(resp_hash, resp);
11343 }
11344
11345 good_response = keys[K_RESP].s &&
11346 !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
11347 if (wrongnonce) {
11348 if (good_response) {
11349 if (sipdebug)
11350 ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
11351
11352 set_nonce_randdata(p, 0);
11353 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
11354 } else {
11355
11356 if (!req->ignore) {
11357 if (sipdebug)
11358 ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
11359 set_nonce_randdata(p, 1);
11360 } else {
11361 if (sipdebug)
11362 ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
11363 }
11364 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
11365 }
11366
11367
11368 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11369 return AUTH_CHALLENGE_SENT;
11370 }
11371 if (good_response) {
11372 append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
11373 return AUTH_SUCCESSFUL;
11374 }
11375
11376
11377
11378
11379
11380
11381 return AUTH_SECRET_FAILED;
11382 }
11383
11384
11385 static void sip_peer_hold(struct sip_pvt *p, int hold)
11386 {
11387 struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE);
11388
11389 if (!peer)
11390 return;
11391
11392
11393 ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
11394
11395
11396 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11397 unref_peer(peer, "sip_peer_hold: from find_peer operation");
11398
11399 return;
11400 }
11401
11402
11403 static void mwi_event_cb(const struct ast_event *event, void *userdata)
11404 {
11405 struct sip_peer *peer = userdata;
11406
11407 ao2_lock(peer);
11408 sip_send_mwi_to_peer(peer, event, 0);
11409 ao2_unlock(peer);
11410 }
11411
11412
11413
11414
11415 static int cb_extensionstate(char *context, char* exten, int state, void *data)
11416 {
11417 struct sip_pvt *p = data;
11418
11419 sip_pvt_lock(p);
11420
11421 switch(state) {
11422 case AST_EXTENSION_DEACTIVATED:
11423 case AST_EXTENSION_REMOVED:
11424 if (p->autokillid > -1 && sip_cancel_destroy(p))
11425 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
11426 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11427 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
11428 p->stateid = -1;
11429 p->subscribed = NONE;
11430 append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
11431 break;
11432 default:
11433 p->laststate = state;
11434 break;
11435 }
11436 if (p->subscribed != NONE) {
11437 if (!p->pendinginvite) {
11438 transmit_state_notify(p, state, 1, FALSE);
11439 } else {
11440
11441
11442 ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
11443 }
11444 }
11445 ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
11446 ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
11447
11448 sip_pvt_unlock(p);
11449
11450 return 0;
11451 }
11452
11453
11454
11455
11456 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
11457 {
11458
11459
11460 const char *response = "407 Proxy Authentication Required";
11461 const char *reqheader = "Proxy-Authorization";
11462 const char *respheader = "Proxy-Authenticate";
11463 const char *authtoken;
11464 struct ast_str *buf;
11465 char *c;
11466
11467
11468 enum keys { K_NONCE, K_LAST };
11469 struct x {
11470 const char *key;
11471 const char *s;
11472 } *i, keys[] = {
11473 [K_NONCE] = { "nonce=", "" },
11474 [K_LAST] = { NULL, NULL}
11475 };
11476
11477 if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
11478 response = "401 Unauthorized";
11479 reqheader = "Authorization";
11480 respheader = "WWW-Authenticate";
11481 }
11482 authtoken = get_header(req, reqheader);
11483 if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
11484
11485
11486 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
11487
11488 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11489 return;
11490 } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
11491
11492 set_nonce_randdata(p, 1);
11493 transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
11494
11495 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11496 return;
11497 }
11498
11499 if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
11500 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11501 return;
11502 }
11503
11504
11505 if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
11506 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11507 return;
11508 }
11509
11510 c = buf->str;
11511
11512 while (c && *(c = ast_skip_blanks(c))) {
11513 for (i = keys; i->key != NULL; i++) {
11514 const char *separator = ",";
11515
11516 if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
11517 continue;
11518 }
11519
11520 c += strlen(i->key);
11521 if (*c == '"') {
11522 c++;
11523 separator = "\"";
11524 }
11525 i->s = c;
11526 strsep(&c, separator);
11527 break;
11528 }
11529 if (i->key == NULL) {
11530 strsep(&c, " ,");
11531 }
11532 }
11533
11534
11535 if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
11536 if (!req->ignore) {
11537 set_nonce_randdata(p, 1);
11538 }
11539 transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
11540
11541
11542 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11543 } else {
11544 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11545 }
11546 }
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559 static char *terminate_uri(char *uri)
11560 {
11561 char *t = uri;
11562 while (*t && *t > ' ' && *t != ';')
11563 t++;
11564 *t = '\0';
11565 return uri;
11566 }
11567
11568
11569
11570
11571
11572
11573 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
11574 struct sip_request *req, char *uri)
11575 {
11576 enum check_auth_result res = AUTH_NOT_FOUND;
11577 struct sip_peer *peer;
11578 char tmp[256];
11579 char *name, *c;
11580 char *domain;
11581
11582 terminate_uri(uri);
11583
11584 ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
11585 if (pedanticsipchecking)
11586 ast_uri_decode(tmp);
11587
11588 c = get_in_brackets(tmp);
11589 c = remove_uri_parameters(c);
11590
11591 if (!strncasecmp(c, "sip:", 4)) {
11592 name = c + 4;
11593 } else if (!strncasecmp(c, "sips:", 5)) {
11594 name = c + 5;
11595 } else {
11596 name = c;
11597 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
11598 }
11599
11600
11601
11602
11603
11604 if ((c = strchr(name, '@'))) {
11605 *c++ = '\0';
11606 domain = c;
11607 if ((c = strchr(domain, ':')))
11608 *c = '\0';
11609 if (!AST_LIST_EMPTY(&domain_list)) {
11610 if (!check_sip_domain(domain, NULL, 0)) {
11611 transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
11612 return AUTH_UNKNOWN_DOMAIN;
11613 }
11614 }
11615 }
11616 c = strchr(name, ';');
11617 if (c)
11618 *c = '\0';
11619
11620 ast_string_field_set(p, exten, name);
11621 build_contact(p);
11622 peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE);
11623 if (!(peer && ast_apply_ha(peer->ha, sin))) {
11624
11625 if (peer) {
11626 unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
11627 peer = NULL;
11628 res = AUTH_ACL_FAILED;
11629 } else
11630 res = AUTH_NOT_FOUND;
11631 }
11632
11633 if (peer) {
11634
11635 if (p->rtp) {
11636 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
11637 p->autoframing = peer->autoframing;
11638 }
11639 if (!peer->host_dynamic) {
11640 ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
11641 res = AUTH_PEER_NOT_DYNAMIC;
11642 } else {
11643 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
11644 if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
11645 transmit_response(p, "100 Trying", req);
11646 if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
11647 if (sip_cancel_destroy(p))
11648 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
11649
11650 if (check_request_transport(peer, req)) {
11651 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
11652 transmit_response_with_date(p, "403 Forbidden", req);
11653 res = AUTH_BAD_TRANSPORT;
11654 } else {
11655
11656
11657
11658 switch (parse_register_contact(p, peer, req)) {
11659 case PARSE_REGISTER_FAILED:
11660 ast_log(LOG_WARNING, "Failed to parse contact info\n");
11661 transmit_response_with_date(p, "400 Bad Request", req);
11662 peer->lastmsgssent = -1;
11663 res = 0;
11664 break;
11665 case PARSE_REGISTER_QUERY:
11666 transmit_response_with_date(p, "200 OK", req);
11667 peer->lastmsgssent = -1;
11668 res = 0;
11669 break;
11670 case PARSE_REGISTER_UPDATE:
11671 update_peer(peer, p->expiry);
11672
11673 transmit_response_with_date(p, "200 OK", req);
11674 if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
11675 peer->lastmsgssent = -1;
11676 res = 0;
11677 break;
11678 }
11679 }
11680
11681 }
11682 }
11683 }
11684 if (!peer && autocreatepeer) {
11685
11686 peer = temp_peer(name);
11687 if (peer) {
11688 ao2_t_link(peers, peer, "link peer into peer table");
11689 if (peer->addr.sin_addr.s_addr) {
11690 ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
11691 }
11692
11693 if (sip_cancel_destroy(p))
11694 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
11695 switch (parse_register_contact(p, peer, req)) {
11696 case PARSE_REGISTER_FAILED:
11697 ast_log(LOG_WARNING, "Failed to parse contact info\n");
11698 transmit_response_with_date(p, "400 Bad Request", req);
11699 peer->lastmsgssent = -1;
11700 res = 0;
11701 break;
11702 case PARSE_REGISTER_QUERY:
11703 transmit_response_with_date(p, "200 OK", req);
11704 peer->lastmsgssent = -1;
11705 res = 0;
11706 break;
11707 case PARSE_REGISTER_UPDATE:
11708
11709 transmit_response_with_date(p, "200 OK", req);
11710 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11711 peer->lastmsgssent = -1;
11712 res = 0;
11713 break;
11714 }
11715 }
11716 }
11717 if (!peer && global_alwaysauthreject) {
11718
11719
11720
11721 transmit_response(p, "100 Trying", req);
11722
11723 sched_yield();
11724 }
11725 if (!res) {
11726 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11727 }
11728 if (res < 0) {
11729 switch (res) {
11730 case AUTH_SECRET_FAILED:
11731
11732 transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
11733 if (global_authfailureevents)
11734 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_SECRET_FAILED\r\nAddress: %s\r\nPort: %d\r\n",
11735 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11736 break;
11737 case AUTH_USERNAME_MISMATCH:
11738
11739
11740
11741
11742 case AUTH_NOT_FOUND:
11743 case AUTH_PEER_NOT_DYNAMIC:
11744 case AUTH_ACL_FAILED:
11745 if (global_alwaysauthreject) {
11746 transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
11747 } else {
11748
11749 if (res == AUTH_PEER_NOT_DYNAMIC) {
11750 transmit_response(p, "403 Forbidden", &p->initreq);
11751 if (global_authfailureevents)
11752 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_PEER_NOT_DYNAMIC\r\nAddress: %s\r\nPort: %d\r\n",
11753 name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11754 }
11755 else
11756 transmit_response(p, "404 Not found", &p->initreq);
11757 if (global_authfailureevents)
11758 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: %s\r\nAddress: %s\r\nPort: %d\r\n",
11759 (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND", name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
11760 }
11761 break;
11762 case AUTH_BAD_TRANSPORT:
11763 default:
11764 break;
11765 }
11766 }
11767 if (peer)
11768 unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
11769
11770 return res;
11771 }
11772
11773
11774 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
11775
11776 if (!strcmp(reason, "unknown")) {
11777 ast_string_field_set(p, redircause, "UNKNOWN");
11778 } else if (!strcmp(reason, "user-busy")) {
11779 ast_string_field_set(p, redircause, "BUSY");
11780 } else if (!strcmp(reason, "no-answer")) {
11781 ast_string_field_set(p, redircause, "NOANSWER");
11782 } else if (!strcmp(reason, "unavailable")) {
11783 ast_string_field_set(p, redircause, "UNREACHABLE");
11784 } else if (!strcmp(reason, "unconditional")) {
11785 ast_string_field_set(p, redircause, "UNCONDITIONAL");
11786 } else if (!strcmp(reason, "time-of-day")) {
11787 ast_string_field_set(p, redircause, "UNKNOWN");
11788 } else if (!strcmp(reason, "do-not-disturb")) {
11789 ast_string_field_set(p, redircause, "UNKNOWN");
11790 } else if (!strcmp(reason, "deflection")) {
11791 ast_string_field_set(p, redircause, "UNKNOWN");
11792 } else if (!strcmp(reason, "follow-me")) {
11793 ast_string_field_set(p, redircause, "UNKNOWN");
11794 } else if (!strcmp(reason, "out-of-service")) {
11795 ast_string_field_set(p, redircause, "UNREACHABLE");
11796 } else if (!strcmp(reason, "away")) {
11797 ast_string_field_set(p, redircause, "UNREACHABLE");
11798 } else {
11799 ast_string_field_set(p, redircause, "UNKNOWN");
11800 }
11801 }
11802
11803
11804 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
11805 {
11806 char tmp[256], *exten, *rexten, *rdomain;
11807 char *params, *reason = NULL;
11808 struct sip_request *req;
11809
11810 req = oreq ? oreq : &p->initreq;
11811
11812 ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
11813 if (ast_strlen_zero(tmp))
11814 return 0;
11815
11816 params = strchr(tmp, ';');
11817
11818 exten = get_in_brackets(tmp);
11819 if (!strncasecmp(exten, "sip:", 4)) {
11820 exten += 4;
11821 } else if (!strncasecmp(exten, "sips:", 5)) {
11822 exten += 5;
11823 } else {
11824 ast_log(LOG_WARNING, "Huh? Not an RDNIS SIP header (%s)?\n", exten);
11825 return -1;
11826 }
11827
11828
11829 if (params) {
11830 *params = '\0';
11831 params++;
11832 while (*params == ';' || *params == ' ')
11833 params++;
11834
11835 if ((reason = strcasestr(params, "reason="))) {
11836 reason+=7;
11837
11838 if (*reason == '"')
11839 ast_strip_quoted(reason, "\"", "\"");
11840 if (!ast_strlen_zero(reason)) {
11841 sip_set_redirstr(p, reason);
11842 if (p->owner) {
11843 pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
11844 pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
11845 }
11846 }
11847 }
11848 }
11849
11850 rdomain = exten;
11851 rexten = strsep(&rdomain, "@");
11852 if (p->owner)
11853 pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
11854
11855 if (sip_debug_test_pvt(p))
11856 ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
11857
11858 ast_string_field_set(p, rdnis, rexten);
11859
11860 return 0;
11861 }
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
11872 {
11873 char tmp[256] = "", *uri, *a;
11874 char tmpf[256] = "", *from = NULL;
11875 struct sip_request *req;
11876 char *colon;
11877 char *decoded_uri;
11878
11879 req = oreq;
11880 if (!req)
11881 req = &p->initreq;
11882
11883
11884 if (req->rlPart2)
11885 ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
11886
11887 if (pedanticsipchecking)
11888 ast_uri_decode(tmp);
11889
11890 uri = get_in_brackets(tmp);
11891
11892 if (!strncasecmp(uri, "sip:", 4)) {
11893 uri += 4;
11894 } else if (!strncasecmp(uri, "sips:", 5)) {
11895 uri += 5;
11896 } else {
11897 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", uri);
11898 return -1;
11899 }
11900
11901
11902
11903
11904
11905 ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
11906 if (!ast_strlen_zero(tmpf)) {
11907 if (pedanticsipchecking)
11908 ast_uri_decode(tmpf);
11909 from = get_in_brackets(tmpf);
11910 }
11911
11912 if (!ast_strlen_zero(from)) {
11913 if (!strncasecmp(from, "sip:", 4)) {
11914 from += 4;
11915 } else if (!strncasecmp(from, "sips:", 5)) {
11916 from += 5;
11917 } else {
11918 ast_log(LOG_WARNING, "Huh? Not a SIP header (%s)?\n", from);
11919 return -1;
11920 }
11921 if ((a = strchr(from, '@')))
11922 *a++ = '\0';
11923 else
11924 a = from;
11925 from = strsep(&from, ";");
11926 a = strsep(&a, ";");
11927 ast_string_field_set(p, fromdomain, a);
11928 }
11929
11930
11931
11932
11933 if ((a = strchr(uri, '@'))) {
11934 *a++ = '\0';
11935 } else {
11936 a = uri;
11937 uri = "s";
11938 }
11939 colon = strchr(a, ':');
11940 if (colon)
11941 *colon = '\0';
11942
11943 uri = strsep(&uri, ";");
11944 a = strsep(&a, ";");
11945
11946 ast_string_field_set(p, domain, a);
11947
11948 if (!AST_LIST_EMPTY(&domain_list)) {
11949 char domain_context[AST_MAX_EXTENSION];
11950
11951 domain_context[0] = '\0';
11952 if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
11953 if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
11954 ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
11955 return -2;
11956 }
11957 }
11958
11959 if (!ast_strlen_zero(domain_context))
11960 ast_string_field_set(p, context, domain_context);
11961 }
11962
11963
11964 if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
11965 ast_string_field_set(p, context, p->subscribecontext);
11966
11967 if (sip_debug_test_pvt(p))
11968 ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
11969
11970
11971 if (req->method == SIP_SUBSCRIBE) {
11972 char hint[AST_MAX_EXTENSION];
11973 return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
11974 } else {
11975 decoded_uri = ast_strdupa(uri);
11976 ast_uri_decode(decoded_uri);
11977
11978
11979
11980
11981
11982 if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
11983 !strcmp(decoded_uri, ast_pickup_ext())) {
11984 if (!oreq)
11985 ast_string_field_set(p, exten, decoded_uri);
11986 return 0;
11987 }
11988 }
11989
11990
11991 if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) &&
11992 ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
11993 !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
11994 return 1;
11995 }
11996
11997 return -1;
11998 }
11999
12000
12001
12002
12003 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
12004 {
12005 struct sip_pvt *sip_pvt_ptr;
12006 struct sip_pvt tmp_dialog = {
12007 .callid = callid,
12008 };
12009
12010 if (totag)
12011 ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
12012
12013
12014
12015 sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
12016 if (sip_pvt_ptr) {
12017
12018 sip_pvt_lock(sip_pvt_ptr);
12019 if (pedanticsipchecking) {
12020 unsigned char frommismatch = 0, tomismatch = 0;
12021
12022 if (ast_strlen_zero(fromtag)) {
12023 sip_pvt_unlock(sip_pvt_ptr);
12024 ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
12025 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12026 return NULL;
12027 }
12028
12029 if (ast_strlen_zero(totag)) {
12030 sip_pvt_unlock(sip_pvt_ptr);
12031 ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
12032 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12033 return NULL;
12034 }
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049 frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
12050 tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
12051 if (frommismatch || tomismatch) {
12052 sip_pvt_unlock(sip_pvt_ptr);
12053 if (frommismatch) {
12054 ast_debug(4, "Matched %s call for callid=%s - But the pedantic check rejected the match; their tag is %s Our tag is %s\n",
12055 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
12056 fromtag, sip_pvt_ptr->theirtag);
12057 }
12058 if (tomismatch) {
12059 ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
12060 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
12061 totag, sip_pvt_ptr->tag);
12062 }
12063 return NULL;
12064 }
12065 }
12066
12067 if (totag)
12068 ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
12069 sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
12070 sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
12071
12072
12073 while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
12074 sip_pvt_unlock(sip_pvt_ptr);
12075 usleep(1);
12076 sip_pvt_lock(sip_pvt_ptr);
12077 }
12078 }
12079
12080 return sip_pvt_ptr;
12081 }
12082
12083
12084
12085 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
12086 {
12087
12088 const char *p_referred_by = NULL;
12089 char *h_refer_to = NULL;
12090 char *h_referred_by = NULL;
12091 char *refer_to;
12092 const char *p_refer_to;
12093 char *referred_by_uri = NULL;
12094 char *ptr;
12095 struct sip_request *req = NULL;
12096 const char *transfer_context = NULL;
12097 struct sip_refer *referdata;
12098
12099
12100 req = outgoing_req;
12101 referdata = transferer->refer;
12102
12103 if (!req)
12104 req = &transferer->initreq;
12105
12106 p_refer_to = get_header(req, "Refer-To");
12107 if (ast_strlen_zero(p_refer_to)) {
12108 ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
12109 return -2;
12110 }
12111 h_refer_to = ast_strdupa(p_refer_to);
12112 refer_to = get_in_brackets(h_refer_to);
12113 if (pedanticsipchecking)
12114 ast_uri_decode(refer_to);
12115
12116 if (!strncasecmp(refer_to, "sip:", 4)) {
12117 refer_to += 4;
12118 } else if (!strncasecmp(refer_to, "sips:", 5)) {
12119 refer_to += 5;
12120 } else {
12121 ast_log(LOG_WARNING, "Can't transfer to non-sip: URI. (Refer-to: %s)?\n", refer_to);
12122 return -3;
12123 }
12124
12125
12126 p_referred_by = get_header(req, "Referred-By");
12127
12128
12129 if (transferer->owner) {
12130 struct ast_channel *peer = ast_bridged_channel(transferer->owner);
12131 if (peer) {
12132 pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
12133 pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
12134 }
12135 }
12136
12137 if (!ast_strlen_zero(p_referred_by)) {
12138 char *lessthan;
12139 h_referred_by = ast_strdupa(p_referred_by);
12140 if (pedanticsipchecking)
12141 ast_uri_decode(h_referred_by);
12142
12143
12144 ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
12145 if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
12146 *(lessthan - 1) = '\0';
12147 }
12148
12149 referred_by_uri = get_in_brackets(h_referred_by);
12150 if (!strncasecmp(referred_by_uri, "sip:", 4)) {
12151 referred_by_uri += 4;
12152 } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
12153 referred_by_uri += 5;
12154 } else {
12155 ast_log(LOG_WARNING, "Huh? Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
12156 referred_by_uri = NULL;
12157 }
12158 }
12159
12160
12161 if ((ptr = strcasestr(refer_to, "replaces="))) {
12162 char *to = NULL, *from = NULL;
12163
12164
12165 referdata->attendedtransfer = 1;
12166 ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
12167 ast_uri_decode(referdata->replaces_callid);
12168 if ((ptr = strchr(referdata->replaces_callid, ';'))) {
12169 *ptr++ = '\0';
12170 }
12171
12172 if (ptr) {
12173
12174 to = strcasestr(ptr, "to-tag=");
12175 from = strcasestr(ptr, "from-tag=");
12176 }
12177
12178
12179 if (to) {
12180 ptr = to + 7;
12181 if ((to = strchr(ptr, '&')))
12182 *to = '\0';
12183 if ((to = strchr(ptr, ';')))
12184 *to = '\0';
12185 ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
12186 }
12187
12188 if (from) {
12189 ptr = from + 9;
12190 if ((to = strchr(ptr, '&')))
12191 *to = '\0';
12192 if ((to = strchr(ptr, ';')))
12193 *to = '\0';
12194 ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
12195 }
12196
12197 if (!pedanticsipchecking)
12198 ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
12199 else
12200 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>" );
12201 }
12202
12203 if ((ptr = strchr(refer_to, '@'))) {
12204 char *urioption = NULL, *domain;
12205 *ptr++ = '\0';
12206
12207 if ((urioption = strchr(ptr, ';')))
12208 *urioption++ = '\0';
12209
12210 domain = ptr;
12211 if ((ptr = strchr(domain, ':')))
12212 *ptr = '\0';
12213
12214
12215 ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
12216 if (urioption)
12217 ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
12218 }
12219
12220 if ((ptr = strchr(refer_to, ';')))
12221 *ptr = '\0';
12222 ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
12223
12224 if (referred_by_uri) {
12225 if ((ptr = strchr(referred_by_uri, ';')))
12226 *ptr = '\0';
12227 ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
12228 } else {
12229 referdata->referred_by[0] = '\0';
12230 }
12231
12232
12233 if (transferer->owner)
12234 transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
12235
12236
12237 if (ast_strlen_zero(transfer_context)) {
12238 transfer_context = S_OR(transferer->owner->macrocontext,
12239 S_OR(transferer->context, default_context));
12240 }
12241
12242 ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
12243
12244
12245 if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
12246 if (sip_debug_test_pvt(transferer)) {
12247 ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
12248 }
12249
12250 return 0;
12251 }
12252 if (sip_debug_test_pvt(transferer))
12253 ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
12254
12255
12256 return -1;
12257 }
12258
12259
12260
12261 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
12262 {
12263 char tmp[256] = "", *c, *a;
12264 struct sip_request *req = oreq ? oreq : &p->initreq;
12265 struct sip_refer *referdata = NULL;
12266 const char *transfer_context = NULL;
12267
12268 if (!p->refer && !sip_refer_allocate(p))
12269 return -1;
12270
12271 referdata = p->refer;
12272
12273 ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
12274 c = get_in_brackets(tmp);
12275
12276 if (pedanticsipchecking)
12277 ast_uri_decode(c);
12278
12279 if (!strncasecmp(c, "sip:", 4)) {
12280 c += 4;
12281 } else if (!strncasecmp(c, "sips:", 5)) {
12282 c += 5;
12283 } else {
12284 ast_log(LOG_WARNING, "Huh? Not a SIP header in Also: transfer (%s)?\n", c);
12285 return -1;
12286 }
12287
12288 if ((a = strchr(c, ';')))
12289 *a = '\0';
12290
12291 if ((a = strchr(c, '@'))) {
12292 *a++ = '\0';
12293 ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
12294 }
12295
12296 if (sip_debug_test_pvt(p))
12297 ast_verbose("Looking for %s in %s\n", c, p->context);
12298
12299 if (p->owner)
12300 transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
12301
12302
12303 if (ast_strlen_zero(transfer_context)) {
12304 transfer_context = S_OR(p->owner->macrocontext,
12305 S_OR(p->context, default_context));
12306 }
12307 if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
12308
12309 ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
12310 ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
12311 ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
12312 ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
12313 referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
12314
12315 ast_string_field_set(p, context, transfer_context);
12316 return 0;
12317 } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
12318 return 1;
12319 }
12320
12321 return -1;
12322 }
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
12335 {
12336 char via[256];
12337 char *cur, *opts;
12338
12339 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12340
12341
12342 opts = strchr(via, ',');
12343 if (opts)
12344 *opts = '\0';
12345
12346
12347 opts = strchr(via, ';');
12348 if (!opts)
12349 return;
12350 *opts++ = '\0';
12351 while ( (cur = strsep(&opts, ";")) ) {
12352 if (!strncmp(cur, "rport=", 6)) {
12353 int port = strtol(cur+6, NULL, 10);
12354
12355 p->ourip.sin_port = ntohs(port);
12356 } else if (!strncmp(cur, "received=", 9)) {
12357 if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
12358 ;
12359 }
12360 }
12361 }
12362
12363
12364 static void check_via(struct sip_pvt *p, struct sip_request *req)
12365 {
12366 char via[512];
12367 char *c, *pt;
12368 struct hostent *hp;
12369 struct ast_hostent ahp;
12370
12371 ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12372
12373
12374 c = strchr(via, ',');
12375 if (c)
12376 *c = '\0';
12377
12378
12379 c = strstr(via, ";rport");
12380 if (c && (c[6] != '='))
12381 ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
12382
12383 c = strchr(via, ';');
12384 if (c)
12385 *c = '\0';
12386
12387 c = strchr(via, ' ');
12388 if (c) {
12389 *c = '\0';
12390 c = ast_skip_blanks(c+1);
12391 if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
12392 ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
12393 return;
12394 }
12395 pt = strchr(c, ':');
12396 if (pt)
12397 *pt++ = '\0';
12398 hp = ast_gethostbyname(c, &ahp);
12399 if (!hp) {
12400 ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
12401 return;
12402 }
12403 memset(&p->sa, 0, sizeof(p->sa));
12404 p->sa.sin_family = AF_INET;
12405 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
12406 p->sa.sin_port = htons(pt ? atoi(pt) : STANDARD_SIP_PORT);
12407
12408 if (sip_debug_test_pvt(p)) {
12409 const struct sockaddr_in *dst = sip_real_dst(p);
12410 ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
12411 }
12412 }
12413 }
12414
12415
12416 static char *get_calleridname(const char *input, char *output, size_t outputsize)
12417 {
12418 const char *end = strchr(input, '<');
12419 const char *tmp = strchr(input, '"');
12420 int bytes = 0;
12421 int maxbytes = outputsize - 1;
12422
12423 if (!end || end == input)
12424 return NULL;
12425
12426 end--;
12427
12428 if (tmp && tmp <= end) {
12429
12430
12431
12432 end = strchr(tmp+1, '"');
12433 if (!end)
12434 return NULL;
12435 bytes = (int) (end - tmp);
12436
12437 if (bytes > maxbytes)
12438 bytes = maxbytes;
12439 ast_copy_string(output, tmp + 1, bytes);
12440 } else {
12441
12442
12443 input = ast_skip_blanks(input);
12444
12445 while(*end && *end < 33 && end > input)
12446 end--;
12447 if (end >= input) {
12448 bytes = (int) (end - input) + 2;
12449
12450 if (bytes > maxbytes)
12451 bytes = maxbytes;
12452 ast_copy_string(output, input, bytes);
12453 } else
12454 return NULL;
12455 }
12456 return output;
12457 }
12458
12459
12460
12461
12462
12463 static int get_rpid_num(const char *input, char *output, int maxlen)
12464 {
12465 char *start;
12466 char *end;
12467
12468 start = strchr(input, ':');
12469 if (!start) {
12470 output[0] = '\0';
12471 return 0;
12472 }
12473 start++;
12474
12475
12476 ast_copy_string(output, start, maxlen);
12477 output[maxlen-1] = '\0';
12478
12479 end = strchr(output, '@');
12480 if (end)
12481 *end = '\0';
12482 else
12483 output[0] = '\0';
12484 if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
12485 return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
12486
12487 return 0;
12488 }
12489
12490
12491
12492
12493 static struct ast_variable *copy_vars(struct ast_variable *src)
12494 {
12495 struct ast_variable *res = NULL, *tmp, *v = NULL;
12496
12497 for (v = src ; v ; v = v->next) {
12498 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
12499 tmp->next = res;
12500 res = tmp;
12501 }
12502 }
12503 return res;
12504 }
12505
12506
12507 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
12508 {
12509
12510 if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
12511 char *tmp = ast_strdupa(rpid_num);
12512 if (!ast_strlen_zero(calleridname))
12513 ast_string_field_set(p, cid_name, calleridname);
12514 if (ast_is_shrinkable_phonenumber(tmp))
12515 ast_shrink_phone_number(tmp);
12516 ast_string_field_set(p, cid_num, tmp);
12517 }
12518 }
12519
12520
12521 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
12522 struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
12523 struct sip_peer **authpeer,
12524 enum xmittype reliable,
12525 char *rpid_num, char *calleridname, char *uri2)
12526 {
12527 enum check_auth_result res;
12528 int debug=sip_debug_test_addr(sin);
12529 struct sip_peer *peer;
12530
12531 if (sipmethod == SIP_SUBSCRIBE) {
12532
12533
12534
12535 peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE);
12536 } else {
12537
12538 peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE);
12539
12540
12541 if (!peer) {
12542 peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE);
12543 }
12544
12545
12546
12547
12548
12549
12550 if (!peer && (p->socket.type != SIP_TRANSPORT_UDP)) {
12551 struct sockaddr_in tmpsin;
12552 char contact[SIPBUFSIZE];
12553 char *tmp;
12554 memcpy(&tmpsin, &p->recv, sizeof(tmpsin));
12555 ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12556 tmp = get_in_brackets(contact);
12557 __set_address_from_contact(tmp, &tmpsin, 1);
12558 peer = find_peer(NULL, &tmpsin, TRUE, FINDPEERS, FALSE);
12559 }
12560 }
12561
12562 if (!peer) {
12563 if (debug)
12564 ast_verbose("No matching peer for '%s' from '%s:%d'\n",
12565 of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12566 return AUTH_DONT_KNOW;
12567 }
12568 if (!ast_apply_ha(peer->ha, sin)) {
12569 ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
12570 unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
12571 return AUTH_ACL_FAILED;
12572 }
12573 if (debug)
12574 ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
12575 peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
12576
12577
12578
12579 if (p->rtp) {
12580 ast_rtp_codec_setpref(p->rtp, &peer->prefs);
12581 p->autoframing = peer->autoframing;
12582 }
12583
12584
12585 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
12586 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
12587
12588 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
12589 set_t38_capabilities(p);
12590 }
12591
12592
12593
12594 if (p->sipoptions)
12595 peer->sipoptions = p->sipoptions;
12596
12597 replace_cid(p, rpid_num, calleridname);
12598 do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
12599
12600 ast_string_field_set(p, peersecret, peer->secret);
12601 ast_string_field_set(p, peermd5secret, peer->md5secret);
12602 ast_string_field_set(p, subscribecontext, peer->subscribecontext);
12603 ast_string_field_set(p, mohinterpret, peer->mohinterpret);
12604 ast_string_field_set(p, mohsuggest, peer->mohsuggest);
12605 ast_string_field_set(p, parkinglot, peer->parkinglot);
12606 if (peer->callingpres)
12607 p->callingpres = peer->callingpres;
12608 if (peer->maxms && peer->lastms)
12609 p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
12610 else
12611 p->timer_t1 = peer->timer_t1;
12612
12613
12614 if (peer->timer_b)
12615 p->timer_b = peer->timer_b;
12616 else
12617 p->timer_b = 64 * p->timer_t1;
12618
12619 if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
12620
12621 ast_string_field_set(p, peersecret, NULL);
12622 ast_string_field_set(p, peermd5secret, NULL);
12623 }
12624 if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
12625 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
12626 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
12627
12628 if (peer->call_limit)
12629 ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
12630 ast_string_field_set(p, peername, peer->name);
12631 ast_string_field_set(p, authname, peer->name);
12632
12633 if (sipmethod == SIP_INVITE) {
12634
12635 p->chanvars = copy_vars(peer->chanvars);
12636 }
12637
12638 if (authpeer) {
12639 ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
12640 (*authpeer) = peer;
12641 }
12642
12643 if (!ast_strlen_zero(peer->username)) {
12644 ast_string_field_set(p, username, peer->username);
12645
12646
12647 ast_string_field_set(p, authname, peer->username);
12648 }
12649 if (!ast_strlen_zero(peer->cid_num)) {
12650 char *tmp = ast_strdupa(peer->cid_num);
12651 if (ast_is_shrinkable_phonenumber(tmp))
12652 ast_shrink_phone_number(tmp);
12653 ast_string_field_set(p, cid_num, tmp);
12654 }
12655 if (!ast_strlen_zero(peer->cid_name))
12656 ast_string_field_set(p, cid_name, peer->cid_name);
12657 ast_string_field_set(p, fullcontact, peer->fullcontact);
12658 if (!ast_strlen_zero(peer->context))
12659 ast_string_field_set(p, context, peer->context);
12660 ast_string_field_set(p, peersecret, peer->secret);
12661 ast_string_field_set(p, peermd5secret, peer->md5secret);
12662 ast_string_field_set(p, language, peer->language);
12663 ast_string_field_set(p, accountcode, peer->accountcode);
12664 p->amaflags = peer->amaflags;
12665 p->callgroup = peer->callgroup;
12666 p->pickupgroup = peer->pickupgroup;
12667 p->capability = peer->capability;
12668 p->prefs = peer->prefs;
12669 p->jointcapability = peer->capability;
12670 if (p->peercapability)
12671 p->jointcapability &= p->peercapability;
12672 p->maxcallbitrate = peer->maxcallbitrate;
12673 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
12674 (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
12675 !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
12676 p->vrtp) {
12677 ast_rtp_destroy(p->vrtp);
12678 p->vrtp = NULL;
12679 }
12680 if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
12681 ast_rtp_destroy(p->trtp);
12682 p->trtp = NULL;
12683 }
12684 if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
12685 (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
12686 p->noncodeccapability |= AST_RTP_DTMF;
12687 else
12688 p->noncodeccapability &= ~AST_RTP_DTMF;
12689 p->jointnoncodeccapability = p->noncodeccapability;
12690 }
12691 unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
12692 return res;
12693 }
12694
12695
12696
12697
12698
12699
12700
12701 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
12702 int sipmethod, char *uri, enum xmittype reliable,
12703 struct sockaddr_in *sin, struct sip_peer **authpeer)
12704 {
12705 char from[256];
12706 char *dummy;
12707 char *domain;
12708 char *of, *of2;
12709 char rpid_num[50];
12710 const char *rpid;
12711 enum check_auth_result res;
12712 char calleridname[50];
12713 char *uri2 = ast_strdupa(uri);
12714
12715 terminate_uri(uri2);
12716
12717 ast_copy_string(from, get_header(req, "From"), sizeof(from));
12718 if (pedanticsipchecking)
12719 ast_uri_decode(from);
12720
12721 memset(calleridname, 0, sizeof(calleridname));
12722 get_calleridname(from, calleridname, sizeof(calleridname));
12723 if (calleridname[0])
12724 ast_string_field_set(p, cid_name, calleridname);
12725
12726 rpid = get_header(req, "Remote-Party-ID");
12727 memset(rpid_num, 0, sizeof(rpid_num));
12728 if (!ast_strlen_zero(rpid))
12729 p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
12730
12731 of = get_in_brackets(from);
12732 if (ast_strlen_zero(p->exten)) {
12733 char *t = uri2;
12734 if (!strncasecmp(t, "sip:", 4))
12735 t+= 4;
12736 else if (!strncasecmp(t, "sips:", 5))
12737 t += 5;
12738 ast_string_field_set(p, exten, t);
12739 t = strchr(p->exten, '@');
12740 if (t)
12741 *t = '\0';
12742 if (ast_strlen_zero(p->our_contact))
12743 build_contact(p);
12744 }
12745
12746 ast_string_field_set(p, from, of);
12747
12748 of2 = ast_strdupa(of);
12749
12750
12751 if (p->socket.type == SIP_TRANSPORT_TLS) {
12752 if (parse_uri(of, "sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
12753 if (parse_uri(of2, "sip:", &of, &dummy, &domain, &dummy, &dummy, NULL))
12754 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
12755 }
12756 } else {
12757 if (parse_uri(of, "sip:", &of, &dummy, &domain, &dummy, &dummy, NULL))
12758 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
12759 }
12760
12761 if (ast_strlen_zero(of)) {
12762
12763
12764
12765
12766
12767
12768 of = domain;
12769 } else {
12770 char *tmp = ast_strdupa(of);
12771
12772
12773
12774 tmp = strsep(&tmp, ";");
12775 if (ast_is_shrinkable_phonenumber(tmp))
12776 ast_shrink_phone_number(tmp);
12777 ast_string_field_set(p, cid_num, tmp);
12778 }
12779
12780 if (global_match_auth_username) {
12781
12782
12783
12784
12785
12786
12787
12788
12789 const char *hdr = get_header(req, "Authorization");
12790 if (ast_strlen_zero(hdr))
12791 hdr = get_header(req, "Proxy-Authorization");
12792
12793 if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
12794 ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
12795 of = from;
12796 of = strsep(&of, "\"");
12797 }
12798 }
12799
12800 res = check_peer_ok(p, of, req, sipmethod, sin,
12801 authpeer, reliable, rpid_num, calleridname, uri2);
12802 if (res != AUTH_DONT_KNOW)
12803 return res;
12804
12805
12806 if (global_allowguest) {
12807 replace_cid(p, rpid_num, calleridname);
12808 res = AUTH_SUCCESSFUL;
12809 } else if (global_alwaysauthreject)
12810 res = AUTH_FAKE_AUTH;
12811 else
12812 res = AUTH_SECRET_FAILED;
12813
12814
12815 if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
12816 ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
12817 }
12818
12819 return res;
12820 }
12821
12822
12823
12824
12825 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
12826 {
12827 return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
12828 }
12829
12830
12831 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
12832 {
12833 int x;
12834 int y;
12835
12836 buf[0] = '\0';
12837
12838 y = len - strlen(buf) - 5;
12839 if (y < 0)
12840 y = 0;
12841 for (x = 0; x < req->lines; x++) {
12842 char *line = REQ_OFFSET_TO_STR(req, line[x]);
12843 strncat(buf, line, y);
12844 y -= strlen(line) + 1;
12845 if (y < 0)
12846 y = 0;
12847 if (y != 0 && addnewline)
12848 strcat(buf, "\n");
12849 }
12850 return 0;
12851 }
12852
12853
12854
12855
12856
12857 static void receive_message(struct sip_pvt *p, struct sip_request *req)
12858 {
12859 char buf[1400];
12860 struct ast_frame f;
12861 const char *content_type = get_header(req, "Content-Type");
12862
12863 if (strncmp(content_type, "text/plain", strlen("text/plain"))) {
12864 transmit_response(p, "415 Unsupported Media Type", req);
12865 if (!p->owner)
12866 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12867 return;
12868 }
12869
12870 if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
12871 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
12872 transmit_response(p, "202 Accepted", req);
12873 if (!p->owner)
12874 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12875 return;
12876 }
12877
12878 if (p->owner) {
12879 if (sip_debug_test_pvt(p))
12880 ast_verbose("SIP Text message received: '%s'\n", buf);
12881 memset(&f, 0, sizeof(f));
12882 f.frametype = AST_FRAME_TEXT;
12883 f.subclass = 0;
12884 f.offset = 0;
12885 f.data.ptr = buf;
12886 f.datalen = strlen(buf);
12887 ast_queue_frame(p->owner, &f);
12888 transmit_response(p, "202 Accepted", req);
12889 return;
12890 }
12891
12892
12893 ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n Content-Type:%s\n Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
12894 transmit_response(p, "405 Method Not Allowed", req);
12895 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12896 return;
12897 }
12898
12899
12900 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12901 {
12902 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
12903 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
12904 char ilimits[40];
12905 char iused[40];
12906 int showall = FALSE;
12907 struct ao2_iterator i;
12908 struct sip_peer *peer;
12909
12910 switch (cmd) {
12911 case CLI_INIT:
12912 e->command = "sip show inuse";
12913 e->usage =
12914 "Usage: sip show inuse [all]\n"
12915 " List all SIP devices usage counters and limits.\n"
12916 " Add option \"all\" to show all devices, not only those with a limit.\n";
12917 return NULL;
12918 case CLI_GENERATE:
12919 return NULL;
12920 }
12921
12922 if (a->argc < 3)
12923 return CLI_SHOWUSAGE;
12924
12925 if (a->argc == 4 && !strcmp(a->argv[3], "all"))
12926 showall = TRUE;
12927
12928 ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
12929
12930 i = ao2_iterator_init(peers, 0);
12931
12932 while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
12933 ao2_lock(peer);
12934 if (peer->call_limit)
12935 snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
12936 else
12937 ast_copy_string(ilimits, "N/A", sizeof(ilimits));
12938 snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
12939 if (showall || peer->call_limit)
12940 ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
12941 ao2_unlock(peer);
12942 unref_peer(peer, "toss iterator pointer");
12943 }
12944
12945 return CLI_SUCCESS;
12946 #undef FORMAT
12947 #undef FORMAT2
12948 }
12949
12950
12951
12952 static char *transfermode2str(enum transfermodes mode)
12953 {
12954 if (mode == TRANSFER_OPENFORALL)
12955 return "open";
12956 else if (mode == TRANSFER_CLOSED)
12957 return "closed";
12958 return "strict";
12959 }
12960
12961 static struct _map_x_s natmodes[] = {
12962 { SIP_NAT_NEVER, "No"},
12963 { SIP_NAT_ROUTE, "Route"},
12964 { SIP_NAT_ALWAYS, "Always"},
12965 { SIP_NAT_RFC3581, "RFC3581"},
12966 { -1, NULL},
12967 };
12968
12969
12970 static const char *nat2str(int nat)
12971 {
12972 return map_x_s(natmodes, nat, "Unknown");
12973 }
12974
12975 #ifdef NOTUSED
12976
12977
12978
12979
12980 static struct _map_x_s natcfgmodes[] = {
12981 { SIP_NAT_NEVER, "never"},
12982 { SIP_NAT_ROUTE, "route"},
12983 { SIP_NAT_ALWAYS, "yes"},
12984 { SIP_NAT_RFC3581, "no"},
12985 { -1, NULL},
12986 };
12987
12988
12989 static const char *nat2strconfig(int nat)
12990 {
12991 return map_x_s(natcfgmodes, nat, "Unknown");
12992 }
12993 #endif
12994
12995
12996
12997
12998
12999
13000
13001 static struct _map_x_s stmodes[] = {
13002 { SESSION_TIMER_MODE_ACCEPT, "Accept"},
13003 { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
13004 { SESSION_TIMER_MODE_REFUSE, "Refuse"},
13005 { -1, NULL},
13006 };
13007
13008 static const char *stmode2str(enum st_mode m)
13009 {
13010 return map_x_s(stmodes, m, "Unknown");
13011 }
13012
13013 static enum st_mode str2stmode(const char *s)
13014 {
13015 return map_s_x(stmodes, s, -1);
13016 }
13017
13018
13019 static struct _map_x_s strefreshers[] = {
13020 { SESSION_TIMER_REFRESHER_AUTO, "auto"},
13021 { SESSION_TIMER_REFRESHER_UAC, "uac"},
13022 { SESSION_TIMER_REFRESHER_UAS, "uas"},
13023 { -1, NULL},
13024 };
13025
13026 static const char *strefresher2str(enum st_refresher r)
13027 {
13028 return map_x_s(strefreshers, r, "Unknown");
13029 }
13030
13031 static enum st_refresher str2strefresher(const char *s)
13032 {
13033 return map_s_x(strefreshers, s, -1);
13034 }
13035
13036
13037 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
13038 {
13039 int res = 0;
13040 if (peer->maxms) {
13041 if (peer->lastms < 0) {
13042 ast_copy_string(status, "UNREACHABLE", statuslen);
13043 } else if (peer->lastms > peer->maxms) {
13044 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
13045 res = 1;
13046 } else if (peer->lastms) {
13047 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
13048 res = 1;
13049 } else {
13050 ast_copy_string(status, "UNKNOWN", statuslen);
13051 }
13052 } else {
13053 ast_copy_string(status, "Unmonitored", statuslen);
13054
13055 res = -1;
13056 }
13057 return res;
13058 }
13059
13060
13061
13062
13063
13064
13065 static const char *cli_yesno(int x)
13066 {
13067 return x ? "Yes" : "No";
13068 }
13069
13070
13071 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13072 {
13073 struct sip_threadinfo *th;
13074
13075 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
13076 #define FORMAT "%-30.30s %-6d %-9.9s %-6.6s\n"
13077
13078 switch (cmd) {
13079 case CLI_INIT:
13080 e->command = "sip show tcp";
13081 e->usage =
13082 "Usage: sip show tcp\n"
13083 " Lists all active TCP/TLS sessions.\n";
13084 return NULL;
13085 case CLI_GENERATE:
13086 return NULL;
13087 }
13088
13089 if (a->argc != 3)
13090 return CLI_SHOWUSAGE;
13091
13092 ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
13093 AST_LIST_LOCK(&threadl);
13094 AST_LIST_TRAVERSE(&threadl, th, list) {
13095 ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr),
13096 ntohs(th->tcptls_session->remote_address.sin_port),
13097 get_transport(th->type),
13098 (th->tcptls_session->client ? "Client" : "Server"));
13099
13100 }
13101 AST_LIST_UNLOCK(&threadl);
13102 return CLI_SUCCESS;
13103 #undef FORMAT
13104 #undef FORMAT2
13105 }
13106
13107
13108 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13109 {
13110 regex_t regexbuf;
13111 int havepattern = FALSE;
13112 struct ao2_iterator user_iter;
13113 struct sip_peer *user;
13114
13115 #define FORMAT "%-25.25s %-15.15s %-15.15s %-15.15s %-5.5s%-10.10s\n"
13116
13117 switch (cmd) {
13118 case CLI_INIT:
13119 e->command = "sip show users";
13120 e->usage =
13121 "Usage: sip show users [like <pattern>]\n"
13122 " Lists all known SIP users.\n"
13123 " Optional regular expression pattern is used to filter the user list.\n";
13124 return NULL;
13125 case CLI_GENERATE:
13126 return NULL;
13127 }
13128
13129 switch (a->argc) {
13130 case 5:
13131 if (!strcasecmp(a->argv[3], "like")) {
13132 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
13133 return CLI_SHOWUSAGE;
13134 havepattern = TRUE;
13135 } else
13136 return CLI_SHOWUSAGE;
13137 case 3:
13138 break;
13139 default:
13140 return CLI_SHOWUSAGE;
13141 }
13142
13143 ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
13144
13145 user_iter = ao2_iterator_init(peers, 0);
13146 while ((user = ao2_iterator_next(&user_iter))) {
13147 ao2_lock(user);
13148 if (!(user->type & SIP_TYPE_USER)) {
13149 ao2_unlock(user);
13150 unref_peer(user, "sip show users");
13151 continue;
13152 }
13153
13154 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0)) {
13155 ao2_unlock(user);
13156 unref_peer(user, "sip show users");
13157 continue;
13158 }
13159
13160 ast_cli(a->fd, FORMAT, user->name,
13161 user->secret,
13162 user->accountcode,
13163 user->context,
13164 cli_yesno(user->ha != NULL),
13165 nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
13166 ao2_unlock(user);
13167 unref_peer(user, "sip show users");
13168 }
13169
13170 if (havepattern)
13171 regfree(®exbuf);
13172
13173 return CLI_SUCCESS;
13174 #undef FORMAT
13175 }
13176
13177
13178 static char mandescr_show_registry[] =
13179 "Description: Lists all registration requests and status\n"
13180 "Registrations will follow as separate events. followed by a final event called\n"
13181 "RegistrationsComplete.\n"
13182 "Variables: \n"
13183 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
13184
13185
13186 static int manager_show_registry(struct mansession *s, const struct message *m)
13187 {
13188 const char *id = astman_get_header(m, "ActionID");
13189 char idtext[256] = "";
13190 int total = 0;
13191
13192 if (!ast_strlen_zero(id))
13193 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13194
13195 astman_send_listack(s, m, "Registrations will follow", "start");
13196
13197 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
13198 ASTOBJ_RDLOCK(iterator);
13199 astman_append(s,
13200 "Event: RegistryEntry\r\n"
13201 "Host: %s\r\n"
13202 "Port: %d\r\n"
13203 "Username: %s\r\n"
13204 "Refresh: %d\r\n"
13205 "State: %s\r\n"
13206 "RegistrationTime: %ld\r\n"
13207 "\r\n", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
13208 iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
13209 ASTOBJ_UNLOCK(iterator);
13210 total++;
13211 } while(0));
13212
13213 astman_append(s,
13214 "Event: RegistrationsComplete\r\n"
13215 "EventList: Complete\r\n"
13216 "ListItems: %d\r\n"
13217 "%s"
13218 "\r\n", total, idtext);
13219
13220 return 0;
13221 }
13222
13223 static char mandescr_show_peers[] =
13224 "Description: Lists SIP peers in text format with details on current status.\n"
13225 "Peerlist will follow as separate events, followed by a final event called\n"
13226 "PeerlistComplete.\n"
13227 "Variables: \n"
13228 " ActionID: <id> Action ID for this transaction. Will be returned.\n";
13229
13230
13231
13232 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
13233 {
13234 const char *id = astman_get_header(m, "ActionID");
13235 const char *a[] = {"sip", "show", "peers"};
13236 char idtext[256] = "";
13237 int total = 0;
13238
13239 if (!ast_strlen_zero(id))
13240 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13241
13242 astman_send_listack(s, m, "Peer status list will follow", "start");
13243
13244 _sip_show_peers(-1, &total, s, m, 3, a);
13245
13246 astman_append(s,
13247 "Event: PeerlistComplete\r\n"
13248 "EventList: Complete\r\n"
13249 "ListItems: %d\r\n"
13250 "%s"
13251 "\r\n", total, idtext);
13252 return 0;
13253 }
13254
13255
13256 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13257 {
13258 switch (cmd) {
13259 case CLI_INIT:
13260 e->command = "sip show peers";
13261 e->usage =
13262 "Usage: sip show peers [like <pattern>]\n"
13263 " Lists all known SIP peers.\n"
13264 " Optional regular expression pattern is used to filter the peer list.\n";
13265 return NULL;
13266 case CLI_GENERATE:
13267 return NULL;
13268 }
13269
13270 return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
13271 }
13272
13273 int peercomparefunc(const void *a, const void *b);
13274
13275 int peercomparefunc(const void *a, const void *b)
13276 {
13277 struct sip_peer **ap = (struct sip_peer **)a;
13278 struct sip_peer **bp = (struct sip_peer **)b;
13279 return strcmp((*ap)->name, (*bp)->name);
13280 }
13281
13282
13283
13284 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
13285 {
13286 regex_t regexbuf;
13287 int havepattern = FALSE;
13288 struct sip_peer *peer;
13289 struct ao2_iterator i;
13290
13291
13292 #define FORMAT2 "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
13293 #define FORMAT "%-25.25s %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
13294
13295 char name[256];
13296 int total_peers = 0;
13297 int peers_mon_online = 0;
13298 int peers_mon_offline = 0;
13299 int peers_unmon_offline = 0;
13300 int peers_unmon_online = 0;
13301 const char *id;
13302 char idtext[256] = "";
13303 int realtimepeers;
13304 int objcount = ao2_container_count(peers);
13305 struct sip_peer **peerarray;
13306 int k;
13307
13308
13309 realtimepeers = ast_check_realtime("sippeers");
13310 peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
13311
13312 if (s) {
13313 id = astman_get_header(m, "ActionID");
13314 if (!ast_strlen_zero(id))
13315 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13316 }
13317
13318 switch (argc) {
13319 case 5:
13320 if (!strcasecmp(argv[3], "like")) {
13321 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
13322 return CLI_SHOWUSAGE;
13323 havepattern = TRUE;
13324 } else
13325 return CLI_SHOWUSAGE;
13326 case 3:
13327 break;
13328 default:
13329 return CLI_SHOWUSAGE;
13330 }
13331
13332 if (!s)
13333 ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
13334
13335
13336 i = ao2_iterator_init(peers, 0);
13337 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13338 ao2_lock(peer);
13339
13340 if (!(peer->type & SIP_TYPE_PEER)) {
13341 ao2_unlock(peer);
13342 unref_peer(peer, "unref peer because it's actually a user");
13343 continue;
13344 }
13345
13346 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
13347 objcount--;
13348 ao2_unlock(peer);
13349 unref_peer(peer, "toss iterator peer ptr before continue");
13350 continue;
13351 }
13352
13353 peerarray[total_peers++] = peer;
13354 ao2_unlock(peer);
13355 }
13356
13357 qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
13358
13359 for(k=0; k < total_peers; k++) {
13360 char status[20] = "";
13361 char srch[2000];
13362 char pstatus;
13363 peer = peerarray[k];
13364
13365 ao2_lock(peer);
13366 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
13367 ao2_unlock(peer);
13368 unref_peer(peer, "toss iterator peer ptr before continue");
13369 continue;
13370 }
13371
13372 if (!ast_strlen_zero(peer->username) && !s)
13373 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
13374 else
13375 ast_copy_string(name, peer->name, sizeof(name));
13376
13377 pstatus = peer_status(peer, status, sizeof(status));
13378 if (pstatus == 1)
13379 peers_mon_online++;
13380 else if (pstatus == 0)
13381 peers_mon_offline++;
13382 else {
13383 if (peer->addr.sin_port == 0)
13384 peers_unmon_offline++;
13385 else
13386 peers_unmon_online++;
13387 }
13388
13389 snprintf(srch, sizeof(srch), FORMAT, name,
13390 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13391 peer->host_dynamic ? " D " : " ",
13392 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
13393 peer->ha ? " A " : " ",
13394 ntohs(peer->addr.sin_port), status,
13395 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13396
13397 if (!s) {
13398 ast_cli(fd, FORMAT, name,
13399 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13400 peer->host_dynamic ? " D " : " ",
13401 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : " ",
13402 peer->ha ? " A " : " ",
13403
13404 ntohs(peer->addr.sin_port), status,
13405 realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13406 } else {
13407
13408 astman_append(s,
13409 "Event: PeerEntry\r\n%s"
13410 "Channeltype: SIP\r\n"
13411 "ObjectName: %s\r\n"
13412 "ChanObjectType: peer\r\n"
13413 "IPaddress: %s\r\n"
13414 "IPport: %d\r\n"
13415 "Dynamic: %s\r\n"
13416 "Natsupport: %s\r\n"
13417 "VideoSupport: %s\r\n"
13418 "TextSupport: %s\r\n"
13419 "ACL: %s\r\n"
13420 "Status: %s\r\n"
13421 "RealtimeDevice: %s\r\n\r\n",
13422 idtext,
13423 peer->name,
13424 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
13425 ntohs(peer->addr.sin_port),
13426 peer->host_dynamic ? "yes" : "no",
13427 ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",
13428 ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",
13429 ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",
13430 peer->ha ? "yes" : "no",
13431 status,
13432 realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
13433 }
13434 ao2_unlock(peer);
13435 unref_peer(peer, "toss iterator peer ptr");
13436 }
13437
13438 if (!s)
13439 ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
13440 total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
13441
13442 if (havepattern)
13443 regfree(®exbuf);
13444
13445 if (total)
13446 *total = total_peers;
13447
13448 ast_free(peerarray);
13449
13450 return CLI_SUCCESS;
13451 #undef FORMAT
13452 #undef FORMAT2
13453 }
13454
13455 static int peer_dump_func(void *userobj, void *arg, int flags)
13456 {
13457 struct sip_peer *peer = userobj;
13458 int refc = ao2_t_ref(userobj, 0, "");
13459 int *fd = arg;
13460
13461 ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
13462 peer->name, 0, refc);
13463 return 0;
13464 }
13465
13466 static int dialog_dump_func(void *userobj, void *arg, int flags)
13467 {
13468 struct sip_pvt *pvt = userobj;
13469 int refc = ao2_t_ref(userobj, 0, "");
13470 int *fd = arg;
13471
13472 ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
13473 pvt->callid, 0, refc);
13474 return 0;
13475 }
13476
13477
13478
13479 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13480 {
13481 char tmp[256];
13482
13483 switch (cmd) {
13484 case CLI_INIT:
13485 e->command = "sip show objects";
13486 e->usage =
13487 "Usage: sip show objects\n"
13488 " Lists status of known SIP objects\n";
13489 return NULL;
13490 case CLI_GENERATE:
13491 return NULL;
13492 }
13493
13494 if (a->argc != 3)
13495 return CLI_SHOWUSAGE;
13496 ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
13497 ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
13498 ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
13499 ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), ®l);
13500 ast_cli(a->fd, "-= Dialog objects:\n\n");
13501 ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
13502 return CLI_SUCCESS;
13503 }
13504
13505 static void print_group(int fd, ast_group_t group, int crlf)
13506 {
13507 char buf[256];
13508 ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
13509 }
13510
13511
13512 static struct _map_x_s dtmfstr[] = {
13513 { SIP_DTMF_RFC2833, "rfc2833" },
13514 { SIP_DTMF_INFO, "info" },
13515 { SIP_DTMF_SHORTINFO, "shortinfo" },
13516 { SIP_DTMF_INBAND, "inband" },
13517 { SIP_DTMF_AUTO, "auto" },
13518 { -1, NULL },
13519 };
13520
13521
13522 static const char *dtmfmode2str(int mode)
13523 {
13524 return map_x_s(dtmfstr, mode, "<error>");
13525 }
13526
13527
13528 static int str2dtmfmode(const char *str)
13529 {
13530 return map_s_x(dtmfstr, str, -1);
13531 }
13532
13533 static struct _map_x_s insecurestr[] = {
13534 { SIP_INSECURE_PORT, "port" },
13535 { SIP_INSECURE_INVITE, "invite" },
13536 { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
13537 { 0, "no" },
13538 { -1, NULL },
13539 };
13540
13541
13542 static const char *insecure2str(int mode)
13543 {
13544 return map_x_s(insecurestr, mode, "<error>");
13545 }
13546
13547
13548
13549
13550 static void cleanup_stale_contexts(char *new, char *old)
13551 {
13552 char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
13553
13554 while ((oldcontext = strsep(&old, "&"))) {
13555 stalecontext = '\0';
13556 ast_copy_string(newlist, new, sizeof(newlist));
13557 stringp = newlist;
13558 while ((newcontext = strsep(&stringp, "&"))) {
13559 if (!strcmp(newcontext, oldcontext)) {
13560
13561 stalecontext = '\0';
13562 break;
13563 } else if (strcmp(newcontext, oldcontext)) {
13564 stalecontext = oldcontext;
13565 }
13566
13567 }
13568 if (stalecontext)
13569 ast_context_destroy(ast_context_find(stalecontext), "SIP");
13570 }
13571 }
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
13582 {
13583 struct sip_pvt *dialog = dialogobj;
13584 time_t *t = arg;
13585
13586
13587
13588 if (sip_pvt_trylock(dialog)) {
13589
13590
13591
13592
13593
13594
13595 ao2_unlock(dialogs);
13596 usleep(1);
13597 ao2_lock(dialogs);
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608 return 0;
13609 }
13610
13611
13612 check_rtp_timeout(dialog, *t);
13613
13614
13615
13616
13617 if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
13618
13619 if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
13620 ast_debug(2, "Bridge still active. Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
13621 sip_pvt_unlock(dialog);
13622 return 0;
13623 }
13624
13625 if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
13626 ast_debug(2, "Bridge still active. Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
13627 sip_pvt_unlock(dialog);
13628 return 0;
13629 }
13630
13631 sip_pvt_unlock(dialog);
13632
13633
13634 dialog_unlink_all(dialog, TRUE, FALSE);
13635 return 0;
13636 }
13637
13638 sip_pvt_unlock(dialog);
13639
13640 return 0;
13641 }
13642
13643
13644
13645 static int peer_is_marked(void *peerobj, void *arg, int flags)
13646 {
13647 struct sip_peer *peer = peerobj;
13648 return peer->the_mark ? CMP_MATCH : 0;
13649 }
13650
13651
13652
13653 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13654 {
13655 struct sip_peer *peer, *pi;
13656 int prunepeer = FALSE;
13657 int multi = FALSE;
13658 char *name = NULL;
13659 regex_t regexbuf;
13660 struct ao2_iterator i;
13661
13662 if (cmd == CLI_INIT) {
13663 e->command = "sip prune realtime [peer|all] [all|like]";
13664 e->usage =
13665 "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
13666 " Prunes object(s) from the cache.\n"
13667 " Optional regular expression pattern is used to filter the objects.\n";
13668 return NULL;
13669 } else if (cmd == CLI_GENERATE) {
13670 if (a->pos == 4) {
13671 if (strcasestr(a->line, "realtime peer"))
13672 return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
13673 }
13674 return NULL;
13675 }
13676 switch (a->argc) {
13677 case 4:
13678 name = a->argv[3];
13679
13680 if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
13681 return CLI_SHOWUSAGE;
13682 prunepeer = TRUE;
13683 if (!strcasecmp(name, "all")) {
13684 multi = TRUE;
13685 name = NULL;
13686 }
13687
13688 break;
13689 case 5:
13690
13691 name = a->argv[4];
13692 if (!strcasecmp(a->argv[3], "peer"))
13693 prunepeer = TRUE;
13694 else if (!strcasecmp(a->argv[3], "like")) {
13695 prunepeer = TRUE;
13696 multi = TRUE;
13697 } else
13698 return CLI_SHOWUSAGE;
13699 if (!strcasecmp(a->argv[4], "like"))
13700 return CLI_SHOWUSAGE;
13701 if (!multi && !strcasecmp(a->argv[4], "all")) {
13702 multi = TRUE;
13703 name = NULL;
13704 }
13705 break;
13706 case 6:
13707 name = a->argv[5];
13708 multi = TRUE;
13709
13710 if (strcasecmp(a->argv[4], "like"))
13711 return CLI_SHOWUSAGE;
13712 if (!strcasecmp(a->argv[3], "peer")) {
13713 prunepeer = TRUE;
13714 } else
13715 return CLI_SHOWUSAGE;
13716 break;
13717 default:
13718 return CLI_SHOWUSAGE;
13719 }
13720
13721 if (multi && name) {
13722 if (regcomp(®exbuf, name, REG_EXTENDED | REG_NOSUB))
13723 return CLI_SHOWUSAGE;
13724 }
13725
13726 if (multi) {
13727 if (prunepeer) {
13728 int pruned = 0;
13729
13730 i = ao2_iterator_init(peers, 0);
13731 while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
13732 ao2_lock(pi);
13733 if (name && regexec(®exbuf, pi->name, 0, NULL, 0)) {
13734 unref_peer(pi, "toss iterator peer ptr before continue");
13735 ao2_unlock(pi);
13736 continue;
13737 };
13738 if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13739 pi->the_mark = 1;
13740 pruned++;
13741 }
13742 ao2_unlock(pi);
13743 unref_peer(pi, "toss iterator peer ptr");
13744 }
13745 if (pruned) {
13746 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0,
13747 "initiating callback to remove marked peers");
13748 ast_cli(a->fd, "%d peers pruned.\n", pruned);
13749 } else
13750 ast_cli(a->fd, "No peers found to prune.\n");
13751 }
13752 } else {
13753 if (prunepeer) {
13754 struct sip_peer tmp;
13755 ast_copy_string(tmp.name, name, sizeof(tmp.name));
13756 if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
13757 if (peer->addr.sin_addr.s_addr) {
13758 ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
13759 }
13760 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
13761 ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
13762
13763 ao2_t_link(peers, peer, "link peer into peer table");
13764 if (peer->addr.sin_addr.s_addr) {
13765 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
13766 }
13767
13768 } else
13769 ast_cli(a->fd, "Peer '%s' pruned.\n", name);
13770 unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
13771 } else
13772 ast_cli(a->fd, "Peer '%s' not found.\n", name);
13773 }
13774 }
13775
13776 return CLI_SUCCESS;
13777 }
13778
13779
13780 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
13781 {
13782 int x, codec;
13783
13784 for(x = 0; x < 32 ; x++) {
13785 codec = ast_codec_pref_index(pref, x);
13786 if (!codec)
13787 break;
13788 ast_cli(fd, "%s", ast_getformatname(codec));
13789 ast_cli(fd, ":%d", pref->framing[x]);
13790 if (x < 31 && ast_codec_pref_index(pref, x + 1))
13791 ast_cli(fd, ",");
13792 }
13793 if (!x)
13794 ast_cli(fd, "none");
13795 }
13796
13797
13798 static const char *domain_mode_to_text(const enum domain_mode mode)
13799 {
13800 switch (mode) {
13801 case SIP_DOMAIN_AUTO:
13802 return "[Automatic]";
13803 case SIP_DOMAIN_CONFIG:
13804 return "[Configured]";
13805 }
13806
13807 return "";
13808 }
13809
13810
13811 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13812 {
13813 struct domain *d;
13814 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
13815
13816 switch (cmd) {
13817 case CLI_INIT:
13818 e->command = "sip show domains";
13819 e->usage =
13820 "Usage: sip show domains\n"
13821 " Lists all configured SIP local domains.\n"
13822 " Asterisk only responds to SIP messages to local domains.\n";
13823 return NULL;
13824 case CLI_GENERATE:
13825 return NULL;
13826 }
13827
13828 if (AST_LIST_EMPTY(&domain_list)) {
13829 ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
13830 return CLI_SUCCESS;
13831 } else {
13832 ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
13833 AST_LIST_LOCK(&domain_list);
13834 AST_LIST_TRAVERSE(&domain_list, d, list)
13835 ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
13836 domain_mode_to_text(d->mode));
13837 AST_LIST_UNLOCK(&domain_list);
13838 ast_cli(a->fd, "\n");
13839 return CLI_SUCCESS;
13840 }
13841 }
13842 #undef FORMAT
13843
13844 static char mandescr_show_peer[] =
13845 "Description: Show one SIP peer with details on current status.\n"
13846 "Variables: \n"
13847 " Peer: <name> The peer name you want to check.\n"
13848 " ActionID: <id> Optional action ID for this AMI transaction.\n";
13849
13850
13851 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
13852 {
13853 const char *a[4];
13854 const char *peer;
13855
13856 peer = astman_get_header(m, "Peer");
13857 if (ast_strlen_zero(peer)) {
13858 astman_send_error(s, m, "Peer: <name> missing.");
13859 return 0;
13860 }
13861 a[0] = "sip";
13862 a[1] = "show";
13863 a[2] = "peer";
13864 a[3] = peer;
13865
13866 _sip_show_peer(1, -1, s, m, 4, a);
13867 astman_append(s, "\r\n\r\n" );
13868 return 0;
13869 }
13870
13871
13872 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13873 {
13874 switch (cmd) {
13875 case CLI_INIT:
13876 e->command = "sip show peer";
13877 e->usage =
13878 "Usage: sip show peer <name> [load]\n"
13879 " Shows all details on one SIP peer and the current status.\n"
13880 " Option \"load\" forces lookup of peer in realtime storage.\n";
13881 return NULL;
13882 case CLI_GENERATE:
13883 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
13884 }
13885 return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
13886 }
13887
13888
13889 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13890 {
13891 struct sip_peer *peer;
13892 int load_realtime;
13893
13894 if (argc < 4)
13895 return CLI_SHOWUSAGE;
13896
13897 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13898 if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE))) {
13899 sip_poke_peer(peer, 1);
13900 unref_peer(peer, "qualify: done with peer");
13901 } else if (type == 0) {
13902 ast_cli(fd, "Peer '%s' not found\n", argv[3]);
13903 } else {
13904 astman_send_error(s, m, "Peer not found");
13905 }
13906 return CLI_SUCCESS;
13907 }
13908
13909
13910 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
13911 {
13912 const char *a[4];
13913 const char *peer;
13914
13915 peer = astman_get_header(m, "Peer");
13916 if (ast_strlen_zero(peer)) {
13917 astman_send_error(s, m, "Peer: <name> missing.");
13918 return 0;
13919 }
13920 a[0] = "sip";
13921 a[1] = "qualify";
13922 a[2] = "peer";
13923 a[3] = peer;
13924
13925 _sip_qualify_peer(1, -1, s, m, 4, a);
13926 astman_append(s, "\r\n\r\n" );
13927 return 0;
13928 }
13929
13930
13931 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13932 {
13933 switch (cmd) {
13934 case CLI_INIT:
13935 e->command = "sip qualify peer";
13936 e->usage =
13937 "Usage: sip qualify peer <name> [load]\n"
13938 " Requests a response from one SIP peer and the current status.\n"
13939 " Option \"load\" forces lookup of peer in realtime storage.\n";
13940 return NULL;
13941 case CLI_GENERATE:
13942 return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
13943 }
13944 return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
13945 }
13946
13947
13948 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
13949 {
13950 struct sip_mailbox *mailbox;
13951
13952 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
13953 ast_str_append(mailbox_str, 0, "%s%s%s%s",
13954 mailbox->mailbox,
13955 ast_strlen_zero(mailbox->context) ? "" : "@",
13956 S_OR(mailbox->context, ""),
13957 AST_LIST_NEXT(mailbox, entry) ? "," : "");
13958 }
13959 }
13960
13961
13962 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
13963 {
13964 char status[30] = "";
13965 char cbuf[256];
13966 struct sip_peer *peer;
13967 char codec_buf[512];
13968 struct ast_codec_pref *pref;
13969 struct ast_variable *v;
13970 struct sip_auth *auth;
13971 int x = 0, codec = 0, load_realtime;
13972 int realtimepeers;
13973
13974 realtimepeers = ast_check_realtime("sippeers");
13975
13976 if (argc < 4)
13977 return CLI_SHOWUSAGE;
13978
13979 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
13980 peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE);
13981
13982 if (s) {
13983 if (peer) {
13984 const char *id = astman_get_header(m, "ActionID");
13985
13986 astman_append(s, "Response: Success\r\n");
13987 if (!ast_strlen_zero(id))
13988 astman_append(s, "ActionID: %s\r\n", id);
13989 } else {
13990 snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
13991 astman_send_error(s, m, cbuf);
13992 return CLI_SUCCESS;
13993 }
13994 }
13995 if (peer && type==0 ) {
13996 struct ast_str *mailbox_str = ast_str_alloca(512);
13997 ast_cli(fd, "\n\n");
13998 ast_cli(fd, " * Name : %s\n", peer->name);
13999 if (realtimepeers) {
14000 ast_cli(fd, " Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
14001 }
14002 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
14003 ast_cli(fd, " MD5Secret : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
14004 for (auth = peer->auth; auth; auth = auth->next) {
14005 ast_cli(fd, " Realm-auth : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
14006 ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
14007 }
14008 ast_cli(fd, " Context : %s\n", peer->context);
14009 ast_cli(fd, " Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
14010 ast_cli(fd, " Language : %s\n", peer->language);
14011 if (!ast_strlen_zero(peer->accountcode))
14012 ast_cli(fd, " Accountcode : %s\n", peer->accountcode);
14013 ast_cli(fd, " AMA flags : %s\n", ast_cdr_flags2str(peer->amaflags));
14014 ast_cli(fd, " Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
14015 ast_cli(fd, " CallingPres : %s\n", ast_describe_caller_presentation(peer->callingpres));
14016 if (!ast_strlen_zero(peer->fromuser))
14017 ast_cli(fd, " FromUser : %s\n", peer->fromuser);
14018 if (!ast_strlen_zero(peer->fromdomain))
14019 ast_cli(fd, " FromDomain : %s\n", peer->fromdomain);
14020 ast_cli(fd, " Callgroup : ");
14021 print_group(fd, peer->callgroup, 0);
14022 ast_cli(fd, " Pickupgroup : ");
14023 print_group(fd, peer->pickupgroup, 0);
14024 peer_mailboxes_to_str(&mailbox_str, peer);
14025 ast_cli(fd, " Mailbox : %s\n", mailbox_str->str);
14026 ast_cli(fd, " VM Extension : %s\n", peer->vmexten);
14027 ast_cli(fd, " LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
14028 ast_cli(fd, " Call limit : %d\n", peer->call_limit);
14029 if (peer->busy_level)
14030 ast_cli(fd, " Busy level : %d\n", peer->busy_level);
14031 ast_cli(fd, " Dynamic : %s\n", cli_yesno(peer->host_dynamic));
14032 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
14033 ast_cli(fd, " MaxCallBR : %d kbps\n", peer->maxcallbitrate);
14034 ast_cli(fd, " Expire : %ld\n", ast_sched_when(sched, peer->expire));
14035 ast_cli(fd, " Insecure : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14036 ast_cli(fd, " Nat : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14037 ast_cli(fd, " ACL : %s\n", cli_yesno(peer->ha != NULL));
14038 ast_cli(fd, " T38 pt UDPTL : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14039 ast_cli(fd, " CanReinvite : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
14040 ast_cli(fd, " PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
14041 ast_cli(fd, " User=Phone : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
14042 ast_cli(fd, " Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14043 ast_cli(fd, " Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
14044 ast_cli(fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14045 ast_cli(fd, " Trust RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
14046 ast_cli(fd, " Send RPID : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
14047 ast_cli(fd, " Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14048 ast_cli(fd, " Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14049 if (peer->outboundproxy)
14050 ast_cli(fd, " Outb. proxy : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
14051 peer->outboundproxy->force ? "(forced)" : "");
14052
14053
14054 ast_cli(fd, " DTMFmode : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14055 ast_cli(fd, " Timer T1 : %d\n", peer->timer_t1);
14056 ast_cli(fd, " Timer B : %d\n", peer->timer_b);
14057 ast_cli(fd, " ToHost : %s\n", peer->tohost);
14058 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
14059 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
14060 ast_cli(fd, " Transport : %s\n", get_transport(peer->socket.type));
14061 if (!ast_strlen_zero(global_regcontext))
14062 ast_cli(fd, " Reg. exten : %s\n", peer->regexten);
14063 ast_cli(fd, " Def. Username: %s\n", peer->username);
14064 ast_cli(fd, " SIP Options : ");
14065 if (peer->sipoptions) {
14066 int lastoption = -1;
14067 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
14068 if (sip_options[x].id != lastoption) {
14069 if (peer->sipoptions & sip_options[x].id)
14070 ast_cli(fd, "%s ", sip_options[x].text);
14071 lastoption = x;
14072 }
14073 }
14074 } else
14075 ast_cli(fd, "(none)");
14076
14077 ast_cli(fd, "\n");
14078 ast_cli(fd, " Codecs : ");
14079 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14080 ast_cli(fd, "%s\n", codec_buf);
14081 ast_cli(fd, " Codec Order : (");
14082 print_codec_to_cli(fd, &peer->prefs);
14083 ast_cli(fd, ")\n");
14084
14085 ast_cli(fd, " Auto-Framing : %s \n", cli_yesno(peer->autoframing));
14086 ast_cli(fd, " 100 on REG : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
14087 ast_cli(fd, " Status : ");
14088 peer_status(peer, status, sizeof(status));
14089 ast_cli(fd, "%s\n", status);
14090 ast_cli(fd, " Useragent : %s\n", peer->useragent);
14091 ast_cli(fd, " Reg. Contact : %s\n", peer->fullcontact);
14092 ast_cli(fd, " Qualify Freq : %d ms\n", peer->qualifyfreq);
14093 if (peer->chanvars) {
14094 ast_cli(fd, " Variables :\n");
14095 for (v = peer->chanvars ; v ; v = v->next)
14096 ast_cli(fd, " %s = %s\n", v->name, v->value);
14097 }
14098
14099 ast_cli(fd, " Sess-Timers : %s\n", stmode2str(peer->stimer.st_mode_oper));
14100 ast_cli(fd, " Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
14101 ast_cli(fd, " Sess-Expires : %d secs\n", peer->stimer.st_max_se);
14102 ast_cli(fd, " Min-Sess : %d secs\n", peer->stimer.st_min_se);
14103 ast_cli(fd, "\n");
14104 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
14105 } else if (peer && type == 1) {
14106 char buffer[256];
14107 struct ast_str *mailbox_str = ast_str_alloca(512);
14108 astman_append(s, "Channeltype: SIP\r\n");
14109 astman_append(s, "ObjectName: %s\r\n", peer->name);
14110 astman_append(s, "ChanObjectType: peer\r\n");
14111 astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
14112 astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
14113 astman_append(s, "Context: %s\r\n", peer->context);
14114 astman_append(s, "Language: %s\r\n", peer->language);
14115 if (!ast_strlen_zero(peer->accountcode))
14116 astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
14117 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
14118 astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
14119 if (!ast_strlen_zero(peer->fromuser))
14120 astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
14121 if (!ast_strlen_zero(peer->fromdomain))
14122 astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
14123 astman_append(s, "Callgroup: ");
14124 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
14125 astman_append(s, "Pickupgroup: ");
14126 astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
14127 peer_mailboxes_to_str(&mailbox_str, peer);
14128 astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
14129 astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
14130 astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
14131 astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
14132 astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
14133 astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
14134 astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
14135 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
14136 astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
14137 astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14138 astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14139 astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
14140 astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
14141 astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
14142 astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
14143 astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
14144 astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
14145 astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
14146 astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
14147 astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
14148 astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
14149
14150
14151 astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14152 astman_append(s, "ToHost: %s\r\n", peer->tohost);
14153 astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
14154 astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
14155 astman_append(s, "Default-Username: %s\r\n", peer->username);
14156 if (!ast_strlen_zero(global_regcontext))
14157 astman_append(s, "RegExtension: %s\r\n", peer->regexten);
14158 astman_append(s, "Codecs: ");
14159 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14160 astman_append(s, "%s\r\n", codec_buf);
14161 astman_append(s, "CodecOrder: ");
14162 pref = &peer->prefs;
14163 for(x = 0; x < 32 ; x++) {
14164 codec = ast_codec_pref_index(pref, x);
14165 if (!codec)
14166 break;
14167 astman_append(s, "%s", ast_getformatname(codec));
14168 if (x < 31 && ast_codec_pref_index(pref, x+1))
14169 astman_append(s, ",");
14170 }
14171
14172 astman_append(s, "\r\n");
14173 astman_append(s, "Status: ");
14174 peer_status(peer, status, sizeof(status));
14175 astman_append(s, "%s\r\n", status);
14176 astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
14177 astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
14178 astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
14179 if (peer->chanvars) {
14180 for (v = peer->chanvars ; v ; v = v->next) {
14181 astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
14182 }
14183 }
14184
14185 peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
14186
14187 } else {
14188 ast_cli(fd, "Peer %s not found.\n", argv[3]);
14189 ast_cli(fd, "\n");
14190 }
14191
14192 return CLI_SUCCESS;
14193 }
14194
14195
14196 static char *complete_sip_user(const char *word, int state)
14197 {
14198 char *result = NULL;
14199 int wordlen = strlen(word);
14200 int which = 0;
14201 struct ao2_iterator user_iter;
14202 struct sip_peer *user;
14203
14204 user_iter = ao2_iterator_init(peers, 0);
14205 while ((user = ao2_iterator_next(&user_iter))) {
14206 ao2_lock(user);
14207 if (!(user->type & SIP_TYPE_USER)) {
14208 ao2_unlock(user);
14209 unref_peer(user, "complete sip user");
14210 continue;
14211 }
14212
14213 if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
14214 result = ast_strdup(user->name);
14215 }
14216 ao2_unlock(user);
14217 unref_peer(user, "complete sip user");
14218 }
14219 return result;
14220 }
14221
14222 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
14223 {
14224 if (pos == 3)
14225 return complete_sip_user(word, state);
14226
14227 return NULL;
14228 }
14229
14230
14231 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14232 {
14233 char cbuf[256];
14234 struct sip_peer *user;
14235 struct ast_variable *v;
14236 int load_realtime;
14237
14238 switch (cmd) {
14239 case CLI_INIT:
14240 e->command = "sip show user";
14241 e->usage =
14242 "Usage: sip show user <name> [load]\n"
14243 " Shows all details on one SIP user and the current status.\n"
14244 " Option \"load\" forces lookup of peer in realtime storage.\n";
14245 return NULL;
14246 case CLI_GENERATE:
14247 return complete_sip_show_user(a->line, a->word, a->pos, a->n);
14248 }
14249
14250 if (a->argc < 4)
14251 return CLI_SHOWUSAGE;
14252
14253
14254 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
14255
14256 if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE))) {
14257 ao2_lock(user);
14258 ast_cli(a->fd, "\n\n");
14259 ast_cli(a->fd, " * Name : %s\n", user->name);
14260 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
14261 ast_cli(a->fd, " MD5Secret : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
14262 ast_cli(a->fd, " Context : %s\n", user->context);
14263 ast_cli(a->fd, " Language : %s\n", user->language);
14264 if (!ast_strlen_zero(user->accountcode))
14265 ast_cli(a->fd, " Accountcode : %s\n", user->accountcode);
14266 ast_cli(a->fd, " AMA flags : %s\n", ast_cdr_flags2str(user->amaflags));
14267 ast_cli(a->fd, " Transfer mode: %s\n", transfermode2str(user->allowtransfer));
14268 ast_cli(a->fd, " MaxCallBR : %d kbps\n", user->maxcallbitrate);
14269 ast_cli(a->fd, " CallingPres : %s\n", ast_describe_caller_presentation(user->callingpres));
14270 ast_cli(a->fd, " Call limit : %d\n", user->call_limit);
14271 ast_cli(a->fd, " Callgroup : ");
14272 print_group(a->fd, user->callgroup, 0);
14273 ast_cli(a->fd, " Pickupgroup : ");
14274 print_group(a->fd, user->pickupgroup, 0);
14275 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
14276 ast_cli(a->fd, " ACL : %s\n", cli_yesno(user->ha != NULL));
14277 ast_cli(a->fd, " Sess-Timers : %s\n", stmode2str(user->stimer.st_mode_oper));
14278 ast_cli(a->fd, " Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
14279 ast_cli(a->fd, " Sess-Expires : %d secs\n", user->stimer.st_max_se);
14280 ast_cli(a->fd, " Sess-Min-SE : %d secs\n", user->stimer.st_min_se);
14281 ast_cli(a->fd, " Ign SDP ver : %s\n", cli_yesno(ast_test_flag(&user->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14282
14283 ast_cli(a->fd, " Codec Order : (");
14284 print_codec_to_cli(a->fd, &user->prefs);
14285 ast_cli(a->fd, ")\n");
14286
14287 ast_cli(a->fd, " Auto-Framing: %s \n", cli_yesno(user->autoframing));
14288 if (user->chanvars) {
14289 ast_cli(a->fd, " Variables :\n");
14290 for (v = user->chanvars ; v ; v = v->next)
14291 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
14292 }
14293
14294 ast_cli(a->fd, "\n");
14295
14296 ao2_unlock(user);
14297 unref_peer(user, "sip show user");
14298 } else {
14299 ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
14300 ast_cli(a->fd, "\n");
14301 }
14302
14303 return CLI_SUCCESS;
14304 }
14305
14306
14307 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14308 {
14309 struct ast_str *cbuf;
14310 struct ast_cb_names cbnames = {9, { "retrans_pkt",
14311 "__sip_autodestruct",
14312 "expire_register",
14313 "auto_congest",
14314 "sip_reg_timeout",
14315 "sip_poke_peer_s",
14316 "sip_poke_noanswer",
14317 "sip_reregister",
14318 "sip_reinvite_retry"},
14319 { retrans_pkt,
14320 __sip_autodestruct,
14321 expire_register,
14322 auto_congest,
14323 sip_reg_timeout,
14324 sip_poke_peer_s,
14325 sip_poke_noanswer,
14326 sip_reregister,
14327 sip_reinvite_retry}};
14328
14329 switch (cmd) {
14330 case CLI_INIT:
14331 e->command = "sip show sched";
14332 e->usage =
14333 "Usage: sip show sched\n"
14334 " Shows stats on what's in the sched queue at the moment\n";
14335 return NULL;
14336 case CLI_GENERATE:
14337 return NULL;
14338 }
14339
14340 cbuf = ast_str_alloca(2048);
14341
14342 ast_cli(a->fd, "\n");
14343 ast_sched_report(sched, &cbuf, &cbnames);
14344 ast_cli(a->fd, "%s", cbuf->str);
14345
14346 return CLI_SUCCESS;
14347 }
14348
14349
14350 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14351 {
14352 #define FORMAT2 "%-30.30s %-6.6s %-12.12s %8.8s %-20.20s %-25.25s\n"
14353 #define FORMAT "%-30.30s %-6.6s %-12.12s %8d %-20.20s %-25.25s\n"
14354 char host[80];
14355 char tmpdat[256];
14356 struct ast_tm tm;
14357 int counter = 0;
14358
14359 switch (cmd) {
14360 case CLI_INIT:
14361 e->command = "sip show registry";
14362 e->usage =
14363 "Usage: sip show registry\n"
14364 " Lists all registration requests and status.\n";
14365 return NULL;
14366 case CLI_GENERATE:
14367 return NULL;
14368 }
14369
14370 if (a->argc != 3)
14371 return CLI_SHOWUSAGE;
14372 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
14373
14374 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
14375 ASTOBJ_RDLOCK(iterator);
14376 snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
14377 if (iterator->regtime.tv_sec) {
14378 ast_localtime(&iterator->regtime, &tm, NULL);
14379 ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
14380 } else
14381 tmpdat[0] = '\0';
14382 ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
14383 ASTOBJ_UNLOCK(iterator);
14384 counter++;
14385 } while(0));
14386 ast_cli(a->fd, "%d SIP registrations.\n", counter);
14387 return CLI_SUCCESS;
14388 #undef FORMAT
14389 #undef FORMAT2
14390 }
14391
14392
14393
14394
14395
14396 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14397 {
14398 struct sip_peer *peer;
14399 int load_realtime = 0;
14400
14401 switch (cmd) {
14402 case CLI_INIT:
14403 e->command = "sip unregister";
14404 e->usage =
14405 "Usage: sip unregister <peer>\n"
14406 " Unregister (force expiration) a SIP peer from the registry\n";
14407 return NULL;
14408 case CLI_GENERATE:
14409 return complete_sip_unregister(a->line, a->word, a->pos, a->n);
14410 }
14411
14412 if (a->argc != 3)
14413 return CLI_SHOWUSAGE;
14414
14415 if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE))) {
14416 if (peer->expire > 0) {
14417 AST_SCHED_DEL_UNREF(sched, peer->expire,
14418 unref_peer(peer, "remove register expire ref"));
14419 expire_register(ref_peer(peer, "ref for expire_register"));
14420 ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
14421 } else {
14422 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
14423 }
14424 unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
14425 } else {
14426 ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
14427 }
14428
14429 return CLI_SUCCESS;
14430 }
14431
14432
14433 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
14434 {
14435 #define FORMAT2 "%-15.15s %-11.11s %-8.8s %-10.10s %-10.10s (%-2.2s) %-6.6s %-10.10s %-10.10s ( %%) %-6.6s\n"
14436 #define FORMAT "%-15.15s %-11.11s %-8.8s %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u %-10.10u%-1.1s %-10.10u (%-2.2u%%) %-6.6u\n"
14437 struct sip_pvt *cur = __cur;
14438 unsigned int rxcount;
14439 unsigned int txcount;
14440 char durbuf[10];
14441 int duration;
14442 int durh, durm, durs;
14443 struct ast_channel *c = cur->owner;
14444 struct __show_chan_arg *arg = __arg;
14445 int fd = arg->fd;
14446
14447
14448 if (cur->subscribed != NONE)
14449 return 0;
14450
14451 if (!cur->rtp) {
14452 if (sipdebug)
14453 ast_cli(fd, "%-15.15s %-11.11s (inv state: %s) -- %s\n", ast_inet_ntoa(cur->sa.sin_addr), cur->callid, invitestate2string[cur->invitestate].desc, "-- No RTP active");
14454 return 0;
14455 }
14456 rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
14457 txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
14458
14459
14460 if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
14461 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
14462 durh = duration / 3600;
14463 durm = (duration % 3600) / 60;
14464 durs = duration % 60;
14465 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
14466 } else {
14467 durbuf[0] = '\0';
14468 }
14469
14470 ast_cli(fd, FORMAT,
14471 ast_inet_ntoa(cur->sa.sin_addr),
14472 cur->callid,
14473 durbuf,
14474 rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
14475 rxcount > (unsigned int) 100000 ? "K":" ",
14476 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS),
14477 rxcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) / rxcount * 100) : 0,
14478 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
14479 txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
14480 txcount > (unsigned int) 100000 ? "K":" ",
14481 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS),
14482 txcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS)/ txcount * 100) : 0,
14483 ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
14484 );
14485 arg->numchans++;
14486
14487 return 0;
14488 }
14489
14490
14491 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14492 {
14493 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
14494
14495 switch (cmd) {
14496 case CLI_INIT:
14497 e->command = "sip show channelstats";
14498 e->usage =
14499 "Usage: sip show channelstats\n"
14500 " Lists all currently active SIP channel's RTCP statistics.\n"
14501 " Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
14502 return NULL;
14503 case CLI_GENERATE:
14504 return NULL;
14505 }
14506
14507 if (a->argc != 3)
14508 return CLI_SHOWUSAGE;
14509
14510 ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "%", "Jitter", "Send: Pack", "Lost", "Jitter");
14511
14512 ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
14513 ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
14514 return CLI_SUCCESS;
14515 }
14516 #undef FORMAT
14517 #undef FORMAT2
14518
14519
14520 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14521 {
14522 int realtimepeers;
14523 int realtimeregs;
14524 char codec_buf[SIPBUFSIZE];
14525 const char *msg;
14526
14527 switch (cmd) {
14528 case CLI_INIT:
14529 e->command = "sip show settings";
14530 e->usage =
14531 "Usage: sip show settings\n"
14532 " Provides detailed list of the configuration of the SIP channel.\n";
14533 return NULL;
14534 case CLI_GENERATE:
14535 return NULL;
14536 }
14537
14538
14539 realtimepeers = ast_check_realtime("sippeers");
14540 realtimeregs = ast_check_realtime("sipregs");
14541
14542 if (a->argc != 3)
14543 return CLI_SHOWUSAGE;
14544 ast_cli(a->fd, "\n\nGlobal Settings:\n");
14545 ast_cli(a->fd, "----------------\n");
14546 ast_cli(a->fd, " UDP SIP Port: %d\n", ntohs(bindaddr.sin_port));
14547 ast_cli(a->fd, " UDP Bindaddress: %s\n", ast_inet_ntoa(bindaddr.sin_addr));
14548 ast_cli(a->fd, " TCP SIP Port: ");
14549 if (sip_tcp_desc.local_address.sin_family == AF_INET) {
14550 ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
14551 ast_cli(a->fd, " TCP Bindaddress: %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
14552 } else {
14553 ast_cli(a->fd, "Disabled\n");
14554 }
14555 ast_cli(a->fd, " TLS SIP Port: ");
14556 if (default_tls_cfg.enabled != FALSE) {
14557 ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
14558 ast_cli(a->fd, " TLS Bindaddress: %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
14559 } else {
14560 ast_cli(a->fd, "Disabled\n");
14561 }
14562 ast_cli(a->fd, " Videosupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14563 ast_cli(a->fd, " Textsupport: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
14564 ast_cli(a->fd, " AutoCreate Peer: %s\n", cli_yesno(autocreatepeer));
14565 ast_cli(a->fd, " Ignore SDP sess. ver.: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14566 ast_cli(a->fd, " Match Auth Username: %s\n", cli_yesno(global_match_auth_username));
14567 ast_cli(a->fd, " Allow unknown access: %s\n", cli_yesno(global_allowguest));
14568 ast_cli(a->fd, " Allow subscriptions: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14569 ast_cli(a->fd, " Allow overlap dialing: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14570 ast_cli(a->fd, " Allow promsic. redir: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
14571 ast_cli(a->fd, " Enable call counters: %s\n", cli_yesno(global_callcounter));
14572 ast_cli(a->fd, " SIP domain support: %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
14573 ast_cli(a->fd, " Realm. auth: %s\n", cli_yesno(authl != NULL));
14574 ast_cli(a->fd, " Our auth realm %s\n", global_realm);
14575 ast_cli(a->fd, " Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
14576 ast_cli(a->fd, " URI user is phone no: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
14577 ast_cli(a->fd, " Always auth rejects: %s\n", cli_yesno(global_alwaysauthreject));
14578 ast_cli(a->fd, " Direct RTP setup: %s\n", cli_yesno(global_directrtpsetup));
14579 ast_cli(a->fd, " User Agent: %s\n", global_useragent);
14580 ast_cli(a->fd, " SDP Session Name: %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
14581 ast_cli(a->fd, " SDP Owner Name: %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
14582 ast_cli(a->fd, " Reg. context: %s\n", S_OR(global_regcontext, "(not set)"));
14583 ast_cli(a->fd, " Regexten on Qualify: %s\n", cli_yesno(global_regextenonqualify));
14584 ast_cli(a->fd, " Caller ID: %s\n", default_callerid);
14585 ast_cli(a->fd, " From: Domain: %s\n", default_fromdomain);
14586 ast_cli(a->fd, " Record SIP history: %s\n", recordhistory ? "On" : "Off");
14587 ast_cli(a->fd, " Call Events: %s\n", global_callevents ? "On" : "Off");
14588 ast_cli(a->fd, " Auth. Failure Events: %s\n", global_authfailureevents ? "On" : "Off");
14589
14590 ast_cli(a->fd, " T38 fax pt UDPTL: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
14591
14592 if (!realtimepeers && !realtimeregs)
14593 ast_cli(a->fd, " SIP realtime: Disabled\n" );
14594 else
14595 ast_cli(a->fd, " SIP realtime: Enabled\n" );
14596 ast_cli(a->fd, " Qualify Freq : %d ms\n", global_qualifyfreq);
14597 ast_cli(a->fd, "\nNetwork QoS Settings:\n");
14598 ast_cli(a->fd, "---------------------------\n");
14599 ast_cli(a->fd, " IP ToS SIP: %s\n", ast_tos2str(global_tos_sip));
14600 ast_cli(a->fd, " IP ToS RTP audio: %s\n", ast_tos2str(global_tos_audio));
14601 ast_cli(a->fd, " IP ToS RTP video: %s\n", ast_tos2str(global_tos_video));
14602 ast_cli(a->fd, " IP ToS RTP text: %s\n", ast_tos2str(global_tos_text));
14603 ast_cli(a->fd, " 802.1p CoS SIP: %d\n", global_cos_sip);
14604 ast_cli(a->fd, " 802.1p CoS RTP audio: %d\n", global_cos_audio);
14605 ast_cli(a->fd, " 802.1p CoS RTP video: %d\n", global_cos_video);
14606 ast_cli(a->fd, " 802.1p CoS RTP text: %d\n", global_cos_text);
14607 ast_cli(a->fd, " Jitterbuffer enabled: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
14608 ast_cli(a->fd, " Jitterbuffer forced: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
14609 ast_cli(a->fd, " Jitterbuffer max size: %ld\n", global_jbconf.max_size);
14610 ast_cli(a->fd, " Jitterbuffer resync: %ld\n", global_jbconf.resync_threshold);
14611 ast_cli(a->fd, " Jitterbuffer impl: %s\n", global_jbconf.impl);
14612 ast_cli(a->fd, " Jitterbuffer log: %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
14613
14614 ast_cli(a->fd, "\nNetwork Settings:\n");
14615 ast_cli(a->fd, "---------------------------\n");
14616
14617 if (localaddr == NULL)
14618 msg = "Disabled, no localnet list";
14619 else if (externip.sin_addr.s_addr == 0)
14620 msg = "Disabled, externip is 0.0.0.0";
14621 else if (stunaddr.sin_addr.s_addr != 0)
14622 msg = "Enabled using STUN";
14623 else if (!ast_strlen_zero(externhost))
14624 msg = "Enabled using externhost";
14625 else
14626 msg = "Enabled using externip";
14627 ast_cli(a->fd, " SIP address remapping: %s\n", msg);
14628 ast_cli(a->fd, " Externhost: %s\n", S_OR(externhost, "<none>"));
14629 ast_cli(a->fd, " Externip: %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
14630 ast_cli(a->fd, " Externrefresh: %d\n", externrefresh);
14631 ast_cli(a->fd, " Internal IP: %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
14632 {
14633 struct ast_ha *d;
14634 const char *prefix = "Localnet:";
14635 char buf[INET_ADDRSTRLEN];
14636
14637 for (d = localaddr; d ; prefix = "", d = d->next) {
14638 ast_cli(a->fd, " %-24s%s/%s\n",
14639 prefix, ast_inet_ntoa(d->netaddr),
14640 inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
14641 }
14642 }
14643 ast_cli(a->fd, " STUN server: %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
14644
14645 ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
14646 ast_cli(a->fd, "---------------------------\n");
14647 ast_cli(a->fd, " Codecs: ");
14648 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
14649 ast_cli(a->fd, "%s\n", codec_buf);
14650 ast_cli(a->fd, " Codec Order: ");
14651 print_codec_to_cli(a->fd, &default_prefs);
14652 ast_cli(a->fd, "\n");
14653 ast_cli(a->fd, " Relax DTMF: %s\n", cli_yesno(global_relaxdtmf));
14654 ast_cli(a->fd, " RFC2833 Compensation: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
14655 ast_cli(a->fd, " Compact SIP headers: %s\n", cli_yesno(compactheaders));
14656 ast_cli(a->fd, " RTP Keepalive: %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
14657 ast_cli(a->fd, " RTP Timeout: %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
14658 ast_cli(a->fd, " RTP Hold Timeout: %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
14659 ast_cli(a->fd, " MWI NOTIFY mime type: %s\n", default_notifymime);
14660 ast_cli(a->fd, " DNS SRV lookup: %s\n", cli_yesno(global_srvlookup));
14661 ast_cli(a->fd, " Pedantic SIP support: %s\n", cli_yesno(pedanticsipchecking));
14662 ast_cli(a->fd, " Reg. min duration %d secs\n", min_expiry);
14663 ast_cli(a->fd, " Reg. max duration: %d secs\n", max_expiry);
14664 ast_cli(a->fd, " Reg. default duration: %d secs\n", default_expiry);
14665 ast_cli(a->fd, " Outbound reg. timeout: %d secs\n", global_reg_timeout);
14666 ast_cli(a->fd, " Outbound reg. attempts: %d\n", global_regattempts_max);
14667 ast_cli(a->fd, " Notify ringing state: %s\n", cli_yesno(global_notifyringing));
14668 ast_cli(a->fd, " Notify hold state: %s\n", cli_yesno(global_notifyhold));
14669 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(global_allowtransfer));
14670 ast_cli(a->fd, " Max Call Bitrate: %d kbps\n", default_maxcallbitrate);
14671 ast_cli(a->fd, " Auto-Framing: %s\n", cli_yesno(global_autoframing));
14672 ast_cli(a->fd, " Outb. proxy: %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
14673 global_outboundproxy.force ? "(forced)" : "");
14674 ast_cli(a->fd, " Session Timers: %s\n", stmode2str(global_st_mode));
14675 ast_cli(a->fd, " Session Refresher: %s\n", strefresher2str (global_st_refresher));
14676 ast_cli(a->fd, " Session Expires: %d secs\n", global_max_se);
14677 ast_cli(a->fd, " Session Min-SE: %d secs\n", global_min_se);
14678 ast_cli(a->fd, " Timer T1: %d\n", global_t1);
14679 ast_cli(a->fd, " Timer T1 minimum: %d\n", global_t1min);
14680 ast_cli(a->fd, " Timer B: %d\n", global_timer_b);
14681
14682 ast_cli(a->fd, "\nDefault Settings:\n");
14683 ast_cli(a->fd, "-----------------\n");
14684 ast_cli(a->fd, " Context: %s\n", default_context);
14685 ast_cli(a->fd, " Nat: %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
14686 ast_cli(a->fd, " DTMF: %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
14687 ast_cli(a->fd, " Qualify: %d\n", default_qualify);
14688 ast_cli(a->fd, " Use ClientCode: %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
14689 ast_cli(a->fd, " Progress inband: %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
14690 ast_cli(a->fd, " Language: %s\n", default_language);
14691 ast_cli(a->fd, " MOH Interpret: %s\n", default_mohinterpret);
14692 ast_cli(a->fd, " MOH Suggest: %s\n", default_mohsuggest);
14693 ast_cli(a->fd, " Voice Mail Extension: %s\n", default_vmexten);
14694
14695
14696 if (realtimepeers || realtimeregs) {
14697 ast_cli(a->fd, "\nRealtime SIP Settings:\n");
14698 ast_cli(a->fd, "----------------------\n");
14699 ast_cli(a->fd, " Realtime Peers: %s\n", cli_yesno(realtimepeers));
14700 ast_cli(a->fd, " Realtime Regs: %s\n", cli_yesno(realtimeregs));
14701 ast_cli(a->fd, " Cache Friends: %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
14702 ast_cli(a->fd, " Update: %s\n", cli_yesno(sip_cfg.peer_rtupdate));
14703 ast_cli(a->fd, " Ignore Reg. Expire: %s\n", cli_yesno(sip_cfg.ignore_regexpire));
14704 ast_cli(a->fd, " Save sys. name: %s\n", cli_yesno(sip_cfg.rtsave_sysname));
14705 ast_cli(a->fd, " Auto Clear: %d\n", global_rtautoclear);
14706 }
14707 ast_cli(a->fd, "\n----\n");
14708 return CLI_SUCCESS;
14709 }
14710
14711
14712 static const char *subscription_type2str(enum subscriptiontype subtype)
14713 {
14714 int i;
14715
14716 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
14717 if (subscription_types[i].type == subtype) {
14718 return subscription_types[i].text;
14719 }
14720 }
14721 return subscription_types[0].text;
14722 }
14723
14724
14725 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
14726 {
14727 int i;
14728
14729 for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
14730 if (subscription_types[i].type == subtype) {
14731 return &subscription_types[i];
14732 }
14733 }
14734 return &subscription_types[0];
14735 }
14736
14737
14738
14739
14740
14741
14742
14743
14744 #define FORMAT4 "%-15.15s %-10.10s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6d\n"
14745 #define FORMAT3 "%-15.15s %-10.10s %-15.15s %-15.15s %-13.13s %-15.15s %-10.10s %-6.6s\n"
14746 #define FORMAT2 "%-15.15s %-10.10s %-15.15s %-15.15s %-7.7s %-15.15s %-6.6s\n"
14747 #define FORMAT "%-15.15s %-10.10s %-15.15s %-15.15s %-3.3s %-3.3s %-15.15s %-10.10s\n"
14748
14749
14750 static int show_channels_cb(void *__cur, void *__arg, int flags)
14751 {
14752 struct sip_pvt *cur = __cur;
14753 struct __show_chan_arg *arg = __arg;
14754 const struct sockaddr_in *dst = sip_real_dst(cur);
14755
14756
14757 if (cur->subscribed == NONE && !arg->subscriptions) {
14758
14759 const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
14760 char formatbuf[SIPBUFSIZE/2];
14761
14762 ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr),
14763 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
14764 cur->callid,
14765 ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
14766 cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
14767 cur->needdestroy ? "(d)" : "",
14768 cur->lastmsg ,
14769 referstatus
14770 );
14771 arg->numchans++;
14772 }
14773 if (cur->subscribed != NONE && arg->subscriptions) {
14774 struct ast_str *mailbox_str = ast_str_alloca(512);
14775 if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
14776 peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
14777 ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
14778 S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
14779 cur->callid,
14780
14781 cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
14782 cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
14783 subscription_type2str(cur->subscribed),
14784 cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
14785 cur->expiry
14786 );
14787 arg->numchans++;
14788 }
14789 return 0;
14790 }
14791
14792
14793
14794
14795
14796
14797 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14798 {
14799 struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
14800
14801
14802 if (cmd == CLI_INIT) {
14803 e->command = "sip show {channels|subscriptions}";
14804 e->usage =
14805 "Usage: sip show channels\n"
14806 " Lists all currently active SIP calls (dialogs).\n"
14807 "Usage: sip show subscriptions\n"
14808 " Lists active SIP subscriptions.\n";
14809 return NULL;
14810 } else if (cmd == CLI_GENERATE)
14811 return NULL;
14812
14813 if (a->argc != e->args)
14814 return CLI_SHOWUSAGE;
14815 arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
14816 if (!arg.subscriptions)
14817 ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
14818 else
14819 ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
14820
14821
14822 ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
14823
14824
14825 ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
14826 (arg.subscriptions ? "subscription" : "dialog"),
14827 ESS(arg.numchans));
14828 return CLI_SUCCESS;
14829 #undef FORMAT
14830 #undef FORMAT2
14831 #undef FORMAT3
14832 }
14833
14834
14835
14836
14837
14838
14839 static char *complete_sipch(const char *line, const char *word, int pos, int state)
14840 {
14841 int which=0;
14842 struct sip_pvt *cur;
14843 char *c = NULL;
14844 int wordlen = strlen(word);
14845 struct ao2_iterator i;
14846
14847 if (pos != 3) {
14848 return NULL;
14849 }
14850
14851 i = ao2_iterator_init(dialogs, 0);
14852
14853 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14854 sip_pvt_lock(cur);
14855 if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
14856 c = ast_strdup(cur->callid);
14857 sip_pvt_unlock(cur);
14858 dialog_unref(cur, "drop ref in iterator loop break");
14859 break;
14860 }
14861 sip_pvt_unlock(cur);
14862 dialog_unref(cur, "drop ref in iterator loop");
14863 }
14864 return c;
14865 }
14866
14867
14868
14869 static char *complete_sip_peer(const char *word, int state, int flags2)
14870 {
14871 char *result = NULL;
14872 int wordlen = strlen(word);
14873 int which = 0;
14874 struct ao2_iterator i = ao2_iterator_init(peers, 0);
14875 struct sip_peer *peer;
14876
14877 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14878
14879 if (!strncasecmp(word, peer->name, wordlen) &&
14880 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
14881 ++which > state)
14882 result = ast_strdup(peer->name);
14883 unref_peer(peer, "toss iterator peer ptr before break");
14884 if (result) {
14885 break;
14886 }
14887 }
14888 return result;
14889 }
14890
14891
14892 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
14893 {
14894 char *result = NULL;
14895 int wordlen = strlen(word);
14896 int which = 0;
14897 struct ao2_iterator i;
14898 struct sip_peer *peer;
14899
14900 i = ao2_iterator_init(peers, 0);
14901 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14902 if (!strncasecmp(word, peer->name, wordlen) &&
14903 (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
14904 ++which > state && peer->expire > 0)
14905 result = ast_strdup(peer->name);
14906 if (result) {
14907 unref_peer(peer, "toss iterator peer ptr before break");
14908 break;
14909 }
14910 unref_peer(peer, "toss iterator peer ptr");
14911 }
14912 return result;
14913 }
14914
14915
14916 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
14917 {
14918 if (pos == 3)
14919 return complete_sipch(line, word, pos, state);
14920
14921 return NULL;
14922 }
14923
14924
14925 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
14926 {
14927 if (pos == 3) {
14928 return complete_sip_peer(word, state, 0);
14929 }
14930
14931 return NULL;
14932 }
14933
14934
14935 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
14936 {
14937 if (pos == 2)
14938 return complete_sip_registered_peer(word, state, 0);
14939
14940 return NULL;
14941 }
14942
14943
14944 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
14945 {
14946 char *c = NULL;
14947
14948 if (pos == 2) {
14949 int which = 0;
14950 char *cat = NULL;
14951 int wordlen = strlen(word);
14952
14953
14954
14955 if (!notify_types)
14956 return NULL;
14957
14958 while ( (cat = ast_category_browse(notify_types, cat)) ) {
14959 if (!strncasecmp(word, cat, wordlen) && ++which > state) {
14960 c = ast_strdup(cat);
14961 break;
14962 }
14963 }
14964 return c;
14965 }
14966
14967 if (pos > 2)
14968 return complete_sip_peer(word, state, 0);
14969
14970 return NULL;
14971 }
14972
14973
14974 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14975 {
14976 struct sip_pvt *cur;
14977 size_t len;
14978 int found = 0;
14979 struct ao2_iterator i;
14980
14981 switch (cmd) {
14982 case CLI_INIT:
14983 e->command = "sip show channel";
14984 e->usage =
14985 "Usage: sip show channel <call-id>\n"
14986 " Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
14987 return NULL;
14988 case CLI_GENERATE:
14989 return complete_sipch(a->line, a->word, a->pos, a->n);
14990 }
14991
14992 if (a->argc != 4)
14993 return CLI_SHOWUSAGE;
14994 len = strlen(a->argv[3]);
14995
14996 i = ao2_iterator_init(dialogs, 0);
14997
14998 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
14999 sip_pvt_lock(cur);
15000
15001 if (!strncasecmp(cur->callid, a->argv[3], len)) {
15002 char formatbuf[SIPBUFSIZE/2];
15003 ast_cli(a->fd, "\n");
15004 if (cur->subscribed != NONE)
15005 ast_cli(a->fd, " * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
15006 else
15007 ast_cli(a->fd, " * SIP Call\n");
15008 ast_cli(a->fd, " Curr. trans. direction: %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
15009 ast_cli(a->fd, " Call-ID: %s\n", cur->callid);
15010 ast_cli(a->fd, " Owner channel ID: %s\n", cur->owner ? cur->owner->name : "<none>");
15011 ast_cli(a->fd, " Our Codec Capability: %d\n", cur->capability);
15012 ast_cli(a->fd, " Non-Codec Capability (DTMF): %d\n", cur->noncodeccapability);
15013 ast_cli(a->fd, " Their Codec Capability: %d\n", cur->peercapability);
15014 ast_cli(a->fd, " Joint Codec Capability: %d\n", cur->jointcapability);
15015 ast_cli(a->fd, " Format: %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
15016 ast_cli(a->fd, " T.38 support %s\n", cli_yesno(cur->udptl != NULL));
15017 ast_cli(a->fd, " Video support %s\n", cli_yesno(cur->vrtp != NULL));
15018 ast_cli(a->fd, " MaxCallBR: %d kbps\n", cur->maxcallbitrate);
15019 ast_cli(a->fd, " Theoretical Address: %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
15020 ast_cli(a->fd, " Received Address: %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
15021 ast_cli(a->fd, " SIP Transfer mode: %s\n", transfermode2str(cur->allowtransfer));
15022 ast_cli(a->fd, " NAT Support: %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
15023 ast_cli(a->fd, " Audio IP: %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
15024 ast_cli(a->fd, " Our Tag: %s\n", cur->tag);
15025 ast_cli(a->fd, " Their Tag: %s\n", cur->theirtag);
15026 ast_cli(a->fd, " SIP User agent: %s\n", cur->useragent);
15027 if (!ast_strlen_zero(cur->username))
15028 ast_cli(a->fd, " Username: %s\n", cur->username);
15029 if (!ast_strlen_zero(cur->peername))
15030 ast_cli(a->fd, " Peername: %s\n", cur->peername);
15031 if (!ast_strlen_zero(cur->uri))
15032 ast_cli(a->fd, " Original uri: %s\n", cur->uri);
15033 if (!ast_strlen_zero(cur->cid_num))
15034 ast_cli(a->fd, " Caller-ID: %s\n", cur->cid_num);
15035 ast_cli(a->fd, " Need Destroy: %s\n", cli_yesno(cur->needdestroy));
15036 ast_cli(a->fd, " Last Message: %s\n", cur->lastmsg);
15037 ast_cli(a->fd, " Promiscuous Redir: %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
15038 ast_cli(a->fd, " Route: %s\n", cur->route ? cur->route->hop : "N/A");
15039 ast_cli(a->fd, " DTMF Mode: %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
15040 ast_cli(a->fd, " SIP Options: ");
15041 if (cur->sipoptions) {
15042 int x;
15043 for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15044 if (cur->sipoptions & sip_options[x].id)
15045 ast_cli(a->fd, "%s ", sip_options[x].text);
15046 }
15047 ast_cli(a->fd, "\n");
15048 } else
15049 ast_cli(a->fd, "(none)\n");
15050
15051 if (!cur->stimer)
15052 ast_cli(a->fd, " Session-Timer: Uninitiallized\n");
15053 else {
15054 ast_cli(a->fd, " Session-Timer: %s\n", cur->stimer->st_active ? "Active" : "Inactive");
15055 if (cur->stimer->st_active == TRUE) {
15056 ast_cli(a->fd, " S-Timer Interval: %d\n", cur->stimer->st_interval);
15057 ast_cli(a->fd, " S-Timer Refresher: %s\n", strefresher2str(cur->stimer->st_ref));
15058 ast_cli(a->fd, " S-Timer Expirys: %d\n", cur->stimer->st_expirys);
15059 ast_cli(a->fd, " S-Timer Sched Id: %d\n", cur->stimer->st_schedid);
15060 ast_cli(a->fd, " S-Timer Peer Sts: %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
15061 ast_cli(a->fd, " S-Timer Cached Min-SE: %d\n", cur->stimer->st_cached_min_se);
15062 ast_cli(a->fd, " S-Timer Cached SE: %d\n", cur->stimer->st_cached_max_se);
15063 ast_cli(a->fd, " S-Timer Cached Ref: %s\n", strefresher2str(cur->stimer->st_cached_ref));
15064 ast_cli(a->fd, " S-Timer Cached Mode: %s\n", stmode2str(cur->stimer->st_cached_mode));
15065 }
15066 }
15067
15068 ast_cli(a->fd, "\n\n");
15069
15070 found++;
15071 }
15072
15073 sip_pvt_unlock(cur);
15074
15075 ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
15076 }
15077
15078 if (!found)
15079 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15080
15081 return CLI_SUCCESS;
15082 }
15083
15084
15085 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15086 {
15087 struct sip_pvt *cur;
15088 size_t len;
15089 int found = 0;
15090 struct ao2_iterator i;
15091
15092 switch (cmd) {
15093 case CLI_INIT:
15094 e->command = "sip show history";
15095 e->usage =
15096 "Usage: sip show history <call-id>\n"
15097 " Provides detailed dialog history on a given SIP call (specified by call-id).\n";
15098 return NULL;
15099 case CLI_GENERATE:
15100 return complete_sip_show_history(a->line, a->word, a->pos, a->n);
15101 }
15102
15103 if (a->argc != 4)
15104 return CLI_SHOWUSAGE;
15105
15106 if (!recordhistory)
15107 ast_cli(a->fd, "\n***Note: History recording is currently DISABLED. Use 'sip set history on' to ENABLE.\n");
15108
15109 len = strlen(a->argv[3]);
15110
15111 i = ao2_iterator_init(dialogs, 0);
15112 while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15113 sip_pvt_lock(cur);
15114 if (!strncasecmp(cur->callid, a->argv[3], len)) {
15115 struct sip_history *hist;
15116 int x = 0;
15117
15118 ast_cli(a->fd, "\n");
15119 if (cur->subscribed != NONE)
15120 ast_cli(a->fd, " * Subscription\n");
15121 else
15122 ast_cli(a->fd, " * SIP Call\n");
15123 if (cur->history)
15124 AST_LIST_TRAVERSE(cur->history, hist, list)
15125 ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
15126 if (x == 0)
15127 ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
15128 found++;
15129 }
15130 sip_pvt_unlock(cur);
15131 ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
15132 }
15133
15134 if (!found)
15135 ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15136
15137 return CLI_SUCCESS;
15138 }
15139
15140
15141 static void sip_dump_history(struct sip_pvt *dialog)
15142 {
15143 int x = 0;
15144 struct sip_history *hist;
15145 static int errmsg = 0;
15146
15147 if (!dialog)
15148 return;
15149
15150 if (!option_debug && !sipdebug) {
15151 if (!errmsg) {
15152 ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
15153 errmsg = 1;
15154 }
15155 return;
15156 }
15157
15158 ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
15159 if (dialog->subscribed)
15160 ast_debug(1, " * Subscription\n");
15161 else
15162 ast_debug(1, " * SIP Call\n");
15163 if (dialog->history)
15164 AST_LIST_TRAVERSE(dialog->history, hist, list)
15165 ast_debug(1, " %-3.3d. %s\n", ++x, hist->event);
15166 if (!x)
15167 ast_debug(1, "Call '%s' has no history\n", dialog->callid);
15168 ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
15169 }
15170
15171
15172
15173 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
15174 {
15175 char buf[1024];
15176 unsigned int event;
15177 const char *c = get_header(req, "Content-Type");
15178
15179
15180 if (!strcasecmp(c, "application/dtmf-relay") ||
15181 !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
15182 unsigned int duration = 0;
15183
15184 if (!p->owner) {
15185 transmit_response(p, "481 Call leg/transaction does not exist", req);
15186 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15187 return;
15188 }
15189
15190
15191 if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
15192 ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
15193 transmit_response(p, "200 OK", req);
15194 return;
15195 } else {
15196 ast_copy_string(buf, c, sizeof(buf));
15197 }
15198
15199 if (!ast_strlen_zero((c = get_body(req, "Duration"))))
15200 duration = atoi(c);
15201 if (!duration)
15202 duration = 100;
15203
15204
15205 if (ast_strlen_zero(buf)) {
15206 transmit_response(p, "200 OK", req);
15207 return;
15208 }
15209
15210 if (buf[0] == '*')
15211 event = 10;
15212 else if (buf[0] == '#')
15213 event = 11;
15214 else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
15215 event = 12 + buf[0] - 'A';
15216 else if (buf[0] == '!')
15217 event = 16;
15218 else
15219 event = atoi(buf);
15220 if (event == 16) {
15221
15222 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15223 ast_queue_frame(p->owner, &f);
15224 if (sipdebug)
15225 ast_verbose("* DTMF-relay event received: FLASH\n");
15226 } else {
15227
15228 struct ast_frame f = { AST_FRAME_DTMF, };
15229 if (event < 10) {
15230 f.subclass = '0' + event;
15231 } else if (event < 11) {
15232 f.subclass = '*';
15233 } else if (event < 12) {
15234 f.subclass = '#';
15235 } else if (event < 16) {
15236 f.subclass = 'A' + (event - 12);
15237 }
15238 f.len = duration;
15239 ast_queue_frame(p->owner, &f);
15240 if (sipdebug)
15241 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15242 }
15243 transmit_response(p, "200 OK", req);
15244 return;
15245 } else if (!strcasecmp(c, "application/dtmf")) {
15246
15247 unsigned int duration = 0;
15248
15249 if (!p->owner) {
15250 transmit_response(p, "481 Call leg/transaction does not exist", req);
15251 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15252 return;
15253 }
15254
15255 get_msg_text(buf, sizeof(buf), req, TRUE);
15256 duration = 100;
15257
15258 if (ast_strlen_zero(buf)) {
15259 transmit_response(p, "200 OK", req);
15260 return;
15261 }
15262 event = atoi(buf);
15263 if (event == 16) {
15264
15265 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15266 ast_queue_frame(p->owner, &f);
15267 if (sipdebug)
15268 ast_verbose("* DTMF-relay event received: FLASH\n");
15269 } else {
15270
15271 struct ast_frame f = { AST_FRAME_DTMF, };
15272 if (event < 10) {
15273 f.subclass = '0' + event;
15274 } else if (event < 11) {
15275 f.subclass = '*';
15276 } else if (event < 12) {
15277 f.subclass = '#';
15278 } else if (event < 16) {
15279 f.subclass = 'A' + (event - 12);
15280 }
15281 f.len = duration;
15282 ast_queue_frame(p->owner, &f);
15283 if (sipdebug)
15284 ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15285 }
15286 transmit_response(p, "200 OK", req);
15287 return;
15288
15289 } else if (!strcasecmp(c, "application/media_control+xml")) {
15290
15291 if (p->owner)
15292 ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
15293 transmit_response(p, "200 OK", req);
15294 return;
15295 } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
15296
15297 if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
15298 if (p->owner && p->owner->cdr)
15299 ast_cdr_setuserfield(p->owner, c);
15300 if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
15301 ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
15302 transmit_response(p, "200 OK", req);
15303 } else {
15304 transmit_response(p, "403 Forbidden", req);
15305 }
15306 return;
15307 } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
15308
15309
15310
15311
15312
15313
15314
15315 struct ast_call_feature *feat;
15316 int j;
15317 struct ast_frame f = { AST_FRAME_DTMF, };
15318
15319 ast_rdlock_call_features();
15320 feat = ast_find_call_feature("automon");
15321 if (!feat || ast_strlen_zero(feat->exten)) {
15322 ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
15323
15324 transmit_response(p, "403 Forbidden", req);
15325 ast_unlock_call_features();
15326 return;
15327 }
15328
15329 f.len = 100;
15330 for (j=0; j < strlen(feat->exten); j++) {
15331 f.subclass = feat->exten[j];
15332 ast_queue_frame(p->owner, &f);
15333 if (sipdebug)
15334 ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
15335 }
15336 ast_unlock_call_features();
15337
15338 ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
15339 transmit_response(p, "200 OK", req);
15340 return;
15341 } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
15342
15343 transmit_response(p, "200 OK", req);
15344 return;
15345 }
15346
15347
15348
15349
15350 ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
15351 transmit_response(p, "415 Unsupported media type", req);
15352 return;
15353 }
15354
15355
15356 static char *sip_do_debug_ip(int fd, char *arg)
15357 {
15358 struct hostent *hp;
15359 struct ast_hostent ahp;
15360 int port = 0;
15361 char *p;
15362
15363 p = arg;
15364 strsep(&p, ":");
15365 if (p)
15366 port = atoi(p);
15367 hp = ast_gethostbyname(arg, &ahp);
15368 if (hp == NULL)
15369 return CLI_SHOWUSAGE;
15370
15371 debugaddr.sin_family = AF_INET;
15372 memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
15373 debugaddr.sin_port = htons(port);
15374 if (port == 0)
15375 ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
15376 else
15377 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
15378
15379 sipdebug |= sip_debug_console;
15380
15381 return CLI_SUCCESS;
15382 }
15383
15384
15385 static char *sip_do_debug_peer(int fd, char *arg)
15386 {
15387 struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE);
15388 if (!peer)
15389 ast_cli(fd, "No such peer '%s'\n", arg);
15390 else if (peer->addr.sin_addr.s_addr == 0)
15391 ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
15392 else {
15393 debugaddr.sin_family = AF_INET;
15394 debugaddr.sin_addr = peer->addr.sin_addr;
15395 debugaddr.sin_port = peer->addr.sin_port;
15396 ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
15397 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
15398 sipdebug |= sip_debug_console;
15399 }
15400 if (peer)
15401 unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
15402 return CLI_SUCCESS;
15403 }
15404
15405
15406 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15407 {
15408 int oldsipdebug = sipdebug & sip_debug_console;
15409 char *what;
15410
15411 if (cmd == CLI_INIT) {
15412 e->command = "sip set debug {on|off|ip|peer}";
15413 e->usage =
15414 "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
15415 " Globally disables dumping of SIP packets,\n"
15416 " or enables it either globally or for a (single)\n"
15417 " IP address or registered peer.\n";
15418 return NULL;
15419 } else if (cmd == CLI_GENERATE) {
15420 if (a->pos == 4 && strcasestr(a->line, " peer"))
15421 return complete_sip_peer(a->word, a->n, 0);
15422 return NULL;
15423 }
15424
15425 what = a->argv[e->args-1];
15426 if (a->argc == e->args) {
15427 if (!strcasecmp(what, "on")) {
15428 sipdebug |= sip_debug_console;
15429 sipdebug_text = 1;
15430 memset(&debugaddr, 0, sizeof(debugaddr));
15431 ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
15432 return CLI_SUCCESS;
15433 } else if (!strcasecmp(what, "off")) {
15434 sipdebug &= ~sip_debug_console;
15435 sipdebug_text = 0;
15436 ast_cli(a->fd, "SIP Debugging Disabled\n");
15437 return CLI_SUCCESS;
15438 }
15439 } else if (a->argc == e->args +1) {
15440 if (!strcasecmp(what, "ip"))
15441 return sip_do_debug_ip(a->fd, a->argv[e->args]);
15442 else if (!strcasecmp(what, "peer"))
15443 return sip_do_debug_peer(a->fd, a->argv[e->args]);
15444 }
15445 return CLI_SHOWUSAGE;
15446 }
15447
15448
15449 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15450 {
15451 struct ast_variable *varlist;
15452 int i;
15453
15454 switch (cmd) {
15455 case CLI_INIT:
15456 e->command = "sip notify";
15457 e->usage =
15458 "Usage: sip notify <type> <peer> [<peer>...]\n"
15459 " Send a NOTIFY message to a SIP peer or peers\n"
15460 " Message types are defined in sip_notify.conf\n";
15461 return NULL;
15462 case CLI_GENERATE:
15463 return complete_sipnotify(a->line, a->word, a->pos, a->n);
15464 }
15465
15466 if (a->argc < 4)
15467 return CLI_SHOWUSAGE;
15468
15469 if (!notify_types) {
15470 ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
15471 return CLI_FAILURE;
15472 }
15473
15474 varlist = ast_variable_browse(notify_types, a->argv[2]);
15475
15476 if (!varlist) {
15477 ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
15478 return CLI_FAILURE;
15479 }
15480
15481 for (i = 3; i < a->argc; i++) {
15482 struct sip_pvt *p;
15483
15484 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
15485 ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
15486 return CLI_FAILURE;
15487 }
15488
15489 if (create_addr(p, a->argv[i], NULL, 1)) {
15490
15491 dialog_unlink_all(p, TRUE, TRUE);
15492 dialog_unref(p, "unref dialog inside for loop" );
15493
15494 ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
15495 continue;
15496 }
15497
15498
15499 ast_set_flag(&p->flags[0], SIP_OUTGOING);
15500
15501
15502 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
15503 build_via(p);
15504 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
15505 build_callid_pvt(p);
15506 ao2_t_link(dialogs, p, "Linking in new name");
15507 ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
15508 dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
15509 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
15510 transmit_notify_custom(p, varlist);
15511 }
15512
15513 return CLI_SUCCESS;
15514 }
15515
15516
15517 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15518 {
15519 switch (cmd) {
15520 case CLI_INIT:
15521 e->command = "sip history [off]";
15522 e->usage =
15523 "Usage: sip history [off]\n"
15524 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
15525 " Use 'sip show history' to view the history of a call number.\n";
15526 return NULL;
15527 case CLI_GENERATE:
15528 return NULL;
15529 }
15530
15531 if (a->argc < 2 || a->argc > 3) {
15532 return CLI_SHOWUSAGE;
15533 }
15534 if (a->argc == 2) {
15535 recordhistory = TRUE;
15536 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
15537 } else {
15538 if (strncasecmp(a->argv[2], "off", 3))
15539 return CLI_SHOWUSAGE;
15540 recordhistory = FALSE;
15541 ast_cli(a->fd, "SIP History Recording Disabled\n");
15542 }
15543 return CLI_SUCCESS;
15544 }
15545
15546
15547 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15548 {
15549 switch (cmd) {
15550 case CLI_INIT:
15551 e->command = "sip set history {on|off}";
15552 e->usage =
15553 "Usage: sip set history {on|off}\n"
15554 " Enables/Disables recording of SIP dialog history for debugging purposes.\n"
15555 " Use 'sip show history' to view the history of a call number.\n";
15556 return NULL;
15557 case CLI_GENERATE:
15558 return NULL;
15559 }
15560
15561 if (a->argc != e->args)
15562 return CLI_SHOWUSAGE;
15563
15564 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
15565 recordhistory = TRUE;
15566 ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
15567 } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
15568 recordhistory = FALSE;
15569 ast_cli(a->fd, "SIP History Recording Disabled\n");
15570 } else {
15571 return CLI_SHOWUSAGE;
15572 }
15573 return CLI_SUCCESS;
15574 }
15575
15576
15577 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
15578 {
15579 char *header, *respheader;
15580 char digest[1024];
15581
15582 p->authtries++;
15583 auth_headers(code, &header, &respheader);
15584 memset(digest, 0, sizeof(digest));
15585 if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
15586
15587
15588 if (sip_debug_test_pvt(p) && p->registry)
15589 ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
15590
15591 return -1;
15592 }
15593 if (p->do_history)
15594 append_history(p, "RegistryAuth", "Try: %d", p->authtries);
15595 if (sip_debug_test_pvt(p) && p->registry)
15596 ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
15597 return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
15598 }
15599
15600
15601 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
15602 {
15603 char *header, *respheader;
15604 char digest[1024];
15605
15606 if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
15607 return -2;
15608
15609 p->authtries++;
15610 auth_headers(code, &header, &respheader);
15611 ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
15612 memset(digest, 0, sizeof(digest));
15613 if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
15614
15615 return -1;
15616 }
15617
15618 p->options->auth = digest;
15619 p->options->authheader = respheader;
15620 return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init);
15621 }
15622
15623
15624
15625
15626
15627 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len)
15628 {
15629 char tmp[512];
15630 char *c;
15631 char oldnonce[256];
15632
15633
15634 const struct x {
15635 const char *key;
15636 const ast_string_field *field;
15637 } *i, keys[] = {
15638 { "realm=", &p->realm },
15639 { "nonce=", &p->nonce },
15640 { "opaque=", &p->opaque },
15641 { "qop=", &p->qop },
15642 { "domain=", &p->domain },
15643 { NULL, 0 },
15644 };
15645
15646 ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
15647 if (ast_strlen_zero(tmp))
15648 return -1;
15649 if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
15650 ast_log(LOG_WARNING, "missing Digest.\n");
15651 return -1;
15652 }
15653 c = tmp + strlen("Digest ");
15654 ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
15655 while (c && *(c = ast_skip_blanks(c))) {
15656 for (i = keys; i->key != NULL; i++) {
15657 char *src, *separator;
15658 if (strncasecmp(c, i->key, strlen(i->key)) != 0)
15659 continue;
15660
15661 c += strlen(i->key);
15662 if (*c == '"') {
15663 src = ++c;
15664 separator = "\"";
15665 } else {
15666 src = c;
15667 separator = ",";
15668 }
15669 strsep(&c, separator);
15670 ast_string_field_ptr_set(p, i->field, src);
15671 break;
15672 }
15673 if (i->key == NULL)
15674 strsep(&c, ",");
15675 }
15676
15677 if (strcmp(p->nonce, oldnonce))
15678 p->noncecount = 0;
15679
15680
15681 if (p->registry) {
15682 struct sip_registry *r = p->registry;
15683
15684 if (strcmp(r->nonce, p->nonce)) {
15685 ast_string_field_set(r, realm, p->realm);
15686 ast_string_field_set(r, nonce, p->nonce);
15687 ast_string_field_set(r, domain, p->domain);
15688 ast_string_field_set(r, opaque, p->opaque);
15689 ast_string_field_set(r, qop, p->qop);
15690 r->noncecount = 0;
15691 }
15692 }
15693 return build_reply_digest(p, sipmethod, digest, digest_len);
15694 }
15695
15696
15697
15698
15699
15700
15701 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
15702 {
15703 char a1[256];
15704 char a2[256];
15705 char a1_hash[256];
15706 char a2_hash[256];
15707 char resp[256];
15708 char resp_hash[256];
15709 char uri[256];
15710 char opaque[256] = "";
15711 char cnonce[80];
15712 const char *username;
15713 const char *secret;
15714 const char *md5secret;
15715 struct sip_auth *auth = NULL;
15716
15717 if (!ast_strlen_zero(p->domain))
15718 ast_copy_string(uri, p->domain, sizeof(uri));
15719 else if (!ast_strlen_zero(p->uri))
15720 ast_copy_string(uri, p->uri, sizeof(uri));
15721 else
15722 snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
15723
15724 snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
15725
15726
15727 if(!(auth = find_realm_authentication(p->peerauth, p->realm)))
15728 auth = find_realm_authentication(authl, p->realm);
15729
15730 if (auth) {
15731 ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
15732 username = auth->username;
15733 secret = auth->secret;
15734 md5secret = auth->md5secret;
15735 if (sipdebug)
15736 ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
15737 } else {
15738
15739 username = p->authname;
15740 secret = p->peersecret;
15741 md5secret = p->peermd5secret;
15742 }
15743 if (ast_strlen_zero(username))
15744 return -1;
15745
15746
15747 snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
15748 snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
15749 if (!ast_strlen_zero(md5secret))
15750 ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
15751 else
15752 ast_md5_hash(a1_hash, a1);
15753 ast_md5_hash(a2_hash, a2);
15754
15755 p->noncecount++;
15756 if (!ast_strlen_zero(p->qop))
15757 snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
15758 else
15759 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
15760 ast_md5_hash(resp_hash, resp);
15761
15762
15763 if (!ast_strlen_zero(p->opaque)) {
15764 snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
15765 }
15766
15767
15768 if (!ast_strlen_zero(p->qop))
15769 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
15770 else
15771 snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
15772
15773 append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
15774
15775 return 0;
15776 }
15777
15778
15779 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
15780 {
15781 struct sip_pvt *p;
15782 const char *content = NULL;
15783 AST_DECLARE_APP_ARGS(args,
15784 AST_APP_ARG(header);
15785 AST_APP_ARG(number);
15786 );
15787 int i, number, start = 0;
15788
15789 if (ast_strlen_zero(data)) {
15790 ast_log(LOG_WARNING, "This function requires a header name.\n");
15791 return -1;
15792 }
15793
15794 ast_channel_lock(chan);
15795 if (!IS_SIP_TECH(chan->tech)) {
15796 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
15797 ast_channel_unlock(chan);
15798 return -1;
15799 }
15800
15801 AST_STANDARD_APP_ARGS(args, data);
15802 if (!args.number) {
15803 number = 1;
15804 } else {
15805 sscanf(args.number, "%30d", &number);
15806 if (number < 1)
15807 number = 1;
15808 }
15809
15810 p = chan->tech_pvt;
15811
15812
15813 if (!p) {
15814 ast_channel_unlock(chan);
15815 return -1;
15816 }
15817
15818 for (i = 0; i < number; i++)
15819 content = __get_header(&p->initreq, args.header, &start);
15820
15821 if (ast_strlen_zero(content)) {
15822 ast_channel_unlock(chan);
15823 return -1;
15824 }
15825
15826 ast_copy_string(buf, content, len);
15827 ast_channel_unlock(chan);
15828
15829 return 0;
15830 }
15831
15832 static struct ast_custom_function sip_header_function = {
15833 .name = "SIP_HEADER",
15834 .synopsis = "Gets the specified SIP header",
15835 .syntax = "SIP_HEADER(<name>[,<number>])",
15836 .desc = "Since there are several headers (such as Via) which can occur multiple\n"
15837 "times, SIP_HEADER takes an optional second argument to specify which header with\n"
15838 "that name to retrieve. Headers start at offset 1.\n",
15839 .read = func_header_read,
15840 };
15841
15842
15843 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15844 {
15845 if (ast_strlen_zero(data)) {
15846 ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
15847 return -1;
15848 }
15849 if (check_sip_domain(data, NULL, 0))
15850 ast_copy_string(buf, data, len);
15851 else
15852 buf[0] = '\0';
15853 return 0;
15854 }
15855
15856 static struct ast_custom_function checksipdomain_function = {
15857 .name = "CHECKSIPDOMAIN",
15858 .synopsis = "Checks if domain is a local domain",
15859 .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
15860 .read = func_check_sipdomain,
15861 .desc = "This function checks if the domain in the argument is configured\n"
15862 "as a local SIP domain that this Asterisk server is configured to handle.\n"
15863 "Returns the domain name if it is locally handled, otherwise an empty string.\n"
15864 "Check the domain= configuration in sip.conf\n",
15865 };
15866
15867
15868 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15869 {
15870 struct sip_peer *peer;
15871 char *colname;
15872
15873 if ((colname = strchr(data, ':'))) {
15874 static int deprecation_warning = 0;
15875 *colname++ = '\0';
15876 if (deprecation_warning++ % 10 == 0)
15877 ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated. Please use ',' instead.\n");
15878 } else if ((colname = strchr(data, ',')))
15879 *colname++ = '\0';
15880 else
15881 colname = "ip";
15882
15883 if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE)))
15884 return -1;
15885
15886 if (!strcasecmp(colname, "ip")) {
15887 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
15888 } else if (!strcasecmp(colname, "port")) {
15889 snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
15890 } else if (!strcasecmp(colname, "status")) {
15891 peer_status(peer, buf, len);
15892 } else if (!strcasecmp(colname, "language")) {
15893 ast_copy_string(buf, peer->language, len);
15894 } else if (!strcasecmp(colname, "regexten")) {
15895 ast_copy_string(buf, peer->regexten, len);
15896 } else if (!strcasecmp(colname, "limit")) {
15897 snprintf(buf, len, "%d", peer->call_limit);
15898 } else if (!strcasecmp(colname, "busylevel")) {
15899 snprintf(buf, len, "%d", peer->busy_level);
15900 } else if (!strcasecmp(colname, "curcalls")) {
15901 snprintf(buf, len, "%d", peer->inUse);
15902 } else if (!strcasecmp(colname, "accountcode")) {
15903 ast_copy_string(buf, peer->accountcode, len);
15904 } else if (!strcasecmp(colname, "callgroup")) {
15905 ast_print_group(buf, len, peer->callgroup);
15906 } else if (!strcasecmp(colname, "pickupgroup")) {
15907 ast_print_group(buf, len, peer->pickupgroup);
15908 } else if (!strcasecmp(colname, "useragent")) {
15909 ast_copy_string(buf, peer->useragent, len);
15910 } else if (!strcasecmp(colname, "mailbox")) {
15911 struct ast_str *mailbox_str = ast_str_alloca(512);
15912 peer_mailboxes_to_str(&mailbox_str, peer);
15913 ast_copy_string(buf, mailbox_str->str, len);
15914 } else if (!strcasecmp(colname, "context")) {
15915 ast_copy_string(buf, peer->context, len);
15916 } else if (!strcasecmp(colname, "expire")) {
15917 snprintf(buf, len, "%d", peer->expire);
15918 } else if (!strcasecmp(colname, "dynamic")) {
15919 ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
15920 } else if (!strcasecmp(colname, "callerid_name")) {
15921 ast_copy_string(buf, peer->cid_name, len);
15922 } else if (!strcasecmp(colname, "callerid_num")) {
15923 ast_copy_string(buf, peer->cid_num, len);
15924 } else if (!strcasecmp(colname, "codecs")) {
15925 ast_getformatname_multiple(buf, len -1, peer->capability);
15926 } else if (!strncasecmp(colname, "chanvar[", 8)) {
15927 char *chanvar=colname + 8;
15928 struct ast_variable *v;
15929
15930 chanvar = strsep(&chanvar, "]");
15931 for (v = peer->chanvars ; v ; v = v->next)
15932 if (!strcasecmp(v->name, chanvar))
15933 ast_copy_string(buf, v->value, len);
15934 } else if (!strncasecmp(colname, "codec[", 6)) {
15935 char *codecnum;
15936 int codec = 0;
15937
15938 codecnum = colname + 6;
15939 codecnum = strsep(&codecnum, "]");
15940 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
15941 ast_copy_string(buf, ast_getformatname(codec), len);
15942 } else {
15943 buf[0] = '\0';
15944 }
15945 } else {
15946 buf[0] = '\0';
15947 }
15948
15949 unref_peer(peer, "unref_peer from function_sippeer, just before return");
15950
15951 return 0;
15952 }
15953
15954
15955 struct ast_custom_function sippeer_function = {
15956 .name = "SIPPEER",
15957 .synopsis = "Gets SIP peer information",
15958 .syntax = "SIPPEER(<peername>[,item])",
15959 .read = function_sippeer,
15960 .desc = "Valid items are:\n"
15961 "- ip (default) The IP address.\n"
15962 "- port The port number\n"
15963 "- mailbox The configured mailbox.\n"
15964 "- context The configured context.\n"
15965 "- expire The epoch time of the next expire.\n"
15966 "- dynamic Is it dynamic? (yes/no).\n"
15967 "- callerid_name The configured Caller ID name.\n"
15968 "- callerid_num The configured Caller ID number.\n"
15969 "- callgroup The configured Callgroup.\n"
15970 "- pickupgroup The configured Pickupgroup.\n"
15971 "- codecs The configured codecs.\n"
15972 "- status Status (if qualify=yes).\n"
15973 "- regexten Registration extension\n"
15974 "- limit Call limit (call-limit)\n"
15975 "- busylevel Configured call level for signalling busy\n"
15976 "- curcalls Current amount of calls \n"
15977 " Only available if call-limit is set\n"
15978 "- language Default language for peer\n"
15979 "- accountcode Account code for this peer\n"
15980 "- useragent Current user agent id for peer\n"
15981 "- chanvar[name] A channel variable configured with setvar for this peer.\n"
15982 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
15983 "\n"
15984 };
15985
15986
15987 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
15988 {
15989 struct sip_pvt *p;
15990 static int deprecated = 0;
15991
15992 *buf = 0;
15993
15994 if (!data) {
15995 ast_log(LOG_WARNING, "This function requires a parameter name.\n");
15996 return -1;
15997 }
15998
15999 ast_channel_lock(chan);
16000 if (!IS_SIP_TECH(chan->tech)) {
16001 ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
16002 ast_channel_unlock(chan);
16003 return -1;
16004 }
16005
16006 if (deprecated++ % 20 == 0) {
16007
16008 ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated. Please transition to using CHANNEL().\n");
16009 }
16010
16011 p = chan->tech_pvt;
16012
16013
16014 if (!p) {
16015 ast_channel_unlock(chan);
16016 return -1;
16017 }
16018
16019 if (!strcasecmp(data, "peerip")) {
16020 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
16021 } else if (!strcasecmp(data, "recvip")) {
16022 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
16023 } else if (!strcasecmp(data, "from")) {
16024 ast_copy_string(buf, p->from, len);
16025 } else if (!strcasecmp(data, "uri")) {
16026 ast_copy_string(buf, p->uri, len);
16027 } else if (!strcasecmp(data, "useragent")) {
16028 ast_copy_string(buf, p->useragent, len);
16029 } else if (!strcasecmp(data, "peername")) {
16030 ast_copy_string(buf, p->peername, len);
16031 } else if (!strcasecmp(data, "t38passthrough")) {
16032 if (p->t38.state == T38_DISABLED)
16033 ast_copy_string(buf, "0", sizeof("0"));
16034 else
16035 ast_copy_string(buf, "1", sizeof("1"));
16036 } else {
16037 ast_channel_unlock(chan);
16038 return -1;
16039 }
16040 ast_channel_unlock(chan);
16041
16042 return 0;
16043 }
16044
16045
16046 static struct ast_custom_function sipchaninfo_function = {
16047 .name = "SIPCHANINFO",
16048 .synopsis = "Gets the specified SIP parameter from the current channel",
16049 .syntax = "SIPCHANINFO(item)",
16050 .read = function_sipchaninfo_read,
16051 .desc = "Valid items are:\n"
16052 "- peerip The IP address of the peer.\n"
16053 "- recvip The source IP address of the peer.\n"
16054 "- from The URI from the From: header.\n"
16055 "- uri The URI from the Contact: header.\n"
16056 "- useragent The useragent.\n"
16057 "- peername The name of the peer.\n"
16058 "- t38passthrough 1 if T38 is offered or enabled in this channel, otherwise 0\n"
16059 };
16060
16061
16062 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
16063 {
16064 char tmp[SIPBUFSIZE];
16065 char *s, *e, *t, *trans;
16066 char *domain;
16067 enum sip_transport transport = SIP_TRANSPORT_UDP;
16068
16069 ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
16070 if ((t = strchr(tmp, ',')))
16071 *t = '\0';
16072
16073 s = get_in_brackets(tmp);
16074 if ((trans = strcasestr(s, ";transport="))) do {
16075 trans += 11;
16076
16077 if ((e = strchr(trans, ';')))
16078 *e = '\0';
16079
16080 if (!strncasecmp(trans, "tcp", 3))
16081 transport = SIP_TRANSPORT_TCP;
16082 else if (!strncasecmp(trans, "tls", 3))
16083 transport = SIP_TRANSPORT_TLS;
16084 else {
16085 if (strncasecmp(trans, "udp", 3))
16086 ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
16087 transport = SIP_TRANSPORT_UDP;
16088 }
16089 } while(0);
16090 s = remove_uri_parameters(s);
16091
16092 if (p->socket.tcptls_session) {
16093 ao2_ref(p->socket.tcptls_session, -1);
16094 p->socket.tcptls_session = NULL;
16095 }
16096
16097 set_socket_transport(&p->socket, transport);
16098
16099 if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
16100 char *host = NULL;
16101 if (!strncasecmp(s, "sip:", 4))
16102 s += 4;
16103 else if (!strncasecmp(s, "sips:", 5))
16104 s += 5;
16105 e = strchr(s, '/');
16106 if (e)
16107 *e = '\0';
16108 if ((host = strchr(s, '@'))) {
16109 *host++ = '\0';
16110 ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
16111 if (p->owner)
16112 ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
16113 } else {
16114 ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
16115 if (p->owner)
16116 ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
16117 }
16118 } else {
16119 e = strchr(tmp, '@');
16120 if (e) {
16121 *e++ = '\0';
16122 domain = e;
16123 } else {
16124
16125 domain = tmp;
16126 }
16127 e = strchr(tmp, '/');
16128 if (e)
16129 *e = '\0';
16130
16131 if (!strncasecmp(s, "sip:", 4))
16132 s += 4;
16133 else if (!strncasecmp(s, "sips:", 5))
16134 s += 5;
16135 e = strchr(s, ';');
16136 if (e)
16137 *e = '\0';
16138 ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
16139 if (p->owner) {
16140 pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
16141 ast_string_field_set(p->owner, call_forward, s);
16142 }
16143 }
16144 }
16145
16146
16147 static void check_pendings(struct sip_pvt *p)
16148 {
16149 if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16150
16151 if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
16152 transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
16153
16154
16155 else {
16156
16157
16158 if (p->pendinginvite)
16159 return;
16160
16161
16162 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
16163 }
16164 ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
16165 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16166 } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
16167
16168 if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
16169 ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
16170 } else {
16171 ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
16172
16173 transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
16174 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
16175 }
16176 }
16177 }
16178
16179
16180
16181
16182
16183 static int sip_reinvite_retry(const void *data)
16184 {
16185 struct sip_pvt *p = (struct sip_pvt *) data;
16186
16187 sip_pvt_lock(p);
16188 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16189 p->waitid = -1;
16190 check_pendings(p);
16191 sip_pvt_unlock(p);
16192 dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
16193 return 0;
16194 }
16195
16196
16197
16198 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16199 {
16200 int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
16201 int res = 0;
16202 int xmitres = 0;
16203 int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
16204 char *p_hdrval;
16205 int rtn;
16206
16207 if (reinvite)
16208 ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
16209 else
16210 ast_debug(4, "SIP response %d to standard invite\n", resp);
16211
16212 if (p->alreadygone) {
16213 ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
16214 return;
16215 }
16216
16217
16218
16219 AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
16220
16221
16222
16223
16224 if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
16225 resp = 183;
16226
16227
16228 if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
16229 p->invitestate = INV_PROCEEDING;
16230
16231
16232 if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
16233 p->invitestate = INV_COMPLETED;
16234
16235
16236 if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
16237 p->pendinginvite = 0;
16238
16239 switch (resp) {
16240 case 100:
16241 case 101:
16242 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16243 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16244 check_pendings(p);
16245 break;
16246
16247 case 180:
16248 case 182:
16249 if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16250 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16251 if (!req->ignore && p->owner) {
16252 ast_queue_control(p->owner, AST_CONTROL_RINGING);
16253 if (p->owner->_state != AST_STATE_UP) {
16254 ast_setstate(p->owner, AST_STATE_RINGING);
16255 }
16256 }
16257 if (find_sdp(req)) {
16258 if (p->invitestate != INV_CANCELLED)
16259 p->invitestate = INV_EARLY_MEDIA;
16260 res = process_sdp(p, req, SDP_T38_NONE);
16261 if (!req->ignore && p->owner) {
16262
16263 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16264 }
16265 }
16266 check_pendings(p);
16267 break;
16268
16269 case 183:
16270 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16271 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16272 if (find_sdp(req)) {
16273 if (p->invitestate != INV_CANCELLED)
16274 p->invitestate = INV_EARLY_MEDIA;
16275 res = process_sdp(p, req, SDP_T38_NONE);
16276 if (!req->ignore && p->owner) {
16277
16278 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16279 }
16280 } else {
16281
16282
16283
16284
16285 if (!req->ignore && p->owner) {
16286 ast_queue_control(p->owner, AST_CONTROL_RINGING);
16287 }
16288 }
16289 check_pendings(p);
16290 break;
16291
16292 case 200:
16293 if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16294 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
16295 p->authtries = 0;
16296 if (find_sdp(req)) {
16297 if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
16298 if (!reinvite)
16299
16300
16301 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16302 }
16303
16304
16305
16306
16307 if (outgoing) {
16308 update_call_counter(p, DEC_CALL_RINGING);
16309 parse_ok_contact(p, req);
16310
16311 if (!reinvite)
16312 build_route(p, req, 1);
16313
16314 if(set_address_from_contact(p)) {
16315
16316
16317 if (!p->route && !req->ignore)
16318 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16319 }
16320
16321 }
16322
16323 if (!req->ignore && p->owner) {
16324 if (!reinvite) {
16325 ast_queue_control(p->owner, AST_CONTROL_ANSWER);
16326 if (global_callevents)
16327 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
16328 "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
16329 p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
16330 } else {
16331 ast_queue_frame(p->owner, &ast_null_frame);
16332 }
16333 } else {
16334
16335
16336
16337 if (!req->ignore)
16338 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16339 }
16340
16341
16342 if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
16343 p_hdrval = (char*)get_header(req, "Session-Expires");
16344 if (!ast_strlen_zero(p_hdrval)) {
16345
16346 enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
16347 int tmp_st_interval = 0;
16348 rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
16349 if (rtn != 0) {
16350 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
16351 }
16352 if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC ||
16353 tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
16354 p->stimer->st_ref = tmp_st_ref;
16355 }
16356 if (tmp_st_interval) {
16357 p->stimer->st_interval = tmp_st_interval;
16358 }
16359 p->stimer->st_active = TRUE;
16360 p->stimer->st_active_peer_ua = TRUE;
16361 start_session_timer(p);
16362 } else {
16363
16364 if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
16365 p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
16366 p->stimer->st_active_peer_ua = FALSE;
16367 start_session_timer(p);
16368 }
16369 }
16370 }
16371
16372
16373
16374 p->invitestate = INV_TERMINATED;
16375 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16376 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
16377 check_pendings(p);
16378 break;
16379
16380 case 407:
16381 case 401:
16382
16383 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16384 if (p->options)
16385 p->options->auth_type = resp;
16386
16387
16388 ast_string_field_set(p, theirtag, NULL);
16389 if (!req->ignore) {
16390 if (p->authtries < MAX_AUTHTRIES)
16391 p->invitestate = INV_CALLING;
16392 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
16393 ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
16394 p->needdestroy = 1;
16395 sip_alreadygone(p);
16396 if (p->owner)
16397 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16398 }
16399 }
16400 break;
16401
16402 case 403:
16403
16404 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16405 ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
16406 if (!req->ignore && p->owner)
16407 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16408 p->needdestroy = 1;
16409 sip_alreadygone(p);
16410 break;
16411
16412 case 404:
16413 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16414 if (p->owner && !req->ignore)
16415 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16416 sip_alreadygone(p);
16417 break;
16418
16419 case 408:
16420 case 481:
16421
16422 ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
16423 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16424 if (p->owner)
16425 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16426 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16427 break;
16428
16429 case 422:
16430 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16431 ast_string_field_set(p, theirtag, NULL);
16432 proc_422_rsp(p, req);
16433 break;
16434
16435 case 487:
16436
16437
16438
16439 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16440 if (p->owner && !req->ignore) {
16441 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
16442 append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
16443 } else if (!req->ignore) {
16444 update_call_counter(p, DEC_CALL_LIMIT);
16445 append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
16446 p->needdestroy = 1;
16447 sip_alreadygone(p);
16448 }
16449 break;
16450 case 488:
16451 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16452 if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
16453 change_t38_state(p, T38_DISABLED);
16454
16455 ast_rtp_set_rtptimers_onhold(p->rtp);
16456
16457
16458 transmit_reinvite_with_sdp(p, FALSE, FALSE);
16459 } else {
16460
16461 if (p->owner && !req->ignore)
16462 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16463 p->needdestroy = 1;
16464
16465 if (!reinvite)
16466 sip_alreadygone(p);
16467 }
16468 break;
16469 case 491:
16470 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16471 if (p->owner && !req->ignore) {
16472 if (p->owner->_state != AST_STATE_UP) {
16473 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16474 p->needdestroy = 1;
16475 } else {
16476
16477
16478
16479 int wait;
16480
16481
16482 if (p->outgoing_call) {
16483 wait = 2100 + ast_random() % 2000;
16484 } else {
16485 wait = ast_random() % 2000;
16486 }
16487 p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
16488 ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
16489 ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
16490 }
16491 }
16492 break;
16493
16494 case 501:
16495 xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16496 if (p->owner)
16497 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16498 break;
16499 }
16500 if (xmitres == XMIT_ERROR)
16501 ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
16502 }
16503
16504
16505
16506
16507 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16508 {
16509 switch (resp) {
16510 case 200:
16511
16512 if (p->owner) {
16513 if (!p->refer) {
16514 ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
16515 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
16516 } else {
16517 ast_debug(4, "Got OK on REFER Notify message\n");
16518 }
16519 } else {
16520 if (p->subscribed == NONE) {
16521 ast_debug(4, "Got 200 accepted on NOTIFY\n");
16522 p->needdestroy = 1;
16523 }
16524 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
16525
16526 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16527 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
16528 }
16529 }
16530 break;
16531 case 401:
16532 case 407:
16533 if (!p->notify_headers) {
16534 break;
16535 }
16536 ast_string_field_set(p, theirtag, NULL);
16537 if (ast_strlen_zero(p->authname)) {
16538 ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s:%d but we have no matching peer or realm auth!\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16539 p->needdestroy = 1;
16540 }
16541 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
16542 ast_log(LOG_NOTICE, "Failed to authenticate on NOTYFY to '%s'\n", get_header(&p->initreq, "From"));
16543 p->needdestroy = 1;
16544 }
16545 break;
16546 }
16547 }
16548
16549
16550
16551
16552 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16553 {
16554
16555 if (!p->refer)
16556 return;
16557
16558 switch (resp) {
16559 case 202:
16560
16561
16562 p->refer->status = REFER_ACCEPTED;
16563
16564 ast_debug(3, "Got 202 accepted on transfer\n");
16565
16566 break;
16567
16568 case 401:
16569 case 407:
16570 if (ast_strlen_zero(p->authname)) {
16571 ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
16572 ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16573 p->needdestroy = 1;
16574 }
16575 if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
16576 ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
16577 p->refer->status = REFER_NOAUTH;
16578 p->needdestroy = 1;
16579 }
16580 break;
16581 case 481:
16582
16583
16584
16585
16586 ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
16587 if (p->owner)
16588 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16589 p->needdestroy = 1;
16590 break;
16591
16592 case 500:
16593 case 501:
16594
16595
16596 ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
16597 p->needdestroy = 1;
16598 p->refer->status = REFER_FAILED;
16599 break;
16600 case 603:
16601 ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
16602 p->refer->status = REFER_FAILED;
16603 p->needdestroy = 1;
16604 break;
16605 }
16606 }
16607
16608
16609 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16610 {
16611 int expires, expires_ms;
16612 struct sip_registry *r;
16613 r=p->registry;
16614
16615 switch (resp) {
16616 case 401:
16617 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
16618 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
16619 p->needdestroy = 1;
16620 }
16621 break;
16622 case 403:
16623 ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
16624 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
16625 r->regstate = REG_STATE_NOAUTH;
16626 p->needdestroy = 1;
16627 break;
16628 case 404:
16629 ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
16630 p->needdestroy = 1;
16631 if (r->call)
16632 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
16633 r->regstate = REG_STATE_REJECTED;
16634 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
16635 break;
16636 case 407:
16637 if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
16638 ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
16639 p->needdestroy = 1;
16640 }
16641 break;
16642 case 408:
16643
16644 if (r) {
16645 r->regattempts = 0;
16646 } else {
16647 ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
16648 }
16649 break;
16650 case 423:
16651 r->expiry = atoi(get_header(req, "Min-Expires"));
16652 ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
16653 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
16654 if (r->call) {
16655 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
16656 p->needdestroy = 1;
16657 }
16658 if (r->expiry > max_expiry) {
16659 ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
16660 r->expiry = default_expiry;
16661 r->regstate = REG_STATE_REJECTED;
16662 } else {
16663 r->regstate = REG_STATE_UNREGISTERED;
16664 transmit_register(r, SIP_REGISTER, NULL, NULL);
16665 }
16666 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));
16667 break;
16668 case 479:
16669 ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
16670 p->needdestroy = 1;
16671 if (r->call)
16672 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
16673 r->regstate = REG_STATE_REJECTED;
16674 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
16675 break;
16676 case 200:
16677 if (!r) {
16678 ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
16679 p->needdestroy = 1;
16680 return 0;
16681 }
16682
16683 r->regstate = REG_STATE_REGISTERED;
16684 r->regtime = ast_tvnow();
16685 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
16686 r->regattempts = 0;
16687 ast_debug(1, "Registration successful\n");
16688 if (r->timeout > -1) {
16689 ast_debug(1, "Cancelling timeout %d\n", r->timeout);
16690 }
16691 AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
16692 if (r->call)
16693 r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
16694 p->registry = registry_unref(p->registry, "unref registry entry p->registry");
16695
16696 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16697
16698
16699
16700
16701
16702
16703 expires = 0;
16704
16705
16706 if (!ast_strlen_zero(get_header(req, "Contact"))) {
16707 const char *contact = NULL;
16708 const char *tmptmp = NULL;
16709 int start = 0;
16710 for(;;) {
16711 contact = __get_header(req, "Contact", &start);
16712
16713 if(!ast_strlen_zero(contact)) {
16714 if( (tmptmp=strstr(contact, p->our_contact))) {
16715 contact=tmptmp;
16716 break;
16717 }
16718 } else
16719 break;
16720 }
16721 tmptmp = strcasestr(contact, "expires=");
16722 if (tmptmp) {
16723 if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
16724 expires = 0;
16725 }
16726
16727 }
16728 if (!expires)
16729 expires=atoi(get_header(req, "expires"));
16730 if (!expires)
16731 expires=default_expiry;
16732
16733 expires_ms = expires * 1000;
16734 if (expires <= EXPIRY_GUARD_LIMIT)
16735 expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
16736 else
16737 expires_ms -= EXPIRY_GUARD_SECS * 1000;
16738 if (sipdebug)
16739 ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
16740
16741 r->refresh= (int) expires_ms / 1000;
16742
16743
16744 AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
16745 registry_unref(_data,"unref in REPLACE del fail"),
16746 registry_unref(r,"unref in REPLACE add fail"),
16747 registry_addref(r,"The Addition side of REPLACE"));
16748 }
16749 return 1;
16750 }
16751
16752
16753 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
16754 {
16755 struct sip_peer *peer = p->relatedpeer ;
16756 int statechanged, is_reachable, was_reachable;
16757 int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
16758
16759
16760
16761
16762
16763
16764 if (pingtime < 1)
16765 pingtime = 1;
16766
16767
16768
16769
16770
16771 was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
16772 is_reachable = pingtime <= peer->maxms;
16773 statechanged = peer->lastms == 0
16774 || was_reachable != is_reachable;
16775
16776 peer->lastms = pingtime;
16777 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
16778 if (statechanged) {
16779 const char *s = is_reachable ? "Reachable" : "Lagged";
16780 char str_lastms[20];
16781 snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
16782
16783 ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
16784 peer->name, s, pingtime, peer->maxms);
16785 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
16786 if (sip_cfg.peer_rtupdate) {
16787 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
16788 }
16789 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
16790 "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
16791 peer->name, s, pingtime);
16792 if (is_reachable && global_regextenonqualify)
16793 register_peer_exten(peer, TRUE);
16794 }
16795
16796 p->needdestroy = 1;
16797
16798
16799 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
16800 is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
16801 sip_poke_peer_s, peer,
16802 unref_peer(_data, "removing poke peer ref"),
16803 unref_peer(peer, "removing poke peer ref"),
16804 ref_peer(peer, "adding poke peer ref"));
16805 }
16806
16807
16808 static void stop_media_flows(struct sip_pvt *p)
16809 {
16810
16811 if (p->rtp)
16812 ast_rtp_stop(p->rtp);
16813 if (p->vrtp)
16814 ast_rtp_stop(p->vrtp);
16815 if (p->trtp)
16816 ast_rtp_stop(p->trtp);
16817 if (p->udptl)
16818 ast_udptl_stop(p->udptl);
16819 }
16820
16821
16822
16823 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16824 {
16825 struct ast_channel *owner;
16826 int sipmethod;
16827 int res = 1;
16828 int ack_res;
16829 const char *c = get_header(req, "Cseq");
16830
16831 char *c_copy = ast_strdupa(c);
16832
16833 const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
16834
16835 if (!msg)
16836 msg = "";
16837
16838 sipmethod = find_sip_method(msg);
16839
16840 owner = p->owner;
16841 if (owner)
16842 owner->hangupcause = hangup_sip2cause(resp);
16843
16844
16845 if ((resp >= 100) && (resp <= 199)) {
16846 ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
16847 } else {
16848 ack_res = __sip_ack(p, seqno, 0, sipmethod);
16849 }
16850
16851 if (ack_res == FALSE) {
16852 append_history(p, "Ignore", "Ignoring this retransmit\n");
16853 return;
16854 }
16855
16856
16857 if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite)
16858 p->pendinginvite = 0;
16859
16860
16861 if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
16862 char tag[128];
16863
16864 gettag(req, "To", tag, sizeof(tag));
16865 ast_string_field_set(p, theirtag, tag);
16866 }
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882 if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
16883 p->needdestroy = 1;
16884 return;
16885 }
16886
16887 if (p->relatedpeer && p->method == SIP_OPTIONS) {
16888
16889
16890
16891 if (resp != 100)
16892 handle_response_peerpoke(p, resp, req);
16893 } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
16894 switch(resp) {
16895 case 100:
16896 case 101:
16897 if (sipmethod == SIP_INVITE)
16898 handle_response_invite(p, resp, rest, req, seqno);
16899 break;
16900 case 183:
16901 if (sipmethod == SIP_INVITE)
16902 handle_response_invite(p, resp, rest, req, seqno);
16903 break;
16904 case 180:
16905 if (sipmethod == SIP_INVITE)
16906 handle_response_invite(p, resp, rest, req, seqno);
16907 break;
16908 case 182:
16909 if (sipmethod == SIP_INVITE)
16910 handle_response_invite(p, resp, rest, req, seqno);
16911 break;
16912 case 200:
16913 p->authtries = 0;
16914 if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
16915
16916
16917
16918 } else if (sipmethod == SIP_INVITE) {
16919 handle_response_invite(p, resp, rest, req, seqno);
16920 } else if (sipmethod == SIP_NOTIFY) {
16921 handle_response_notify(p, resp, rest, req, seqno);
16922 } else if (sipmethod == SIP_REGISTER)
16923 res = handle_response_register(p, resp, rest, req, seqno);
16924 else if (sipmethod == SIP_BYE) {
16925 p->needdestroy = 1;
16926 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16927 } else if (sipmethod == SIP_SUBSCRIBE) {
16928 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16929 }
16930 break;
16931 case 202:
16932 if (sipmethod == SIP_REFER)
16933 handle_response_refer(p, resp, rest, req, seqno);
16934 break;
16935 case 401:
16936 case 407:
16937 if (sipmethod == SIP_INVITE)
16938 handle_response_invite(p, resp, rest, req, seqno);
16939 else if (sipmethod == SIP_NOTIFY)
16940 handle_response_notify(p, resp, rest, req, seqno);
16941 else if (sipmethod == SIP_REFER)
16942 handle_response_refer(p, resp, rest, req, seqno);
16943 else if (p->registry && sipmethod == SIP_REGISTER)
16944 res = handle_response_register(p, resp, rest, req, seqno);
16945 else if (sipmethod == SIP_BYE) {
16946 if (p->options)
16947 p->options->auth_type = resp;
16948 if (ast_strlen_zero(p->authname)) {
16949 ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
16950 msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
16951 p->needdestroy = 1;
16952 } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, sipmethod, 0)) {
16953 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
16954 p->needdestroy = 1;
16955 }
16956 } else {
16957 ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
16958 p->needdestroy = 1;
16959 }
16960 break;
16961 case 403:
16962 if (sipmethod == SIP_INVITE)
16963 handle_response_invite(p, resp, rest, req, seqno);
16964 else if (p->registry && sipmethod == SIP_REGISTER)
16965 res = handle_response_register(p, resp, rest, req, seqno);
16966 else {
16967 ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
16968 p->needdestroy = 1;
16969 }
16970 break;
16971 case 404:
16972 if (p->registry && sipmethod == SIP_REGISTER)
16973 res = handle_response_register(p, resp, rest, req, seqno);
16974 else if (sipmethod == SIP_INVITE)
16975 handle_response_invite(p, resp, rest, req, seqno);
16976 else if (owner)
16977 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16978 break;
16979 case 423:
16980 if (sipmethod == SIP_REGISTER)
16981 res = handle_response_register(p, resp, rest, req, seqno);
16982 break;
16983 case 408:
16984 if (sipmethod == SIP_INVITE)
16985 handle_response_invite(p, resp, rest, req, seqno);
16986 else if (sipmethod == SIP_REGISTER)
16987 res = handle_response_register(p, resp, rest, req, seqno);
16988 else if (sipmethod == SIP_BYE) {
16989 p->needdestroy = 1;
16990 ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
16991 } else {
16992 if (owner)
16993 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16994 p->needdestroy = 1;
16995 }
16996 break;
16997
16998 case 422:
16999 if (sipmethod == SIP_INVITE) {
17000 handle_response_invite(p, resp, rest, req, seqno);
17001 }
17002 break;
17003
17004 case 481:
17005 if (sipmethod == SIP_INVITE) {
17006 handle_response_invite(p, resp, rest, req, seqno);
17007 } else if (sipmethod == SIP_REFER) {
17008 handle_response_refer(p, resp, rest, req, seqno);
17009 } else if (sipmethod == SIP_BYE) {
17010
17011
17012 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17013 } else if (sipmethod == SIP_CANCEL) {
17014
17015
17016 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17017 } else {
17018 ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17019
17020 }
17021 break;
17022 case 487:
17023 if (sipmethod == SIP_INVITE)
17024 handle_response_invite(p, resp, rest, req, seqno);
17025 break;
17026 case 488:
17027 if (sipmethod == SIP_INVITE)
17028 handle_response_invite(p, resp, rest, req, seqno);
17029 break;
17030 case 491:
17031 if (sipmethod == SIP_INVITE)
17032 handle_response_invite(p, resp, rest, req, seqno);
17033 else {
17034 ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
17035 p->needdestroy = 1;
17036 }
17037 break;
17038 case 501:
17039 if (sipmethod == SIP_INVITE)
17040 handle_response_invite(p, resp, rest, req, seqno);
17041 else if (sipmethod == SIP_REFER)
17042 handle_response_refer(p, resp, rest, req, seqno);
17043 else
17044 ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
17045 break;
17046 case 603:
17047 if (sipmethod == SIP_REFER) {
17048 handle_response_refer(p, resp, rest, req, seqno);
17049 break;
17050 }
17051
17052 default:
17053 if ((resp >= 300) && (resp < 700)) {
17054
17055 if ((resp != 487))
17056 ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17057
17058 if (sipmethod == SIP_INVITE)
17059 stop_media_flows(p);
17060
17061
17062 switch(resp) {
17063 case 300:
17064 case 301:
17065 case 302:
17066 case 305:
17067 parse_moved_contact(p, req);
17068
17069 case 486:
17070 case 600:
17071 case 603:
17072 if (p->owner)
17073 ast_queue_control(p->owner, AST_CONTROL_BUSY);
17074 break;
17075 case 482:
17076
17077
17078
17079
17080 ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
17081 if (p->owner)
17082 ast_string_field_build(p->owner, call_forward,
17083 "Local/%s@%s", p->username, p->context);
17084
17085 case 480:
17086 case 404:
17087 case 410:
17088 case 400:
17089 case 500:
17090 if (sipmethod == SIP_REFER) {
17091 handle_response_refer(p, resp, rest, req, seqno);
17092 break;
17093 }
17094
17095 case 502:
17096 case 503:
17097 case 504:
17098 if (owner)
17099 ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17100 break;
17101 default:
17102
17103 if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
17104 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
17105 break;
17106 }
17107
17108 if (sipmethod == SIP_INVITE)
17109 transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17110 if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO)
17111 sip_alreadygone(p);
17112 if (!p->owner)
17113 p->needdestroy = 1;
17114 } else if ((resp >= 100) && (resp < 200)) {
17115 if (sipmethod == SIP_INVITE) {
17116 if (!req->ignore && sip_cancel_destroy(p))
17117 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17118 if (find_sdp(req))
17119 process_sdp(p, req, SDP_T38_NONE);
17120 if (p->owner) {
17121
17122 ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17123 }
17124 }
17125 } else
17126 ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
17127 }
17128 } else {
17129
17130
17131 if (req->debug)
17132 ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
17133
17134 if (sipmethod == SIP_INVITE && resp == 200) {
17135
17136
17137 char tag[128];
17138
17139 gettag(req, "To", tag, sizeof(tag));
17140 ast_string_field_set(p, theirtag, tag);
17141 }
17142
17143 switch(resp) {
17144 case 200:
17145 if (sipmethod == SIP_INVITE) {
17146 handle_response_invite(p, resp, rest, req, seqno);
17147 } else if (sipmethod == SIP_CANCEL) {
17148 ast_debug(1, "Got 200 OK on CANCEL\n");
17149
17150
17151 } else if (sipmethod == SIP_NOTIFY) {
17152
17153 if (p->owner) {
17154 if (p->refer) {
17155 ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
17156 } else
17157 ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
17158
17159 } else {
17160 if (!p->subscribed && !p->refer)
17161 p->needdestroy = 1;
17162 if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17163
17164 ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17165 cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17166 }
17167 }
17168 } else if (sipmethod == SIP_BYE)
17169 p->needdestroy = 1;
17170 else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
17171
17172
17173 ;
17174 else if (sipmethod == SIP_BYE)
17175
17176 p->needdestroy = 1;
17177 break;
17178 case 202:
17179 if (sipmethod == SIP_REFER)
17180 handle_response_refer(p, resp, rest, req, seqno);
17181 break;
17182 case 401:
17183 case 407:
17184 if (sipmethod == SIP_REFER)
17185 handle_response_refer(p, resp, rest, req, seqno);
17186 else if (sipmethod == SIP_INVITE)
17187 handle_response_invite(p, resp, rest, req, seqno);
17188 else if (sipmethod == SIP_BYE) {
17189 if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
17190 ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
17191 p->needdestroy = 1;
17192 }
17193 }
17194 break;
17195 case 481:
17196 if (sipmethod == SIP_INVITE) {
17197
17198 handle_response_invite(p, resp, rest, req, seqno);
17199 } else if (sipmethod == SIP_BYE) {
17200 p->needdestroy = 1;
17201 } else if (sipdebug) {
17202 ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
17203 }
17204 break;
17205 case 501:
17206 if (sipmethod == SIP_INVITE)
17207 handle_response_invite(p, resp, rest, req, seqno);
17208 else if (sipmethod == SIP_REFER)
17209 handle_response_refer(p, resp, rest, req, seqno);
17210 break;
17211 case 603:
17212 if (sipmethod == SIP_REFER) {
17213 handle_response_refer(p, resp, rest, req, seqno);
17214 break;
17215 }
17216
17217 default:
17218 if ((resp >= 100) && (resp < 200)) {
17219 if (sipmethod == SIP_INVITE) {
17220 if (!req->ignore && sip_cancel_destroy(p))
17221 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17222 }
17223 }
17224 if ((resp >= 300) && (resp < 700)) {
17225 if ((resp != 487))
17226 ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17227 switch(resp) {
17228 case 488:
17229 case 603:
17230 case 500:
17231 case 502:
17232 case 503:
17233 case 504:
17234
17235
17236 if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
17237 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
17238 break;
17239 }
17240 }
17241 break;
17242 }
17243 }
17244 }
17245
17246
17247
17248
17249
17250
17251
17252 static void *sip_park_thread(void *stuff)
17253 {
17254 struct ast_channel *transferee, *transferer;
17255 struct sip_dual *d;
17256 struct sip_request req = {0,};
17257 int ext;
17258 int res;
17259
17260 d = stuff;
17261 transferee = d->chan1;
17262 transferer = d->chan2;
17263 copy_request(&req, &d->req);
17264
17265 if (!transferee || !transferer) {
17266 ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
17267 if (d->req.data)
17268 ast_free(d->req.data);
17269 free(d);
17270 return NULL;
17271 }
17272 ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
17273
17274 ast_channel_lock(transferee);
17275 if (ast_do_masquerade(transferee)) {
17276 ast_log(LOG_WARNING, "Masquerade failed.\n");
17277 transmit_response(transferer->tech_pvt, "503 Internal error", &req);
17278 ast_channel_unlock(transferee);
17279 if (d->req.data)
17280 ast_free(d->req.data);
17281 free(d);
17282 return NULL;
17283 }
17284 ast_channel_unlock(transferee);
17285
17286 res = ast_park_call(transferee, transferer, 0, &ext);
17287
17288
17289 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
17290 if (!res) {
17291 transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
17292 } else {
17293
17294 sprintf(buf, "Call parked on extension '%d'", ext);
17295 transmit_message_with_text(transferer->tech_pvt, buf);
17296 }
17297 #endif
17298
17299
17300
17301 transmit_response(transferer->tech_pvt, "202 Accepted", &req);
17302 if (!res) {
17303
17304 append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
17305 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
17306 transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17307 ast_hangup(transferer);
17308 ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
17309 } else {
17310 transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
17311 append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
17312 ast_debug(1, "SIP Call parked failed \n");
17313
17314 }
17315 if (d->req.data)
17316 ast_free(d->req.data);
17317 free(d);
17318 return NULL;
17319 }
17320
17321
17322
17323
17324 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
17325 {
17326 struct sip_dual *d;
17327 struct ast_channel *transferee, *transferer;
17328
17329 pthread_t th;
17330
17331 transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
17332 transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
17333 if ((!transferer) || (!transferee)) {
17334 if (transferee) {
17335 transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17336 ast_hangup(transferee);
17337 }
17338 if (transferer) {
17339 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17340 ast_hangup(transferer);
17341 }
17342 return -1;
17343 }
17344
17345
17346 transferee->readformat = chan1->readformat;
17347 transferee->writeformat = chan1->writeformat;
17348
17349
17350 ast_channel_masquerade(transferee, chan1);
17351
17352
17353 ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
17354 ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
17355 transferee->priority = chan1->priority;
17356
17357
17358
17359
17360
17361 transferer->readformat = chan2->readformat;
17362 transferer->writeformat = chan2->writeformat;
17363
17364
17365
17366
17367 while (ast_channel_trylock(chan2)) {
17368 struct sip_pvt *pvt = chan2->tech_pvt;
17369 sip_pvt_unlock(pvt);
17370 usleep(1);
17371 sip_pvt_lock(pvt);
17372 }
17373 ast_channel_masquerade(transferer, chan2);
17374 ast_channel_unlock(chan2);
17375
17376
17377 ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
17378 ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
17379 transferer->priority = chan2->priority;
17380
17381 ast_channel_lock(transferer);
17382 if (ast_do_masquerade(transferer)) {
17383 ast_log(LOG_WARNING, "Masquerade failed :(\n");
17384 ast_channel_unlock(transferer);
17385 transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17386 ast_hangup(transferer);
17387 return -1;
17388 }
17389 ast_channel_unlock(transferer);
17390 if (!transferer || !transferee) {
17391 if (!transferer) {
17392 ast_debug(1, "No transferer channel, giving up parking\n");
17393 }
17394 if (!transferee) {
17395 ast_debug(1, "No transferee channel, giving up parking\n");
17396 }
17397 return -1;
17398 }
17399 if ((d = ast_calloc(1, sizeof(*d)))) {
17400
17401
17402 copy_request(&d->req, req);
17403 d->chan1 = transferee;
17404 d->chan2 = transferer;
17405 d->seqno = seqno;
17406 if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
17407
17408 if (d->req.data)
17409 ast_free(d->req.data);
17410 ast_free(d);
17411
17412 return 0;
17413 }
17414 }
17415 return -1;
17416 }
17417
17418
17419
17420
17421 static void ast_quiet_chan(struct ast_channel *chan)
17422 {
17423 if (chan && chan->_state == AST_STATE_UP) {
17424 if (ast_test_flag(chan, AST_FLAG_MOH))
17425 ast_moh_stop(chan);
17426 else if (chan->generatordata)
17427 ast_deactivate_generator(chan);
17428 }
17429 }
17430
17431
17432
17433 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
17434 {
17435 int res = 0;
17436 struct ast_channel *peera = NULL,
17437 *peerb = NULL,
17438 *peerc = NULL,
17439 *peerd = NULL;
17440
17441
17442
17443
17444 ast_debug(4, "Sip transfer:--------------------\n");
17445 if (transferer->chan1)
17446 ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
17447 else
17448 ast_debug(4, "-- No transferer first channel - odd??? \n");
17449 if (target->chan1)
17450 ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
17451 else
17452 ast_debug(4, "-- No target first channel ---\n");
17453 if (transferer->chan2)
17454 ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
17455 else
17456 ast_debug(4, "-- No bridged call to transferee\n");
17457 if (target->chan2)
17458 ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
17459 else
17460 ast_debug(4, "-- No target second channel ---\n");
17461 ast_debug(4, "-- END Sip transfer:--------------------\n");
17462 if (transferer->chan2) {
17463 peera = transferer->chan1;
17464 peerb = target->chan1;
17465 peerc = transferer->chan2;
17466 peerd = target->chan2;
17467 ast_debug(3, "SIP transfer: Four channels to handle\n");
17468 } else if (target->chan2) {
17469 peera = target->chan1;
17470 peerb = transferer->chan1;
17471 peerc = target->chan2;
17472 peerd = transferer->chan2;
17473 ast_debug(3, "SIP transfer: Three channels to handle\n");
17474 }
17475
17476 if (peera && peerb && peerc && (peerb != peerc)) {
17477 ast_quiet_chan(peera);
17478 ast_quiet_chan(peerb);
17479 ast_quiet_chan(peerc);
17480 if (peerd)
17481 ast_quiet_chan(peerd);
17482
17483 ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
17484 if (ast_channel_masquerade(peerb, peerc)) {
17485 ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
17486 res = -1;
17487 } else
17488 ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
17489 return res;
17490 } else {
17491 ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
17492 if (transferer->chan1)
17493 ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
17494 if (target->chan1)
17495 ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
17496 return -1;
17497 }
17498 return 0;
17499 }
17500
17501
17502
17503
17504
17505
17506 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
17507 {
17508 const char *thetag;
17509
17510 if (!tagbuf)
17511 return NULL;
17512 tagbuf[0] = '\0';
17513 thetag = get_header(req, header);
17514 thetag = strcasestr(thetag, ";tag=");
17515 if (thetag) {
17516 thetag += 5;
17517 ast_copy_string(tagbuf, thetag, tagbufsize);
17518 return strsep(&tagbuf, ";");
17519 }
17520 return NULL;
17521 }
17522
17523
17524 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
17525 {
17526
17527
17528 int res = 0;
17529 const char *event = get_header(req, "Event");
17530 char *eventid = NULL;
17531 char *sep;
17532
17533 if( (sep = strchr(event, ';')) ) {
17534 *sep++ = '\0';
17535 eventid = sep;
17536 }
17537
17538 if (sipdebug)
17539 ast_debug(2, "Got NOTIFY Event: %s\n", event);
17540
17541 if (strcmp(event, "refer")) {
17542
17543
17544 transmit_response(p, "489 Bad event", req);
17545 res = -1;
17546 } else {
17547
17548
17549
17550
17551
17552 char buf[1024];
17553 char *cmd, *code;
17554 int respcode;
17555 int success = TRUE;
17556
17557
17558
17559
17560
17561
17562
17563
17564 if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
17565
17566 transmit_response(p, "400 Bad request", req);
17567 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17568 return -1;
17569 }
17570
17571
17572 if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
17573 ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
17574 transmit_response(p, "400 Bad request", req);
17575 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17576 return -1;
17577 }
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599 ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
17600 cmd = ast_skip_blanks(buf);
17601 code = cmd;
17602
17603 while(*code && (*code > 32)) {
17604 code++;
17605 }
17606 *code++ = '\0';
17607 code = ast_skip_blanks(code);
17608 sep = code;
17609 sep++;
17610 while(*sep && (*sep > 32)) {
17611 sep++;
17612 }
17613 *sep++ = '\0';
17614 respcode = atoi(code);
17615 switch (respcode) {
17616 case 100:
17617 case 101:
17618
17619 break;
17620 case 183:
17621
17622 break;
17623 case 200:
17624
17625 break;
17626 case 301:
17627 case 302:
17628
17629 success = FALSE;
17630 break;
17631 case 503:
17632
17633 success = FALSE;
17634 break;
17635 case 603:
17636
17637 success = FALSE;
17638 break;
17639 }
17640 if (!success) {
17641 ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
17642 }
17643
17644
17645 transmit_response(p, "200 OK", req);
17646 };
17647
17648 if (!p->lastinvite)
17649 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17650
17651 return res;
17652 }
17653
17654
17655
17656
17657 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
17658 {
17659 int res;
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671 if (p->lastinvite) {
17672
17673 transmit_response_with_allow(p, "200 OK", req, 0);
17674 return 0;
17675 }
17676
17677 res = get_destination(p, req);
17678 build_contact(p);
17679
17680 if (ast_strlen_zero(p->context))
17681 ast_string_field_set(p, context, default_context);
17682
17683 if (ast_shutting_down())
17684 transmit_response_with_allow(p, "503 Unavailable", req, 0);
17685 else if (res < 0)
17686 transmit_response_with_allow(p, "404 Not Found", req, 0);
17687 else
17688 transmit_response_with_allow(p, "200 OK", req, 0);
17689
17690
17691
17692 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17693
17694 return res;
17695 }
17696
17697
17698
17699
17700
17701
17702 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin)
17703 {
17704 struct ast_frame *f;
17705 int earlyreplace = 0;
17706 int oneleggedreplace = 0;
17707 struct ast_channel *c = p->owner;
17708 struct ast_channel *replacecall = p->refer->refer_call->owner;
17709 struct ast_channel *targetcall;
17710
17711 struct ast_channel *test;
17712
17713
17714 if (replacecall->_state == AST_STATE_RING)
17715 earlyreplace = 1;
17716
17717
17718 if (!(targetcall = ast_bridged_channel(replacecall))) {
17719
17720 if (!earlyreplace) {
17721 ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
17722 oneleggedreplace = 1;
17723 }
17724 }
17725 if (targetcall && targetcall->_state == AST_STATE_RINGING)
17726 ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
17727
17728 if (targetcall)
17729 ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
17730 else
17731 ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
17732
17733 if (req->ignore) {
17734 ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
17735
17736
17737
17738 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
17739
17740 ast_channel_unlock(c);
17741 sip_pvt_unlock(p->refer->refer_call);
17742 return 1;
17743 }
17744 if (!c) {
17745
17746 ast_log(LOG_ERROR, "Unable to create new channel. Invite/replace failed.\n");
17747 transmit_response_reliable(p, "503 Service Unavailable", req);
17748 append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
17749 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17750 sip_pvt_unlock(p->refer->refer_call);
17751 return 1;
17752 }
17753 append_history(p, "Xfer", "INVITE/Replace received");
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765 transmit_response(p, "100 Trying", req);
17766 ast_setstate(c, AST_STATE_RING);
17767
17768
17769
17770
17771
17772 transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
17773
17774 ast_setstate(c, AST_STATE_UP);
17775
17776
17777 ast_quiet_chan(replacecall);
17778 ast_quiet_chan(targetcall);
17779 ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
17780
17781 if (!oneleggedreplace)
17782 ast_channel_unlock(c);
17783
17784
17785 sip_pvt_unlock(p->refer->refer_call);
17786
17787
17788 if (! earlyreplace && ! oneleggedreplace )
17789 ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
17790
17791
17792 if(ast_channel_masquerade(replacecall, c))
17793 ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
17794 else
17795 ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
17796
17797
17798
17799
17800
17801 ast_channel_unlock(c);
17802
17803 if (earlyreplace || oneleggedreplace ) {
17804
17805 if ((f = ast_read(replacecall))) {
17806 ast_frfree(f);
17807 f = NULL;
17808 ast_debug(4, "Invite/Replace: Could successfully read frame from RING channel!\n");
17809 } else {
17810 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from RING channel \n");
17811 }
17812 c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17813 if (!oneleggedreplace)
17814 ast_channel_unlock(replacecall);
17815 } else {
17816 if ((f = ast_read(replacecall))) {
17817
17818 ast_frfree(f);
17819 f = NULL;
17820 ast_debug(3, "Invite/Replace: Could successfully read frame from channel! Masq done.\n");
17821 } else {
17822 ast_log(LOG_WARNING, "Invite/Replace: Could not read frame from channel. Transfer failed\n");
17823 }
17824 ast_channel_unlock(replacecall);
17825 }
17826 sip_pvt_unlock(p->refer->refer_call);
17827
17828 ast_setstate(c, AST_STATE_DOWN);
17829 ast_debug(4, "After transfer:----------------------------\n");
17830 ast_debug(4, " -- C: %s State %s\n", c->name, ast_state2str(c->_state));
17831 if (replacecall)
17832 ast_debug(4, " -- replacecall: %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
17833 if (p->owner) {
17834 ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
17835 test = ast_bridged_channel(p->owner);
17836 if (test)
17837 ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
17838 else
17839 ast_debug(4, " -- No call bridged to C->owner \n");
17840 } else
17841 ast_debug(4, " -- No channel yet \n");
17842 ast_debug(4, "End After transfer:----------------------------\n");
17843
17844 ast_channel_unlock(p->owner);
17845 if (!oneleggedreplace)
17846 sip_pvt_unlock(p);
17847
17848
17849 c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
17850 ast_hangup(c);
17851 return 0;
17852 }
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870 static int sip_uri_params_cmp(const char *input1, const char *input2)
17871 {
17872 char *params1 = NULL;
17873 char *params2 = NULL;
17874 char *pos1;
17875 char *pos2;
17876 int zerolength1 = 0;
17877 int zerolength2 = 0;
17878 int maddrmatch = 0;
17879 int ttlmatch = 0;
17880 int usermatch = 0;
17881 int methodmatch = 0;
17882
17883 if (ast_strlen_zero(input1)) {
17884 zerolength1 = 1;
17885 } else {
17886 params1 = ast_strdupa(input1);
17887 }
17888 if (ast_strlen_zero(input2)) {
17889 zerolength2 = 1;
17890 } else {
17891 params2 = ast_strdupa(input2);
17892 }
17893
17894
17895
17896
17897 if (zerolength1 && zerolength2) {
17898 return 0;
17899 }
17900
17901 pos1 = params1;
17902 while (!ast_strlen_zero(pos1)) {
17903 char *name1 = pos1;
17904 char *value1 = strchr(pos1, '=');
17905 char *semicolon1 = strchr(pos1, ';');
17906 int matched = 0;
17907 if (semicolon1) {
17908 *semicolon1++ = '\0';
17909 }
17910 if (!value1) {
17911 goto fail;
17912 }
17913 *value1++ = '\0';
17914
17915
17916
17917
17918
17919 pos2 = ast_strdupa(params2);
17920 while (!ast_strlen_zero(pos2)) {
17921 char *name2 = pos2;
17922 char *value2 = strchr(pos2, '=');
17923 char *semicolon2 = strchr(pos2, ';');
17924 if (semicolon2) {
17925 *semicolon2++ = '\0';
17926 }
17927 if (!value2) {
17928 goto fail;
17929 }
17930 *value2++ = '\0';
17931 if (!strcasecmp(name1, name2)) {
17932 if (strcasecmp(value1, value2)) {
17933 goto fail;
17934 } else {
17935 matched = 1;
17936 break;
17937 }
17938 }
17939 pos2 = semicolon2;
17940 }
17941
17942 if (!strcasecmp(name1, "maddr")) {
17943 if (matched) {
17944 maddrmatch = 1;
17945 } else {
17946 goto fail;
17947 }
17948 } else if (!strcasecmp(name1, "ttl")) {
17949 if (matched) {
17950 ttlmatch = 1;
17951 } else {
17952 goto fail;
17953 }
17954 } else if (!strcasecmp(name1, "user")) {
17955 if (matched) {
17956 usermatch = 1;
17957 } else {
17958 goto fail;
17959 }
17960 } else if (!strcasecmp(name1, "method")) {
17961 if (matched) {
17962 methodmatch = 1;
17963 } else {
17964 goto fail;
17965 }
17966 }
17967 pos1 = semicolon1;
17968 }
17969
17970
17971
17972
17973
17974 pos2 = params2;
17975 while (!ast_strlen_zero(pos2)) {
17976 char *name2 = pos2;
17977 char *value2 = strchr(pos2, '=');
17978 char *semicolon2 = strchr(pos2, ';');
17979 if (semicolon2) {
17980 *semicolon2++ = '\0';
17981 }
17982 if (!value2) {
17983 goto fail;
17984 }
17985 *value2++ = '\0';
17986 if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
17987 (!strcasecmp(name2, "ttl") && !ttlmatch) ||
17988 (!strcasecmp(name2, "user") && !usermatch) ||
17989 (!strcasecmp(name2, "method") && !methodmatch)) {
17990 goto fail;
17991 }
17992 }
17993 return 0;
17994
17995 fail:
17996 return 1;
17997 }
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010 static int sip_uri_headers_cmp(const char *input1, const char *input2)
18011 {
18012 char *headers1 = NULL;
18013 char *headers2 = NULL;
18014 int zerolength1 = 0;
18015 int zerolength2 = 0;
18016 int different = 0;
18017 char *header1;
18018
18019 if (ast_strlen_zero(input1)) {
18020 zerolength1 = 1;
18021 } else {
18022 headers1 = ast_strdupa(input1);
18023 }
18024
18025 if (ast_strlen_zero(input2)) {
18026 zerolength2 = 1;
18027 } else {
18028 headers2 = ast_strdupa(input2);
18029 }
18030
18031 if ((zerolength1 && !zerolength2) ||
18032 (zerolength2 && !zerolength1))
18033 return 1;
18034
18035 if (zerolength1 && zerolength2)
18036 return 0;
18037
18038
18039
18040
18041
18042 if (strlen(headers1) != strlen(headers2)) {
18043 return 1;
18044 }
18045
18046 for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
18047 if (!strcasestr(headers2, header1)) {
18048 different = 1;
18049 break;
18050 }
18051 }
18052
18053 return different;
18054 }
18055
18056 static int sip_uri_cmp(const char *input1, const char *input2)
18057 {
18058 char *uri1 = ast_strdupa(input1);
18059 char *uri2 = ast_strdupa(input2);
18060 char *host1;
18061 char *host2;
18062 char *params1;
18063 char *params2;
18064 char *headers1;
18065 char *headers2;
18066
18067
18068
18069
18070 strsep(&uri1, ":");
18071 strsep(&uri2, ":");
18072
18073 if ((host1 = strchr(uri1, '@'))) {
18074 *host1++ = '\0';
18075 }
18076 if ((host2 = strchr(uri2, '@'))) {
18077 *host2++ = '\0';
18078 }
18079
18080
18081
18082
18083 if ((host1 && !host2) ||
18084 (host2 && !host1) ||
18085 (host1 && host2 && strcmp(uri1, uri2))) {
18086 return 1;
18087 }
18088
18089 if (!host1)
18090 host1 = uri1;
18091 if (!host2)
18092 host2 = uri2;
18093
18094
18095
18096
18097
18098 if ((params1 = strchr(host1, ';'))) {
18099 *params1++ = '\0';
18100 }
18101 if ((params2 = strchr(host2, ';'))) {
18102 *params2++ = '\0';
18103 }
18104
18105
18106
18107
18108 if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
18109 *headers1++ = '\0';
18110 }
18111 if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
18112 *headers2++ = '\0';
18113 }
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125 if (strcasecmp(host1, host2)) {
18126 return 1;
18127 }
18128
18129
18130 if (sip_uri_headers_cmp(headers1, headers2)) {
18131 return 1;
18132 }
18133
18134
18135 return sip_uri_params_cmp(params1, params2);
18136 }
18137
18138
18139 static int sip_t38_abort(const void *data)
18140 {
18141 struct sip_pvt *p = (struct sip_pvt *) data;
18142
18143 change_t38_state(p, T38_DISABLED);
18144 transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
18145 p->t38id = -1;
18146 dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
18147
18148 return 0;
18149 }
18150
18151
18152
18153
18154
18155
18156
18157 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
18158 {
18159 int res = 1;
18160 int gotdest;
18161 const char *p_replaces;
18162 char *replace_id = NULL;
18163 const char *required;
18164 unsigned int required_profile = 0;
18165 struct ast_channel *c = NULL;
18166 int reinvite = 0;
18167 int rtn;
18168
18169 const char *p_uac_se_hdr;
18170 const char *p_uac_min_se;
18171 int uac_max_se = -1;
18172 int uac_min_se = -1;
18173 int st_active = FALSE;
18174 int st_interval = 0;
18175 enum st_refresher st_ref;
18176 int dlg_min_se = -1;
18177 st_ref = SESSION_TIMER_REFRESHER_AUTO;
18178
18179
18180 if (!p->sipoptions) {
18181 const char *supported = get_header(req, "Supported");
18182 if (!ast_strlen_zero(supported))
18183 parse_sip_options(p, supported);
18184 }
18185
18186
18187 required = get_header(req, "Require");
18188 if (!ast_strlen_zero(required)) {
18189 required_profile = parse_sip_options(NULL, required);
18190 if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
18191
18192 transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
18193 ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
18194 p->invitestate = INV_COMPLETED;
18195 if (!p->lastinvite)
18196 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18197 return -1;
18198 }
18199 }
18200
18201
18202
18203 p->sipoptions |= required_profile;
18204 p->reqsipoptions = required_profile;
18205
18206
18207 if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
18208
18209
18210
18211
18212
18213 int different;
18214 char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
18215 char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
18216 if (pedanticsipchecking)
18217 different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
18218 else
18219 different = strcmp(initial_rlPart2, this_rlPart2);
18220 if (!different) {
18221 transmit_response(p, "482 Loop Detected", req);
18222 p->invitestate = INV_COMPLETED;
18223 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18224 return 0;
18225 } else {
18226
18227
18228
18229
18230
18231
18232
18233 char *uri = ast_strdupa(this_rlPart2);
18234 char *at = strchr(uri, '@');
18235 char *peerorhost;
18236 ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
18237 if (at) {
18238 *at = '\0';
18239 }
18240
18241 if ((peerorhost = strchr(uri, ':'))) {
18242 *peerorhost++ = '\0';
18243 }
18244 ast_string_field_set(p, theirtag, NULL);
18245
18246
18247 ast_string_field_set(p->owner, call_forward, peerorhost);
18248 ast_queue_control(p->owner, AST_CONTROL_BUSY);
18249 return 0;
18250 }
18251 }
18252
18253 if (!req->ignore && p->pendinginvite) {
18254 if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265 __sip_ack(p, p->pendinginvite, 1, 0);
18266 } else {
18267
18268 p->glareinvite = seqno;
18269 if (p->rtp && find_sdp(req)) {
18270 struct sockaddr_in sin;
18271 if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
18272 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
18273 } else {
18274 ast_rtp_set_alt_peer(p->rtp, &sin);
18275 }
18276 if (p->vrtp) {
18277 if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
18278 ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
18279 } else {
18280 ast_rtp_set_alt_peer(p->vrtp, &sin);
18281 }
18282 }
18283 }
18284 transmit_response_reliable(p, "491 Request Pending", req);
18285 ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
18286
18287 return 0;
18288 }
18289 }
18290
18291 p_replaces = get_header(req, "Replaces");
18292 if (!ast_strlen_zero(p_replaces)) {
18293
18294 char *ptr;
18295 char *fromtag = NULL;
18296 char *totag = NULL;
18297 char *start, *to;
18298 int error = 0;
18299
18300 if (p->owner) {
18301 ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
18302 transmit_response_reliable(p, "400 Bad request", req);
18303
18304 return -1;
18305 }
18306
18307 if (sipdebug)
18308 ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
18309
18310 replace_id = ast_strdupa(p_replaces);
18311 ast_uri_decode(replace_id);
18312
18313 if (!p->refer && !sip_refer_allocate(p)) {
18314 transmit_response_reliable(p, "500 Server Internal Error", req);
18315 append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
18316 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18317 p->invitestate = INV_COMPLETED;
18318 return -1;
18319 }
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330 replace_id = ast_skip_blanks(replace_id);
18331
18332 start = replace_id;
18333 while ( (ptr = strsep(&start, ";")) ) {
18334 ptr = ast_skip_blanks(ptr);
18335 if ( (to = strcasestr(ptr, "to-tag=") ) )
18336 totag = to + 7;
18337 else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
18338 fromtag = to + 9;
18339 fromtag = strsep(&fromtag, "&");
18340 }
18341 }
18342
18343 if (sipdebug)
18344 ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id, fromtag ? fromtag : "<no from tag>", totag ? totag : "<no to tag>");
18345
18346
18347
18348
18349
18350 if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
18351 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
18352 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
18353 error = 1;
18354 }
18355
18356
18357
18358
18359
18360
18361
18362 if (p->refer->refer_call == p) {
18363 ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
18364 p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
18365 transmit_response_reliable(p, "400 Bad request", req);
18366 error = 1;
18367 }
18368
18369 if (!error && !p->refer->refer_call->owner) {
18370
18371 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
18372
18373 transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
18374 error = 1;
18375 }
18376
18377 if (!error && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
18378 ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
18379 transmit_response_reliable(p, "603 Declined (Replaces)", req);
18380 error = 1;
18381 }
18382
18383 if (error) {
18384 append_history(p, "Xfer", "INVITE/Replace Failed.");
18385 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18386 sip_pvt_unlock(p);
18387 if (p->refer->refer_call) {
18388 sip_pvt_unlock(p->refer->refer_call);
18389 if (p->refer->refer_call->owner) {
18390 ast_channel_unlock(p->refer->refer_call->owner);
18391 }
18392 }
18393 p->invitestate = INV_COMPLETED;
18394 return -1;
18395 }
18396 }
18397
18398
18399
18400
18401 if (!req->ignore) {
18402 int newcall = (p->initreq.headers ? TRUE : FALSE);
18403
18404 if (sip_cancel_destroy(p))
18405 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
18406
18407 p->pendinginvite = seqno;
18408 check_via(p, req);
18409
18410 copy_request(&p->initreq, req);
18411 if (sipdebug)
18412 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
18413 if (!p->owner) {
18414 if (debug)
18415 ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
18416 if (newcall)
18417 append_history(p, "Invite", "New call: %s", p->callid);
18418 parse_ok_contact(p, req);
18419 } else {
18420 ast_clear_flag(&p->flags[0], SIP_OUTGOING);
18421
18422 if (find_sdp(req)) {
18423 if (process_sdp(p, req, SDP_T38_INITIATE)) {
18424 transmit_response_reliable(p, "488 Not acceptable here", req);
18425 if (!p->lastinvite)
18426 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18427 return -1;
18428 }
18429 } else {
18430 p->jointcapability = p->capability;
18431 ast_debug(1, "Hm.... No sdp for the moment\n");
18432 }
18433 if (p->do_history)
18434 append_history(p, "ReInv", "Re-invite received");
18435 }
18436 } else if (debug)
18437 ast_verbose("Ignoring this INVITE request\n");
18438
18439
18440 if (!p->lastinvite && !req->ignore && !p->owner) {
18441
18442
18443 res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
18444 if (res == AUTH_CHALLENGE_SENT) {
18445 p->invitestate = INV_COMPLETED;
18446 return 0;
18447 }
18448 if (res < 0) {
18449 if (res == AUTH_FAKE_AUTH) {
18450 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
18451 transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
18452 } else {
18453 ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
18454 transmit_response_reliable(p, "403 Forbidden", req);
18455 }
18456 p->invitestate = INV_COMPLETED;
18457 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18458 ast_string_field_set(p, theirtag, NULL);
18459 return 0;
18460 }
18461
18462
18463 if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
18464 set_t38_capabilities(p);
18465 }
18466
18467
18468 if (find_sdp(req)) {
18469 if (process_sdp(p, req, SDP_T38_INITIATE)) {
18470
18471 transmit_response_reliable(p, "488 Not acceptable here", req);
18472 p->invitestate = INV_COMPLETED;
18473 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18474 ast_debug(1, "No compatible codecs for this SIP call.\n");
18475 return -1;
18476 }
18477 } else {
18478 p->jointcapability = p->capability;
18479 ast_debug(2, "No SDP in Invite, third party call control\n");
18480 }
18481
18482
18483
18484 if (p->owner)
18485 ast_queue_frame(p->owner, &ast_null_frame);
18486
18487
18488
18489 if (ast_strlen_zero(p->context))
18490 ast_string_field_set(p, context, default_context);
18491
18492
18493
18494 ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
18495 if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
18496 if (res < 0) {
18497 ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
18498 transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
18499 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18500 p->invitestate = INV_COMPLETED;
18501 }
18502 return 0;
18503 }
18504 gotdest = get_destination(p, NULL);
18505 get_rdnis(p, NULL);
18506 extract_uri(p, req);
18507 build_contact(p);
18508
18509 if (p->rtp) {
18510 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
18511 ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
18512 }
18513
18514 if (!replace_id && gotdest) {
18515 if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
18516 transmit_response_reliable(p, "484 Address Incomplete", req);
18517 else {
18518 char *decoded_exten = ast_strdupa(p->exten);
18519
18520 transmit_response_reliable(p, "404 Not Found", req);
18521 ast_uri_decode(decoded_exten);
18522 ast_log(LOG_NOTICE, "Call from '%s' to extension"
18523 " '%s' rejected because extension not found.\n",
18524 S_OR(p->username, p->peername), decoded_exten);
18525 }
18526 p->invitestate = INV_COMPLETED;
18527 update_call_counter(p, DEC_CALL_LIMIT);
18528 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18529 return 0;
18530 } else {
18531
18532
18533
18534 if (ast_strlen_zero(p->exten))
18535 ast_string_field_set(p, exten, "s");
18536
18537
18538 make_our_tag(p->tag, sizeof(p->tag));
18539
18540 c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
18541 *recount = 1;
18542
18543
18544 build_route(p, req, 0);
18545
18546 if (c) {
18547
18548 ast_channel_lock(c);
18549 }
18550 }
18551 } else {
18552 if (sipdebug) {
18553 if (!req->ignore)
18554 ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
18555 else
18556 ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
18557 }
18558 if (!req->ignore)
18559 reinvite = 1;
18560 c = p->owner;
18561 }
18562
18563
18564 if (p->sipoptions & SIP_OPT_TIMER) {
18565
18566
18567 ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
18568
18569
18570 if (!p->stimer)
18571 sip_st_alloc(p);
18572
18573
18574 p_uac_se_hdr = get_header(req, "Session-Expires");
18575 if (!ast_strlen_zero(p_uac_se_hdr)) {
18576 rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
18577 if (rtn != 0) {
18578 transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
18579 p->invitestate = INV_COMPLETED;
18580 if (!p->lastinvite) {
18581 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18582 }
18583 return -1;
18584 }
18585 }
18586
18587
18588 p_uac_min_se = get_header(req, "Min-SE");
18589 if (!ast_strlen_zero(p_uac_min_se)) {
18590 rtn = parse_minse(p_uac_min_se, &uac_min_se);
18591 if (rtn != 0) {
18592 transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
18593 p->invitestate = INV_COMPLETED;
18594 if (!p->lastinvite) {
18595 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18596 }
18597 return -1;
18598 }
18599 }
18600
18601 dlg_min_se = st_get_se(p, FALSE);
18602 switch (st_get_mode(p)) {
18603 case SESSION_TIMER_MODE_ACCEPT:
18604 case SESSION_TIMER_MODE_ORIGINATE:
18605 if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
18606 transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
18607 p->invitestate = INV_COMPLETED;
18608 if (!p->lastinvite) {
18609 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18610 }
18611 return -1;
18612 }
18613
18614 p->stimer->st_active_peer_ua = TRUE;
18615 st_active = TRUE;
18616 if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
18617 st_ref = st_get_refresher(p);
18618 }
18619
18620 if (uac_max_se > 0) {
18621 int dlg_max_se = st_get_se(p, TRUE);
18622 if (dlg_max_se >= uac_min_se) {
18623 st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
18624 } else {
18625 st_interval = uac_max_se;
18626 }
18627 } else {
18628 st_interval = uac_min_se;
18629 }
18630 break;
18631
18632 case SESSION_TIMER_MODE_REFUSE:
18633 if (p->reqsipoptions & SIP_OPT_TIMER) {
18634 transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
18635 ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
18636 p->invitestate = INV_COMPLETED;
18637 if (!p->lastinvite) {
18638 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18639 }
18640 return -1;
18641 }
18642 break;
18643
18644 default:
18645 ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
18646 break;
18647 }
18648 } else {
18649
18650
18651
18652 switch (st_get_mode(p)) {
18653 case SESSION_TIMER_MODE_ORIGINATE:
18654 st_active = TRUE;
18655 st_interval = st_get_se(p, TRUE);
18656 st_ref = SESSION_TIMER_REFRESHER_UAS;
18657 p->stimer->st_active_peer_ua = FALSE;
18658 break;
18659
18660 default:
18661 break;
18662 }
18663 }
18664
18665 if (reinvite == 0) {
18666
18667 if (st_active == TRUE) {
18668 p->stimer->st_active = TRUE;
18669 p->stimer->st_interval = st_interval;
18670 p->stimer->st_ref = st_ref;
18671 start_session_timer(p);
18672 }
18673 } else {
18674 if (p->stimer->st_active == TRUE) {
18675
18676
18677
18678 ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
18679
18680
18681 if (st_interval > 0) {
18682 p->stimer->st_interval = st_interval;
18683 p->stimer->st_ref = st_ref;
18684 }
18685
18686 restart_session_timer(p);
18687 if (p->stimer->st_expirys > 0) {
18688 p->stimer->st_expirys--;
18689 }
18690 }
18691 }
18692
18693 if (!req->ignore && p)
18694 p->lastinvite = seqno;
18695
18696 if (replace_id) {
18697
18698 if (sipdebug)
18699 ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
18700 return handle_invite_replaces(p, req, debug, seqno, sin);
18701 }
18702
18703
18704 if (c) {
18705 enum ast_channel_state c_state = c->_state;
18706
18707 if (c_state != AST_STATE_UP && reinvite &&
18708 (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718 c_state = AST_STATE_UP;
18719 }
18720
18721 switch(c_state) {
18722 case AST_STATE_DOWN:
18723 ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
18724 transmit_response(p, "100 Trying", req);
18725 p->invitestate = INV_PROCEEDING;
18726 ast_setstate(c, AST_STATE_RING);
18727 if (strcmp(p->exten, ast_pickup_ext())) {
18728 enum ast_pbx_result result;
18729
18730 result = ast_pbx_start(c);
18731
18732 switch(result) {
18733 case AST_PBX_FAILED:
18734 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
18735 p->invitestate = INV_COMPLETED;
18736 transmit_response_reliable(p, "503 Unavailable", req);
18737 break;
18738 case AST_PBX_CALL_LIMIT:
18739 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
18740 p->invitestate = INV_COMPLETED;
18741 transmit_response_reliable(p, "480 Temporarily Unavailable", req);
18742 break;
18743 case AST_PBX_SUCCESS:
18744
18745 break;
18746 }
18747
18748 if (result) {
18749
18750
18751 ast_channel_unlock(c);
18752 sip_pvt_unlock(p);
18753 ast_hangup(c);
18754 sip_pvt_lock(p);
18755 c = NULL;
18756 }
18757 } else {
18758 ast_channel_unlock(c);
18759 *nounlock = 1;
18760 if (ast_pickup_call(c)) {
18761 ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
18762 transmit_response_reliable(p, "503 Unavailable", req);
18763 sip_alreadygone(p);
18764
18765 sip_pvt_unlock(p);
18766 c->hangupcause = AST_CAUSE_CALL_REJECTED;
18767 } else {
18768 sip_pvt_unlock(p);
18769 ast_setstate(c, AST_STATE_DOWN);
18770 c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18771 }
18772 p->invitestate = INV_COMPLETED;
18773 ast_hangup(c);
18774 sip_pvt_lock(p);
18775 c = NULL;
18776 }
18777 break;
18778 case AST_STATE_RING:
18779 transmit_response(p, "100 Trying", req);
18780 p->invitestate = INV_PROCEEDING;
18781 break;
18782 case AST_STATE_RINGING:
18783 transmit_response(p, "180 Ringing", req);
18784 p->invitestate = INV_PROCEEDING;
18785 break;
18786 case AST_STATE_UP:
18787 ast_debug(2, "%s: This call is UP.... \n", c->name);
18788
18789 transmit_response(p, "100 Trying", req);
18790
18791 if (p->t38.state == T38_PEER_REINVITE) {
18792 p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
18793 } else if (p->t38.state == T38_ENABLED) {
18794 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18795 transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)));
18796 } else if (p->t38.state == T38_DISABLED) {
18797
18798 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18799 transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE);
18800 }
18801
18802 p->invitestate = INV_TERMINATED;
18803 break;
18804 default:
18805 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
18806 transmit_response(p, "100 Trying", req);
18807 break;
18808 }
18809 } else {
18810 if (p && (p->autokillid == -1)) {
18811 const char *msg;
18812
18813 if (!p->jointcapability)
18814 msg = "488 Not Acceptable Here (codec error)";
18815 else {
18816 ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
18817 msg = "503 Unavailable";
18818 }
18819 transmit_response_reliable(p, msg, req);
18820 p->invitestate = INV_COMPLETED;
18821 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18822 }
18823 }
18824 return res;
18825 }
18826
18827
18828
18829 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
18830 {
18831 struct sip_dual target;
18832
18833 int res = 0;
18834 struct sip_pvt *targetcall_pvt;
18835
18836
18837 if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
18838 transferer->refer->replaces_callid_fromtag))) {
18839 if (transferer->refer->localtransfer) {
18840
18841 transmit_response(transferer, "202 Accepted", req);
18842
18843
18844 transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
18845 append_history(transferer, "Xfer", "Refer failed");
18846 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
18847 transferer->refer->status = REFER_FAILED;
18848 return -1;
18849 }
18850
18851 ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
18852 return 0;
18853 }
18854
18855
18856 transmit_response(transferer, "202 Accepted", req);
18857 append_history(transferer, "Xfer", "Refer accepted");
18858 if (!targetcall_pvt->owner) {
18859 ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
18860
18861 transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
18862 append_history(transferer, "Xfer", "Refer failed");
18863 ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
18864 transferer->refer->status = REFER_FAILED;
18865 sip_pvt_unlock(targetcall_pvt);
18866 if (targetcall_pvt)
18867 ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
18868 return -1;
18869 }
18870
18871
18872 target.chan1 = targetcall_pvt->owner;
18873 target.chan2 = ast_bridged_channel(targetcall_pvt->owner);
18874
18875 if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
18876
18877 if (target.chan2)
18878 ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
18879 else if (target.chan1->_state != AST_STATE_RING)
18880 ast_debug(4, "SIP attended transfer: Error: No target channel\n");
18881 else
18882 ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
18883 }
18884
18885
18886 if (sipdebug) {
18887 if (current->chan2)
18888 ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
18889 else
18890 ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
18891 }
18892
18893 ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
18894
18895
18896 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
18897 transferer->owner->name,
18898 transferer->owner->uniqueid,
18899 transferer->callid,
18900 target.chan1->name,
18901 target.chan1->uniqueid);
18902 res = attempt_transfer(current, &target);
18903 sip_pvt_unlock(targetcall_pvt);
18904 if (res) {
18905
18906 transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
18907 append_history(transferer, "Xfer", "Refer failed");
18908 if (targetcall_pvt->owner)
18909 ast_channel_unlock(targetcall_pvt->owner);
18910 ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
18911 } else {
18912
18913
18914
18915 transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
18916 append_history(transferer, "Xfer", "Refer succeeded");
18917 transferer->refer->status = REFER_200OK;
18918 if (targetcall_pvt->owner) {
18919 ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
18920 ast_channel_unlock(targetcall_pvt->owner);
18921 }
18922 }
18923 if (targetcall_pvt)
18924 ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
18925 return 1;
18926 }
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
18993 {
18994 struct sip_dual current;
18995
18996
18997 int res = 0;
18998 current.req.data = NULL;
18999
19000 if (req->debug)
19001 ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
19002
19003 if (!p->owner) {
19004
19005
19006 ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
19007 transmit_response(p, "603 Declined (No dialog)", req);
19008 if (!req->ignore) {
19009 append_history(p, "Xfer", "Refer failed. Outside of dialog.");
19010 sip_alreadygone(p);
19011 p->needdestroy = 1;
19012 }
19013 return 0;
19014 }
19015
19016
19017
19018 if (p->allowtransfer == TRANSFER_CLOSED ) {
19019
19020 transmit_response(p, "603 Declined (policy)", req);
19021 append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
19022
19023 return 0;
19024 }
19025
19026 if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
19027
19028 transmit_response(p, "491 Request pending", req);
19029 append_history(p, "Xfer", "Refer failed. Request pending.");
19030 return 0;
19031 }
19032
19033
19034 if (!p->refer && !sip_refer_allocate(p)) {
19035 transmit_response(p, "500 Internal Server Error", req);
19036 append_history(p, "Xfer", "Refer failed. Memory allocation error.");
19037 return -3;
19038 }
19039
19040 res = get_refer_info(p, req);
19041
19042 p->refer->status = REFER_SENT;
19043
19044 if (res != 0) {
19045 switch (res) {
19046 case -2:
19047 transmit_response(p, "400 Bad Request (Refer-to missing)", req);
19048 append_history(p, "Xfer", "Refer failed. Refer-to missing.");
19049 if (req->debug)
19050 ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
19051 break;
19052 case -3:
19053 transmit_response(p, "603 Declined (Non sip: uri)", req);
19054 append_history(p, "Xfer", "Refer failed. Non SIP uri");
19055 if (req->debug)
19056 ast_debug(1, "SIP transfer to non-SIP uri denied\n");
19057 break;
19058 default:
19059
19060 transmit_response(p, "202 Accepted", req);
19061 append_history(p, "Xfer", "Refer failed. Bad extension.");
19062 transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
19063 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19064 if (req->debug)
19065 ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
19066 break;
19067 }
19068 return 0;
19069 }
19070 if (ast_strlen_zero(p->context))
19071 ast_string_field_set(p, context, default_context);
19072
19073
19074 if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19075 p->refer->localtransfer = 1;
19076 if (sipdebug)
19077 ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
19078 } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19079
19080 p->refer->localtransfer = 1;
19081 } else if (sipdebug)
19082 ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
19083
19084
19085
19086 if (req->ignore)
19087 return res;
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115 current.chan1 = p->owner;
19116
19117
19118 current.chan2 = ast_bridged_channel(current.chan1);
19119
19120 if (sipdebug)
19121 ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
19122
19123 if (!current.chan2 && !p->refer->attendedtransfer) {
19124
19125
19126
19127 if (sipdebug)
19128 ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
19129 p->refer->status = REFER_FAILED;
19130 append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
19131 transmit_response(p, "603 Declined", req);
19132 return -1;
19133 }
19134
19135 if (current.chan2) {
19136 if (sipdebug)
19137 ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
19138
19139 ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
19140 }
19141
19142 ast_set_flag(&p->flags[0], SIP_GOTREFER);
19143
19144
19145 if (p->refer->attendedtransfer) {
19146 if ((res = local_attended_transfer(p, ¤t, req, seqno)))
19147 return res;
19148
19149 if (sipdebug)
19150 ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
19151
19152 }
19153
19154
19155
19156 if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
19157
19158 *nounlock = 1;
19159 ast_channel_unlock(current.chan1);
19160 copy_request(¤t.req, req);
19161 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19162 p->refer->status = REFER_200OK;
19163 append_history(p, "Xfer", "REFER to call parking.");
19164 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
19165 current.chan1->name,
19166 current.chan1->uniqueid,
19167 p->callid,
19168 current.chan2->name,
19169 current.chan2->uniqueid,
19170 p->refer->refer_to);
19171 if (sipdebug)
19172 ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
19173 sip_park(current.chan2, current.chan1, req, seqno);
19174 return res;
19175 }
19176
19177
19178 transmit_response(p, "202 Accepted", req);
19179
19180 if (current.chan1 && current.chan2) {
19181 ast_debug(3, "chan1->name: %s\n", current.chan1->name);
19182 pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
19183 }
19184 if (current.chan2) {
19185 pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
19186 pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
19187 pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
19188
19189 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
19190
19191 if (p->refer->referred_by)
19192 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
19193 }
19194
19195 if (!ast_strlen_zero(p->refer->replaces_callid)) {
19196 char tempheader[SIPBUFSIZE];
19197 snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
19198 p->refer->replaces_callid_totag ? ";to-tag=" : "",
19199 p->refer->replaces_callid_totag,
19200 p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
19201 p->refer->replaces_callid_fromtag);
19202 if (current.chan2)
19203 pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
19204 }
19205
19206
19207 *nounlock = 1;
19208 ast_channel_unlock(current.chan1);
19209
19210
19211
19212
19213 if (!p->refer->attendedtransfer)
19214 transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE);
19215
19216
19217
19218
19219
19220 if (!current.chan2) {
19221
19222
19223
19224
19225
19226
19227
19228 p->refer->status = REFER_FAILED;
19229 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
19230 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19231 append_history(p, "Xfer", "Refer failed (only bridged calls).");
19232 return -1;
19233 }
19234 ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19235
19236
19237
19238
19239 res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
19240
19241 if (!res) {
19242 manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
19243 current.chan1->name,
19244 current.chan1->uniqueid,
19245 p->callid,
19246 current.chan2->name,
19247 current.chan2->uniqueid,
19248 p->refer->refer_to, p->refer->refer_to_context);
19249
19250 ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19251 transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
19252 if (p->refer->localtransfer)
19253 p->refer->status = REFER_200OK;
19254 if (p->owner)
19255 p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19256 append_history(p, "Xfer", "Refer succeeded.");
19257 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19258
19259
19260 res = 0;
19261 } else {
19262 ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19263 ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19264 append_history(p, "Xfer", "Refer failed.");
19265
19266 p->refer->status = REFER_FAILED;
19267 transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
19268 ast_clear_flag(&p->flags[0], SIP_GOTREFER);
19269 res = -1;
19270 }
19271 return res;
19272 }
19273
19274
19275 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
19276 {
19277
19278 check_via(p, req);
19279 sip_alreadygone(p);
19280
19281
19282
19283
19284
19285
19286 if (p->invitestate == INV_TERMINATED)
19287 __sip_pretend_ack(p);
19288 else
19289 p->invitestate = INV_CANCELLED;
19290
19291 if (p->owner && p->owner->_state == AST_STATE_UP) {
19292
19293 transmit_response(p, "200 OK", req);
19294 ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
19295 return 0;
19296 }
19297
19298 if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
19299 update_call_counter(p, DEC_CALL_LIMIT);
19300
19301 stop_media_flows(p);
19302 if (p->owner)
19303 ast_queue_hangup(p->owner);
19304 else
19305 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19306 if (p->initreq.len > 0) {
19307 struct sip_pkt *pkt, *prev_pkt;
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319 for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
19320 if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
19321 AST_SCHED_DEL(sched, pkt->retransid);
19322 UNLINK(pkt, p->packets, prev_pkt);
19323 ast_free(pkt);
19324 break;
19325 }
19326 }
19327 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
19328 transmit_response(p, "200 OK", req);
19329 return 1;
19330 } else {
19331 transmit_response(p, "481 Call Leg Does Not Exist", req);
19332 return 0;
19333 }
19334 }
19335
19336 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
19337 {
19338 struct sip_pvt *p = chan->tech_pvt;
19339 char *all = "", *parse = ast_strdupa(preparse);
19340 int res = 0;
19341 AST_DECLARE_APP_ARGS(args,
19342 AST_APP_ARG(param);
19343 AST_APP_ARG(type);
19344 AST_APP_ARG(field);
19345 );
19346 AST_STANDARD_APP_ARGS(args, parse);
19347
19348
19349 if (!IS_SIP_TECH(chan->tech)) {
19350 ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
19351 return 0;
19352 }
19353
19354 memset(buf, 0, buflen);
19355
19356 if (p == NULL) {
19357 return -1;
19358 }
19359
19360 if (!strcasecmp(args.param, "peerip")) {
19361 ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
19362 } else if (!strcasecmp(args.param, "recvip")) {
19363 ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
19364 } else if (!strcasecmp(args.param, "from")) {
19365 ast_copy_string(buf, p->from, buflen);
19366 } else if (!strcasecmp(args.param, "uri")) {
19367 ast_copy_string(buf, p->uri, buflen);
19368 } else if (!strcasecmp(args.param, "useragent")) {
19369 ast_copy_string(buf, p->useragent, buflen);
19370 } else if (!strcasecmp(args.param, "peername")) {
19371 ast_copy_string(buf, p->peername, buflen);
19372 } else if (!strcasecmp(args.param, "t38passthrough")) {
19373 ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
19374 } else if (!strcasecmp(args.param, "rtpdest")) {
19375 struct sockaddr_in sin;
19376
19377 if (ast_strlen_zero(args.type))
19378 args.type = "audio";
19379
19380 if (!strcasecmp(args.type, "audio"))
19381 ast_rtp_get_peer(p->rtp, &sin);
19382 else if (!strcasecmp(args.type, "video"))
19383 ast_rtp_get_peer(p->vrtp, &sin);
19384 else if (!strcasecmp(args.type, "text"))
19385 ast_rtp_get_peer(p->trtp, &sin);
19386 else
19387 return -1;
19388
19389 snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
19390 } else if (!strcasecmp(args.param, "rtpqos")) {
19391 struct ast_rtp_quality qos;
19392 struct ast_rtp *rtp = p->rtp;
19393
19394 memset(&qos, 0, sizeof(qos));
19395
19396 if (ast_strlen_zero(args.type))
19397 args.type = "audio";
19398 if (ast_strlen_zero(args.field))
19399 args.field = "all";
19400
19401 if (!strcasecmp(args.type, "AUDIO")) {
19402 all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
19403 } else if (!strcasecmp(args.type, "VIDEO")) {
19404 all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
19405 } else if (!strcasecmp(args.type, "TEXT")) {
19406 all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
19407 } else {
19408 return -1;
19409 }
19410
19411 if (!strcasecmp(args.field, "local_ssrc"))
19412 snprintf(buf, buflen, "%u", qos.local_ssrc);
19413 else if (!strcasecmp(args.field, "local_lostpackets"))
19414 snprintf(buf, buflen, "%u", qos.local_lostpackets);
19415 else if (!strcasecmp(args.field, "local_jitter"))
19416 snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
19417 else if (!strcasecmp(args.field, "local_count"))
19418 snprintf(buf, buflen, "%u", qos.local_count);
19419 else if (!strcasecmp(args.field, "remote_ssrc"))
19420 snprintf(buf, buflen, "%u", qos.remote_ssrc);
19421 else if (!strcasecmp(args.field, "remote_lostpackets"))
19422 snprintf(buf, buflen, "%u", qos.remote_lostpackets);
19423 else if (!strcasecmp(args.field, "remote_jitter"))
19424 snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
19425 else if (!strcasecmp(args.field, "remote_count"))
19426 snprintf(buf, buflen, "%u", qos.remote_count);
19427 else if (!strcasecmp(args.field, "rtt"))
19428 snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
19429 else if (!strcasecmp(args.field, "all"))
19430 ast_copy_string(buf, all, buflen);
19431 else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
19432 ;
19433 else {
19434 ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
19435 return -1;
19436 }
19437 } else {
19438 res = -1;
19439 }
19440 return res;
19441 }
19442
19443
19444 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
19445 {
19446 struct ast_channel *c=NULL;
19447 int res;
19448 struct ast_channel *bridged_to;
19449
19450
19451 if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
19452 transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
19453 }
19454
19455 __sip_pretend_ack(p);
19456
19457 p->invitestate = INV_TERMINATED;
19458
19459 copy_request(&p->initreq, req);
19460 if (sipdebug)
19461 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19462 check_via(p, req);
19463 sip_alreadygone(p);
19464
19465
19466 if (p->do_history || p->owner) {
19467 struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
19468 char *videoqos, *textqos;
19469
19470
19471
19472
19473 while (bridge && ast_channel_trylock(bridge)) {
19474 ast_channel_unlock(p->owner);
19475 do {
19476
19477 sip_pvt_unlock(p);
19478 usleep(1);
19479 sip_pvt_lock(p);
19480 } while (p->owner && ast_channel_trylock(p->owner));
19481 bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
19482 }
19483
19484 if (p->rtp) {
19485 if (p->do_history) {
19486 char *audioqos,
19487 *audioqos_jitter,
19488 *audioqos_loss,
19489 *audioqos_rtt;
19490
19491 audioqos = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
19492 audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
19493 audioqos_loss = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
19494 audioqos_rtt = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
19495
19496 append_history(p, "RTCPaudio", "Quality:%s", audioqos);
19497 append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
19498 append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
19499 append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
19500 }
19501
19502 if (p->owner) {
19503 ast_rtp_set_vars(p->owner, p->rtp);
19504 }
19505 }
19506
19507 if (bridge) {
19508 struct sip_pvt *q = bridge->tech_pvt;
19509
19510 if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
19511 ast_rtp_set_vars(bridge, q->rtp);
19512 ast_channel_unlock(bridge);
19513 }
19514
19515 if (p->vrtp) {
19516 videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
19517 if (p->do_history)
19518 append_history(p, "RTCPvideo", "Quality:%s", videoqos);
19519 if (p->owner)
19520 pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
19521 }
19522
19523 if (p->trtp) {
19524 textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
19525 if (p->do_history)
19526 append_history(p, "RTCPtext", "Quality:%s", textqos);
19527 if (p->owner)
19528 pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
19529 }
19530 }
19531
19532 stop_media_flows(p);
19533 stop_session_timer(p);
19534
19535 if (!ast_strlen_zero(get_header(req, "Also"))) {
19536 ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method. Ask vendor to support REFER instead\n",
19537 ast_inet_ntoa(p->recv.sin_addr));
19538 if (ast_strlen_zero(p->context))
19539 ast_string_field_set(p, context, default_context);
19540 res = get_also_info(p, req);
19541 if (!res) {
19542 c = p->owner;
19543 if (c) {
19544 bridged_to = ast_bridged_channel(c);
19545 if (bridged_to) {
19546
19547 ast_queue_control(c, AST_CONTROL_UNHOLD);
19548 ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
19549 } else
19550 ast_queue_hangup(p->owner);
19551 }
19552 } else {
19553 ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
19554 if (p->owner)
19555 ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
19556 }
19557 } else if (p->owner) {
19558 ast_queue_hangup(p->owner);
19559 ast_debug(3, "Received bye, issuing owner hangup\n");
19560 } else {
19561 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19562 ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
19563 }
19564 ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19565 transmit_response(p, "200 OK", req);
19566
19567 return 1;
19568 }
19569
19570
19571 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
19572 {
19573 if (!req->ignore) {
19574 if (req->debug)
19575 ast_verbose("Receiving message!\n");
19576 receive_message(p, req);
19577 } else
19578 transmit_response(p, "202 Accepted", req);
19579 return 1;
19580 }
19581
19582 static void add_peer_mwi_subs(struct sip_peer *peer)
19583 {
19584 struct sip_mailbox *mailbox;
19585
19586 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
19587 mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
19588 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
19589 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
19590 AST_EVENT_IE_END);
19591 }
19592 }
19593
19594
19595 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
19596 {
19597 int gotdest = 0;
19598 int res = 0;
19599 int firststate = AST_EXTENSION_REMOVED;
19600 struct sip_peer *authpeer = NULL;
19601 const char *eventheader = get_header(req, "Event");
19602 const char *acceptheader = get_header(req, "Accept");
19603 int resubscribe = (p->subscribed != NONE);
19604 char *temp, *event;
19605 struct ao2_iterator i;
19606
19607 if (p->initreq.headers) {
19608
19609 if (p->initreq.method != SIP_SUBSCRIBE) {
19610
19611
19612 transmit_response(p, "403 Forbidden (within dialog)", req);
19613
19614 ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
19615 return 0;
19616 } else if (req->debug) {
19617 if (resubscribe)
19618 ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
19619 else
19620 ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
19621 }
19622 }
19623
19624
19625
19626
19627 if (!global_allowsubscribe) {
19628 transmit_response(p, "403 Forbidden (policy)", req);
19629 p->needdestroy = 1;
19630 return 0;
19631 }
19632
19633 if (!req->ignore && !resubscribe) {
19634 const char *to = get_header(req, "To");
19635 char totag[128];
19636
19637
19638 if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
19639 if (req->debug)
19640 ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
19641 transmit_response(p, "481 Subscription does not exist", req);
19642 p->needdestroy = 1;
19643 return 0;
19644 }
19645
19646
19647 if (req->debug)
19648 ast_verbose("Creating new subscription\n");
19649
19650 copy_request(&p->initreq, req);
19651 if (sipdebug)
19652 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19653 check_via(p, req);
19654 build_route(p, req, 0);
19655 } else if (req->debug && req->ignore)
19656 ast_verbose("Ignoring this SUBSCRIBE request\n");
19657
19658
19659 if (ast_strlen_zero(eventheader)) {
19660 transmit_response(p, "489 Bad Event", req);
19661 ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
19662 p->needdestroy = 1;
19663 return 0;
19664 }
19665
19666 if ( (strchr(eventheader, ';'))) {
19667 event = ast_strdupa(eventheader);
19668 temp = strchr(event, ';');
19669 *temp = '\0';
19670
19671 } else
19672 event = (char *) eventheader;
19673
19674
19675 res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
19676
19677 if (res == AUTH_CHALLENGE_SENT)
19678 return 0;
19679 if (res < 0) {
19680 if (res == AUTH_FAKE_AUTH) {
19681 ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
19682 transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
19683 } else {
19684 ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
19685 transmit_response_reliable(p, "403 Forbidden", req);
19686 }
19687 p->needdestroy = 1;
19688 return 0;
19689 }
19690
19691
19692
19693
19694
19695
19696
19697 if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
19698 transmit_response(p, "403 Forbidden (policy)", req);
19699 p->needdestroy = 1;
19700 if (authpeer)
19701 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
19702 return 0;
19703 }
19704
19705 if (strcmp(event, "message-summary")) {
19706
19707 gotdest = get_destination(p, NULL);
19708 }
19709
19710
19711 parse_ok_contact(p, req);
19712
19713 build_contact(p);
19714 if (gotdest) {
19715 transmit_response(p, "404 Not Found", req);
19716 p->needdestroy = 1;
19717 if (authpeer)
19718 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
19719 return 0;
19720 }
19721
19722
19723 if (ast_strlen_zero(p->tag))
19724 make_our_tag(p->tag, sizeof(p->tag));
19725
19726 if (!strcmp(event, "presence") || !strcmp(event, "dialog")) {
19727 unsigned int pidf_xml;
19728
19729 if (authpeer)
19730 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
19731
19732
19733
19734 pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
19735
19736
19737
19738 if (pidf_xml && strstr(p->useragent, "Polycom")) {
19739 p->subscribed = XPIDF_XML;
19740 } else if (pidf_xml) {
19741 p->subscribed = PIDF_XML;
19742 } else if (strstr(acceptheader, "application/dialog-info+xml")) {
19743 p->subscribed = DIALOG_INFO_XML;
19744
19745 } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
19746 p->subscribed = CPIM_PIDF_XML;
19747 } else if (strstr(acceptheader, "application/xpidf+xml")) {
19748 p->subscribed = XPIDF_XML;
19749 } else if (ast_strlen_zero(acceptheader)) {
19750 if (p->subscribed == NONE) {
19751 transmit_response(p, "489 Bad Event", req);
19752
19753 ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
19754 p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
19755 p->needdestroy = 1;
19756 return 0;
19757 }
19758
19759
19760 } else {
19761
19762 char mybuf[200];
19763 snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
19764 transmit_response(p, mybuf, req);
19765
19766 ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
19767 acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
19768 p->needdestroy = 1;
19769 return 0;
19770 }
19771 } else if (!strcmp(event, "message-summary")) {
19772 if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
19773
19774 transmit_response(p, "406 Not Acceptable", req);
19775 ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
19776 p->needdestroy = 1;
19777 if (authpeer)
19778 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
19779 return 0;
19780 }
19781
19782
19783
19784
19785
19786 if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
19787 transmit_response(p, "404 Not found (no mailbox)", req);
19788 p->needdestroy = 1;
19789 ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
19790 if (authpeer)
19791 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
19792 return 0;
19793 }
19794
19795 p->subscribed = MWI_NOTIFICATION;
19796 if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
19797 add_peer_mwi_subs(authpeer);
19798 }
19799 if (authpeer->mwipvt && authpeer->mwipvt != p) {
19800
19801 dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
19802 authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
19803
19804 }
19805 if (authpeer->mwipvt)
19806 dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
19807 authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
19808 if (p->relatedpeer)
19809 unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
19810 p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
19811
19812 } else {
19813 transmit_response(p, "489 Bad Event", req);
19814 ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
19815 p->needdestroy = 1;
19816 if (authpeer)
19817 unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
19818 return 0;
19819 }
19820
19821
19822 if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
19823 if (p->stateid > -1) {
19824 ast_extension_state_del(p->stateid, cb_extensionstate);
19825
19826 dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
19827 }
19828 p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
19829 }
19830
19831 if (!req->ignore && p)
19832 p->lastinvite = seqno;
19833 if (p && !p->needdestroy) {
19834 p->expiry = atoi(get_header(req, "Expires"));
19835
19836
19837 if (p->expiry > max_expiry)
19838 p->expiry = max_expiry;
19839 if (p->expiry < min_expiry && p->expiry > 0)
19840 p->expiry = min_expiry;
19841
19842 if (sipdebug) {
19843 if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
19844 ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
19845 else
19846 ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
19847 }
19848 if (p->autokillid > -1 && sip_cancel_destroy(p))
19849 ast_log(LOG_WARNING, "Unable to cancel SIP destruction. Expect bad things.\n");
19850 if (p->expiry > 0)
19851 sip_scheddestroy(p, (p->expiry + 10) * 1000);
19852
19853 if (p->subscribed == MWI_NOTIFICATION) {
19854 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19855 transmit_response(p, "200 OK", req);
19856 if (p->relatedpeer) {
19857 ao2_lock(p->relatedpeer);
19858 sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
19859 ao2_unlock(p->relatedpeer);
19860 }
19861 } else {
19862 struct sip_pvt *p_old;
19863
19864 if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
19865
19866 ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
19867 transmit_response(p, "404 Not found", req);
19868 p->needdestroy = 1;
19869 return 0;
19870 }
19871 ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19872 transmit_response(p, "200 OK", req);
19873 transmit_state_notify(p, firststate, 1, FALSE);
19874 append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
19875
19876 ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
19877
19878
19879
19880
19881
19882
19883 i = ao2_iterator_init(dialogs, 0);
19884
19885 while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19886 if (p_old == p) {
19887 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19888 continue;
19889 }
19890 if (p_old->initreq.method != SIP_SUBSCRIBE) {
19891 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19892 continue;
19893 }
19894 if (p_old->subscribed == NONE) {
19895 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
19896 continue;
19897 }
19898 sip_pvt_lock(p_old);
19899 if (!strcmp(p_old->username, p->username)) {
19900 if (!strcmp(p_old->exten, p->exten) &&
19901 !strcmp(p_old->context, p->context)) {
19902 p_old->needdestroy = 1;
19903 sip_pvt_unlock(p_old);
19904 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
19905 break;
19906 }
19907 }
19908 sip_pvt_unlock(p_old);
19909 ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
19910 }
19911 }
19912 if (!p->expiry)
19913 p->needdestroy = 1;
19914 }
19915 return 1;
19916 }
19917
19918
19919 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
19920 {
19921 enum check_auth_result res;
19922
19923
19924 copy_request(&p->initreq, req);
19925 if (sipdebug)
19926 ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19927 check_via(p, req);
19928 if ((res = register_verify(p, sin, req, e)) < 0) {
19929 const char *reason;
19930
19931 switch (res) {
19932 case AUTH_SECRET_FAILED:
19933 reason = "Wrong password";
19934 break;
19935 case AUTH_USERNAME_MISMATCH:
19936 reason = "Username/auth name mismatch";
19937 break;
19938 case AUTH_NOT_FOUND:
19939 reason = "No matching peer found";
19940 break;
19941 case AUTH_UNKNOWN_DOMAIN:
19942 reason = "Not a local domain";
19943 break;
19944 case AUTH_PEER_NOT_DYNAMIC:
19945 reason = "Peer is not supposed to register";
19946 break;
19947 case AUTH_ACL_FAILED:
19948 reason = "Device does not match ACL";
19949 break;
19950 case AUTH_BAD_TRANSPORT:
19951 reason = "Device not configured to use this transport type";
19952 break;
19953 default:
19954 reason = "Unknown failure";
19955 break;
19956 }
19957 ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
19958 get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
19959 reason);
19960 append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
19961 } else
19962 append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
19963
19964 if (res < 1) {
19965
19966
19967 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19968 }
19969 return res;
19970 }
19971
19972
19973
19974
19975 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
19976 {
19977
19978
19979 const char *cmd;
19980 const char *cseq;
19981 const char *useragent;
19982 int seqno;
19983 int len;
19984 int respid;
19985 int res = 0;
19986 int debug = sip_debug_test_pvt(p);
19987 char *e;
19988 int error = 0;
19989
19990
19991 cseq = get_header(req, "Cseq");
19992 cmd = REQ_OFFSET_TO_STR(req, header[0]);
19993
19994
19995 if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
19996 ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
19997 error = 1;
19998 }
19999 if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
20000 ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
20001 error = 1;
20002 }
20003 if (error) {
20004 if (!p->initreq.headers)
20005 p->needdestroy = 1;
20006 return -1;
20007 }
20008
20009
20010 cmd = REQ_OFFSET_TO_STR(req, rlPart1);
20011 e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
20012
20013
20014 useragent = get_header(req, "User-Agent");
20015 if (!ast_strlen_zero(useragent))
20016 ast_string_field_set(p, useragent, useragent);
20017
20018
20019 if (req->method == SIP_RESPONSE) {
20020
20021
20022
20023
20024
20025
20026 if (ast_strlen_zero(e)) {
20027 return 0;
20028 }
20029 if (sscanf(e, "%30d %n", &respid, &len) != 1) {
20030 ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
20031 return 0;
20032 }
20033 if (respid <= 0) {
20034 ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
20035 return 0;
20036 }
20037 if (p->ocseq && (p->ocseq < seqno)) {
20038 if (option_debug)
20039 ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
20040 return -1;
20041 } else {
20042 if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
20043 extract_uri(p, req);
20044 }
20045 handle_response(p, respid, e + len, req, seqno);
20046 }
20047 return 0;
20048 }
20049
20050
20051
20052
20053
20054 p->method = req->method;
20055 ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
20056
20057 if (p->icseq && (p->icseq > seqno) ) {
20058 if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
20059 ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
20060 } else {
20061 ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
20062 if (req->method != SIP_ACK)
20063 transmit_response(p, "503 Server error", req);
20064 return -1;
20065 }
20066 } else if (p->icseq &&
20067 p->icseq == seqno &&
20068 req->method != SIP_ACK &&
20069 (p->method != SIP_CANCEL || p->alreadygone)) {
20070
20071
20072
20073 req->ignore = 1;
20074 ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
20075 }
20076
20077 if (seqno >= p->icseq)
20078
20079
20080
20081 p->icseq = seqno;
20082
20083
20084 if (ast_strlen_zero(p->theirtag)) {
20085 char tag[128];
20086
20087 gettag(req, "From", tag, sizeof(tag));
20088 ast_string_field_set(p, theirtag, tag);
20089 }
20090 snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
20091
20092 if (pedanticsipchecking) {
20093
20094
20095
20096
20097 if (!p->initreq.headers && req->has_to_tag) {
20098
20099 if (!req->ignore && req->method == SIP_INVITE) {
20100 transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
20101
20102 } else if (req->method != SIP_ACK) {
20103 transmit_response(p, "481 Call/Transaction Does Not Exist", req);
20104 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20105 } else {
20106 ast_debug(1, "Got ACK for unknown dialog... strange.\n");
20107 }
20108 return res;
20109 }
20110 }
20111
20112 if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
20113 transmit_response(p, "400 Bad request", req);
20114 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20115 return -1;
20116 }
20117
20118
20119 switch (p->method) {
20120 case SIP_OPTIONS:
20121 res = handle_request_options(p, req);
20122 break;
20123 case SIP_INVITE:
20124 res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
20125 break;
20126 case SIP_REFER:
20127 res = handle_request_refer(p, req, debug, seqno, nounlock);
20128 break;
20129 case SIP_CANCEL:
20130 res = handle_request_cancel(p, req);
20131 break;
20132 case SIP_BYE:
20133 res = handle_request_bye(p, req);
20134 break;
20135 case SIP_MESSAGE:
20136 res = handle_request_message(p, req);
20137 break;
20138 case SIP_SUBSCRIBE:
20139 res = handle_request_subscribe(p, req, sin, seqno, e);
20140 break;
20141 case SIP_REGISTER:
20142 res = handle_request_register(p, req, sin, e);
20143 break;
20144 case SIP_INFO:
20145 if (req->debug)
20146 ast_verbose("Receiving INFO!\n");
20147 if (!req->ignore)
20148 handle_request_info(p, req);
20149 else
20150 transmit_response(p, "200 OK", req);
20151 break;
20152 case SIP_NOTIFY:
20153 res = handle_request_notify(p, req, sin, seqno, e);
20154 break;
20155 case SIP_ACK:
20156
20157 if (seqno == p->pendinginvite) {
20158 p->invitestate = INV_TERMINATED;
20159 p->pendinginvite = 0;
20160 __sip_ack(p, seqno, 1 , 0);
20161 if (find_sdp(req)) {
20162 if (process_sdp(p, req, SDP_T38_NONE))
20163 return -1;
20164 }
20165 check_pendings(p);
20166 } else if (p->glareinvite == seqno) {
20167
20168 p->glareinvite = 0;
20169 __sip_ack(p, seqno, 1, 0);
20170 }
20171
20172 if (!p->lastinvite && ast_strlen_zero(p->randdata))
20173 p->needdestroy = 1;
20174 break;
20175 default:
20176 transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
20177 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
20178 cmd, ast_inet_ntoa(p->sa.sin_addr));
20179
20180 if (!p->initreq.headers)
20181 p->needdestroy = 1;
20182 break;
20183 }
20184 return res;
20185 }
20186
20187 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
20188 {
20189 struct sip_request *req;
20190
20191 while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
20192 if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
20193
20194 if (option_debug) {
20195 ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
20196 }
20197 }
20198 ast_free(req);
20199 }
20200 }
20201
20202 static int scheduler_process_request_queue(const void *data)
20203 {
20204 struct sip_pvt *p = (struct sip_pvt *) data;
20205 int recount = 0;
20206 int nounlock = 0;
20207 int lockretry;
20208
20209 for (lockretry = 10; lockretry > 0; lockretry--) {
20210 sip_pvt_lock(p);
20211
20212
20213
20214 if (!p->owner || !ast_channel_trylock(p->owner)) {
20215 break;
20216 }
20217
20218 if (lockretry != 1) {
20219 sip_pvt_unlock(p);
20220
20221 usleep(1);
20222 }
20223 }
20224
20225 if (!lockretry) {
20226 int retry = !AST_LIST_EMPTY(&p->request_queue);
20227
20228
20229
20230
20231
20232
20233 sip_pvt_unlock(p);
20234 if (!retry) {
20235 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20236 }
20237 return retry;
20238 };
20239
20240 process_request_queue(p, &recount, &nounlock);
20241 p->request_queue_sched_id = -1;
20242
20243 if (p->owner && !nounlock) {
20244 ast_channel_unlock(p->owner);
20245 }
20246 sip_pvt_unlock(p);
20247
20248 if (recount) {
20249 ast_update_use_count();
20250 }
20251
20252 dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20253
20254 return 0;
20255 }
20256
20257 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
20258 {
20259 struct sip_request *newreq;
20260
20261 if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
20262 return -1;
20263 }
20264
20265 copy_request(newreq, req);
20266 AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
20267 if (p->request_queue_sched_id == -1) {
20268 if ((p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, dialog_ref(p, "Increment refcount to pass dialog pointer to sched callback"))) == -1) {
20269 dialog_unref(p, "Decrement refcount due to sched_add failure");
20270 }
20271 }
20272
20273 return 0;
20274 }
20275
20276
20277
20278
20279
20280
20281 static int sipsock_read(int *id, int fd, short events, void *ignore)
20282 {
20283 struct sip_request req;
20284 struct sockaddr_in sin = { 0, };
20285 int res;
20286 socklen_t len = sizeof(sin);
20287 static char readbuf[65535];
20288
20289 memset(&req, 0, sizeof(req));
20290 res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
20291 if (res < 0) {
20292 #if !defined(__FreeBSD__)
20293 if (errno == EAGAIN)
20294 ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
20295 else
20296 #endif
20297 if (errno != ECONNREFUSED)
20298 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
20299 return 1;
20300 }
20301
20302 readbuf[res] = '\0';
20303
20304 if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
20305 return 1;
20306 }
20307
20308 if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
20309 return -1;
20310 }
20311
20312 req.len = res;
20313 req.socket.fd = sipsock;
20314 set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
20315 req.socket.tcptls_session = NULL;
20316 req.socket.port = bindaddr.sin_port;
20317
20318 handle_request_do(&req, &sin);
20319 if (req.data) {
20320 ast_free(req.data);
20321 req.data = NULL;
20322 }
20323
20324 return 1;
20325 }
20326
20327 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin)
20328 {
20329 struct sip_pvt *p;
20330 int recount = 0;
20331 int nounlock = 0;
20332 int lockretry;
20333
20334 if (sip_debug_test_addr(sin))
20335 req->debug = 1;
20336 if (pedanticsipchecking)
20337 req->len = lws2sws(req->data->str, req->len);
20338 if (req->debug) {
20339 ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n",
20340 get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr),
20341 ntohs(sin->sin_port), req->data->str);
20342 }
20343
20344 if (parse_request(req) == -1) {
20345 ast_str_reset(req->data);
20346 return 1;
20347 }
20348 req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
20349
20350 if (req->debug)
20351 ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
20352
20353 if (req->headers < 2) {
20354 ast_str_reset(req->data);
20355 return 1;
20356 }
20357
20358
20359 for (lockretry = 10; lockretry > 0; lockretry--) {
20360 ast_mutex_lock(&netlock);
20361
20362
20363 p = find_call(req, sin, req->method);
20364 if (p == NULL) {
20365 ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
20366 ast_mutex_unlock(&netlock);
20367 return 1;
20368 }
20369
20370 copy_socket_data(&p->socket, &req->socket);
20371
20372
20373
20374 if (!p->owner || !ast_channel_trylock(p->owner))
20375 break;
20376
20377 if (lockretry != 1) {
20378 sip_pvt_unlock(p);
20379 ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop");
20380 ast_mutex_unlock(&netlock);
20381
20382 usleep(1);
20383 }
20384 }
20385 p->recv = *sin;
20386
20387 if (p->do_history)
20388 append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
20389
20390 if (!lockretry) {
20391 if (!queue_request(p, req)) {
20392
20393 sip_pvt_unlock(p);
20394 ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
20395 ast_mutex_unlock(&netlock);
20396 return 1;
20397 }
20398
20399 if (p->owner)
20400 ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
20401 ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
20402 if (req->method != SIP_ACK)
20403 transmit_response(p, "503 Server error", req);
20404
20405 append_history(p, "LockFail", "Owner lock failed, transaction failed.");
20406 sip_pvt_unlock(p);
20407 ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry");
20408 ast_mutex_unlock(&netlock);
20409 return 1;
20410 }
20411
20412
20413
20414
20415 if (!AST_LIST_EMPTY(&p->request_queue)) {
20416 AST_SCHED_DEL_UNREF(sched, p->request_queue_sched_id, dialog_unref(p, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
20417 process_request_queue(p, &recount, &nounlock);
20418 }
20419
20420 if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
20421
20422 ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
20423 }
20424
20425 if (recount)
20426 ast_update_use_count();
20427
20428 if (p->owner && !nounlock)
20429 ast_channel_unlock(p->owner);
20430 sip_pvt_unlock(p);
20431 ast_mutex_unlock(&netlock);
20432 ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine");
20433 return 1;
20434 }
20435
20436
20437
20438
20439
20440
20441
20442 static int sip_standard_port(enum sip_transport type, int port)
20443 {
20444 if (type & SIP_TRANSPORT_TLS)
20445 return port == STANDARD_TLS_PORT;
20446 else
20447 return port == STANDARD_SIP_PORT;
20448 }
20449
20450
20451
20452
20453
20454
20455 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
20456 {
20457 struct sip_threadinfo *th;
20458 struct ast_tcptls_session_instance *tcptls_instance = NULL;
20459
20460 AST_LIST_LOCK(&threadl);
20461 AST_LIST_TRAVERSE(&threadl, th, list) {
20462 if ((s->sin_family == th->tcptls_session->remote_address.sin_family) &&
20463 (s->sin_addr.s_addr == th->tcptls_session->remote_address.sin_addr.s_addr) &&
20464 (s->sin_port == th->tcptls_session->remote_address.sin_port)) {
20465 tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
20466 break;
20467 }
20468 }
20469 AST_LIST_UNLOCK(&threadl);
20470
20471 return tcptls_instance;
20472 }
20473
20474
20475 static int sip_prepare_socket(struct sip_pvt *p)
20476 {
20477 struct sip_socket *s = &p->socket;
20478 static const char name[] = "SIP socket";
20479 struct ast_tcptls_session_instance *tcptls_session;
20480 struct ast_tcptls_session_args ca = {
20481 .name = name,
20482 .accept_fd = -1,
20483 };
20484
20485 if (s->fd != -1)
20486 return s->fd;
20487
20488 if (p->outboundproxy && p->outboundproxy->transport) {
20489 s->type = p->outboundproxy->transport;
20490 }
20491
20492 if (s->type & SIP_TRANSPORT_UDP) {
20493 s->fd = sipsock;
20494 return s->fd;
20495 }
20496
20497 ca.remote_address = *(sip_real_dst(p));
20498
20499 if ((tcptls_session = sip_tcp_locate(&ca.remote_address))) {
20500 s->fd = tcptls_session->fd;
20501 if (s->tcptls_session) {
20502 ao2_ref(s->tcptls_session, -1);
20503 s->tcptls_session = NULL;
20504 }
20505 s->tcptls_session = tcptls_session;
20506 return s->fd;
20507 }
20508
20509 if (s->tcptls_session && s->tcptls_session->parent->tls_cfg) {
20510 ca.tls_cfg = s->tcptls_session->parent->tls_cfg;
20511 } else {
20512 if (s->type & SIP_TRANSPORT_TLS) {
20513 ca.tls_cfg = ast_calloc(1, sizeof(*ca.tls_cfg));
20514 if (!ca.tls_cfg)
20515 return -1;
20516 memcpy(ca.tls_cfg, &default_tls_cfg, sizeof(*ca.tls_cfg));
20517 if (!ast_strlen_zero(p->tohost))
20518 ast_copy_string(ca.hostname, p->tohost, sizeof(ca.hostname));
20519 }
20520 }
20521
20522 if (s->tcptls_session) {
20523
20524 } else {
20525 s->tcptls_session = ast_tcptls_client_start(&ca);
20526 }
20527
20528 if (!s->tcptls_session) {
20529 if (ca.tls_cfg)
20530 ast_free(ca.tls_cfg);
20531 return -1;
20532 }
20533
20534 s->fd = ca.accept_fd;
20535
20536
20537 ao2_ref(s->tcptls_session, +1);
20538
20539 if (ast_pthread_create_background(&ca.master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
20540 ast_debug(1, "Unable to launch '%s'.", ca.name);
20541 ao2_ref(s->tcptls_session, -1);
20542 close(ca.accept_fd);
20543 s->fd = ca.accept_fd = -1;
20544 }
20545
20546 return s->fd;
20547 }
20548
20549
20550
20551
20552
20553 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
20554 {
20555 char *port;
20556
20557 if ((*hostname = strstr(line, "://"))) {
20558 *hostname += 3;
20559
20560 if (!strncasecmp(line, "tcp", 3))
20561 *transport = SIP_TRANSPORT_TCP;
20562 else if (!strncasecmp(line, "tls", 3))
20563 *transport = SIP_TRANSPORT_TLS;
20564 else if (!strncasecmp(line, "udp", 3))
20565 *transport = SIP_TRANSPORT_UDP;
20566 else
20567 ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
20568 } else {
20569 *hostname = line;
20570 *transport = SIP_TRANSPORT_UDP;
20571 }
20572
20573 if ((line = strrchr(*hostname, '@')))
20574 line++;
20575 else
20576 line = *hostname;
20577
20578 if ((port = strrchr(line, ':'))) {
20579 *port++ = '\0';
20580
20581 if (!sscanf(port, "%5u", portnum)) {
20582 ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
20583 port = NULL;
20584 }
20585 }
20586
20587 if (!port) {
20588 if (*transport & SIP_TRANSPORT_TLS) {
20589 *portnum = STANDARD_TLS_PORT;
20590 } else {
20591 *portnum = STANDARD_SIP_PORT;
20592 }
20593 }
20594
20595 return 0;
20596 }
20597
20598
20599
20600
20601
20602
20603 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
20604 {
20605 struct sip_mailbox *mailbox;
20606
20607 AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
20608 struct ast_event *event;
20609 event = ast_event_get_cached(AST_EVENT_MWI,
20610 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
20611 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
20612 AST_EVENT_IE_END);
20613 if (!event)
20614 continue;
20615 *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
20616 *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
20617 ast_event_destroy(event);
20618 }
20619
20620 return (*new || *old) ? 0 : 1;
20621 }
20622
20623
20624 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
20625 {
20626
20627 struct sip_pvt *p;
20628 int newmsgs = 0, oldmsgs = 0;
20629
20630 if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
20631 return 0;
20632
20633
20634 if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr)
20635 return 0;
20636
20637 if (event) {
20638 newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
20639 oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
20640 } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
20641
20642 } else if (cache_only) {
20643 return 0;
20644 } else {
20645 struct ast_str *mailbox_str = ast_str_alloca(512);
20646 peer_mailboxes_to_str(&mailbox_str, peer);
20647 ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
20648 }
20649
20650 if (peer->mwipvt) {
20651
20652 p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
20653 } else {
20654
20655 if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL)))
20656 return -1;
20657
20658
20659
20660
20661 set_socket_transport(&p->socket, 0);
20662 if (create_addr_from_peer(p, peer)) {
20663
20664 dialog_unlink_all(p, TRUE, TRUE);
20665 dialog_unref(p, "unref dialog p just created via sip_alloc");
20666
20667 return 0;
20668 }
20669
20670 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
20671 build_via(p);
20672 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
20673 build_callid_pvt(p);
20674 ao2_t_link(dialogs, p, "Linking in under new name");
20675
20676 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20677 }
20678
20679
20680 ast_set_flag(&p->flags[0], SIP_OUTGOING);
20681
20682 transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
20683 dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
20684 return 0;
20685 }
20686
20687
20688 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
20689 {
20690
20691 if (!dialog->rtp || !dialog->owner)
20692 return;
20693
20694
20695 if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
20696 return;
20697
20698
20699 if (dialog->t38.state == T38_ENABLED)
20700 return;
20701
20702
20703 if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
20704 return;
20705
20706
20707 if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
20708 (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
20709
20710 dialog->lastrtptx = time(NULL);
20711 ast_rtp_sendcng(dialog->rtp, 0);
20712 }
20713
20714
20715
20716
20717
20718
20719
20720
20721 if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
20722 (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
20723
20724
20725 struct sockaddr_in sin;
20726 ast_rtp_get_peer(dialog->rtp, &sin);
20727 if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
20728 (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
20729
20730 if (ast_rtp_get_rtptimeout(dialog->rtp)) {
20731 while (dialog->owner && ast_channel_trylock(dialog->owner)) {
20732 sip_pvt_unlock(dialog);
20733 usleep(1);
20734 sip_pvt_lock(dialog);
20735 }
20736 ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
20737 dialog->owner->name, (long) (t - dialog->lastrtprx));
20738
20739 ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
20740 ast_channel_unlock(dialog->owner);
20741
20742
20743
20744
20745 ast_rtp_set_rtptimeout(dialog->rtp, 0);
20746 ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
20747 if (dialog->vrtp) {
20748 ast_rtp_set_rtptimeout(dialog->vrtp, 0);
20749 ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
20750 }
20751 }
20752 }
20753 }
20754 }
20755
20756
20757
20758
20759
20760 static void *do_monitor(void *data)
20761 {
20762 int res;
20763 time_t t;
20764 int reloading;
20765
20766
20767 if (sipsock > -1)
20768 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
20769
20770
20771 for(;;) {
20772
20773 ast_mutex_lock(&sip_reload_lock);
20774 reloading = sip_reloading;
20775 sip_reloading = FALSE;
20776 ast_mutex_unlock(&sip_reload_lock);
20777 if (reloading) {
20778 ast_verb(1, "Reloading SIP\n");
20779 sip_do_reload(sip_reloadreason);
20780
20781
20782 if (sipsock > -1) {
20783 if (sipsock_read_id)
20784 sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
20785 else
20786 sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
20787 } else if (sipsock_read_id) {
20788 ast_io_remove(io, sipsock_read_id);
20789 sipsock_read_id = NULL;
20790 }
20791 }
20792
20793
20794 t = time(NULL);
20795
20796
20797
20798
20799 ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
20800 "callback to remove dialogs w/needdestroy");
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812 pthread_testcancel();
20813
20814 res = ast_sched_wait(sched);
20815 if ((res < 0) || (res > 1000))
20816 res = 1000;
20817 res = ast_io_wait(io, res);
20818 if (res > 20)
20819 ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
20820 ast_mutex_lock(&monlock);
20821 res = ast_sched_runq(sched);
20822 if (res >= 20)
20823 ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
20824 ast_mutex_unlock(&monlock);
20825 }
20826
20827
20828 return NULL;
20829 }
20830
20831
20832 static int restart_monitor(void)
20833 {
20834
20835 if (monitor_thread == AST_PTHREADT_STOP)
20836 return 0;
20837 ast_mutex_lock(&monlock);
20838 if (monitor_thread == pthread_self()) {
20839 ast_mutex_unlock(&monlock);
20840 ast_log(LOG_WARNING, "Cannot kill myself\n");
20841 return -1;
20842 }
20843 if (monitor_thread != AST_PTHREADT_NULL) {
20844
20845 pthread_kill(monitor_thread, SIGURG);
20846 } else {
20847
20848 if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
20849 ast_mutex_unlock(&monlock);
20850 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
20851 return -1;
20852 }
20853 }
20854 ast_mutex_unlock(&monlock);
20855 return 0;
20856 }
20857
20858
20859
20860 static void restart_session_timer(struct sip_pvt *p)
20861 {
20862 if (!p->stimer) {
20863 ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
20864 return;
20865 }
20866
20867 if (p->stimer->st_active == TRUE) {
20868 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
20869 dialog_unref(p, "Removing session timer ref"));
20870 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
20871 start_session_timer(p);
20872 }
20873 }
20874
20875
20876
20877 static void stop_session_timer(struct sip_pvt *p)
20878 {
20879 if (!p->stimer) {
20880 ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
20881 return;
20882 }
20883
20884 if (p->stimer->st_active == TRUE) {
20885 p->stimer->st_active = FALSE;
20886 AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
20887 dialog_unref(p, "removing session timer ref"));
20888 ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
20889 }
20890 }
20891
20892
20893
20894 static void start_session_timer(struct sip_pvt *p)
20895 {
20896 if (!p->stimer) {
20897 ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
20898 return;
20899 }
20900
20901 p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer,
20902 dialog_ref(p, "adding session timer ref"));
20903 if (p->stimer->st_schedid < 0) {
20904 dialog_unref(p, "removing session timer ref");
20905 ast_log(LOG_ERROR, "ast_sched_add failed.\n");
20906 }
20907 ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
20908 }
20909
20910
20911
20912 static int proc_session_timer(const void *vp)
20913 {
20914 struct sip_pvt *p = (struct sip_pvt *) vp;
20915 int sendreinv = FALSE;
20916 int res = 0;
20917
20918 if (!p->stimer) {
20919 ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
20920 goto return_unref;
20921 }
20922
20923 ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
20924
20925 if (!p->owner) {
20926 goto return_unref;
20927 }
20928
20929 if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
20930 goto return_unref;
20931 }
20932
20933 switch (p->stimer->st_ref) {
20934 case SESSION_TIMER_REFRESHER_UAC:
20935 if (p->outgoing_call == TRUE) {
20936 sendreinv = TRUE;
20937 }
20938 break;
20939 case SESSION_TIMER_REFRESHER_UAS:
20940 if (p->outgoing_call != TRUE) {
20941 sendreinv = TRUE;
20942 }
20943 break;
20944 default:
20945 ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
20946 goto return_unref;
20947 }
20948
20949 if (sendreinv == TRUE) {
20950 res = 1;
20951 transmit_reinvite_with_sdp(p, FALSE, TRUE);
20952 } else {
20953 p->stimer->st_expirys++;
20954 if (p->stimer->st_expirys >= 2) {
20955 ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
20956
20957 while (p->owner && ast_channel_trylock(p->owner)) {
20958 sip_pvt_unlock(p);
20959 usleep(1);
20960 sip_pvt_lock(p);
20961 }
20962
20963 ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20964 ast_channel_unlock(p->owner);
20965 }
20966 }
20967
20968 return_unref:
20969 if (!res) {
20970
20971 p->stimer->st_schedid = -1;
20972 stop_session_timer(p);
20973
20974
20975
20976 dialog_unref(p, "removing session timer ref");
20977 }
20978
20979 return res;
20980 }
20981
20982
20983
20984 int parse_minse (const char *p_hdrval, int *const p_interval)
20985 {
20986 if (ast_strlen_zero(p_hdrval)) {
20987 ast_log(LOG_WARNING, "Null Min-SE header\n");
20988 return -1;
20989 }
20990
20991 *p_interval = 0;
20992 p_hdrval = ast_skip_blanks(p_hdrval);
20993 if (!sscanf(p_hdrval, "%30d", p_interval)) {
20994 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
20995 return -1;
20996 }
20997
20998 ast_debug(2, "Received Min-SE: %d\n", *p_interval);
20999 return 0;
21000 }
21001
21002
21003
21004 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
21005 {
21006 char *p_token;
21007 int ref_idx;
21008 char *p_se_hdr;
21009
21010 if (ast_strlen_zero(p_hdrval)) {
21011 ast_log(LOG_WARNING, "Null Session-Expires header\n");
21012 return -1;
21013 }
21014
21015 *p_ref = SESSION_TIMER_REFRESHER_AUTO;
21016 *p_interval = 0;
21017
21018 p_se_hdr = ast_strdupa(p_hdrval);
21019 p_se_hdr = ast_skip_blanks(p_se_hdr);
21020
21021 while ((p_token = strsep(&p_se_hdr, ";"))) {
21022 p_token = ast_skip_blanks(p_token);
21023 if (!sscanf(p_token, "%30d", p_interval)) {
21024 ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
21025 return -1;
21026 }
21027
21028 ast_debug(2, "Session-Expires: %d\n", *p_interval);
21029
21030 if (!p_se_hdr)
21031 continue;
21032
21033 ref_idx = strlen("refresher=");
21034 if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
21035 p_se_hdr += ref_idx;
21036 p_se_hdr = ast_skip_blanks(p_se_hdr);
21037
21038 if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
21039 *p_ref = SESSION_TIMER_REFRESHER_UAC;
21040 ast_debug(2, "Refresher: UAC\n");
21041 } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
21042 *p_ref = SESSION_TIMER_REFRESHER_UAS;
21043 ast_debug(2, "Refresher: UAS\n");
21044 } else {
21045 ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
21046 return -1;
21047 }
21048 break;
21049 }
21050 }
21051 return 0;
21052 }
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
21063 {
21064 int rtn;
21065 const char *p_hdrval;
21066 int minse;
21067
21068 p_hdrval = get_header(rsp, "Min-SE");
21069 if (ast_strlen_zero(p_hdrval)) {
21070 ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
21071 return;
21072 }
21073 rtn = parse_minse(p_hdrval, &minse);
21074 if (rtn != 0) {
21075 ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
21076 return;
21077 }
21078 p->stimer->st_interval = minse;
21079 transmit_invite(p, SIP_INVITE, 1, 2);
21080 }
21081
21082
21083
21084
21085
21086
21087 int st_get_se(struct sip_pvt *p, int max)
21088 {
21089 if (max == TRUE) {
21090 if (p->stimer->st_cached_max_se) {
21091 return p->stimer->st_cached_max_se;
21092 } else if (p->peername) {
21093 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21094 if (pp) {
21095 p->stimer->st_cached_max_se = pp->stimer.st_max_se;
21096 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
21097 return (p->stimer->st_cached_max_se);
21098 }
21099 }
21100 p->stimer->st_cached_max_se = global_max_se;
21101 return (p->stimer->st_cached_max_se);
21102 } else {
21103 if (p->stimer->st_cached_min_se) {
21104 return p->stimer->st_cached_min_se;
21105 } else if (p->peername) {
21106 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21107 if (pp) {
21108 p->stimer->st_cached_min_se = pp->stimer.st_min_se;
21109 unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
21110 return (p->stimer->st_cached_min_se);
21111 }
21112 }
21113 p->stimer->st_cached_min_se = global_min_se;
21114 return (p->stimer->st_cached_min_se);
21115 }
21116 }
21117
21118
21119
21120
21121
21122 enum st_refresher st_get_refresher(struct sip_pvt *p)
21123 {
21124 if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO)
21125 return p->stimer->st_cached_ref;
21126
21127 if (p->peername) {
21128 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21129 if (pp) {
21130 p->stimer->st_cached_ref = pp->stimer.st_ref;
21131 unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
21132 return pp->stimer.st_ref;
21133 }
21134 }
21135
21136 p->stimer->st_cached_ref = global_st_refresher;
21137 return global_st_refresher;
21138 }
21139
21140
21141
21142
21143
21144 enum st_mode st_get_mode(struct sip_pvt *p)
21145 {
21146 if (!p->stimer)
21147 sip_st_alloc(p);
21148
21149 if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
21150 return p->stimer->st_cached_mode;
21151
21152 if (p->peername) {
21153 struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE);
21154 if (pp) {
21155 p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
21156 unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
21157 return pp->stimer.st_mode_oper;
21158 }
21159 }
21160
21161 p->stimer->st_cached_mode = global_st_mode;
21162 return global_st_mode;
21163 }
21164
21165
21166
21167 static int sip_poke_noanswer(const void *data)
21168 {
21169 struct sip_peer *peer = (struct sip_peer *)data;
21170
21171 peer->pokeexpire = -1;
21172
21173 if (peer->lastms > -1) {
21174 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Last qualify: %d\n", peer->name, peer->lastms);
21175 if (sip_cfg.peer_rtupdate) {
21176 ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
21177 }
21178 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
21179 if (global_regextenonqualify) {
21180 register_peer_exten(peer, FALSE);
21181 }
21182 }
21183
21184 if (peer->call) {
21185 dialog_unlink_all(peer->call, TRUE, TRUE);
21186 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21187
21188 }
21189
21190 peer->lastms = -1;
21191 ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
21192
21193
21194 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21195 DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
21196 unref_peer(_data, "removing poke peer ref"),
21197 unref_peer(peer, "removing poke peer ref"),
21198 ref_peer(peer, "adding poke peer ref"));
21199
21200
21201 unref_peer(peer, "release peer poke noanswer ref");
21202
21203 return 0;
21204 }
21205
21206
21207
21208
21209
21210
21211 static int sip_poke_peer(struct sip_peer *peer, int force)
21212 {
21213 struct sip_pvt *p;
21214 int xmitres = 0;
21215
21216 if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
21217
21218
21219 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21220 unref_peer(peer, "removing poke peer ref"));
21221
21222 peer->lastms = 0;
21223 if (peer->call) {
21224 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21225 }
21226 return 0;
21227 }
21228 if (peer->call) {
21229 if (sipdebug) {
21230 ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
21231 }
21232 dialog_unlink_all(peer->call, TRUE, TRUE);
21233 peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21234
21235 }
21236 if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
21237 return -1;
21238 }
21239 peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
21240
21241 p->sa = peer->addr;
21242 p->recv = peer->addr;
21243 copy_socket_data(&p->socket, &peer->socket);
21244 ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
21245 ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21246
21247
21248 if (!ast_strlen_zero(peer->fullcontact))
21249 ast_string_field_set(p, fullcontact, peer->fullcontact);
21250
21251 if (!ast_strlen_zero(peer->tohost))
21252 ast_string_field_set(p, tohost, peer->tohost);
21253 else
21254 ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
21255
21256
21257 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21258 build_via(p);
21259 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21260 build_callid_pvt(p);
21261 ao2_t_link(dialogs, p, "Linking in under new name");
21262
21263 AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21264 unref_peer(peer, "removing poke peer ref"));
21265
21266 if (p->relatedpeer)
21267 p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
21268 p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
21269 ast_set_flag(&p->flags[0], SIP_OUTGOING);
21270 #ifdef VOCAL_DATA_HACK
21271 ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
21272 xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
21273 #else
21274 xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
21275 #endif
21276 peer->ps = ast_tvnow();
21277 if (xmitres == XMIT_ERROR) {
21278 sip_poke_noanswer(peer);
21279 } else if (!force) {
21280 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
21281 unref_peer(_data, "removing poke peer ref"),
21282 unref_peer(peer, "removing poke peer ref"),
21283 ref_peer(peer, "adding poke peer ref"));
21284 }
21285 dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
21286 return 0;
21287 }
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322 static int sip_devicestate(void *data)
21323 {
21324 char *host;
21325 char *tmp;
21326 struct sip_peer *p;
21327
21328 int res = AST_DEVICE_INVALID;
21329
21330
21331 host = ast_strdupa(data ? data : "");
21332 if ((tmp = strchr(host, '@')))
21333 host = tmp + 1;
21334
21335 ast_debug(3, "Checking device state for peer %s\n", host);
21336
21337
21338
21339
21340
21341
21342
21343
21344 if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE))) {
21345 if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357 if (p->onHold)
21358
21359 res = AST_DEVICE_ONHOLD;
21360 else if (p->inRinging) {
21361 if (p->inRinging == p->inUse)
21362 res = AST_DEVICE_RINGING;
21363 else
21364 res = AST_DEVICE_RINGINUSE;
21365 } else if (p->call_limit && (p->inUse == p->call_limit))
21366
21367 res = AST_DEVICE_BUSY;
21368 else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
21369
21370 res = AST_DEVICE_BUSY;
21371 else if (p->call_limit && p->inUse)
21372
21373 res = AST_DEVICE_INUSE;
21374 else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
21375
21376 res = AST_DEVICE_UNAVAILABLE;
21377 else
21378 res = AST_DEVICE_NOT_INUSE;
21379 } else {
21380
21381 res = AST_DEVICE_UNAVAILABLE;
21382 }
21383 unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
21384 } else {
21385 res = AST_DEVICE_UNKNOWN;
21386 }
21387
21388 return res;
21389 }
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
21402 {
21403 struct sip_pvt *p;
21404 struct ast_channel *tmpc = NULL;
21405 char *ext = NULL, *host;
21406 char tmp[256];
21407 char *dest = data;
21408 char *dnid;
21409 char *secret = NULL;
21410 char *md5secret = NULL;
21411 char *authname = NULL;
21412 char *trans = NULL;
21413 enum sip_transport transport = 0;
21414 int oldformat = format;
21415
21416
21417
21418
21419
21420
21421
21422
21423 format &= AST_FORMAT_AUDIO_MASK;
21424 if (!format) {
21425 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
21426 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
21427 return NULL;
21428 }
21429 ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
21430
21431 if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
21432 ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
21433 *cause = AST_CAUSE_SWITCH_CONGESTION;
21434 return NULL;
21435 }
21436
21437 p->outgoing_call = TRUE;
21438
21439 if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
21440 dialog_unlink_all(p, TRUE, TRUE);
21441 dialog_unref(p, "unref dialog p from mem fail");
21442
21443 ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
21444 *cause = AST_CAUSE_SWITCH_CONGESTION;
21445 return NULL;
21446 }
21447
21448
21449 ast_copy_string(tmp, dest, sizeof(tmp));
21450
21451
21452
21453 dnid = strchr(tmp, '!');
21454 if (dnid != NULL) {
21455 *dnid++ = '\0';
21456 ast_string_field_set(p, todnid, dnid);
21457 }
21458
21459
21460 host = strchr(tmp, '@');
21461 if (host) {
21462 *host++ = '\0';
21463 ext = tmp;
21464 secret = strchr(ext, ':');
21465 }
21466 if (secret) {
21467 *secret++ = '\0';
21468 md5secret = strchr(secret, ':');
21469 }
21470 if (md5secret) {
21471 *md5secret++ = '\0';
21472 authname = strchr(md5secret, ':');
21473 }
21474 if (authname) {
21475 *authname++ = '\0';
21476 trans = strchr(authname, ':');
21477 }
21478 if (trans) {
21479 *trans++ = '\0';
21480 if (!strcasecmp(trans, "tcp"))
21481 transport = SIP_TRANSPORT_TCP;
21482 else if (!strcasecmp(trans, "tls"))
21483 transport = SIP_TRANSPORT_TLS;
21484 else {
21485 if (strcasecmp(trans, "udp"))
21486 ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
21487 transport = SIP_TRANSPORT_UDP;
21488 }
21489 } else {
21490 transport = SIP_TRANSPORT_UDP;
21491 }
21492
21493 if (!host) {
21494 ext = strchr(tmp, '/');
21495 if (ext)
21496 *ext++ = '\0';
21497 host = tmp;
21498 }
21499
21500 set_socket_transport(&p->socket, transport);
21501
21502
21503
21504
21505
21506
21507 if (create_addr(p, host, NULL, 1)) {
21508 *cause = AST_CAUSE_UNREGISTERED;
21509 ast_debug(3, "Cant create SIP call - target device not registered\n");
21510 dialog_unlink_all(p, TRUE, TRUE);
21511 dialog_unref(p, "unref dialog p UNREGISTERED");
21512
21513 return NULL;
21514 }
21515 if (ast_strlen_zero(p->peername) && ext)
21516 ast_string_field_set(p, peername, ext);
21517
21518 ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21519 build_via(p);
21520 ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21521 build_callid_pvt(p);
21522 ao2_t_link(dialogs, p, "Linking in under new name");
21523
21524
21525
21526
21527
21528
21529 if (ext) {
21530 ast_string_field_set(p, username, ext);
21531 ast_string_field_set(p, fullcontact, NULL);
21532 }
21533 if (secret && !ast_strlen_zero(secret))
21534 ast_string_field_set(p, peersecret, secret);
21535
21536 if (md5secret && !ast_strlen_zero(md5secret))
21537 ast_string_field_set(p, peermd5secret, md5secret);
21538
21539 if (authname && !ast_strlen_zero(authname))
21540 ast_string_field_set(p, authname, authname);
21541 #if 0
21542 printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
21543 #endif
21544 p->prefcodec = oldformat;
21545 p->jointcapability = oldformat;
21546 sip_pvt_lock(p);
21547 tmpc = sip_new(p, AST_STATE_DOWN, host);
21548 if (global_callevents)
21549 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
21550 "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
21551 p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
21552 sip_pvt_unlock(p);
21553 if (!tmpc) {
21554 dialog_unlink_all(p, TRUE, TRUE);
21555
21556 }
21557 dialog_unref(p, "toss pvt ptr at end of sip_request_call");
21558 ast_update_use_count();
21559 restart_monitor();
21560 return tmpc;
21561 }
21562
21563
21564 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
21565 {
21566 if (ast_strlen_zero(value))
21567 return;
21568
21569 if (!ast_false(value)) {
21570 char buf[64];
21571 char *word, *next;
21572
21573 ast_copy_string(buf, value, sizeof(buf));
21574 next = buf;
21575 while ((word = strsep(&next, ","))) {
21576 if (!strcasecmp(word, "port"))
21577 ast_set_flag(&flags[0], SIP_INSECURE_PORT);
21578 else if (!strcasecmp(word, "invite"))
21579 ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
21580 else
21581 ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
21582 }
21583 }
21584 }
21585
21586
21587
21588
21589
21590
21591
21592
21593 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
21594 {
21595 int res = 1;
21596
21597 if (!strcasecmp(v->name, "trustrpid")) {
21598 ast_set_flag(&mask[0], SIP_TRUSTRPID);
21599 ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
21600 } else if (!strcasecmp(v->name, "sendrpid")) {
21601 ast_set_flag(&mask[0], SIP_SENDRPID);
21602 ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
21603 } else if (!strcasecmp(v->name, "g726nonstandard")) {
21604 ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
21605 ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
21606 } else if (!strcasecmp(v->name, "useclientcode")) {
21607 ast_set_flag(&mask[0], SIP_USECLIENTCODE);
21608 ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
21609 } else if (!strcasecmp(v->name, "dtmfmode")) {
21610 ast_set_flag(&mask[0], SIP_DTMF);
21611 ast_clear_flag(&flags[0], SIP_DTMF);
21612 if (!strcasecmp(v->value, "inband"))
21613 ast_set_flag(&flags[0], SIP_DTMF_INBAND);
21614 else if (!strcasecmp(v->value, "rfc2833"))
21615 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
21616 else if (!strcasecmp(v->value, "info"))
21617 ast_set_flag(&flags[0], SIP_DTMF_INFO);
21618 else if (!strcasecmp(v->value, "shortinfo"))
21619 ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
21620 else if (!strcasecmp(v->value, "auto"))
21621 ast_set_flag(&flags[0], SIP_DTMF_AUTO);
21622 else {
21623 ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
21624 ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
21625 }
21626 } else if (!strcasecmp(v->name, "nat")) {
21627 ast_set_flag(&mask[0], SIP_NAT);
21628 ast_clear_flag(&flags[0], SIP_NAT);
21629 if (!strcasecmp(v->value, "never"))
21630 ast_set_flag(&flags[0], SIP_NAT_NEVER);
21631 else if (!strcasecmp(v->value, "route"))
21632 ast_set_flag(&flags[0], SIP_NAT_ROUTE);
21633 else if (ast_true(v->value))
21634 ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
21635 else
21636 ast_set_flag(&flags[0], SIP_NAT_RFC3581);
21637 } else if (!strcasecmp(v->name, "canreinvite")) {
21638 ast_set_flag(&mask[0], SIP_REINVITE);
21639 ast_clear_flag(&flags[0], SIP_REINVITE);
21640 if (ast_true(v->value)) {
21641 ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
21642 } else if (!ast_false(v->value)) {
21643 char buf[64];
21644 char *word, *next = buf;
21645
21646 ast_copy_string(buf, v->value, sizeof(buf));
21647 while ((word = strsep(&next, ","))) {
21648 if (!strcasecmp(word, "update")) {
21649 ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
21650 } else if (!strcasecmp(word, "nonat")) {
21651 ast_set_flag(&flags[0], SIP_CAN_REINVITE);
21652 ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
21653 } else {
21654 ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
21655 }
21656 }
21657 }
21658 } else if (!strcasecmp(v->name, "insecure")) {
21659 ast_set_flag(&mask[0], SIP_INSECURE);
21660 ast_clear_flag(&flags[0], SIP_INSECURE);
21661 set_insecure_flags(&flags[0], v->value, v->lineno);
21662 } else if (!strcasecmp(v->name, "progressinband")) {
21663 ast_set_flag(&mask[0], SIP_PROG_INBAND);
21664 ast_clear_flag(&flags[0], SIP_PROG_INBAND);
21665 if (ast_true(v->value))
21666 ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
21667 else if (strcasecmp(v->value, "never"))
21668 ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
21669 } else if (!strcasecmp(v->name, "promiscredir")) {
21670 ast_set_flag(&mask[0], SIP_PROMISCREDIR);
21671 ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
21672 } else if (!strcasecmp(v->name, "videosupport")) {
21673 if (!strcasecmp(v->value, "always")) {
21674 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
21675 ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
21676 } else {
21677 ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
21678 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
21679 }
21680 } else if (!strcasecmp(v->name, "textsupport")) {
21681 ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
21682 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
21683 res = 1;
21684 } else if (!strcasecmp(v->name, "allowoverlap")) {
21685 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
21686 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
21687 } else if (!strcasecmp(v->name, "allowsubscribe")) {
21688 ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
21689 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
21690 } else if (!strcasecmp(v->name, "ignoresdpversion")) {
21691 ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
21692 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
21693 } else if (!strcasecmp(v->name, "t38pt_udptl")) {
21694 char buf[16], *word, *next = buf;
21695
21696 ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
21697
21698 ast_copy_string(buf, v->value, sizeof(buf));
21699
21700 while ((word = strsep(&next, ","))) {
21701 if (ast_true(word) || !strcasecmp(word, "fec")) {
21702 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
21703 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
21704 } else if (!strcasecmp(word, "redundancy")) {
21705 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
21706 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
21707 } else if (!strcasecmp(word, "none")) {
21708 ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
21709 ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
21710 }
21711 }
21712 } else if (!strcasecmp(v->name, "rfc2833compensate")) {
21713 ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
21714 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
21715 } else if (!strcasecmp(v->name, "buggymwi")) {
21716 ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
21717 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
21718 } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
21719 ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
21720 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
21721 } else
21722 res = 0;
21723
21724 return res;
21725 }
21726
21727
21728 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
21729 {
21730 struct domain *d;
21731
21732 if (ast_strlen_zero(domain)) {
21733 ast_log(LOG_WARNING, "Zero length domain.\n");
21734 return 1;
21735 }
21736
21737 if (!(d = ast_calloc(1, sizeof(*d))))
21738 return 0;
21739
21740 ast_copy_string(d->domain, domain, sizeof(d->domain));
21741
21742 if (!ast_strlen_zero(context))
21743 ast_copy_string(d->context, context, sizeof(d->context));
21744
21745 d->mode = mode;
21746
21747 AST_LIST_LOCK(&domain_list);
21748 AST_LIST_INSERT_TAIL(&domain_list, d, list);
21749 AST_LIST_UNLOCK(&domain_list);
21750
21751 if (sipdebug)
21752 ast_debug(1, "Added local SIP domain '%s'\n", domain);
21753
21754 return 1;
21755 }
21756
21757
21758 static int check_sip_domain(const char *domain, char *context, size_t len)
21759 {
21760 struct domain *d;
21761 int result = 0;
21762
21763 AST_LIST_LOCK(&domain_list);
21764 AST_LIST_TRAVERSE(&domain_list, d, list) {
21765 if (strcasecmp(d->domain, domain))
21766 continue;
21767
21768 if (len && !ast_strlen_zero(d->context))
21769 ast_copy_string(context, d->context, len);
21770
21771 result = 1;
21772 break;
21773 }
21774 AST_LIST_UNLOCK(&domain_list);
21775
21776 return result;
21777 }
21778
21779
21780 static void clear_sip_domains(void)
21781 {
21782 struct domain *d;
21783
21784 AST_LIST_LOCK(&domain_list);
21785 while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
21786 ast_free(d);
21787 AST_LIST_UNLOCK(&domain_list);
21788 }
21789
21790
21791
21792 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
21793 {
21794 char authcopy[256];
21795 char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
21796 char *stringp;
21797 struct sip_auth *a, *b, *auth;
21798
21799 if (ast_strlen_zero(configuration))
21800 return authlist;
21801
21802 ast_debug(1, "Auth config :: %s\n", configuration);
21803
21804 ast_copy_string(authcopy, configuration, sizeof(authcopy));
21805 stringp = authcopy;
21806
21807 username = stringp;
21808 realm = strrchr(stringp, '@');
21809 if (realm)
21810 *realm++ = '\0';
21811 if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
21812 ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
21813 return authlist;
21814 }
21815 stringp = username;
21816 username = strsep(&stringp, ":");
21817 if (username) {
21818 secret = strsep(&stringp, ":");
21819 if (!secret) {
21820 stringp = username;
21821 md5secret = strsep(&stringp, "#");
21822 }
21823 }
21824 if (!(auth = ast_calloc(1, sizeof(*auth))))
21825 return authlist;
21826
21827 ast_copy_string(auth->realm, realm, sizeof(auth->realm));
21828 ast_copy_string(auth->username, username, sizeof(auth->username));
21829 if (secret)
21830 ast_copy_string(auth->secret, secret, sizeof(auth->secret));
21831 if (md5secret)
21832 ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
21833
21834
21835 for (b = NULL, a = authlist; a ; b = a, a = a->next)
21836 ;
21837 if (b)
21838 b->next = auth;
21839 else
21840 authlist = auth;
21841
21842 ast_verb(3, "Added authentication for realm %s\n", realm);
21843
21844 return authlist;
21845
21846 }
21847
21848
21849 static int clear_realm_authentication(struct sip_auth *authlist)
21850 {
21851 struct sip_auth *a = authlist;
21852 struct sip_auth *b;
21853
21854 while (a) {
21855 b = a;
21856 a = a->next;
21857 ast_free(b);
21858 }
21859
21860 return 1;
21861 }
21862
21863
21864 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
21865 {
21866 struct sip_auth *a;
21867
21868 for (a = authlist; a; a = a->next) {
21869 if (!strcasecmp(a->realm, realm))
21870 break;
21871 }
21872
21873 return a;
21874 }
21875
21876
21877
21878
21879 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
21880 {
21881 struct ast_variable *tmpvar = NULL;
21882 char *varname = ast_strdupa(buf), *varval = NULL;
21883
21884 if ((varval = strchr(varname, '='))) {
21885 *varval++ = '\0';
21886 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
21887 tmpvar->next = list;
21888 list = tmpvar;
21889 }
21890 }
21891 return list;
21892 }
21893
21894
21895 static void set_peer_defaults(struct sip_peer *peer)
21896 {
21897 if (peer->expire == 0) {
21898
21899
21900
21901 peer->expire = -1;
21902 peer->pokeexpire = -1;
21903 peer->addr.sin_port = htons(STANDARD_SIP_PORT);
21904 set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
21905 }
21906 peer->type = SIP_TYPE_PEER;
21907 ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
21908 ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21909 strcpy(peer->context, default_context);
21910 strcpy(peer->subscribecontext, default_subscribecontext);
21911 strcpy(peer->language, default_language);
21912 strcpy(peer->mohinterpret, default_mohinterpret);
21913 strcpy(peer->mohsuggest, default_mohsuggest);
21914 peer->addr.sin_family = AF_INET;
21915 peer->defaddr.sin_family = AF_INET;
21916 peer->capability = global_capability;
21917 peer->maxcallbitrate = default_maxcallbitrate;
21918 peer->rtptimeout = global_rtptimeout;
21919 peer->rtpholdtimeout = global_rtpholdtimeout;
21920 peer->rtpkeepalive = global_rtpkeepalive;
21921 peer->allowtransfer = global_allowtransfer;
21922 peer->autoframing = global_autoframing;
21923 peer->qualifyfreq = global_qualifyfreq;
21924 if (global_callcounter)
21925 peer->call_limit=999;
21926 strcpy(peer->vmexten, default_vmexten);
21927 peer->secret[0] = '\0';
21928 peer->md5secret[0] = '\0';
21929 peer->cid_num[0] = '\0';
21930 peer->cid_name[0] = '\0';
21931 peer->fromdomain[0] = '\0';
21932 peer->fromuser[0] = '\0';
21933 peer->regexten[0] = '\0';
21934 peer->callgroup = 0;
21935 peer->pickupgroup = 0;
21936 peer->maxms = default_qualify;
21937 peer->prefs = default_prefs;
21938 peer->stimer.st_mode_oper = global_st_mode;
21939 peer->stimer.st_ref = global_st_refresher;
21940 peer->stimer.st_min_se = global_min_se;
21941 peer->stimer.st_max_se = global_max_se;
21942 peer->timer_t1 = global_t1;
21943 peer->timer_b = global_timer_b;
21944 clear_peer_mailboxes(peer);
21945 }
21946
21947
21948 static struct sip_peer *temp_peer(const char *name)
21949 {
21950 struct sip_peer *peer;
21951
21952 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
21953 return NULL;
21954
21955 ast_atomic_fetchadd_int(&apeerobjs, 1);
21956 set_peer_defaults(peer);
21957
21958 ast_copy_string(peer->name, name, sizeof(peer->name));
21959
21960 peer->selfdestruct = TRUE;
21961 peer->host_dynamic = TRUE;
21962 peer->prefs = default_prefs;
21963 reg_source_db(peer);
21964
21965 return peer;
21966 }
21967
21968
21969 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
21970 {
21971 char *next, *mbox, *context;
21972
21973 next = ast_strdupa(value);
21974
21975 while ((mbox = context = strsep(&next, ","))) {
21976 struct sip_mailbox *mailbox;
21977
21978 if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
21979 continue;
21980
21981 strsep(&context, "@");
21982 if (ast_strlen_zero(mbox)) {
21983 ast_free(mailbox);
21984 continue;
21985 }
21986 mailbox->mailbox = ast_strdup(mbox);
21987 mailbox->context = ast_strdup(context);
21988
21989 AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
21990 }
21991 }
21992
21993
21994 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
21995 {
21996 struct sip_peer *peer = NULL;
21997 struct ast_ha *oldha = NULL;
21998 int found = 0;
21999 int firstpass = 1;
22000 int format = 0;
22001 time_t regseconds = 0;
22002 struct ast_flags peerflags[2] = {{(0)}};
22003 struct ast_flags mask[2] = {{(0)}};
22004 char callback[256] = "";
22005 struct sip_peer tmp_peer;
22006 const char *srvlookup = NULL;
22007 static int deprecation_warning = 1;
22008 int alt_fullcontact = alt ? 1 : 0;
22009 struct ast_str *fullcontact = ast_str_alloca(512);
22010
22011 if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22012
22013
22014
22015
22016
22017 ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
22018 peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
22019 }
22020
22021 if (peer) {
22022
22023 found++;
22024 if (!(peer->the_mark))
22025 firstpass = 0;
22026 } else {
22027 if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
22028 return NULL;
22029
22030 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22031 ast_atomic_fetchadd_int(&rpeerobjs, 1);
22032 ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
22033 } else
22034 ast_atomic_fetchadd_int(&speerobjs, 1);
22035 }
22036
22037
22038 if (firstpass) {
22039 peer->lastmsgssent = -1;
22040 oldha = peer->ha;
22041 peer->ha = NULL;
22042 set_peer_defaults(peer);
22043 peer->type = 0;
22044 }
22045 if (!found && name)
22046 ast_copy_string(peer->name, name, sizeof(peer->name));
22047
22048
22049 if (peer->chanvars) {
22050 ast_variables_destroy(peer->chanvars);
22051 peer->chanvars = NULL;
22052
22053 }
22054
22055
22056 clear_realm_authentication(peer->auth);
22057 peer->auth = NULL;
22058 peer->default_outbound_transport = 0;
22059 peer->transports = 0;
22060
22061 for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
22062 if (handle_common_options(&peerflags[0], &mask[0], v))
22063 continue;
22064 if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
22065 char *val = ast_strdupa(v->value);
22066 char *trans;
22067
22068 while ((trans = strsep(&val, ","))) {
22069 trans = ast_skip_blanks(trans);
22070
22071 if (!strncasecmp(trans, "udp", 3))
22072 peer->transports |= SIP_TRANSPORT_UDP;
22073 else if (!strncasecmp(trans, "tcp", 3))
22074 peer->transports |= SIP_TRANSPORT_TCP;
22075 else if (!strncasecmp(trans, "tls", 3))
22076 peer->transports |= SIP_TRANSPORT_TLS;
22077 else
22078 ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
22079
22080 if (!peer->default_outbound_transport) {
22081 peer->default_outbound_transport = peer->transports;
22082 }
22083 }
22084 } else if (realtime && !strcasecmp(v->name, "regseconds")) {
22085 ast_get_time_t(v->value, ®seconds, 0, NULL);
22086 } else if (realtime && !strcasecmp(v->name, "lastms")) {
22087 sscanf(v->value, "%30d", &peer->lastms);
22088 } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
22089 inet_aton(v->value, &(peer->addr.sin_addr));
22090 } else if (realtime && !strcasecmp(v->name, "name"))
22091 ast_copy_string(peer->name, v->value, sizeof(peer->name));
22092 else if (realtime && !strcasecmp(v->name, "fullcontact")) {
22093 if (alt_fullcontact && !alt) {
22094
22095
22096
22097
22098
22099 alt_fullcontact = 0;
22100 ast_str_reset(fullcontact);
22101 }
22102
22103 if (fullcontact->used > 0) {
22104 ast_str_append(&fullcontact, 0, ";%s", v->value);
22105 } else {
22106 ast_str_set(&fullcontact, 0, "%s", v->value);
22107 }
22108 } else if (!strcasecmp(v->name, "type")) {
22109 if (!strcasecmp(v->value, "peer")) {
22110 peer->type |= SIP_TYPE_PEER;
22111 } else if (!strcasecmp(v->value, "user")) {
22112 peer->type |= SIP_TYPE_USER;
22113 } else if (!strcasecmp(v->value, "friend")) {
22114 peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
22115 }
22116 } else if (!strcasecmp(v->name, "secret"))
22117 ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
22118 else if (!strcasecmp(v->name, "md5secret"))
22119 ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
22120 else if (!strcasecmp(v->name, "auth"))
22121 peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
22122 else if (!strcasecmp(v->name, "callerid")) {
22123 ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
22124 } else if (!strcasecmp(v->name, "fullname")) {
22125 ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
22126 } else if (!strcasecmp(v->name, "cid_number")) {
22127 ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
22128 } else if (!strcasecmp(v->name, "context")) {
22129 ast_copy_string(peer->context, v->value, sizeof(peer->context));
22130 } else if (!strcasecmp(v->name, "subscribecontext")) {
22131 ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
22132 } else if (!strcasecmp(v->name, "fromdomain")) {
22133 ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
22134 } else if (!strcasecmp(v->name, "usereqphone")) {
22135 ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
22136 } else if (!strcasecmp(v->name, "fromuser")) {
22137 ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
22138 } else if (!strcasecmp(v->name, "outboundproxy")) {
22139 char *port, *next, *force, *proxyname;
22140 int forceopt = FALSE;
22141
22142 next = proxyname = ast_strdupa(v->value);
22143 if ((port = strchr(proxyname, ':'))) {
22144 *port++ = '\0';
22145 next = port;
22146 }
22147 if ((force = strchr(next, ','))) {
22148 *force++ = '\0';
22149 forceopt = strcmp(force, "force");
22150 }
22151
22152 peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
22153 } else if (!strcasecmp(v->name, "host")) {
22154 if (!strcasecmp(v->value, "dynamic")) {
22155
22156 if (!found || !peer->host_dynamic) {
22157
22158
22159 memset(&peer->addr.sin_addr, 0, 4);
22160 if (peer->addr.sin_port) {
22161
22162 peer->defaddr.sin_port = peer->addr.sin_port;
22163 peer->addr.sin_port = 0;
22164 }
22165 }
22166 peer->host_dynamic = TRUE;
22167 } else {
22168
22169 AST_SCHED_DEL_UNREF(sched, peer->expire,
22170 unref_peer(peer, "removing register expire ref"));
22171 peer->host_dynamic = FALSE;
22172 srvlookup = v->value;
22173 if (global_dynamic_exclude_static) {
22174 int err = 0;
22175 global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
22176 if (err) {
22177 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22178 }
22179 }
22180 }
22181 } else if (!strcasecmp(v->name, "defaultip")) {
22182 if (ast_get_ip(&peer->defaddr, v->value)) {
22183 unref_peer(peer, "unref_peer: from build_peer defaultip");
22184 return NULL;
22185 }
22186 } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
22187 int ha_error = 0;
22188
22189 peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
22190 if (ha_error)
22191 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22192 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
22193 int ha_error = 0;
22194 peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
22195 if (ha_error) {
22196 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22197 }
22198 } else if (!strcasecmp(v->name, "port")) {
22199 if (!realtime && peer->host_dynamic)
22200 peer->defaddr.sin_port = htons(atoi(v->value));
22201 else
22202 peer->addr.sin_port = htons(atoi(v->value));
22203 } else if (!strcasecmp(v->name, "callingpres")) {
22204 peer->callingpres = ast_parse_caller_presentation(v->value);
22205 if (peer->callingpres == -1)
22206 peer->callingpres = atoi(v->value);
22207 } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {
22208 ast_copy_string(peer->username, v->value, sizeof(peer->username));
22209 if (!strcasecmp(v->name, "username")) {
22210 if (deprecation_warning) {
22211 ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
22212 deprecation_warning = 0;
22213 }
22214 peer->deprecated_username = 1;
22215 }
22216 } else if (!strcasecmp(v->name, "language")) {
22217 ast_copy_string(peer->language, v->value, sizeof(peer->language));
22218 } else if (!strcasecmp(v->name, "regexten")) {
22219 ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
22220 } else if (!strcasecmp(v->name, "callbackextension")) {
22221 ast_copy_string(callback, v->value, sizeof(callback));
22222 } else if (!strcasecmp(v->name, "callcounter")) {
22223 peer->call_limit = ast_true(v->value) ? 999 : 0;
22224 } else if (!strcasecmp(v->name, "call-limit")) {
22225 peer->call_limit = atoi(v->value);
22226 if (peer->call_limit < 0)
22227 peer->call_limit = 0;
22228 } else if (!strcasecmp(v->name, "busylevel")) {
22229 peer->busy_level = atoi(v->value);
22230 if (peer->busy_level < 0)
22231 peer->busy_level = 0;
22232 } else if (!strcasecmp(v->name, "amaflags")) {
22233 format = ast_cdr_amaflags2int(v->value);
22234 if (format < 0) {
22235 ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
22236 } else {
22237 peer->amaflags = format;
22238 }
22239 } else if (!strcasecmp(v->name, "accountcode")) {
22240 ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
22241 } else if (!strcasecmp(v->name, "mohinterpret")) {
22242 ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
22243 } else if (!strcasecmp(v->name, "mohsuggest")) {
22244 ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
22245 } else if (!strcasecmp(v->name, "parkinglot")) {
22246 ast_copy_string(peer->parkinglot, v->value, sizeof(peer->parkinglot));
22247 } else if (!strcasecmp(v->name, "mailbox")) {
22248 add_peer_mailboxes(peer, v->value);
22249 } else if (!strcasecmp(v->name, "hasvoicemail")) {
22250
22251
22252 if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
22253 add_peer_mailboxes(peer, name);
22254 }
22255 } else if (!strcasecmp(v->name, "subscribemwi")) {
22256 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
22257 } else if (!strcasecmp(v->name, "vmexten")) {
22258 ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
22259 } else if (!strcasecmp(v->name, "callgroup")) {
22260 peer->callgroup = ast_get_group(v->value);
22261 } else if (!strcasecmp(v->name, "allowtransfer")) {
22262 peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
22263 } else if (!strcasecmp(v->name, "pickupgroup")) {
22264 peer->pickupgroup = ast_get_group(v->value);
22265 } else if (!strcasecmp(v->name, "allow")) {
22266 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
22267 if (error)
22268 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22269 } else if (!strcasecmp(v->name, "disallow")) {
22270 int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
22271 if (error)
22272 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22273 } else if (!strcasecmp(v->name, "registertrying")) {
22274 ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
22275 } else if (!strcasecmp(v->name, "autoframing")) {
22276 peer->autoframing = ast_true(v->value);
22277 } else if (!strcasecmp(v->name, "rtptimeout")) {
22278 if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
22279 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
22280 peer->rtptimeout = global_rtptimeout;
22281 }
22282 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
22283 if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
22284 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
22285 peer->rtpholdtimeout = global_rtpholdtimeout;
22286 }
22287 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
22288 if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
22289 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
22290 peer->rtpkeepalive = global_rtpkeepalive;
22291 }
22292 } else if (!strcasecmp(v->name, "timert1")) {
22293 if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
22294 ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d. Using default.\n", v->value, v->lineno);
22295 peer->timer_t1 = global_t1;
22296 }
22297
22298
22299 if (peer->timer_b < peer->timer_t1 * 64) {
22300 peer->timer_b = peer->timer_t1 * 64;
22301 }
22302 } else if (!strcasecmp(v->name, "timerb")) {
22303 if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
22304 ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d. Using default.\n", v->value, v->lineno);
22305 peer->timer_b = global_timer_b;
22306 }
22307 if (peer->timer_b < peer->timer_t1 * 64) {
22308 static int warning = 0;
22309 if (warning++ % 20 == 0) {
22310 ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
22311 }
22312 }
22313 } else if (!strcasecmp(v->name, "setvar")) {
22314 peer->chanvars = add_var(v->value, peer->chanvars);
22315 } else if (!strcasecmp(v->name, "qualify")) {
22316 if (!strcasecmp(v->value, "no")) {
22317 peer->maxms = 0;
22318 } else if (!strcasecmp(v->value, "yes")) {
22319 peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
22320 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
22321 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
22322 peer->maxms = 0;
22323 }
22324 if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
22325
22326
22327
22328
22329 ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime. Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
22330 peer->maxms = 0;
22331 }
22332 } else if (!strcasecmp(v->name, "qualifyfreq")) {
22333 int i;
22334 if (sscanf(v->value, "%30d", &i) == 1)
22335 peer->qualifyfreq = i * 1000;
22336 else {
22337 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
22338 peer->qualifyfreq = global_qualifyfreq;
22339 }
22340 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
22341 peer->maxcallbitrate = atoi(v->value);
22342 if (peer->maxcallbitrate < 0)
22343 peer->maxcallbitrate = default_maxcallbitrate;
22344 } else if (!strcasecmp(v->name, "session-timers")) {
22345 int i = (int) str2stmode(v->value);
22346 if (i < 0) {
22347 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
22348 peer->stimer.st_mode_oper = global_st_mode;
22349 } else {
22350 peer->stimer.st_mode_oper = i;
22351 }
22352 } else if (!strcasecmp(v->name, "session-expires")) {
22353 if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
22354 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
22355 peer->stimer.st_max_se = global_max_se;
22356 }
22357 } else if (!strcasecmp(v->name, "session-minse")) {
22358 if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
22359 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
22360 peer->stimer.st_min_se = global_min_se;
22361 }
22362 if (peer->stimer.st_min_se < 90) {
22363 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
22364 peer->stimer.st_min_se = global_min_se;
22365 }
22366 } else if (!strcasecmp(v->name, "session-refresher")) {
22367 int i = (int) str2strefresher(v->value);
22368 if (i < 0) {
22369 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
22370 peer->stimer.st_ref = global_st_refresher;
22371 } else {
22372 peer->stimer.st_ref = i;
22373 }
22374 }
22375 }
22376
22377 if (!peer->default_outbound_transport) {
22378 peer->transports = SIP_TRANSPORT_UDP;
22379 peer->default_outbound_transport = SIP_TRANSPORT_UDP;
22380 }
22381
22382
22383
22384
22385
22386 if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
22387 !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
22388
22389 set_socket_transport(&peer->socket, peer->default_outbound_transport);
22390 }
22391
22392 if (fullcontact->used > 0) {
22393 ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
22394 peer->rt_fromcontact = TRUE;
22395
22396
22397
22398
22399
22400
22401
22402
22403 if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
22404 __set_address_from_contact(fullcontact->str, &peer->addr, 0);
22405 }
22406 }
22407
22408 if (srvlookup && peer->dnsmgr == NULL) {
22409 char transport[MAXHOSTNAMELEN];
22410 char _srvlookup[MAXHOSTNAMELEN];
22411 char *params;
22412
22413 ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
22414 if ((params = strchr(_srvlookup, ';'))) {
22415 *params++ = '\0';
22416 }
22417
22418 snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
22419
22420 if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, global_srvlookup ? transport : NULL)) {
22421 ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
22422 unref_peer(peer, "getting rid of a peer pointer");
22423 return NULL;
22424 }
22425
22426 ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
22427 }
22428
22429 if (!peer->addr.sin_port)
22430 peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
22431
22432 if (!peer->socket.port)
22433 peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
22434
22435 if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
22436 time_t nowtime = time(NULL);
22437
22438 if ((nowtime - regseconds) > 0) {
22439 destroy_association(peer);
22440 memset(&peer->addr, 0, sizeof(peer->addr));
22441 peer->lastms = -1;
22442 ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
22443 }
22444 }
22445
22446
22447 if (realtime && peer->lastms > 0) {
22448 ref_peer(peer, "schedule qualify");
22449 sip_poke_peer(peer, 0);
22450 }
22451
22452 ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
22453 ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
22454 if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
22455 global_allowsubscribe = TRUE;
22456 if (!found && peer->host_dynamic && !peer->is_realtime)
22457 reg_source_db(peer);
22458
22459
22460
22461 if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
22462 !AST_LIST_EMPTY(&peer->mailboxes)) {
22463 add_peer_mwi_subs(peer);
22464
22465
22466
22467 sip_send_mwi_to_peer(peer, NULL, 1);
22468 }
22469 peer->the_mark = 0;
22470
22471 ast_free_ha(oldha);
22472 if (!ast_strlen_zero(callback)) {
22473 char *reg_string;
22474
22475 if (asprintf(®_string, "%s?%s:%s@%s/%s", peer->name, peer->username, peer->secret, peer->tohost, callback) < 0) {
22476 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
22477 } else if (reg_string) {
22478 sip_register(reg_string, 0);
22479 ast_free(reg_string);
22480 }
22481 }
22482 return peer;
22483 }
22484
22485 static int peer_markall_func(void *device, void *arg, int flags)
22486 {
22487 struct sip_peer *peer = device;
22488 peer->the_mark = 1;
22489 return 0;
22490 }
22491
22492
22493
22494
22495
22496
22497
22498 static int reload_config(enum channelreloadreason reason)
22499 {
22500 struct ast_config *cfg, *ucfg;
22501 struct ast_variable *v;
22502 struct sip_peer *peer;
22503 char *cat, *stringp, *context, *oldregcontext;
22504 char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
22505 struct ast_flags dummy[2];
22506 struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : CONFIG_FLAG_FILEUNCHANGED };
22507 int auto_sip_domains = FALSE;
22508 struct sockaddr_in old_bindaddr = bindaddr;
22509 int registry_count = 0, peer_count = 0;
22510 time_t run_start, run_end;
22511
22512 run_start = time(0);
22513 ast_unload_realtime("sipregs");
22514 ast_unload_realtime("sippeers");
22515 cfg = ast_config_load(config, config_flags);
22516
22517
22518 if (!cfg) {
22519 ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
22520 return -1;
22521 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
22522 ucfg = ast_config_load("users.conf", config_flags);
22523 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
22524 return 1;
22525
22526 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
22527 cfg = ast_config_load(config, config_flags);
22528 } else {
22529 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
22530 ucfg = ast_config_load("users.conf", config_flags);
22531 }
22532
22533
22534 memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
22535 memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
22536
22537 ast_free_ha(global_contact_ha);
22538 global_contact_ha = NULL;
22539
22540 default_tls_cfg.enabled = FALSE;
22541
22542 sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
22543 sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
22544
22545 if (reason != CHANNEL_MODULE_LOAD) {
22546 ast_debug(4, "--------------- SIP reload started\n");
22547
22548 clear_realm_authentication(authl);
22549 clear_sip_domains();
22550 authl = NULL;
22551
22552
22553
22554 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
22555
22556 ASTOBJ_RDLOCK(iterator);
22557 if (iterator->call) {
22558 ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
22559
22560 dialog_unlink_all(iterator->call, TRUE, TRUE);
22561 iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
22562 }
22563 if (iterator->expire > -1) {
22564 AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
22565 }
22566 if (iterator->timeout > -1) {
22567 AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
22568 }
22569 ASTOBJ_UNLOCK(iterator);
22570
22571 } while(0));
22572
22573
22574 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
22575 ast_debug(4, "--------------- Done destroying registry list\n");
22576 ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, 0, "callback to mark all peers");
22577 }
22578
22579
22580 if (reason != CHANNEL_MODULE_LOAD) {
22581 ast_free(default_tls_cfg.certfile);
22582 ast_free(default_tls_cfg.cipher);
22583 ast_free(default_tls_cfg.cafile);
22584 ast_free(default_tls_cfg.capath);
22585 }
22586 default_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
22587 default_tls_cfg.cipher = ast_strdup("");
22588 default_tls_cfg.cafile = ast_strdup("");
22589 default_tls_cfg.capath = ast_strdup("");
22590
22591
22592 ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
22593 oldregcontext = oldcontexts;
22594
22595
22596
22597 sipdebug &= sip_debug_console;
22598 ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
22599 ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
22600
22601
22602 memset(&bindaddr, 0, sizeof(bindaddr));
22603 memset(&stunaddr, 0, sizeof(stunaddr));
22604 memset(&internip, 0, sizeof(internip));
22605
22606
22607 ast_free_ha(localaddr);
22608 memset(&localaddr, 0, sizeof(localaddr));
22609 memset(&externip, 0, sizeof(externip));
22610 memset(&default_prefs, 0 , sizeof(default_prefs));
22611 memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
22612 global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
22613 global_outboundproxy.ip.sin_family = AF_INET;
22614 global_outboundproxy.force = FALSE;
22615 ourport_tcp = STANDARD_SIP_PORT;
22616 ourport_tls = STANDARD_TLS_PORT;
22617 bindaddr.sin_port = htons(STANDARD_SIP_PORT);
22618 global_srvlookup = DEFAULT_SRVLOOKUP;
22619 global_tos_sip = DEFAULT_TOS_SIP;
22620 global_tos_audio = DEFAULT_TOS_AUDIO;
22621 global_tos_video = DEFAULT_TOS_VIDEO;
22622 global_tos_text = DEFAULT_TOS_TEXT;
22623 global_cos_sip = DEFAULT_COS_SIP;
22624 global_cos_audio = DEFAULT_COS_AUDIO;
22625 global_cos_video = DEFAULT_COS_VIDEO;
22626 global_cos_text = DEFAULT_COS_TEXT;
22627
22628 externhost[0] = '\0';
22629 externexpire = 0;
22630 externrefresh = 10;
22631
22632
22633 allow_external_domains = DEFAULT_ALLOW_EXT_DOM;
22634 global_regcontext[0] = '\0';
22635 global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
22636 global_notifyringing = DEFAULT_NOTIFYRINGING;
22637 global_notifyhold = FALSE;
22638 global_directrtpsetup = FALSE;
22639 global_alwaysauthreject = 0;
22640 global_allowsubscribe = FALSE;
22641 snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
22642 snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
22643 snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
22644 ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
22645 ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
22646 ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
22647 compactheaders = DEFAULT_COMPACTHEADERS;
22648 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
22649 global_regattempts_max = 0;
22650 pedanticsipchecking = DEFAULT_PEDANTIC;
22651 autocreatepeer = DEFAULT_AUTOCREATEPEER;
22652 global_autoframing = 0;
22653 global_allowguest = DEFAULT_ALLOWGUEST;
22654 global_callcounter = DEFAULT_CALLCOUNTER;
22655 global_match_auth_username = FALSE;
22656 global_rtptimeout = 0;
22657 global_rtpholdtimeout = 0;
22658 global_rtpkeepalive = 0;
22659 global_allowtransfer = TRANSFER_OPENFORALL;
22660 global_rtautoclear = 120;
22661 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);
22662 ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);
22663 sip_cfg.peer_rtupdate = TRUE;
22664
22665
22666 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
22667 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
22668 global_min_se = DEFAULT_MIN_SE;
22669 global_max_se = DEFAULT_MAX_SE;
22670
22671
22672 ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
22673 default_subscribecontext[0] = '\0';
22674 default_language[0] = '\0';
22675 default_fromdomain[0] = '\0';
22676 default_qualify = DEFAULT_QUALIFY;
22677 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
22678 ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
22679 ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
22680 ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
22681 ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);
22682 ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);
22683 ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);
22684
22685
22686 dumphistory = FALSE;
22687 recordhistory = FALSE;
22688 sipdebug &= ~sip_debug_config;
22689
22690
22691 global_relaxdtmf = FALSE;
22692 global_callevents = FALSE;
22693 global_authfailureevents = FALSE;
22694 global_t1 = SIP_TIMER_T1;
22695 global_timer_b = 64 * SIP_TIMER_T1;
22696 global_t1min = DEFAULT_T1MIN;
22697 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
22698
22699 global_matchexterniplocally = FALSE;
22700
22701
22702 memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
22703
22704 ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
22705 ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
22706 ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
22707
22708
22709
22710 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
22711 if (handle_common_options(&global_flags[0], &dummy[0], v))
22712 continue;
22713
22714 if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
22715 continue;
22716
22717 if (!strcasecmp(v->name, "context")) {
22718 ast_copy_string(default_context, v->value, sizeof(default_context));
22719 } else if (!strcasecmp(v->name, "subscribecontext")) {
22720 ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
22721 } else if (!strcasecmp(v->name, "callcounter")) {
22722 global_callcounter = ast_true(v->value) ? 1 : 0;
22723 } else if (!strcasecmp(v->name, "allowguest")) {
22724 global_allowguest = ast_true(v->value) ? 1 : 0;
22725 } else if (!strcasecmp(v->name, "realm")) {
22726 ast_copy_string(global_realm, v->value, sizeof(global_realm));
22727 } else if (!strcasecmp(v->name, "useragent")) {
22728 ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
22729 ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
22730 } else if (!strcasecmp(v->name, "sdpsession")) {
22731 ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
22732 } else if (!strcasecmp(v->name, "sdpowner")) {
22733
22734 if (!strstr(v->value, " "))
22735 ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
22736 else
22737 ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d. Using default.\n", v->value, v->lineno);
22738 } else if (!strcasecmp(v->name, "allowtransfer")) {
22739 global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
22740 } else if (!strcasecmp(v->name, "rtcachefriends")) {
22741 ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
22742 } else if (!strcasecmp(v->name, "rtsavesysname")) {
22743 sip_cfg.rtsave_sysname = ast_true(v->value);
22744 } else if (!strcasecmp(v->name, "rtupdate")) {
22745 sip_cfg.peer_rtupdate = ast_true(v->value);
22746 } else if (!strcasecmp(v->name, "ignoreregexpire")) {
22747 sip_cfg.ignore_regexpire = ast_true(v->value);
22748 } else if (!strcasecmp(v->name, "timert1")) {
22749
22750
22751
22752 global_t1 = atoi(v->value);
22753
22754 global_timer_b = global_t1 * 64;
22755 } else if (!strcasecmp(v->name, "t1min")) {
22756 global_t1min = atoi(v->value);
22757 } else if (!strcasecmp(v->name, "tcpenable")) {
22758 sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
22759 ast_debug(2, "Enabling TCP socket for listening\n");
22760 } else if (!strcasecmp(v->name, "tcpbindaddr")) {
22761 int family = sip_tcp_desc.local_address.sin_family;
22762 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
22763 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
22764 sip_tcp_desc.local_address.sin_family = family;
22765 ast_debug(2, "Setting TCP socket address to %s\n", v->value);
22766 } else if (!strcasecmp(v->name, "tlsenable")) {
22767 default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
22768 sip_tls_desc.local_address.sin_family = AF_INET;
22769 } else if (!strcasecmp(v->name, "tlscertfile")) {
22770 ast_free(default_tls_cfg.certfile);
22771 default_tls_cfg.certfile = ast_strdup(v->value);
22772 } else if (!strcasecmp(v->name, "tlscipher")) {
22773 ast_free(default_tls_cfg.cipher);
22774 default_tls_cfg.cipher = ast_strdup(v->value);
22775 } else if (!strcasecmp(v->name, "tlscafile")) {
22776 ast_free(default_tls_cfg.cafile);
22777 default_tls_cfg.cafile = ast_strdup(v->value);
22778 } else if (!strcasecmp(v->name, "tlscapath")) {
22779 ast_free(default_tls_cfg.capath);
22780 default_tls_cfg.capath = ast_strdup(v->value);
22781 } else if (!strcasecmp(v->name, "tlsverifyclient")) {
22782 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);
22783 } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
22784 ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);
22785 } else if (!strcasecmp(v->name, "tlsbindaddr")) {
22786 if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
22787 ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
22788 } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
22789 global_dynamic_exclude_static = ast_true(v->value);
22790 } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
22791 int ha_error = 0;
22792 global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
22793 if (ha_error) {
22794 ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22795 }
22796 } else if (!strcasecmp(v->name, "rtautoclear")) {
22797 int i = atoi(v->value);
22798 if (i > 0)
22799 global_rtautoclear = i;
22800 else
22801 i = 0;
22802 ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
22803 } else if (!strcasecmp(v->name, "usereqphone")) {
22804 ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
22805 } else if (!strcasecmp(v->name, "relaxdtmf")) {
22806 global_relaxdtmf = ast_true(v->value);
22807 } else if (!strcasecmp(v->name, "vmexten")) {
22808 ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
22809 } else if (!strcasecmp(v->name, "rtptimeout")) {
22810 if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
22811 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
22812 global_rtptimeout = 0;
22813 }
22814 } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
22815 if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
22816 ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d. Using default.\n", v->value, v->lineno);
22817 global_rtpholdtimeout = 0;
22818 }
22819 } else if (!strcasecmp(v->name, "rtpkeepalive")) {
22820 if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
22821 ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d. Using default.\n", v->value, v->lineno);
22822 global_rtpkeepalive = 0;
22823 }
22824 } else if (!strcasecmp(v->name, "compactheaders")) {
22825 compactheaders = ast_true(v->value);
22826 } else if (!strcasecmp(v->name, "notifymimetype")) {
22827 ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
22828 } else if (!strcasecmp(v->name, "directrtpsetup")) {
22829 global_directrtpsetup = ast_true(v->value);
22830 } else if (!strcasecmp(v->name, "notifyringing")) {
22831 global_notifyringing = ast_true(v->value);
22832 } else if (!strcasecmp(v->name, "notifyhold")) {
22833 global_notifyhold = ast_true(v->value);
22834 } else if (!strcasecmp(v->name, "alwaysauthreject")) {
22835 global_alwaysauthreject = ast_true(v->value);
22836 } else if (!strcasecmp(v->name, "mohinterpret")) {
22837 ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
22838 } else if (!strcasecmp(v->name, "mohsuggest")) {
22839 ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
22840 } else if (!strcasecmp(v->name, "language")) {
22841 ast_copy_string(default_language, v->value, sizeof(default_language));
22842 } else if (!strcasecmp(v->name, "regcontext")) {
22843 ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
22844 stringp = newcontexts;
22845
22846 cleanup_stale_contexts(stringp, oldregcontext);
22847
22848 while ((context = strsep(&stringp, "&"))) {
22849 ast_copy_string(used_context, context, sizeof(used_context));
22850 ast_context_find_or_create(NULL, NULL, context, "SIP");
22851 }
22852 ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
22853 } else if (!strcasecmp(v->name, "regextenonqualify")) {
22854 global_regextenonqualify = ast_true(v->value);
22855 } else if (!strcasecmp(v->name, "callerid")) {
22856 ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
22857 } else if (!strcasecmp(v->name, "fromdomain")) {
22858 ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
22859 } else if (!strcasecmp(v->name, "outboundproxy")) {
22860 int portnum;
22861 char *tok, *proxyname;
22862
22863 if (ast_strlen_zero(v->value)) {
22864 ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
22865 continue;
22866 }
22867
22868 tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
22869
22870 sip_parse_host(tok, v->lineno, &proxyname, &portnum, &global_outboundproxy.transport);
22871
22872 global_outboundproxy.ip.sin_port = htons(portnum);
22873
22874 if ((tok = strtok(NULL, ","))) {
22875 global_outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
22876 } else {
22877 global_outboundproxy.force = FALSE;
22878 }
22879
22880 if (ast_strlen_zero(proxyname)) {
22881 ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
22882 global_outboundproxy.name[0] = '\0';
22883 continue;
22884 }
22885
22886 ast_copy_string(global_outboundproxy.name, proxyname, sizeof(global_outboundproxy.name));
22887
22888 proxy_update(&global_outboundproxy);
22889 } else if (!strcasecmp(v->name, "autocreatepeer")) {
22890 autocreatepeer = ast_true(v->value);
22891 } else if (!strcasecmp(v->name, "match_auth_username")) {
22892 global_match_auth_username = ast_true(v->value);
22893 } else if (!strcasecmp(v->name, "srvlookup")) {
22894 global_srvlookup = ast_true(v->value);
22895 } else if (!strcasecmp(v->name, "pedantic")) {
22896 pedanticsipchecking = ast_true(v->value);
22897 } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
22898 max_expiry = atoi(v->value);
22899 if (max_expiry < 1)
22900 max_expiry = DEFAULT_MAX_EXPIRY;
22901 } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
22902 min_expiry = atoi(v->value);
22903 if (min_expiry < 1)
22904 min_expiry = DEFAULT_MIN_EXPIRY;
22905 } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
22906 default_expiry = atoi(v->value);
22907 if (default_expiry < 1)
22908 default_expiry = DEFAULT_DEFAULT_EXPIRY;
22909 } else if (!strcasecmp(v->name, "sipdebug")) {
22910 if (ast_true(v->value))
22911 sipdebug |= sip_debug_config;
22912 } else if (!strcasecmp(v->name, "dumphistory")) {
22913 dumphistory = ast_true(v->value);
22914 } else if (!strcasecmp(v->name, "recordhistory")) {
22915 recordhistory = ast_true(v->value);
22916 } else if (!strcasecmp(v->name, "registertimeout")) {
22917 global_reg_timeout = atoi(v->value);
22918 if (global_reg_timeout < 1)
22919 global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
22920 } else if (!strcasecmp(v->name, "registerattempts")) {
22921 global_regattempts_max = atoi(v->value);
22922 } else if (!strcasecmp(v->name, "stunaddr")) {
22923 stunaddr.sin_port = htons(3478);
22924 if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
22925 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
22926 externexpire = time(NULL);
22927 } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
22928 if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
22929 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
22930 } else if (!strcasecmp(v->name, "localnet")) {
22931 struct ast_ha *na;
22932 int ha_error = 0;
22933
22934 if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
22935 ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
22936 else
22937 localaddr = na;
22938 if (ha_error)
22939 ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
22940 } else if (!strcasecmp(v->name, "externip")) {
22941 if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
22942 ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
22943 externexpire = 0;
22944
22945 if (!externip.sin_port)
22946 externip.sin_port = bindaddr.sin_port;
22947 } else if (!strcasecmp(v->name, "externhost")) {
22948 ast_copy_string(externhost, v->value, sizeof(externhost));
22949 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
22950 ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
22951 externexpire = time(NULL);
22952
22953 if (!externip.sin_port)
22954 externip.sin_port = bindaddr.sin_port;
22955 } else if (!strcasecmp(v->name, "externrefresh")) {
22956 if (sscanf(v->value, "%30d", &externrefresh) != 1) {
22957 ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
22958 externrefresh = 10;
22959 }
22960 } else if (!strcasecmp(v->name, "allow")) {
22961 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
22962 if (error)
22963 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22964 } else if (!strcasecmp(v->name, "disallow")) {
22965 int error = ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
22966 if (error)
22967 ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22968 } else if (!strcasecmp(v->name, "autoframing")) {
22969 global_autoframing = ast_true(v->value);
22970 } else if (!strcasecmp(v->name, "allowexternaldomains")) {
22971 allow_external_domains = ast_true(v->value);
22972 } else if (!strcasecmp(v->name, "autodomain")) {
22973 auto_sip_domains = ast_true(v->value);
22974 } else if (!strcasecmp(v->name, "domain")) {
22975 char *domain = ast_strdupa(v->value);
22976 char *cntx = strchr(domain, ',');
22977
22978 if (cntx)
22979 *cntx++ = '\0';
22980
22981 if (ast_strlen_zero(cntx))
22982 ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
22983 if (ast_strlen_zero(domain))
22984 ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
22985 else
22986 add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
22987 } else if (!strcasecmp(v->name, "register")) {
22988 if (sip_register(v->value, v->lineno) == 0)
22989 registry_count++;
22990 } else if (!strcasecmp(v->name, "tos_sip")) {
22991 if (ast_str2tos(v->value, &global_tos_sip))
22992 ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
22993 } else if (!strcasecmp(v->name, "tos_audio")) {
22994 if (ast_str2tos(v->value, &global_tos_audio))
22995 ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
22996 } else if (!strcasecmp(v->name, "tos_video")) {
22997 if (ast_str2tos(v->value, &global_tos_video))
22998 ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
22999 } else if (!strcasecmp(v->name, "tos_text")) {
23000 if (ast_str2tos(v->value, &global_tos_text))
23001 ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
23002 } else if (!strcasecmp(v->name, "cos_sip")) {
23003 if (ast_str2cos(v->value, &global_cos_sip))
23004 ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
23005 } else if (!strcasecmp(v->name, "cos_audio")) {
23006 if (ast_str2cos(v->value, &global_cos_audio))
23007 ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
23008 } else if (!strcasecmp(v->name, "cos_video")) {
23009 if (ast_str2cos(v->value, &global_cos_video))
23010 ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
23011 } else if (!strcasecmp(v->name, "cos_text")) {
23012 if (ast_str2cos(v->value, &global_cos_text))
23013 ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
23014 } else if (!strcasecmp(v->name, "bindport")) {
23015 int i;
23016 if (sscanf(v->value, "%5d", &i) == 1) {
23017 bindaddr.sin_port = htons(i);
23018 } else {
23019 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
23020 }
23021 } else if (!strcasecmp(v->name, "hash_user")) {
23022 int i;
23023 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23024 hash_user_size = i;
23025 } else {
23026 ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23027 }
23028 } else if (!strcasecmp(v->name, "hash_peer")) {
23029 int i;
23030 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23031 hash_peer_size = i;
23032 } else {
23033 ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23034 }
23035 } else if (!strcasecmp(v->name, "hash_dialog")) {
23036 int i;
23037 if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23038 hash_dialog_size = i;
23039 } else {
23040 ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
23041 }
23042 } else if (!strcasecmp(v->name, "qualify")) {
23043 if (!strcasecmp(v->value, "no")) {
23044 default_qualify = 0;
23045 } else if (!strcasecmp(v->value, "yes")) {
23046 default_qualify = DEFAULT_MAXMS;
23047 } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
23048 ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
23049 default_qualify = 0;
23050 }
23051 } else if (!strcasecmp(v->name, "qualifyfreq")) {
23052 int i;
23053 if (sscanf(v->value, "%30d", &i) == 1)
23054 global_qualifyfreq = i * 1000;
23055 else {
23056 ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
23057 global_qualifyfreq = DEFAULT_QUALIFYFREQ;
23058 }
23059 } else if (!strcasecmp(v->name, "callevents")) {
23060 global_callevents = ast_true(v->value);
23061 } else if (!strcasecmp(v->name, "authfailureevents")) {
23062 global_authfailureevents = ast_true(v->value);
23063 } else if (!strcasecmp(v->name, "maxcallbitrate")) {
23064 default_maxcallbitrate = atoi(v->value);
23065 if (default_maxcallbitrate < 0)
23066 default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
23067 } else if (!strcasecmp(v->name, "matchexterniplocally")) {
23068 global_matchexterniplocally = ast_true(v->value);
23069 } else if (!strcasecmp(v->name, "session-timers")) {
23070 int i = (int) str2stmode(v->value);
23071 if (i < 0) {
23072 ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
23073 global_st_mode = SESSION_TIMER_MODE_ACCEPT;
23074 } else {
23075 global_st_mode = i;
23076 }
23077 } else if (!strcasecmp(v->name, "session-expires")) {
23078 if (sscanf(v->value, "%30d", &global_max_se) != 1) {
23079 ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
23080 global_max_se = DEFAULT_MAX_SE;
23081 }
23082 } else if (!strcasecmp(v->name, "session-minse")) {
23083 if (sscanf(v->value, "%30d", &global_min_se) != 1) {
23084 ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
23085 global_min_se = DEFAULT_MIN_SE;
23086 }
23087 if (global_min_se < 90) {
23088 ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
23089 global_min_se = DEFAULT_MIN_SE;
23090 }
23091 } else if (!strcasecmp(v->name, "session-refresher")) {
23092 int i = (int) str2strefresher(v->value);
23093 if (i < 0) {
23094 ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
23095 global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
23096 } else {
23097 global_st_refresher = i;
23098 }
23099 }
23100 }
23101
23102 if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
23103 ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
23104 allow_external_domains = 1;
23105 }
23106
23107
23108 for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
23109
23110 if (!strcasecmp(v->name, "auth"))
23111 authl = add_realm_authentication(authl, v->value, v->lineno);
23112 }
23113
23114 if (ucfg) {
23115 struct ast_variable *gen;
23116 int genhassip, genregistersip;
23117 const char *hassip, *registersip;
23118
23119 genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
23120 genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
23121 gen = ast_variable_browse(ucfg, "general");
23122 cat = ast_category_browse(ucfg, NULL);
23123 while (cat) {
23124 if (strcasecmp(cat, "general")) {
23125 hassip = ast_variable_retrieve(ucfg, cat, "hassip");
23126 registersip = ast_variable_retrieve(ucfg, cat, "registersip");
23127 if (ast_true(hassip) || (!hassip && genhassip)) {
23128 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
23129 if (peer) {
23130 ao2_t_link(peers, peer, "link peer into peer table");
23131 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23132 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23133 }
23134
23135 unref_peer(peer, "unref_peer: from reload_config");
23136 peer_count++;
23137 }
23138 }
23139 if (ast_true(registersip) || (!registersip && genregistersip)) {
23140 char tmp[256];
23141 const char *host = ast_variable_retrieve(ucfg, cat, "host");
23142 const char *username = ast_variable_retrieve(ucfg, cat, "username");
23143 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
23144 const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
23145 if (!host)
23146 host = ast_variable_retrieve(ucfg, "general", "host");
23147 if (!username)
23148 username = ast_variable_retrieve(ucfg, "general", "username");
23149 if (!secret)
23150 secret = ast_variable_retrieve(ucfg, "general", "secret");
23151 if (!contact)
23152 contact = "s";
23153 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
23154 if (!ast_strlen_zero(secret))
23155 snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
23156 else
23157 snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
23158 if (sip_register(tmp, 0) == 0)
23159 registry_count++;
23160 }
23161 }
23162 }
23163 cat = ast_category_browse(ucfg, cat);
23164 }
23165 ast_config_destroy(ucfg);
23166 }
23167
23168
23169
23170 cat = NULL;
23171 while ( (cat = ast_category_browse(cfg, cat)) ) {
23172 const char *utype;
23173 if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
23174 continue;
23175 utype = ast_variable_retrieve(cfg, cat, "type");
23176 if (!utype) {
23177 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
23178 continue;
23179 } else {
23180 if (!strcasecmp(utype, "user")) {
23181 ;
23182 } else if (!strcasecmp(utype, "friend")) {
23183 ;
23184 } else if (!strcasecmp(utype, "peer")) {
23185 ;
23186 } else {
23187 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
23188 continue;
23189 }
23190 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
23191 if (peer) {
23192 ao2_t_link(peers, peer, "link peer into peers table");
23193 if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23194 ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23195 }
23196 unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
23197 peer_count++;
23198 }
23199 }
23200 }
23201
23202
23203 bindaddr.sin_family = AF_INET;
23204 internip = bindaddr;
23205 if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
23206 ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
23207 ast_config_destroy(cfg);
23208 return 0;
23209 }
23210 ast_mutex_lock(&netlock);
23211 if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
23212 close(sipsock);
23213 sipsock = -1;
23214 }
23215 if (sipsock < 0) {
23216 sipsock = socket(AF_INET, SOCK_DGRAM, 0);
23217 if (sipsock < 0) {
23218 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
23219 ast_config_destroy(cfg);
23220 return -1;
23221 } else {
23222
23223 const int reuseFlag = 1;
23224
23225 setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
23226 (const char*)&reuseFlag,
23227 sizeof reuseFlag);
23228
23229 ast_enable_packet_fragmentation(sipsock);
23230
23231 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
23232 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
23233 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
23234 strerror(errno));
23235 close(sipsock);
23236 sipsock = -1;
23237 } else {
23238 ast_verb(2, "SIP Listening on %s:%d\n",
23239 ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
23240 ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
23241 }
23242 }
23243 }
23244 if (stunaddr.sin_addr.s_addr != 0) {
23245 ast_debug(1, "stun to %s:%d\n",
23246 ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
23247 ast_stun_request(sipsock, &stunaddr,
23248 NULL, &externip);
23249 ast_debug(1, "STUN sees us at %s:%d\n",
23250 ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
23251 }
23252 ast_mutex_unlock(&netlock);
23253
23254
23255 ast_tcptls_server_start(&sip_tcp_desc);
23256
23257
23258 memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
23259
23260 if (ast_ssl_setup(sip_tls_desc.tls_cfg))
23261 ast_tcptls_server_start(&sip_tls_desc);
23262 else if (sip_tls_desc.tls_cfg->enabled) {
23263 sip_tls_desc.tls_cfg = NULL;
23264 ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
23265 }
23266
23267
23268
23269
23270
23271
23272
23273 if (auto_sip_domains) {
23274 char temp[MAXHOSTNAMELEN];
23275
23276
23277 if (bindaddr.sin_addr.s_addr)
23278 add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
23279 else
23280 ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
23281
23282
23283 if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
23284 add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
23285
23286
23287 if (sip_tls_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.local_address) && inaddrcmp(&sip_tcp_desc.local_address, &sip_tls_desc.local_address))
23288 add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
23289
23290
23291 if (externip.sin_addr.s_addr)
23292 add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
23293
23294
23295 if (!ast_strlen_zero(externhost))
23296 add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
23297
23298
23299 if (!gethostname(temp, sizeof(temp)))
23300 add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
23301 }
23302
23303
23304 ast_config_destroy(cfg);
23305
23306
23307 if (notify_types)
23308 ast_config_destroy(notify_types);
23309 notify_types = ast_config_load(notify_config, config_flags);
23310
23311
23312 manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
23313 run_end = time(0);
23314 ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
23315
23316 return 0;
23317 }
23318
23319 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
23320 {
23321 struct sip_pvt *p;
23322 struct ast_udptl *udptl = NULL;
23323
23324 p = chan->tech_pvt;
23325 if (!p)
23326 return NULL;
23327
23328 sip_pvt_lock(p);
23329 if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23330 udptl = p->udptl;
23331 sip_pvt_unlock(p);
23332 return udptl;
23333 }
23334
23335 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
23336 {
23337 struct sip_pvt *p;
23338
23339 p = chan->tech_pvt;
23340 if (!p)
23341 return -1;
23342 sip_pvt_lock(p);
23343 if (udptl)
23344 ast_udptl_get_peer(udptl, &p->udptlredirip);
23345 else
23346 memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
23347 if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23348 if (!p->pendinginvite) {
23349 ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
23350 transmit_reinvite_with_sdp(p, TRUE, FALSE);
23351 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
23352 ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
23353 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
23354 }
23355 }
23356
23357 p->lastrtprx = p->lastrtptx = time(NULL);
23358 sip_pvt_unlock(p);
23359 return 0;
23360 }
23361
23362
23363 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
23364 {
23365 struct sip_pvt *p = NULL;
23366 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
23367
23368 if (!(p = chan->tech_pvt))
23369 return AST_RTP_GET_FAILED;
23370
23371 sip_pvt_lock(p);
23372 if (!(p->rtp)) {
23373 sip_pvt_unlock(p);
23374 return AST_RTP_GET_FAILED;
23375 }
23376
23377 *rtp = p->rtp;
23378
23379 if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
23380 res = AST_RTP_TRY_PARTIAL;
23381 else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23382 res = AST_RTP_TRY_NATIVE;
23383 else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
23384 res = AST_RTP_GET_FAILED;
23385
23386 sip_pvt_unlock(p);
23387
23388 return res;
23389 }
23390
23391
23392 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
23393 {
23394 struct sip_pvt *p = NULL;
23395 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
23396
23397 if (!(p = chan->tech_pvt))
23398 return AST_RTP_GET_FAILED;
23399
23400 sip_pvt_lock(p);
23401 if (!(p->vrtp)) {
23402 sip_pvt_unlock(p);
23403 return AST_RTP_GET_FAILED;
23404 }
23405
23406 *rtp = p->vrtp;
23407
23408 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23409 res = AST_RTP_TRY_NATIVE;
23410
23411 sip_pvt_unlock(p);
23412
23413 return res;
23414 }
23415
23416
23417 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
23418 {
23419 struct sip_pvt *p = NULL;
23420 enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
23421
23422 if (!(p = chan->tech_pvt))
23423 return AST_RTP_GET_FAILED;
23424
23425 sip_pvt_lock(p);
23426 if (!(p->trtp)) {
23427 sip_pvt_unlock(p);
23428 return AST_RTP_GET_FAILED;
23429 }
23430
23431 *rtp = p->trtp;
23432
23433 if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
23434 res = AST_RTP_TRY_NATIVE;
23435
23436 sip_pvt_unlock(p);
23437
23438 return res;
23439 }
23440
23441
23442 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
23443 {
23444 struct sip_pvt *p;
23445 int changed = 0;
23446
23447 p = chan->tech_pvt;
23448 if (!p)
23449 return -1;
23450
23451
23452 if (!ast_bridged_channel(chan) && !global_directrtpsetup)
23453 return 0;
23454
23455 sip_pvt_lock(p);
23456 if (p->alreadygone) {
23457
23458 sip_pvt_unlock(p);
23459 return 0;
23460 }
23461
23462
23463
23464
23465 if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
23466 sip_pvt_unlock(p);
23467 return 0;
23468 }
23469
23470 if (rtp) {
23471 changed |= ast_rtp_get_peer(rtp, &p->redirip);
23472 } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
23473 memset(&p->redirip, 0, sizeof(p->redirip));
23474 changed = 1;
23475 }
23476 if (vrtp) {
23477 changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
23478 } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
23479 memset(&p->vredirip, 0, sizeof(p->vredirip));
23480 changed = 1;
23481 }
23482 if (trtp) {
23483 changed |= ast_rtp_get_peer(trtp, &p->tredirip);
23484 } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
23485 memset(&p->tredirip, 0, sizeof(p->tredirip));
23486 changed = 1;
23487 }
23488 if (codecs && (p->redircodecs != codecs)) {
23489 p->redircodecs = codecs;
23490 changed = 1;
23491 }
23492 if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
23493 if (chan->_state != AST_STATE_UP) {
23494 if (p->do_history)
23495 append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
23496 ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
23497 } else if (!p->pendinginvite) {
23498 ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
23499 transmit_reinvite_with_sdp(p, FALSE, FALSE);
23500 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
23501 ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
23502
23503 ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
23504 }
23505 }
23506
23507 p->lastrtprx = p->lastrtptx = time(NULL);
23508 sip_pvt_unlock(p);
23509 return 0;
23510 }
23511
23512 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
23513 static char *descrip_dtmfmode = " SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
23514 static char *app_dtmfmode = "SIPDtmfMode";
23515
23516 static char *app_sipaddheader = "SIPAddHeader";
23517 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
23518
23519 static char *descrip_sipaddheader = ""
23520 " SIPAddHeader(Header: Content):\n"
23521 "Adds a header to a SIP call placed with DIAL.\n"
23522 "Remember to user the X-header if you are adding non-standard SIP\n"
23523 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
23524 "Adding the wrong headers may jeopardize the SIP dialog.\n"
23525 "Always returns 0\n";
23526
23527
23528
23529 static int sip_dtmfmode(struct ast_channel *chan, void *data)
23530 {
23531 struct sip_pvt *p;
23532 char *mode = data;
23533
23534 if (!data) {
23535 ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
23536 return 0;
23537 }
23538 ast_channel_lock(chan);
23539 if (!IS_SIP_TECH(chan->tech)) {
23540 ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
23541 ast_channel_unlock(chan);
23542 return 0;
23543 }
23544 p = chan->tech_pvt;
23545 if (!p) {
23546 ast_channel_unlock(chan);
23547 return 0;
23548 }
23549 sip_pvt_lock(p);
23550 if (!strcasecmp(mode, "info")) {
23551 ast_clear_flag(&p->flags[0], SIP_DTMF);
23552 ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
23553 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
23554 } else if (!strcasecmp(mode, "shortinfo")) {
23555 ast_clear_flag(&p->flags[0], SIP_DTMF);
23556 ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
23557 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
23558 } else if (!strcasecmp(mode, "rfc2833")) {
23559 ast_clear_flag(&p->flags[0], SIP_DTMF);
23560 ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
23561 p->jointnoncodeccapability |= AST_RTP_DTMF;
23562 } else if (!strcasecmp(mode, "inband")) {
23563 ast_clear_flag(&p->flags[0], SIP_DTMF);
23564 ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
23565 p->jointnoncodeccapability &= ~AST_RTP_DTMF;
23566 } else
23567 ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
23568 if (p->rtp)
23569 ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
23570 if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
23571 if (!p->vad) {
23572 p->vad = ast_dsp_new();
23573 ast_dsp_set_features(p->vad, DSP_FEATURE_DIGIT_DETECT);
23574 }
23575 } else {
23576 if (p->vad) {
23577 ast_dsp_free(p->vad);
23578 p->vad = NULL;
23579 }
23580 }
23581 sip_pvt_unlock(p);
23582 ast_channel_unlock(chan);
23583 return 0;
23584 }
23585
23586
23587 static int sip_addheader(struct ast_channel *chan, void *data)
23588 {
23589 int no = 0;
23590 int ok = FALSE;
23591 char varbuf[30];
23592 char *inbuf = data, *subbuf;
23593
23594 if (ast_strlen_zero(inbuf)) {
23595 ast_log(LOG_WARNING, "This application requires the argument: Header\n");
23596 return 0;
23597 }
23598 ast_channel_lock(chan);
23599
23600
23601 while (!ok && no <= 50) {
23602 no++;
23603 snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
23604
23605
23606 if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
23607 ok = TRUE;
23608 }
23609 }
23610 if (ok) {
23611 size_t len = strlen(inbuf);
23612 subbuf = alloca(len + 1);
23613 ast_get_encoded_str(inbuf, subbuf, len + 1);
23614 pbx_builtin_setvar_helper(chan, varbuf, subbuf);
23615 if (sipdebug) {
23616 ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
23617 }
23618 } else {
23619 ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
23620 }
23621 ast_channel_unlock(chan);
23622 return 0;
23623 }
23624
23625
23626
23627
23628
23629
23630
23631 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
23632 {
23633 char *cdest;
23634 char *extension, *host, *port;
23635 char tmp[80];
23636
23637 cdest = ast_strdupa(dest);
23638
23639 extension = strsep(&cdest, "@");
23640 host = strsep(&cdest, ":");
23641 port = strsep(&cdest, ":");
23642 if (ast_strlen_zero(extension)) {
23643 ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
23644 return 0;
23645 }
23646
23647
23648 if (!host) {
23649 char *localtmp;
23650
23651 ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
23652 if (ast_strlen_zero(tmp)) {
23653 ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
23654 return 0;
23655 }
23656 if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) )
23657 && (localtmp = strchr(localtmp, '@'))) {
23658 char lhost[80], lport[80];
23659
23660 memset(lhost, 0, sizeof(lhost));
23661 memset(lport, 0, sizeof(lport));
23662 localtmp++;
23663
23664 sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
23665 if (ast_strlen_zero(lhost)) {
23666 ast_log(LOG_ERROR, "Can't find the host address\n");
23667 return 0;
23668 }
23669 host = ast_strdupa(lhost);
23670 if (!ast_strlen_zero(lport)) {
23671 port = ast_strdupa(lport);
23672 }
23673 }
23674 }
23675
23676 ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
23677 transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
23678
23679 sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
23680 sip_alreadygone(p);
23681
23682 return 0;
23683 }
23684
23685
23686 static int sip_get_codec(struct ast_channel *chan)
23687 {
23688 struct sip_pvt *p = chan->tech_pvt;
23689 return p->jointcapability ? p->jointcapability : p->capability;
23690 }
23691
23692
23693
23694
23695
23696 static void sip_poke_all_peers(void)
23697 {
23698 int ms = 0;
23699 struct ao2_iterator i;
23700 struct sip_peer *peer;
23701
23702 i = ao2_iterator_init(peers, 0);
23703
23704 if (!speerobjs)
23705 return;
23706
23707 while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
23708 ao2_lock(peer);
23709 ms += 100;
23710 AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
23711 unref_peer(_data, "removing poke peer ref"),
23712 unref_peer(peer, "removing poke peer ref"),
23713 ref_peer(peer, "adding poke peer ref"));
23714 ao2_unlock(peer);
23715 unref_peer(peer, "toss iterator peer ptr");
23716 }
23717 }
23718
23719
23720 static void sip_send_all_registers(void)
23721 {
23722 int ms;
23723 int regspacing;
23724 if (!regobjs)
23725 return;
23726 regspacing = default_expiry * 1000/regobjs;
23727 if (regspacing > 100)
23728 regspacing = 100;
23729 ms = regspacing;
23730 ASTOBJ_CONTAINER_TRAVERSE(®l, 1, do {
23731 ASTOBJ_WRLOCK(iterator);
23732 ms += regspacing;
23733 AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
23734 registry_unref(_data, "REPLACE sched del decs the refcount"),
23735 registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
23736 registry_addref(iterator, "REPLACE sched add incs the refcount"));
23737 ASTOBJ_UNLOCK(iterator);
23738 } while (0)
23739 );
23740 }
23741
23742
23743 static int sip_do_reload(enum channelreloadreason reason)
23744 {
23745 time_t start_poke, end_poke;
23746
23747 reload_config(reason);
23748 ast_sched_dump(sched);
23749
23750 start_poke = time(0);
23751
23752 ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0,
23753 "callback to remove marked peers");
23754
23755 ast_debug(4, "--------------- Done destroying pruned peers\n");
23756
23757
23758 sip_poke_all_peers();
23759
23760
23761 sip_send_all_registers();
23762 end_poke = time(0);
23763
23764 ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
23765
23766 ast_debug(4, "--------------- SIP reload done\n");
23767
23768 return 0;
23769 }
23770
23771
23772 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
23773 {
23774
23775 switch (cmd) {
23776 case CLI_INIT:
23777 e->command = "sip reload";
23778 e->usage =
23779 "Usage: sip reload\n"
23780 " Reloads SIP configuration from sip.conf\n";
23781 return NULL;
23782 case CLI_GENERATE:
23783 return NULL;
23784 }
23785
23786 ast_mutex_lock(&sip_reload_lock);
23787 if (sip_reloading)
23788 ast_verbose("Previous SIP reload not yet done\n");
23789 else {
23790 sip_reloading = TRUE;
23791 sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
23792 }
23793 ast_mutex_unlock(&sip_reload_lock);
23794 restart_monitor();
23795
23796 return CLI_SUCCESS;
23797 }
23798
23799
23800 static int reload(void)
23801 {
23802 if (sip_reload(0, 0, NULL))
23803 return 0;
23804 return 1;
23805 }
23806
23807 static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
23808
23809 static struct ast_cli_entry cli_sip[] = {
23810 AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
23811 AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
23812 AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
23813 AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
23814 AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
23815 AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
23816 AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
23817 AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
23818 AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
23819 AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
23820 AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
23821 AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
23822 AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
23823 AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
23824 AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
23825 AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
23826 AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
23827 AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
23828 AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
23829 AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
23830 AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
23831 AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
23832 };
23833
23834
23835 static int load_module(void)
23836 {
23837 ast_verbose("SIP channel loading...\n");
23838
23839
23840 peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
23841 peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
23842 dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
23843
23844 ASTOBJ_CONTAINER_INIT(®l);
23845
23846 if (!(sched = sched_context_create())) {
23847 ast_log(LOG_ERROR, "Unable to create scheduler context\n");
23848 return AST_MODULE_LOAD_FAILURE;
23849 }
23850
23851 if (!(io = io_context_create())) {
23852 ast_log(LOG_ERROR, "Unable to create I/O context\n");
23853 sched_context_destroy(sched);
23854 return AST_MODULE_LOAD_FAILURE;
23855 }
23856
23857 sip_reloadreason = CHANNEL_MODULE_LOAD;
23858
23859 if(reload_config(sip_reloadreason))
23860 return AST_MODULE_LOAD_DECLINE;
23861
23862
23863
23864
23865
23866 memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
23867 memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
23868
23869
23870 if (ast_channel_register(&sip_tech)) {
23871 ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
23872 io_context_destroy(io);
23873 sched_context_destroy(sched);
23874 return AST_MODULE_LOAD_FAILURE;
23875 }
23876
23877
23878 ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
23879
23880
23881 ast_rtp_proto_register(&sip_rtp);
23882
23883
23884 ast_udptl_proto_register(&sip_udptl);
23885
23886
23887 ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
23888 ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
23889
23890
23891 ast_custom_function_register(&sip_header_function);
23892 ast_custom_function_register(&sippeer_function);
23893 ast_custom_function_register(&sipchaninfo_function);
23894 ast_custom_function_register(&checksipdomain_function);
23895
23896
23897 ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
23898 "List SIP peers (text format)", mandescr_show_peers);
23899 ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
23900 "Show SIP peer (text format)", mandescr_show_peer);
23901 ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
23902 "Show SIP peer (text format)", mandescr_show_peer);
23903 ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
23904 "Show SIP registrations (text format)", mandescr_show_registry);
23905 ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
23906 "Send a SIP notify", mandescr_sipnotify);
23907 sip_poke_all_peers();
23908 sip_send_all_registers();
23909
23910
23911 restart_monitor();
23912
23913 ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
23914 "name", RQ_CHAR, 10,
23915 "ipaddr", RQ_CHAR, 15,
23916 "port", RQ_UINTEGER2, 5,
23917 "regseconds", RQ_INTEGER4, 11,
23918 "defaultuser", RQ_CHAR, 10,
23919 "fullcontact", RQ_CHAR, 35,
23920 "regserver", RQ_CHAR, 20,
23921 "useragent", RQ_CHAR, 20,
23922 "lastms", RQ_INTEGER4, 11,
23923 SENTINEL);
23924
23925 return AST_MODULE_LOAD_SUCCESS;
23926 }
23927
23928
23929 static int unload_module(void)
23930 {
23931 struct sip_pvt *p;
23932 struct sip_threadinfo *th;
23933 struct ast_context *con;
23934 struct ao2_iterator i;
23935
23936 ast_sched_dump(sched);
23937
23938
23939 ast_channel_unregister(&sip_tech);
23940
23941
23942 ast_custom_function_unregister(&sipchaninfo_function);
23943 ast_custom_function_unregister(&sippeer_function);
23944 ast_custom_function_unregister(&sip_header_function);
23945 ast_custom_function_unregister(&checksipdomain_function);
23946
23947
23948 ast_unregister_application(app_dtmfmode);
23949 ast_unregister_application(app_sipaddheader);
23950
23951
23952 ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
23953
23954
23955 ast_rtp_proto_unregister(&sip_rtp);
23956
23957
23958 ast_udptl_proto_unregister(&sip_udptl);
23959
23960
23961 ast_manager_unregister("SIPpeers");
23962 ast_manager_unregister("SIPshowpeer");
23963 ast_manager_unregister("SIPqualifypeer");
23964 ast_manager_unregister("SIPshowregistry");
23965 ast_manager_unregister("SIPnotify");
23966
23967
23968 if (sip_tcp_desc.master)
23969 ast_tcptls_server_stop(&sip_tcp_desc);
23970 if (sip_tls_desc.master)
23971 ast_tcptls_server_stop(&sip_tls_desc);
23972
23973
23974 AST_LIST_LOCK(&threadl);
23975 AST_LIST_TRAVERSE_SAFE_BEGIN(&threadl, th, list) {
23976 pthread_t thread = th->threadid;
23977 th->stop = 1;
23978 AST_LIST_UNLOCK(&threadl);
23979 pthread_kill(thread, SIGURG);
23980 pthread_join(thread, NULL);
23981 AST_LIST_LOCK(&threadl);
23982 }
23983 AST_LIST_TRAVERSE_SAFE_END;
23984 AST_LIST_UNLOCK(&threadl);
23985
23986
23987 i = ao2_iterator_init(dialogs, 0);
23988 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
23989 if (p->owner)
23990 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
23991 ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
23992 }
23993
23994 ast_mutex_lock(&monlock);
23995 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
23996 pthread_cancel(monitor_thread);
23997 pthread_kill(monitor_thread, SIGURG);
23998 pthread_join(monitor_thread, NULL);
23999 }
24000 monitor_thread = AST_PTHREADT_STOP;
24001 ast_mutex_unlock(&monlock);
24002
24003
24004 i = ao2_iterator_init(dialogs, 0);
24005 while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
24006 dialog_unlink_all(p, TRUE, TRUE);
24007 ao2_t_ref(p, -1, "throw away iterator result");
24008 }
24009
24010
24011 ast_free_ha(localaddr);
24012
24013 clear_realm_authentication(authl);
24014
24015
24016 if (default_tls_cfg.certfile)
24017 ast_free(default_tls_cfg.certfile);
24018 if (default_tls_cfg.cipher)
24019 ast_free(default_tls_cfg.cipher);
24020 if (default_tls_cfg.cafile)
24021 ast_free(default_tls_cfg.cafile);
24022 if (default_tls_cfg.capath)
24023 ast_free(default_tls_cfg.capath);
24024
24025 ASTOBJ_CONTAINER_DESTROYALL(®l, sip_registry_destroy);
24026 ASTOBJ_CONTAINER_DESTROY(®l);
24027
24028 ao2_t_ref(peers, -1, "unref the peers table");
24029 ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
24030 ao2_t_ref(dialogs, -1, "unref the dialogs table");
24031
24032 clear_sip_domains();
24033 close(sipsock);
24034 sched_context_destroy(sched);
24035 con = ast_context_find(used_context);
24036 if (con)
24037 ast_context_destroy(con, "SIP");
24038 ast_unload_realtime("sipregs");
24039 ast_unload_realtime("sippeers");
24040
24041 return 0;
24042 }
24043
24044 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
24045 .load = load_module,
24046 .unload = unload_module,
24047 .reload = reload,
24048 );