res_pjsip_outbound_registration.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2013, Digium, Inc.
  5. *
  6. * Joshua Colp <jcolp@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*** MODULEINFO
  19. <depend>pjproject</depend>
  20. <depend>res_pjsip</depend>
  21. <use type="module">res_statsd</use>
  22. <support_level>core</support_level>
  23. ***/
  24. #include "asterisk.h"
  25. #include <pjsip.h>
  26. #include <pjsip_ua.h>
  27. #include "asterisk/res_pjsip.h"
  28. #include "asterisk/res_pjsip_cli.h"
  29. #include "asterisk/module.h"
  30. #include "asterisk/taskprocessor.h"
  31. #include "asterisk/cli.h"
  32. #include "asterisk/stasis_system.h"
  33. #include "asterisk/threadstorage.h"
  34. #include "asterisk/threadpool.h"
  35. #include "asterisk/statsd.h"
  36. #include "res_pjsip/include/res_pjsip_private.h"
  37. /*** DOCUMENTATION
  38. <configInfo name="res_pjsip_outbound_registration" language="en_US">
  39. <synopsis>SIP resource for outbound registrations</synopsis>
  40. <description><para>
  41. <emphasis>Outbound Registration</emphasis>
  42. </para>
  43. <para>This module allows <literal>res_pjsip</literal> to register to other SIP servers.</para>
  44. </description>
  45. <configFile name="pjsip.conf">
  46. <configObject name="registration">
  47. <synopsis>The configuration for outbound registration</synopsis>
  48. <description><para>
  49. Registration is <emphasis>COMPLETELY</emphasis> separate from the rest of
  50. <literal>pjsip.conf</literal>. A minimal configuration consists of
  51. setting a <literal>server_uri</literal> and a <literal>client_uri</literal>.
  52. </para></description>
  53. <configOption name="auth_rejection_permanent" default="yes">
  54. <synopsis>Determines whether failed authentication challenges are treated
  55. as permanent failures.</synopsis>
  56. <description><para>If this option is enabled and an authentication challenge fails,
  57. registration will not be attempted again until the configuration is reloaded.</para></description>
  58. </configOption>
  59. <configOption name="client_uri">
  60. <synopsis>Client SIP URI used when attemping outbound registration</synopsis>
  61. <description><para>
  62. This is the address-of-record for the outbound registration (i.e. the URI in
  63. the To header of the REGISTER).</para>
  64. <para>For registration with an ITSP, the client SIP URI may need to consist of
  65. an account name or number and the provider's hostname for their registrar, e.g.
  66. client_uri=1234567890@example.com. This may differ between providers.</para>
  67. <para>For registration to generic registrars, the client SIP URI will depend
  68. on networking specifics and configuration of the registrar.
  69. </para></description>
  70. </configOption>
  71. <configOption name="contact_user">
  72. <synopsis>Contact User to use in request</synopsis>
  73. </configOption>
  74. <configOption name="expiration" default="3600">
  75. <synopsis>Expiration time for registrations in seconds</synopsis>
  76. </configOption>
  77. <configOption name="max_retries" default="10">
  78. <synopsis>Maximum number of registration attempts.</synopsis>
  79. </configOption>
  80. <configOption name="outbound_auth" default="">
  81. <synopsis>Authentication object(s) to be used for outbound registrations.</synopsis>
  82. <description><para>
  83. This is a comma-delimited list of <replaceable>auth</replaceable>
  84. sections defined in <filename>pjsip.conf</filename> used to respond
  85. to outbound authentication challenges.</para>
  86. <note><para>
  87. Using the same auth section for inbound and outbound
  88. authentication is not recommended. There is a difference in
  89. meaning for an empty realm setting between inbound and outbound
  90. authentication uses. See the auth realm description for details.
  91. </para></note>
  92. </description>
  93. </configOption>
  94. <configOption name="outbound_proxy" default="">
  95. <synopsis>Full SIP URI of the outbound proxy used to send registrations</synopsis>
  96. </configOption>
  97. <configOption name="retry_interval" default="60">
  98. <synopsis>Interval in seconds between retries if outbound registration is unsuccessful</synopsis>
  99. </configOption>
  100. <configOption name="forbidden_retry_interval" default="0">
  101. <synopsis>Interval used when receiving a 403 Forbidden response.</synopsis>
  102. <description><para>
  103. If a 403 Forbidden is received, chan_pjsip will wait
  104. <replaceable>forbidden_retry_interval</replaceable> seconds before
  105. attempting registration again. If 0 is specified, chan_pjsip will not
  106. retry after receiving a 403 Forbidden response. Setting this to a non-zero
  107. value goes against a "SHOULD NOT" in RFC3261, but can be used to work around
  108. buggy registrars.
  109. </para></description>
  110. </configOption>
  111. <configOption name="fatal_retry_interval" default="0">
  112. <synopsis>Interval used when receiving a Fatal response.</synopsis>
  113. <description><para>
  114. If a fatal response is received, chan_pjsip will wait
  115. <replaceable>fatal_retry_interval</replaceable> seconds before
  116. attempting registration again. If 0 is specified, chan_pjsip will not
  117. retry after receiving a fatal (non-temporary 4xx, 5xx, 6xx) response.
  118. Setting this to a non-zero value may go against a "SHOULD NOT" in RFC3261,
  119. but can be used to work around buggy registrars.</para>
  120. <note><para>if also set the <replaceable>forbidden_retry_interval</replaceable>
  121. takes precedence over this one when a 403 is received.
  122. Also, if <replaceable>auth_rejection_permanent</replaceable> equals 'yes' then
  123. a 401 and 407 become subject to this retry interval.</para></note>
  124. </description>
  125. </configOption>
  126. <configOption name="server_uri">
  127. <synopsis>SIP URI of the server to register against</synopsis>
  128. <description><para>
  129. This is the URI at which to find the registrar to send the outbound REGISTER. This URI
  130. is used as the request URI of the outbound REGISTER request from Asterisk.</para>
  131. <para>For registration with an ITSP, the setting may often be just the domain of
  132. the registrar, e.g. sip:sip.example.com.
  133. </para></description>
  134. </configOption>
  135. <configOption name="transport">
  136. <synopsis>Transport used for outbound authentication</synopsis>
  137. <description>
  138. <note><para>A <replaceable>transport</replaceable> configured in
  139. <literal>pjsip.conf</literal>. As with other <literal>res_pjsip</literal> modules, this will use the first available transport of the appropriate type if unconfigured.</para></note>
  140. </description>
  141. </configOption>
  142. <configOption name="line">
  143. <synopsis>Whether to add a 'line' parameter to the Contact for inbound call matching</synopsis>
  144. <description><para>
  145. When enabled this option will cause a 'line' parameter to be added to the Contact
  146. header placed into the outgoing registration request. If the remote server sends a call
  147. this line parameter will be used to establish a relationship to the outbound registration,
  148. ultimately causing the configured endpoint to be used.
  149. </para></description>
  150. </configOption>
  151. <configOption name="endpoint">
  152. <synopsis>Endpoint to use for incoming related calls</synopsis>
  153. <description><para>
  154. When line support is enabled this configured endpoint name is used for incoming calls
  155. that are related to the outbound registration.
  156. </para></description>
  157. </configOption>
  158. <configOption name="type">
  159. <synopsis>Must be of type 'registration'.</synopsis>
  160. </configOption>
  161. <configOption name="support_path">
  162. <synopsis>Enables Path support for outbound REGISTER requests.</synopsis>
  163. <description><para>
  164. When this option is enabled, outbound REGISTER requests will advertise
  165. support for Path headers so that intervening proxies can add to the Path
  166. header as necessary.
  167. </para></description>
  168. </configOption>
  169. </configObject>
  170. </configFile>
  171. </configInfo>
  172. <manager name="PJSIPUnregister" language="en_US">
  173. <synopsis>
  174. Unregister an outbound registration.
  175. </synopsis>
  176. <syntax>
  177. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  178. <parameter name="Registration" required="true">
  179. <para>The outbound registration to unregister or '*all' to unregister them all.</para>
  180. </parameter>
  181. </syntax>
  182. <description>
  183. <para>
  184. Unregisters the specified (or all) outbound registration(s) and stops future registration attempts.
  185. Call PJSIPRegister to start registration and schedule re-registrations according to configuration.
  186. </para>
  187. </description>
  188. </manager>
  189. <manager name="PJSIPRegister" language="en_US">
  190. <synopsis>
  191. Register an outbound registration.
  192. </synopsis>
  193. <syntax>
  194. <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
  195. <parameter name="Registration" required="true">
  196. <para>The outbound registration to register or '*all' to register them all.</para>
  197. </parameter>
  198. </syntax>
  199. <description>
  200. <para>
  201. Unregisters the specified (or all) outbound registration(s) then starts registration and schedules re-registrations
  202. according to configuration.
  203. </para>
  204. </description>
  205. </manager>
  206. <manager name="PJSIPShowRegistrationsOutbound" language="en_US">
  207. <synopsis>
  208. Lists PJSIP outbound registrations.
  209. </synopsis>
  210. <syntax />
  211. <description>
  212. <para>
  213. In response <literal>OutboundRegistrationDetail</literal> events showing configuration and status
  214. information are raised for each outbound registration object. <literal>AuthDetail</literal>
  215. events are raised for each associated auth object as well. Once all events are completed an
  216. <literal>OutboundRegistrationDetailComplete</literal> is issued.
  217. </para>
  218. </description>
  219. </manager>
  220. ***/
  221. /*! \brief Some thread local storage used to determine if the running thread invoked the callback */
  222. AST_THREADSTORAGE(register_callback_invoked);
  223. /*! \brief Amount of buffer time (in seconds) before expiration that we re-register at */
  224. #define REREGISTER_BUFFER_TIME 10
  225. /*! \brief Size of the buffer for creating a unique string for the line */
  226. #define LINE_PARAMETER_SIZE 8
  227. /*! \brief Various states that an outbound registration may be in */
  228. enum sip_outbound_registration_status {
  229. /*! \brief Currently unregistered */
  230. SIP_REGISTRATION_UNREGISTERED = 0,
  231. /*! \brief Registered, yay! */
  232. SIP_REGISTRATION_REGISTERED,
  233. /*! \brief Registration was rejected, but response was temporal */
  234. SIP_REGISTRATION_REJECTED_TEMPORARY,
  235. /*! \brief Registration was rejected, permanently */
  236. SIP_REGISTRATION_REJECTED_PERMANENT,
  237. /*! \brief Registration is stopping. */
  238. SIP_REGISTRATION_STOPPING,
  239. /*! \brief Registration has been stopped */
  240. SIP_REGISTRATION_STOPPED,
  241. };
  242. /*!
  243. * \internal
  244. * \brief Convert the internal registration state to an external status string.
  245. * \since 13.5.0
  246. *
  247. * \param state Current outbound registration state.
  248. *
  249. * \return External registration status string.
  250. */
  251. static const char *sip_outbound_registration_status_str(enum sip_outbound_registration_status state)
  252. {
  253. const char *str;
  254. str = "Unregistered";
  255. switch (state) {
  256. case SIP_REGISTRATION_STOPPING:
  257. case SIP_REGISTRATION_STOPPED:
  258. case SIP_REGISTRATION_UNREGISTERED:
  259. break;
  260. case SIP_REGISTRATION_REGISTERED:
  261. str = "Registered";
  262. break;
  263. case SIP_REGISTRATION_REJECTED_TEMPORARY:
  264. case SIP_REGISTRATION_REJECTED_PERMANENT:
  265. str = "Rejected";
  266. break;
  267. }
  268. return str;
  269. }
  270. /*! \brief Outbound registration information */
  271. struct sip_outbound_registration {
  272. /*! \brief Sorcery object details */
  273. SORCERY_OBJECT(details);
  274. /*! \brief Stringfields */
  275. AST_DECLARE_STRING_FIELDS(
  276. /*! \brief URI for the registrar */
  277. AST_STRING_FIELD(server_uri);
  278. /*! \brief URI for the AOR */
  279. AST_STRING_FIELD(client_uri);
  280. /*! \brief Optional user for contact header */
  281. AST_STRING_FIELD(contact_user);
  282. /*! \brief Explicit transport to use for registration */
  283. AST_STRING_FIELD(transport);
  284. /*! \brief Outbound proxy to use */
  285. AST_STRING_FIELD(outbound_proxy);
  286. /*! \brief Endpoint to use for related incoming calls */
  287. AST_STRING_FIELD(endpoint);
  288. );
  289. /*! \brief Requested expiration time */
  290. unsigned int expiration;
  291. /*! \brief Interval at which retries should occur for temporal responses */
  292. unsigned int retry_interval;
  293. /*! \brief Interval at which retries should occur for permanent responses */
  294. unsigned int forbidden_retry_interval;
  295. /*! \brief Interval at which retries should occur for all permanent responses */
  296. unsigned int fatal_retry_interval;
  297. /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
  298. unsigned int auth_rejection_permanent;
  299. /*! \brief Maximum number of retries permitted */
  300. unsigned int max_retries;
  301. /*! \brief Whether to add a line parameter to the outbound Contact or not */
  302. unsigned int line;
  303. /*! \brief Configured authentication credentials */
  304. struct ast_sip_auth_vector outbound_auths;
  305. /*! \brief Whether Path support is enabled */
  306. unsigned int support_path;
  307. };
  308. /*! \brief Outbound registration client state information (persists for lifetime of regc) */
  309. struct sip_outbound_registration_client_state {
  310. /*! \brief Current state of this registration */
  311. enum sip_outbound_registration_status status;
  312. /*!
  313. * \brief Outbound registration client
  314. * \note May only be accessed within the serializer thread
  315. * because it might get destroyed and set to NULL for
  316. * module unload.
  317. */
  318. pjsip_regc *client;
  319. /*! \brief Timer entry for retrying on temporal responses */
  320. pj_timer_entry timer;
  321. /*! \brief Optional line parameter placed into Contact */
  322. char line[LINE_PARAMETER_SIZE];
  323. /*! \brief Current number of retries */
  324. unsigned int retries;
  325. /*! \brief Maximum number of retries permitted */
  326. unsigned int max_retries;
  327. /*! \brief Interval at which retries should occur for temporal responses */
  328. unsigned int retry_interval;
  329. /*! \brief Interval at which retries should occur for permanent responses */
  330. unsigned int forbidden_retry_interval;
  331. /*! \brief Interval at which retries should occur for all permanent responses */
  332. unsigned int fatal_retry_interval;
  333. /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
  334. unsigned int auth_rejection_permanent;
  335. /*! \brief Determines whether SIP Path support should be advertised */
  336. unsigned int support_path;
  337. /*! CSeq number of last sent auth request. */
  338. unsigned int auth_cseq;
  339. /*! \brief Serializer for stuff and things */
  340. struct ast_taskprocessor *serializer;
  341. /*! \brief Configured authentication credentials */
  342. struct ast_sip_auth_vector outbound_auths;
  343. /*! \brief Registration should be destroyed after completion of transaction */
  344. unsigned int destroy:1;
  345. /*! \brief Non-zero if we have attempted sending a REGISTER with authentication */
  346. unsigned int auth_attempted:1;
  347. /*! \brief The name of the transport to be used for the registration */
  348. char *transport_name;
  349. /*! \brief The name of the registration sorcery object */
  350. char *registration_name;
  351. };
  352. /*! \brief Outbound registration state information (persists for lifetime that registration should exist) */
  353. struct sip_outbound_registration_state {
  354. /*! \brief Outbound registration configuration object */
  355. struct sip_outbound_registration *registration;
  356. /*! \brief Client state information */
  357. struct sip_outbound_registration_client_state *client_state;
  358. };
  359. /*! Time needs to be long enough for a transaction to timeout if nothing replies. */
  360. #define MAX_UNLOAD_TIMEOUT_TIME 35 /* Seconds */
  361. /*! Shutdown group to monitor sip_outbound_registration_client_state serializers. */
  362. static struct ast_serializer_shutdown_group *shutdown_group;
  363. /*! \brief Default number of state container buckets */
  364. #define DEFAULT_STATE_BUCKETS 53
  365. static AO2_GLOBAL_OBJ_STATIC(current_states);
  366. /*! subscription id for network change events */
  367. static struct stasis_subscription *network_change_sub;
  368. /*! \brief hashing function for state objects */
  369. static int registration_state_hash(const void *obj, const int flags)
  370. {
  371. const struct sip_outbound_registration_state *object;
  372. const char *key;
  373. switch (flags & OBJ_SEARCH_MASK) {
  374. case OBJ_SEARCH_KEY:
  375. key = obj;
  376. break;
  377. case OBJ_SEARCH_OBJECT:
  378. object = obj;
  379. key = ast_sorcery_object_get_id(object->registration);
  380. break;
  381. default:
  382. ast_assert(0);
  383. return 0;
  384. }
  385. return ast_str_hash(key);
  386. }
  387. /*! \brief comparator function for state objects */
  388. static int registration_state_cmp(void *obj, void *arg, int flags)
  389. {
  390. const struct sip_outbound_registration_state *object_left = obj;
  391. const struct sip_outbound_registration_state *object_right = arg;
  392. const char *right_key = arg;
  393. int cmp;
  394. switch (flags & OBJ_SEARCH_MASK) {
  395. case OBJ_SEARCH_OBJECT:
  396. right_key = ast_sorcery_object_get_id(object_right->registration);
  397. /* Fall through */
  398. case OBJ_SEARCH_KEY:
  399. cmp = strcmp(ast_sorcery_object_get_id(object_left->registration), right_key);
  400. break;
  401. case OBJ_SEARCH_PARTIAL_KEY:
  402. /* Not supported by container. */
  403. ast_assert(0);
  404. return 0;
  405. default:
  406. cmp = 0;
  407. break;
  408. }
  409. if (cmp) {
  410. return 0;
  411. }
  412. return CMP_MATCH;
  413. }
  414. static struct sip_outbound_registration_state *get_state(const char *id)
  415. {
  416. struct sip_outbound_registration_state *state = NULL;
  417. struct ao2_container *states;
  418. states = ao2_global_obj_ref(current_states);
  419. if (states) {
  420. state = ao2_find(states, id, OBJ_SEARCH_KEY);
  421. ao2_ref(states, -1);
  422. }
  423. return state;
  424. }
  425. static struct ao2_container *get_registrations(void)
  426. {
  427. struct ao2_container *registrations = ast_sorcery_retrieve_by_fields(
  428. ast_sip_get_sorcery(), "registration",
  429. AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  430. return registrations;
  431. }
  432. /*! \brief Callback function for matching an outbound registration based on line */
  433. static int line_identify_relationship(void *obj, void *arg, int flags)
  434. {
  435. struct sip_outbound_registration_state *state = obj;
  436. pjsip_param *line = arg;
  437. return !pj_strcmp2(&line->value, state->client_state->line) ? CMP_MATCH : 0;
  438. }
  439. static struct pjsip_param *get_uri_option_line(const void *uri)
  440. {
  441. pjsip_sip_uri *pjuri;
  442. static const pj_str_t LINE_STR = { "line", 4 };
  443. if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) {
  444. return NULL;
  445. }
  446. pjuri = pjsip_uri_get_uri(uri);
  447. return pjsip_param_find(&pjuri->other_param, &LINE_STR);
  448. }
  449. /*! \brief Endpoint identifier which uses the 'line' parameter to establish a relationship to an outgoing registration */
  450. static struct ast_sip_endpoint *line_identify(pjsip_rx_data *rdata)
  451. {
  452. pjsip_param *line;
  453. RAII_VAR(struct ao2_container *, states, NULL, ao2_cleanup);
  454. RAII_VAR(struct sip_outbound_registration_state *, state, NULL, ao2_cleanup);
  455. if (!(line = get_uri_option_line(rdata->msg_info.to->uri))
  456. && !(line = get_uri_option_line(rdata->msg_info.msg->line.req.uri))) {
  457. return NULL;
  458. }
  459. states = ao2_global_obj_ref(current_states);
  460. if (!states) {
  461. return NULL;
  462. }
  463. state = ao2_callback(states, 0, line_identify_relationship, line);
  464. if (!state || ast_strlen_zero(state->registration->endpoint)) {
  465. return NULL;
  466. }
  467. ast_debug(3, "Determined relationship to outbound registration '%s' based on line '%s', using configured endpoint '%s'\n",
  468. ast_sorcery_object_get_id(state->registration), state->client_state->line, state->registration->endpoint);
  469. return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", state->registration->endpoint);
  470. }
  471. static struct ast_sip_endpoint_identifier line_identifier = {
  472. .identify_endpoint = line_identify,
  473. };
  474. /*! \brief Helper function which cancels the timer on a client */
  475. static void cancel_registration(struct sip_outbound_registration_client_state *client_state)
  476. {
  477. if (pj_timer_heap_cancel_if_active(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
  478. &client_state->timer, client_state->timer.id)) {
  479. /* The timer was successfully cancelled, drop the refcount of client_state */
  480. ao2_ref(client_state, -1);
  481. }
  482. }
  483. static pj_str_t PATH_NAME = { "path", 4 };
  484. /*! \brief Helper function which sends a message and cleans up, if needed, on failure */
  485. static pj_status_t registration_client_send(struct sip_outbound_registration_client_state *client_state,
  486. pjsip_tx_data *tdata)
  487. {
  488. pj_status_t status;
  489. int *callback_invoked;
  490. pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
  491. callback_invoked = ast_threadstorage_get(&register_callback_invoked, sizeof(int));
  492. if (!callback_invoked) {
  493. pjsip_tx_data_dec_ref(tdata);
  494. return PJ_ENOMEM;
  495. }
  496. *callback_invoked = 0;
  497. /* Due to the message going out the callback may now be invoked, so bump the count */
  498. ao2_ref(client_state, +1);
  499. /*
  500. * Set the transport in case transports were reloaded.
  501. * When pjproject removes the extraneous error messages produced,
  502. * we can check status and only set the transport and resend if there was an error
  503. */
  504. ast_sip_set_tpselector_from_transport_name(client_state->transport_name, &selector);
  505. pjsip_regc_set_transport(client_state->client, &selector);
  506. ast_sip_record_request_serializer(tdata);
  507. status = pjsip_regc_send(client_state->client, tdata);
  508. /* If the attempt to send the message failed and the callback was not invoked we need to
  509. * drop the reference we just added
  510. */
  511. if ((status != PJ_SUCCESS) && !(*callback_invoked)) {
  512. ao2_ref(client_state, -1);
  513. }
  514. return status;
  515. }
  516. /*! \brief Callback function for registering */
  517. static int handle_client_registration(void *data)
  518. {
  519. RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
  520. pjsip_tx_data *tdata;
  521. if (client_state->status == SIP_REGISTRATION_STOPPED
  522. || pjsip_regc_register(client_state->client, PJ_FALSE, &tdata) != PJ_SUCCESS) {
  523. return 0;
  524. }
  525. if (DEBUG_ATLEAST(1)) {
  526. pjsip_regc_info info;
  527. pjsip_regc_get_info(client_state->client, &info);
  528. ast_log(LOG_DEBUG, "Outbound REGISTER attempt %u to '%.*s' with client '%.*s'\n",
  529. client_state->retries + 1,
  530. (int) info.server_uri.slen, info.server_uri.ptr,
  531. (int) info.client_uri.slen, info.client_uri.ptr);
  532. }
  533. if (client_state->support_path) {
  534. pjsip_supported_hdr *hdr;
  535. hdr = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_SUPPORTED, NULL);
  536. if (!hdr) {
  537. /* insert a new Supported header */
  538. hdr = pjsip_supported_hdr_create(tdata->pool);
  539. if (!hdr) {
  540. pjsip_tx_data_dec_ref(tdata);
  541. return -1;
  542. }
  543. pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *)hdr);
  544. }
  545. /* add on to the existing Supported header */
  546. pj_strassign(&hdr->values[hdr->count++], &PATH_NAME);
  547. }
  548. registration_client_send(client_state, tdata);
  549. return 0;
  550. }
  551. /*! \brief Timer callback function, used just for registrations */
  552. static void sip_outbound_registration_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
  553. {
  554. struct sip_outbound_registration_client_state *client_state = entry->user_data;
  555. entry->id = 0;
  556. /*
  557. * Transfer client_state reference to serializer task so the
  558. * nominal path will not dec the client_state ref in this
  559. * pjproject callback thread.
  560. */
  561. if (ast_sip_push_task(client_state->serializer, handle_client_registration, client_state)) {
  562. ast_log(LOG_WARNING, "Scheduled outbound registration could not be executed.\n");
  563. ao2_ref(client_state, -1);
  564. }
  565. }
  566. /*! \brief Helper function which sets up the timer to re-register in a specific amount of time */
  567. static void schedule_registration(struct sip_outbound_registration_client_state *client_state, unsigned int seconds)
  568. {
  569. pj_time_val delay = { .sec = seconds, };
  570. pjsip_regc_info info;
  571. cancel_registration(client_state);
  572. pjsip_regc_get_info(client_state->client, &info);
  573. ast_debug(1, "Scheduling outbound registration to server '%.*s' from client '%.*s' in %d seconds\n",
  574. (int) info.server_uri.slen, info.server_uri.ptr,
  575. (int) info.client_uri.slen, info.client_uri.ptr,
  576. seconds);
  577. ao2_ref(client_state, +1);
  578. if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &client_state->timer, &delay) != PJ_SUCCESS) {
  579. ast_log(LOG_WARNING, "Failed to schedule registration to server '%.*s' from client '%.*s'\n",
  580. (int) info.server_uri.slen, info.server_uri.ptr,
  581. (int) info.client_uri.slen, info.client_uri.ptr);
  582. ao2_ref(client_state, -1);
  583. }
  584. }
  585. static void update_client_state_status(struct sip_outbound_registration_client_state *client_state, enum sip_outbound_registration_status status)
  586. {
  587. const char *status_old;
  588. const char *status_new;
  589. if (client_state->status == status) {
  590. /* Status state did not change at all. */
  591. return;
  592. }
  593. status_old = sip_outbound_registration_status_str(client_state->status);
  594. status_new = sip_outbound_registration_status_str(status);
  595. client_state->status = status;
  596. if (!strcmp(status_old, status_new)) {
  597. /*
  598. * The internal status state may have changed but the status
  599. * state we tell the world did not change at all.
  600. */
  601. return;
  602. }
  603. ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "-1", 1.0,
  604. status_old);
  605. ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "+1", 1.0,
  606. status_new);
  607. }
  608. /*! \brief Callback function for unregistering (potentially) and destroying state */
  609. static int handle_client_state_destruction(void *data)
  610. {
  611. struct sip_outbound_registration_client_state *client_state = data;
  612. cancel_registration(client_state);
  613. if (client_state->client) {
  614. pjsip_regc_info info;
  615. pjsip_tx_data *tdata;
  616. pjsip_regc_get_info(client_state->client, &info);
  617. if (info.is_busy == PJ_TRUE) {
  618. /* If a client transaction is in progress we defer until it is complete */
  619. ast_debug(1,
  620. "Registration transaction is busy with server '%.*s' from client '%.*s'.\n",
  621. (int) info.server_uri.slen, info.server_uri.ptr,
  622. (int) info.client_uri.slen, info.client_uri.ptr);
  623. client_state->destroy = 1;
  624. ao2_ref(client_state, -1);
  625. return 0;
  626. }
  627. switch (client_state->status) {
  628. case SIP_REGISTRATION_UNREGISTERED:
  629. break;
  630. case SIP_REGISTRATION_REGISTERED:
  631. ast_debug(1,
  632. "Trying to unregister with server '%.*s' from client '%.*s' before destruction.\n",
  633. (int) info.server_uri.slen, info.server_uri.ptr,
  634. (int) info.client_uri.slen, info.client_uri.ptr);
  635. update_client_state_status(client_state, SIP_REGISTRATION_STOPPING);
  636. client_state->destroy = 1;
  637. if (pjsip_regc_unregister(client_state->client, &tdata) == PJ_SUCCESS
  638. && registration_client_send(client_state, tdata) == PJ_SUCCESS) {
  639. ao2_ref(client_state, -1);
  640. return 0;
  641. }
  642. break;
  643. case SIP_REGISTRATION_REJECTED_TEMPORARY:
  644. case SIP_REGISTRATION_REJECTED_PERMANENT:
  645. case SIP_REGISTRATION_STOPPING:
  646. case SIP_REGISTRATION_STOPPED:
  647. break;
  648. }
  649. pjsip_regc_destroy(client_state->client);
  650. client_state->client = NULL;
  651. }
  652. update_client_state_status(client_state, SIP_REGISTRATION_STOPPED);
  653. ast_sip_auth_vector_destroy(&client_state->outbound_auths);
  654. ao2_ref(client_state, -1);
  655. return 0;
  656. }
  657. /*! \brief Structure for registration response */
  658. struct registration_response {
  659. /*! \brief Response code for the registration attempt */
  660. int code;
  661. /*! \brief Expiration time for registration */
  662. int expiration;
  663. /*! \brief Retry-After value */
  664. int retry_after;
  665. /*! \brief Outbound registration client state */
  666. struct sip_outbound_registration_client_state *client_state;
  667. /*! \brief The response message */
  668. pjsip_rx_data *rdata;
  669. /*! \brief Request for which the response was received */
  670. pjsip_tx_data *old_request;
  671. };
  672. /*! \brief Registration response structure destructor */
  673. static void registration_response_destroy(void *obj)
  674. {
  675. struct registration_response *response = obj;
  676. if (response->rdata) {
  677. pjsip_rx_data_free_cloned(response->rdata);
  678. }
  679. if (response->old_request) {
  680. pjsip_tx_data_dec_ref(response->old_request);
  681. }
  682. ao2_cleanup(response->client_state);
  683. }
  684. /*! \brief Helper function which determines if a response code is temporal or not */
  685. static int sip_outbound_registration_is_temporal(unsigned int code,
  686. struct sip_outbound_registration_client_state *client_state)
  687. {
  688. /* Shamelessly taken from pjsua */
  689. if (code == PJSIP_SC_REQUEST_TIMEOUT ||
  690. code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
  691. code == PJSIP_SC_BAD_GATEWAY ||
  692. code == PJSIP_SC_SERVICE_UNAVAILABLE ||
  693. code == PJSIP_SC_SERVER_TIMEOUT ||
  694. ((code == PJSIP_SC_UNAUTHORIZED ||
  695. code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED) &&
  696. !client_state->auth_rejection_permanent) ||
  697. PJSIP_IS_STATUS_IN_CLASS(code, 600)) {
  698. return 1;
  699. } else {
  700. return 0;
  701. }
  702. }
  703. static void schedule_retry(struct registration_response *response, unsigned int interval,
  704. const char *server_uri, const char *client_uri)
  705. {
  706. update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_TEMPORARY);
  707. schedule_registration(response->client_state, interval);
  708. if (response->rdata) {
  709. ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on "
  710. "registration attempt to '%s', retrying in '%u'\n",
  711. response->code, server_uri, client_uri, interval);
  712. } else {
  713. ast_log(LOG_WARNING, "No response received from '%s' on "
  714. "registration attempt to '%s', retrying in '%u'\n",
  715. server_uri, client_uri, interval);
  716. }
  717. }
  718. static int reregister_immediately_cb(void *obj)
  719. {
  720. struct sip_outbound_registration_state *state = obj;
  721. if (state->client_state->status != SIP_REGISTRATION_REGISTERED) {
  722. ao2_ref(state, -1);
  723. return 0;
  724. }
  725. if (DEBUG_ATLEAST(1)) {
  726. pjsip_regc_info info;
  727. pjsip_regc_get_info(state->client_state->client, &info);
  728. ast_log(LOG_DEBUG,
  729. "Outbound registration transport to server '%.*s' from client '%.*s' shutdown\n",
  730. (int) info.server_uri.slen, info.server_uri.ptr,
  731. (int) info.client_uri.slen, info.client_uri.ptr);
  732. }
  733. cancel_registration(state->client_state);
  734. ao2_ref(state->client_state, +1);
  735. handle_client_registration(state->client_state);
  736. ao2_ref(state, -1);
  737. return 0;
  738. }
  739. /*!
  740. * \internal
  741. * \brief The reliable transport we registered using has shutdown.
  742. * \since 13.18.0
  743. *
  744. * \param obj What is needed to initiate a reregister attempt.
  745. *
  746. * \note Normally executed by the pjsip monitor thread.
  747. *
  748. * \return Nothing
  749. */
  750. static void registration_transport_shutdown_cb(void *obj)
  751. {
  752. const char *registration_name = obj;
  753. struct sip_outbound_registration_state *state;
  754. state = get_state(registration_name);
  755. if (!state) {
  756. /* Registration no longer exists or shutting down. */
  757. return;
  758. }
  759. if (ast_sip_push_task(state->client_state->serializer, reregister_immediately_cb, state)) {
  760. ao2_ref(state, -1);
  761. }
  762. }
  763. static int monitor_matcher(void *a, void *b)
  764. {
  765. char *ma = a;
  766. char *mb = b;
  767. return strcmp(ma, mb) == 0;
  768. }
  769. static void registration_transport_monitor_setup(pjsip_transport *transport, const char *registration_name)
  770. {
  771. char *monitor;
  772. if (!PJSIP_TRANSPORT_IS_RELIABLE(transport)) {
  773. return;
  774. }
  775. monitor = ao2_alloc_options(strlen(registration_name) + 1, NULL,
  776. AO2_ALLOC_OPT_LOCK_NOLOCK);
  777. if (!monitor) {
  778. return;
  779. }
  780. strcpy(monitor, registration_name);/* Safe */
  781. /*
  782. * We'll ignore if the transport has already been shutdown before we
  783. * register the monitor. We might get into a message spamming infinite
  784. * loop of registration, shutdown, reregistration...
  785. */
  786. ast_sip_transport_monitor_register(transport, registration_transport_shutdown_cb,
  787. monitor);
  788. ao2_ref(monitor, -1);
  789. }
  790. /*! \brief Callback function for handling a response to a registration attempt */
  791. static int handle_registration_response(void *data)
  792. {
  793. struct registration_response *response = data;
  794. pjsip_regc_info info;
  795. char server_uri[PJSIP_MAX_URL_SIZE];
  796. char client_uri[PJSIP_MAX_URL_SIZE];
  797. if (response->client_state->status == SIP_REGISTRATION_STOPPED) {
  798. ao2_ref(response, -1);
  799. return 0;
  800. }
  801. pjsip_regc_get_info(response->client_state->client, &info);
  802. ast_copy_pj_str(server_uri, &info.server_uri, sizeof(server_uri));
  803. ast_copy_pj_str(client_uri, &info.client_uri, sizeof(client_uri));
  804. ast_debug(1, "Processing REGISTER response %d from server '%s' for client '%s'\n",
  805. response->code, server_uri, client_uri);
  806. if ((response->code == 401 || response->code == 407)
  807. && (!response->client_state->auth_attempted
  808. || response->rdata->msg_info.cseq->cseq != response->client_state->auth_cseq)) {
  809. int res;
  810. pjsip_cseq_hdr *cseq_hdr;
  811. pjsip_tx_data *tdata;
  812. if (!ast_sip_create_request_with_auth_from_old(&response->client_state->outbound_auths,
  813. response->rdata, response->old_request, &tdata)) {
  814. response->client_state->auth_attempted = 1;
  815. ast_debug(1, "Sending authenticated REGISTER to server '%s' from client '%s'\n",
  816. server_uri, client_uri);
  817. pjsip_tx_data_add_ref(tdata);
  818. res = registration_client_send(response->client_state, tdata);
  819. /* Save the cseq that actually got sent. */
  820. cseq_hdr = (pjsip_cseq_hdr *) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ,
  821. NULL);
  822. response->client_state->auth_cseq = cseq_hdr->cseq;
  823. pjsip_tx_data_dec_ref(tdata);
  824. if (res == PJ_SUCCESS) {
  825. ao2_ref(response, -1);
  826. return 0;
  827. }
  828. } else {
  829. ast_log(LOG_WARNING, "Failed to create authenticated REGISTER request to server '%s' from client '%s'\n",
  830. server_uri, client_uri);
  831. }
  832. /* Otherwise, fall through so the failure is processed appropriately */
  833. }
  834. response->client_state->auth_attempted = 0;
  835. if (PJSIP_IS_STATUS_IN_CLASS(response->code, 200)) {
  836. /* Check if this is in regards to registering or unregistering */
  837. if (response->expiration) {
  838. int next_registration_round;
  839. /* If the registration went fine simply reschedule registration for the future */
  840. ast_debug(1, "Outbound registration to '%s' with client '%s' successful\n", server_uri, client_uri);
  841. update_client_state_status(response->client_state, SIP_REGISTRATION_REGISTERED);
  842. response->client_state->retries = 0;
  843. next_registration_round = response->expiration - REREGISTER_BUFFER_TIME;
  844. if (next_registration_round < 0) {
  845. /* Re-register immediately. */
  846. next_registration_round = 0;
  847. }
  848. schedule_registration(response->client_state, next_registration_round);
  849. /* See if we should monitor for transport shutdown */
  850. registration_transport_monitor_setup(response->rdata->tp_info.transport,
  851. response->client_state->registration_name);
  852. } else {
  853. ast_debug(1, "Outbound unregistration to '%s' with client '%s' successful\n", server_uri, client_uri);
  854. update_client_state_status(response->client_state, SIP_REGISTRATION_UNREGISTERED);
  855. ast_sip_transport_monitor_unregister(response->rdata->tp_info.transport,
  856. registration_transport_shutdown_cb, response->client_state->registration_name,
  857. monitor_matcher);
  858. }
  859. } else if (response->client_state->destroy) {
  860. /* We need to deal with the pending destruction instead. */
  861. } else if (response->retry_after) {
  862. /* If we have been instructed to retry after a period of time, schedule it as such */
  863. schedule_retry(response, response->retry_after, server_uri, client_uri);
  864. } else if (response->client_state->retry_interval
  865. && sip_outbound_registration_is_temporal(response->code, response->client_state)) {
  866. if (response->client_state->retries == response->client_state->max_retries) {
  867. /* If we received enough temporal responses to exceed our maximum give up permanently */
  868. update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_PERMANENT);
  869. ast_log(LOG_WARNING, "Maximum retries reached when attempting outbound registration to '%s' with client '%s', stopping registration attempt\n",
  870. server_uri, client_uri);
  871. } else {
  872. /* On the other hand if we can still try some more do so */
  873. response->client_state->retries++;
  874. schedule_retry(response, response->client_state->retry_interval, server_uri, client_uri);
  875. }
  876. } else {
  877. if (response->code == 403
  878. && response->client_state->forbidden_retry_interval
  879. && response->client_state->retries < response->client_state->max_retries) {
  880. /* A forbidden response retry interval is configured and there are retries remaining */
  881. update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_TEMPORARY);
  882. response->client_state->retries++;
  883. schedule_registration(response->client_state, response->client_state->forbidden_retry_interval);
  884. ast_log(LOG_WARNING, "403 Forbidden fatal response received from '%s' on registration attempt to '%s', retrying in '%u' seconds\n",
  885. server_uri, client_uri, response->client_state->forbidden_retry_interval);
  886. } else if (response->client_state->fatal_retry_interval
  887. && response->client_state->retries < response->client_state->max_retries) {
  888. /* Some kind of fatal failure response received, so retry according to configured interval */
  889. update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_TEMPORARY);
  890. response->client_state->retries++;
  891. schedule_registration(response->client_state, response->client_state->fatal_retry_interval);
  892. ast_log(LOG_WARNING, "'%d' fatal response received from '%s' on registration attempt to '%s', retrying in '%u' seconds\n",
  893. response->code, server_uri, client_uri, response->client_state->fatal_retry_interval);
  894. } else {
  895. /* Finally if there's no hope of registering give up */
  896. update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_PERMANENT);
  897. if (response->rdata) {
  898. ast_log(LOG_WARNING, "Fatal response '%d' received from '%s' on registration attempt to '%s', stopping outbound registration\n",
  899. response->code, server_uri, client_uri);
  900. } else {
  901. ast_log(LOG_WARNING, "Fatal registration attempt to '%s', stopping outbound registration\n", client_uri);
  902. }
  903. }
  904. }
  905. ast_system_publish_registry("PJSIP", client_uri, server_uri,
  906. sip_outbound_registration_status_str(response->client_state->status), NULL);
  907. if (response->client_state->destroy) {
  908. /* We have a pending deferred destruction to complete now. */
  909. ao2_ref(response->client_state, +1);
  910. handle_client_state_destruction(response->client_state);
  911. }
  912. ao2_ref(response, -1);
  913. return 0;
  914. }
  915. /*! \brief Callback function for outbound registration client */
  916. static void sip_outbound_registration_response_cb(struct pjsip_regc_cbparam *param)
  917. {
  918. struct sip_outbound_registration_client_state *client_state = param->token;
  919. struct registration_response *response;
  920. int *callback_invoked;
  921. callback_invoked = ast_threadstorage_get(&register_callback_invoked, sizeof(int));
  922. ast_assert(callback_invoked != NULL);
  923. ast_assert(client_state != NULL);
  924. *callback_invoked = 1;
  925. response = ao2_alloc(sizeof(*response), registration_response_destroy);
  926. if (!response) {
  927. ao2_ref(client_state, -1);
  928. return;
  929. }
  930. response->code = param->code;
  931. response->expiration = param->expiration;
  932. /*
  933. * Transfer client_state reference to response so the
  934. * nominal path will not dec the client_state ref in this
  935. * pjproject callback thread.
  936. */
  937. response->client_state = client_state;
  938. ast_debug(1, "Received REGISTER response %d(%.*s)\n",
  939. param->code, (int) param->reason.slen, param->reason.ptr);
  940. if (param->rdata) {
  941. struct pjsip_retry_after_hdr *retry_after;
  942. pjsip_transaction *tsx;
  943. retry_after = pjsip_msg_find_hdr(param->rdata->msg_info.msg, PJSIP_H_RETRY_AFTER,
  944. NULL);
  945. response->retry_after = retry_after ? retry_after->ivalue : 0;
  946. tsx = pjsip_rdata_get_tsx(param->rdata);
  947. response->old_request = tsx->last_tx;
  948. pjsip_tx_data_add_ref(response->old_request);
  949. pjsip_rx_data_clone(param->rdata, 0, &response->rdata);
  950. }
  951. /*
  952. * Transfer response reference to serializer task so the
  953. * nominal path will not dec the response ref in this
  954. * pjproject callback thread.
  955. */
  956. if (ast_sip_push_task(client_state->serializer, handle_registration_response, response)) {
  957. ast_log(LOG_WARNING, "Failed to pass incoming registration response to threadpool\n");
  958. ao2_cleanup(response);
  959. }
  960. }
  961. /*! \brief Destructor function for registration state */
  962. static void sip_outbound_registration_state_destroy(void *obj)
  963. {
  964. struct sip_outbound_registration_state *state = obj;
  965. ast_debug(3, "Destroying registration state for registration to server '%s' from client '%s'\n",
  966. state->registration ? state->registration->server_uri : "",
  967. state->registration ? state->registration->client_uri : "");
  968. ao2_cleanup(state->registration);
  969. if (!state->client_state) {
  970. /* Nothing to do */
  971. } else if (!state->client_state->serializer) {
  972. ao2_ref(state->client_state, -1);
  973. } else if (ast_sip_push_task(state->client_state->serializer,
  974. handle_client_state_destruction, state->client_state)) {
  975. ast_log(LOG_WARNING, "Failed to pass outbound registration client destruction to threadpool\n");
  976. ao2_ref(state->client_state, -1);
  977. }
  978. }
  979. /*! \brief Destructor function for client registration state */
  980. static void sip_outbound_registration_client_state_destroy(void *obj)
  981. {
  982. struct sip_outbound_registration_client_state *client_state = obj;
  983. ast_statsd_log_string("PJSIP.registrations.count", AST_STATSD_GAUGE, "-1", 1.0);
  984. ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "-1", 1.0,
  985. sip_outbound_registration_status_str(client_state->status));
  986. ast_taskprocessor_unreference(client_state->serializer);
  987. ast_free(client_state->transport_name);
  988. ast_free(client_state->registration_name);
  989. }
  990. /*! \brief Allocator function for registration state */
  991. static struct sip_outbound_registration_state *sip_outbound_registration_state_alloc(struct sip_outbound_registration *registration)
  992. {
  993. struct sip_outbound_registration_state *state;
  994. char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
  995. state = ao2_alloc(sizeof(*state), sip_outbound_registration_state_destroy);
  996. if (!state) {
  997. return NULL;
  998. }
  999. state->client_state = ao2_alloc(sizeof(*state->client_state),
  1000. sip_outbound_registration_client_state_destroy);
  1001. if (!state->client_state) {
  1002. ao2_cleanup(state);
  1003. return NULL;
  1004. }
  1005. state->client_state->status = SIP_REGISTRATION_UNREGISTERED;
  1006. pj_timer_entry_init(&state->client_state->timer, 0, state->client_state,
  1007. sip_outbound_registration_timer_cb);
  1008. state->client_state->transport_name = ast_strdup(registration->transport);
  1009. state->client_state->registration_name =
  1010. ast_strdup(ast_sorcery_object_get_id(registration));
  1011. ast_statsd_log_string("PJSIP.registrations.count", AST_STATSD_GAUGE, "+1", 1.0);
  1012. ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "+1", 1.0,
  1013. sip_outbound_registration_status_str(state->client_state->status));
  1014. if (!state->client_state->transport_name
  1015. || !state->client_state->registration_name) {
  1016. ao2_cleanup(state);
  1017. return NULL;
  1018. }
  1019. /* Create name with seq number appended. */
  1020. ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outreg/%s",
  1021. ast_sorcery_object_get_id(registration));
  1022. state->client_state->serializer = ast_sip_create_serializer_group_named(tps_name,
  1023. shutdown_group);
  1024. if (!state->client_state->serializer) {
  1025. ao2_cleanup(state);
  1026. return NULL;
  1027. }
  1028. state->registration = ao2_bump(registration);
  1029. return state;
  1030. }
  1031. /*! \brief Destructor function for registration information */
  1032. static void sip_outbound_registration_destroy(void *obj)
  1033. {
  1034. struct sip_outbound_registration *registration = obj;
  1035. ast_sip_auth_vector_destroy(&registration->outbound_auths);
  1036. ast_string_field_free_memory(registration);
  1037. }
  1038. /*! \brief Allocator function for registration information */
  1039. static void *sip_outbound_registration_alloc(const char *name)
  1040. {
  1041. struct sip_outbound_registration *registration;
  1042. registration = ast_sorcery_generic_alloc(sizeof(*registration),
  1043. sip_outbound_registration_destroy);
  1044. if (!registration || ast_string_field_init(registration, 256)) {
  1045. ao2_cleanup(registration);
  1046. return NULL;
  1047. }
  1048. return registration;
  1049. }
  1050. /*! \brief Helper function which populates a pj_str_t with a contact header */
  1051. static int sip_dialog_create_contact(pj_pool_t *pool, pj_str_t *contact, const char *user,
  1052. const pj_str_t *target, pjsip_tpselector *selector, const char *line)
  1053. {
  1054. pj_str_t tmp, local_addr;
  1055. pjsip_uri *uri;
  1056. pjsip_sip_uri *sip_uri;
  1057. pjsip_transport_type_e type;
  1058. int local_port;
  1059. pj_strdup_with_null(pool, &tmp, target);
  1060. if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
  1061. (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
  1062. return -1;
  1063. }
  1064. sip_uri = pjsip_uri_get_uri(uri);
  1065. type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
  1066. if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
  1067. if (type == PJSIP_TRANSPORT_UNSPECIFIED
  1068. || !(pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE)) {
  1069. type = PJSIP_TRANSPORT_TLS;
  1070. }
  1071. } else if (!sip_uri->transport_param.slen) {
  1072. type = PJSIP_TRANSPORT_UDP;
  1073. } else if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
  1074. return -1;
  1075. }
  1076. if (pj_strchr(&sip_uri->host, ':')) {
  1077. type |= PJSIP_TRANSPORT_IPV6;
  1078. }
  1079. if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()),
  1080. pool, type, selector, &local_addr, &local_port) != PJ_SUCCESS) {
  1081. return -1;
  1082. }
  1083. if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
  1084. type |= PJSIP_TRANSPORT_IPV6;
  1085. }
  1086. contact->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
  1087. contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
  1088. "<%s:%s@%s%.*s%s:%d%s%s%s%s>",
  1089. ((pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) && PJSIP_URI_SCHEME_IS_SIPS(uri)) ? "sips" : "sip",
  1090. user,
  1091. (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
  1092. (int)local_addr.slen,
  1093. local_addr.ptr,
  1094. (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
  1095. local_port,
  1096. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
  1097. (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "",
  1098. !ast_strlen_zero(line) ? ";line=" : "",
  1099. S_OR(line, ""));
  1100. return 0;
  1101. }
  1102. /*!
  1103. * \internal
  1104. * \brief Check if a registration can be reused
  1105. *
  1106. * This checks if the existing outbound registration's configuration differs from a newly-applied
  1107. * outbound registration to see if the applied one.
  1108. *
  1109. * \param existing The pre-existing outbound registration
  1110. * \param applied The newly-created registration
  1111. */
  1112. static int can_reuse_registration(struct sip_outbound_registration *existing,
  1113. struct sip_outbound_registration *applied)
  1114. {
  1115. int rc = 1;
  1116. struct ast_sorcery *sorcery = ast_sip_get_sorcery();
  1117. struct ast_variable *ve = ast_sorcery_objectset_create(sorcery, existing);
  1118. struct ast_variable *va = ast_sorcery_objectset_create(sorcery, applied);
  1119. struct ast_variable *vc = NULL;
  1120. if (ast_sorcery_changeset_create(ve, va, &vc) || vc != NULL) {
  1121. rc = 0;
  1122. ast_debug(4, "Registration '%s' changed. Can't re-use.\n", ast_sorcery_object_get_id(existing));
  1123. } else {
  1124. ast_debug(4, "Registration '%s' didn't change. Can re-use\n", ast_sorcery_object_get_id(existing));
  1125. }
  1126. ast_variables_destroy(ve);
  1127. ast_variables_destroy(va);
  1128. ast_variables_destroy(vc);
  1129. return rc;
  1130. }
  1131. /*! \brief Helper function that allocates a pjsip registration client and configures it */
  1132. static int sip_outbound_registration_regc_alloc(void *data)
  1133. {
  1134. struct sip_outbound_registration_state *state = data;
  1135. RAII_VAR(struct sip_outbound_registration *, registration,
  1136. ao2_bump(state->registration), ao2_cleanup);
  1137. pj_pool_t *pool;
  1138. pj_str_t tmp;
  1139. pjsip_uri *uri;
  1140. pj_str_t server_uri, client_uri, contact_uri;
  1141. pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
  1142. pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "URI Validation", 256, 256);
  1143. if (!pool) {
  1144. ast_log(LOG_ERROR, "Could not create pool for URI validation on outbound registration '%s'\n",
  1145. ast_sorcery_object_get_id(registration));
  1146. return -1;
  1147. }
  1148. pj_strdup2_with_null(pool, &tmp, registration->server_uri);
  1149. uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
  1150. if (!uri) {
  1151. ast_log(LOG_ERROR, "Invalid server URI '%s' specified on outbound registration '%s'\n",
  1152. registration->server_uri, ast_sorcery_object_get_id(registration));
  1153. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1154. return -1;
  1155. }
  1156. pj_strdup2_with_null(pool, &tmp, registration->client_uri);
  1157. uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
  1158. if (!uri) {
  1159. ast_log(LOG_ERROR, "Invalid client URI '%s' specified on outbound registration '%s'\n",
  1160. registration->client_uri, ast_sorcery_object_get_id(registration));
  1161. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1162. return -1;
  1163. }
  1164. if (!ast_strlen_zero(registration->outbound_proxy)) {
  1165. pj_strdup2_with_null(pool, &tmp, registration->outbound_proxy);
  1166. uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
  1167. if (!uri) {
  1168. ast_log(LOG_ERROR, "Invalid outbound proxy URI '%s' specified on outbound registration '%s'\n",
  1169. registration->outbound_proxy, ast_sorcery_object_get_id(registration));
  1170. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1171. return -1;
  1172. }
  1173. }
  1174. pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
  1175. ast_assert(state->client_state->client == NULL);
  1176. if (pjsip_regc_create(ast_sip_get_pjsip_endpoint(), state->client_state,
  1177. sip_outbound_registration_response_cb,
  1178. &state->client_state->client) != PJ_SUCCESS) {
  1179. return -1;
  1180. }
  1181. ast_sip_set_tpselector_from_transport_name(registration->transport, &selector);
  1182. pjsip_regc_set_transport(state->client_state->client, &selector);
  1183. if (!ast_strlen_zero(registration->outbound_proxy)) {
  1184. pjsip_route_hdr route_set, *route;
  1185. static const pj_str_t ROUTE_HNAME = { "Route", 5 };
  1186. pj_str_t tmp;
  1187. pj_list_init(&route_set);
  1188. pj_strdup2_with_null(pjsip_regc_get_pool(state->client_state->client), &tmp,
  1189. registration->outbound_proxy);
  1190. route = pjsip_parse_hdr(pjsip_regc_get_pool(state->client_state->client),
  1191. &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL);
  1192. if (!route) {
  1193. return -1;
  1194. }
  1195. pj_list_insert_nodes_before(&route_set, route);
  1196. pjsip_regc_set_route_set(state->client_state->client, &route_set);
  1197. }
  1198. if (state->registration->line) {
  1199. ast_generate_random_string(state->client_state->line, sizeof(state->client_state->line));
  1200. }
  1201. pj_cstr(&server_uri, registration->server_uri);
  1202. if (sip_dialog_create_contact(pjsip_regc_get_pool(state->client_state->client),
  1203. &contact_uri, S_OR(registration->contact_user, "s"), &server_uri, &selector,
  1204. state->client_state->line)) {
  1205. return -1;
  1206. }
  1207. pj_cstr(&client_uri, registration->client_uri);
  1208. if (pjsip_regc_init(state->client_state->client, &server_uri, &client_uri,
  1209. &client_uri, 1, &contact_uri, registration->expiration) != PJ_SUCCESS) {
  1210. return -1;
  1211. }
  1212. return 0;
  1213. }
  1214. /*! \brief Helper function which performs a single registration */
  1215. static int sip_outbound_registration_perform(void *data)
  1216. {
  1217. struct sip_outbound_registration_state *state = data;
  1218. struct sip_outbound_registration *registration = ao2_bump(state->registration);
  1219. size_t i;
  1220. /* Just in case the client state is being reused for this registration, free the auth information */
  1221. ast_sip_auth_vector_destroy(&state->client_state->outbound_auths);
  1222. AST_VECTOR_INIT(&state->client_state->outbound_auths, AST_VECTOR_SIZE(&registration->outbound_auths));
  1223. for (i = 0; i < AST_VECTOR_SIZE(&registration->outbound_auths); ++i) {
  1224. char *name = ast_strdup(AST_VECTOR_GET(&registration->outbound_auths, i));
  1225. if (name && AST_VECTOR_APPEND(&state->client_state->outbound_auths, name)) {
  1226. ast_free(name);
  1227. }
  1228. }
  1229. state->client_state->retry_interval = registration->retry_interval;
  1230. state->client_state->forbidden_retry_interval = registration->forbidden_retry_interval;
  1231. state->client_state->fatal_retry_interval = registration->fatal_retry_interval;
  1232. state->client_state->max_retries = registration->max_retries;
  1233. state->client_state->retries = 0;
  1234. state->client_state->support_path = registration->support_path;
  1235. state->client_state->auth_rejection_permanent = registration->auth_rejection_permanent;
  1236. pjsip_regc_update_expires(state->client_state->client, registration->expiration);
  1237. schedule_registration(state->client_state, (ast_random() % 10) + 1);
  1238. ao2_ref(registration, -1);
  1239. ao2_ref(state, -1);
  1240. return 0;
  1241. }
  1242. /*! \brief Apply function which finds or allocates a state structure */
  1243. static int sip_outbound_registration_apply(const struct ast_sorcery *sorcery, void *obj)
  1244. {
  1245. RAII_VAR(struct ao2_container *, states, ao2_global_obj_ref(current_states), ao2_cleanup);
  1246. RAII_VAR(struct sip_outbound_registration_state *, state, NULL, ao2_cleanup);
  1247. RAII_VAR(struct sip_outbound_registration_state *, new_state, NULL, ao2_cleanup);
  1248. struct sip_outbound_registration *applied = obj;
  1249. if (!states) {
  1250. /* Global container has gone. Likely shutting down. */
  1251. return -1;
  1252. }
  1253. state = ao2_find(states, ast_sorcery_object_get_id(applied), OBJ_SEARCH_KEY);
  1254. ast_debug(4, "Applying configuration to outbound registration '%s'\n", ast_sorcery_object_get_id(applied));
  1255. if (ast_strlen_zero(applied->server_uri)) {
  1256. ast_log(LOG_ERROR, "No server URI specified on outbound registration '%s'\n",
  1257. ast_sorcery_object_get_id(applied));
  1258. return -1;
  1259. } else if (ast_sip_validate_uri_length(applied->server_uri)) {
  1260. ast_log(LOG_ERROR, "Server URI or hostname length exceeds pjproject limit or is not a sip(s) uri: '%s'\n",
  1261. ast_sorcery_object_get_id(applied));
  1262. return -1;
  1263. } else if (ast_strlen_zero(applied->client_uri)) {
  1264. ast_log(LOG_ERROR, "No client URI specified on outbound registration '%s'\n",
  1265. ast_sorcery_object_get_id(applied));
  1266. return -1;
  1267. } else if (ast_sip_validate_uri_length(applied->client_uri)) {
  1268. ast_log(LOG_ERROR, "Client URI or hostname length exceeds pjproject limit or is not a sip(s) uri: '%s'\n",
  1269. ast_sorcery_object_get_id(applied));
  1270. return -1;
  1271. } else if (applied->line && ast_strlen_zero(applied->endpoint)) {
  1272. ast_log(LOG_ERROR, "Line support has been enabled on outbound registration '%s' without providing an endpoint\n",
  1273. ast_sorcery_object_get_id(applied));
  1274. return -1;
  1275. } else if (!ast_strlen_zero(applied->endpoint) && !applied->line) {
  1276. ast_log(LOG_ERROR, "An endpoint has been specified on outbound registration '%s' without enabling line support\n",
  1277. ast_sorcery_object_get_id(applied));
  1278. return -1;
  1279. }
  1280. if (state && can_reuse_registration(state->registration, applied)) {
  1281. ast_debug(4,
  1282. "No change between old configuration and new configuration on outbound registration '%s'. Using previous state\n",
  1283. ast_sorcery_object_get_id(applied));
  1284. /*
  1285. * This is OK to replace without relinking the state in the
  1286. * current_states container since state->registration and
  1287. * applied have the same key.
  1288. */
  1289. ao2_lock(states);
  1290. ao2_replace(state->registration, applied);
  1291. ao2_unlock(states);
  1292. return 0;
  1293. }
  1294. if (!(new_state = sip_outbound_registration_state_alloc(applied))) {
  1295. return -1;
  1296. }
  1297. if (ast_sip_push_task_wait_serializer(new_state->client_state->serializer,
  1298. sip_outbound_registration_regc_alloc, new_state)) {
  1299. return -1;
  1300. }
  1301. if (ast_sip_push_task(new_state->client_state->serializer,
  1302. sip_outbound_registration_perform, ao2_bump(new_state))) {
  1303. ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n",
  1304. ast_sorcery_object_get_id(new_state->registration));
  1305. ao2_ref(new_state, -1);
  1306. return -1;
  1307. }
  1308. ao2_lock(states);
  1309. if (state) {
  1310. ao2_unlink(states, state);
  1311. }
  1312. ao2_link(states, new_state);
  1313. ao2_unlock(states);
  1314. return 0;
  1315. }
  1316. static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
  1317. {
  1318. struct sip_outbound_registration *registration = obj;
  1319. return ast_sip_auth_vector_init(&registration->outbound_auths, var->value);
  1320. }
  1321. static int outbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
  1322. {
  1323. const struct sip_outbound_registration *registration = obj;
  1324. return ast_sip_auths_to_str(&registration->outbound_auths, buf);
  1325. }
  1326. static int outbound_auths_to_var_list(const void *obj, struct ast_variable **fields)
  1327. {
  1328. const struct sip_outbound_registration *registration = obj;
  1329. int i;
  1330. struct ast_variable *head = NULL;
  1331. for (i = 0; i < AST_VECTOR_SIZE(&registration->outbound_auths) ; i++) {
  1332. ast_variable_list_append(&head, ast_variable_new("outbound_auth",
  1333. AST_VECTOR_GET(&registration->outbound_auths, i), ""));
  1334. }
  1335. if (head) {
  1336. *fields = head;
  1337. }
  1338. return 0;
  1339. }
  1340. static int unregister_task(void *obj)
  1341. {
  1342. struct sip_outbound_registration_state *state = obj;
  1343. struct pjsip_regc *client = state->client_state->client;
  1344. pjsip_tx_data *tdata;
  1345. pjsip_regc_info info;
  1346. pjsip_regc_get_info(client, &info);
  1347. ast_debug(1, "Unregistering contacts with server '%s' from client '%s'\n",
  1348. state->registration->server_uri, state->registration->client_uri);
  1349. cancel_registration(state->client_state);
  1350. if (pjsip_regc_unregister(client, &tdata) == PJ_SUCCESS) {
  1351. registration_client_send(state->client_state, tdata);
  1352. }
  1353. ao2_ref(state, -1);
  1354. return 0;
  1355. }
  1356. static int queue_unregister(struct sip_outbound_registration_state *state)
  1357. {
  1358. ao2_ref(state, +1);
  1359. if (ast_sip_push_task(state->client_state->serializer, unregister_task, state)) {
  1360. ao2_ref(state, -1);
  1361. return -1;
  1362. }
  1363. return 0;
  1364. }
  1365. static int queue_register(struct sip_outbound_registration_state *state)
  1366. {
  1367. ao2_ref(state, +1);
  1368. if (ast_sip_push_task(state->client_state->serializer, sip_outbound_registration_perform, state)) {
  1369. ao2_ref(state, -1);
  1370. return -1;
  1371. }
  1372. return 0;
  1373. }
  1374. static void unregister_all(void)
  1375. {
  1376. struct ao2_container *states;
  1377. states = ao2_global_obj_ref(current_states);
  1378. if (!states) {
  1379. return;
  1380. }
  1381. /* Clean out all the states and let sorcery handle recreating the registrations */
  1382. ao2_callback(states, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
  1383. ao2_ref(states, -1);
  1384. }
  1385. static void reregister_all(void)
  1386. {
  1387. unregister_all();
  1388. ast_sorcery_load_object(ast_sip_get_sorcery(), "registration");
  1389. }
  1390. static char *cli_complete_registration(const char *line, const char *word,
  1391. int pos, int state)
  1392. {
  1393. char *result = NULL;
  1394. int wordlen;
  1395. int which = 0;
  1396. struct sip_outbound_registration *registration;
  1397. struct ao2_container *registrations;
  1398. struct ao2_iterator i;
  1399. if (pos != 3) {
  1400. return NULL;
  1401. }
  1402. wordlen = strlen(word);
  1403. if (wordlen == 0 && ++which > state) {
  1404. return ast_strdup("*all");
  1405. }
  1406. registrations = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
  1407. AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  1408. if (!registrations) {
  1409. return NULL;
  1410. }
  1411. i = ao2_iterator_init(registrations, 0);
  1412. while ((registration = ao2_iterator_next(&i))) {
  1413. const char *name = ast_sorcery_object_get_id(registration);
  1414. if (!strncasecmp(word, name, wordlen) && ++which > state) {
  1415. result = ast_strdup(name);
  1416. }
  1417. ao2_ref(registration, -1);
  1418. if (result) {
  1419. break;
  1420. }
  1421. }
  1422. ao2_iterator_destroy(&i);
  1423. ao2_ref(registrations, -1);
  1424. return result;
  1425. }
  1426. static char *cli_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1427. {
  1428. struct sip_outbound_registration_state *state;
  1429. const char *registration_name;
  1430. switch (cmd) {
  1431. case CLI_INIT:
  1432. e->command = "pjsip send unregister";
  1433. e->usage =
  1434. "Usage: pjsip send unregister <registration> | *all\n"
  1435. " Unregisters the specified (or all) outbound registration(s) "
  1436. "and stops future registration attempts.\n";
  1437. return NULL;
  1438. case CLI_GENERATE:
  1439. return cli_complete_registration(a->line, a->word, a->pos, a->n);
  1440. }
  1441. if (a->argc != 4) {
  1442. return CLI_SHOWUSAGE;
  1443. }
  1444. registration_name = a->argv[3];
  1445. if (strcmp(registration_name, "*all") == 0) {
  1446. unregister_all();
  1447. ast_cli(a->fd, "Unregister all queued\n");
  1448. return CLI_SUCCESS;
  1449. }
  1450. state = get_state(registration_name);
  1451. if (!state) {
  1452. ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
  1453. return CLI_FAILURE;
  1454. }
  1455. if (queue_unregister(state)) {
  1456. ast_cli(a->fd, "Failed to queue unregistration\n");
  1457. }
  1458. ao2_ref(state, -1);
  1459. return CLI_SUCCESS;
  1460. }
  1461. static char *cli_register(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1462. {
  1463. struct sip_outbound_registration_state *state;
  1464. const char *registration_name;
  1465. switch (cmd) {
  1466. case CLI_INIT:
  1467. e->command = "pjsip send register";
  1468. e->usage =
  1469. "Usage: pjsip send register <registration> | *all \n"
  1470. " Unregisters the specified (or all) outbound "
  1471. "registration(s) then starts registration(s) and schedules re-registrations.\n";
  1472. return NULL;
  1473. case CLI_GENERATE:
  1474. return cli_complete_registration(a->line, a->word, a->pos, a->n);
  1475. }
  1476. if (a->argc != 4) {
  1477. return CLI_SHOWUSAGE;
  1478. }
  1479. registration_name = a->argv[3];
  1480. if (strcmp(registration_name, "*all") == 0) {
  1481. reregister_all();
  1482. ast_cli(a->fd, "Re-register all queued\n");
  1483. return CLI_SUCCESS;
  1484. }
  1485. state = get_state(registration_name);
  1486. if (!state) {
  1487. ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
  1488. return CLI_FAILURE;
  1489. }
  1490. /* We need to serialize the unregister and register so they need
  1491. * to be queued as separate tasks.
  1492. */
  1493. if (queue_unregister(state)) {
  1494. ast_cli(a->fd, "Failed to queue unregistration\n");
  1495. } else if (queue_register(state)) {
  1496. ast_cli(a->fd, "Failed to queue registration\n");
  1497. }
  1498. ao2_ref(state, -1);
  1499. return CLI_SUCCESS;
  1500. }
  1501. static int ami_unregister(struct mansession *s, const struct message *m)
  1502. {
  1503. const char *registration_name = astman_get_header(m, "Registration");
  1504. struct sip_outbound_registration_state *state;
  1505. if (ast_strlen_zero(registration_name)) {
  1506. astman_send_error(s, m, "Registration parameter missing.");
  1507. return 0;
  1508. }
  1509. if (strcmp(registration_name, "*all") == 0) {
  1510. unregister_all();
  1511. astman_send_ack(s, m, "Unregistrations queued.");
  1512. return 0;
  1513. }
  1514. state = get_state(registration_name);
  1515. if (!state) {
  1516. astman_send_error(s, m, "Unable to retrieve registration entry\n");
  1517. return 0;
  1518. }
  1519. if (queue_unregister(state)) {
  1520. astman_send_ack(s, m, "Failed to queue unregistration");
  1521. } else {
  1522. astman_send_ack(s, m, "Unregistration sent");
  1523. }
  1524. ao2_ref(state, -1);
  1525. return 0;
  1526. }
  1527. static int ami_register(struct mansession *s, const struct message *m)
  1528. {
  1529. const char *registration_name = astman_get_header(m, "Registration");
  1530. struct sip_outbound_registration_state *state;
  1531. if (ast_strlen_zero(registration_name)) {
  1532. astman_send_error(s, m, "Registration parameter missing.");
  1533. return 0;
  1534. }
  1535. if (strcmp(registration_name, "*all") == 0) {
  1536. reregister_all();
  1537. astman_send_ack(s, m, "Reregistrations queued.");
  1538. return 0;
  1539. }
  1540. state = get_state(registration_name);
  1541. if (!state) {
  1542. astman_send_error(s, m, "Unable to retrieve registration entry\n");
  1543. return 0;
  1544. }
  1545. /* We need to serialize the unregister and register so they need
  1546. * to be queued as separate tasks.
  1547. */
  1548. if (queue_unregister(state)) {
  1549. astman_send_ack(s, m, "Failed to queue unregistration");
  1550. } else if (queue_register(state)) {
  1551. astman_send_ack(s, m, "Failed to queue unregistration");
  1552. } else {
  1553. astman_send_ack(s, m, "Reregistration sent");
  1554. }
  1555. ao2_ref(state, -1);
  1556. return 0;
  1557. }
  1558. struct sip_ami_outbound {
  1559. struct ast_sip_ami *ami;
  1560. int registered;
  1561. int not_registered;
  1562. struct sip_outbound_registration *registration;
  1563. };
  1564. static int ami_outbound_registration_task(void *obj)
  1565. {
  1566. struct sip_ami_outbound *ami = obj;
  1567. struct ast_str *buf;
  1568. struct sip_outbound_registration_state *state;
  1569. buf = ast_sip_create_ami_event("OutboundRegistrationDetail", ami->ami);
  1570. if (!buf) {
  1571. return -1;
  1572. }
  1573. ast_sip_sorcery_object_to_ami(ami->registration, &buf);
  1574. if ((state = get_state(ast_sorcery_object_get_id(ami->registration)))) {
  1575. pjsip_regc_info info;
  1576. if (state->client_state->status == SIP_REGISTRATION_REGISTERED) {
  1577. ++ami->registered;
  1578. } else {
  1579. ++ami->not_registered;
  1580. }
  1581. ast_str_append(&buf, 0, "Status: %s\r\n",
  1582. sip_outbound_registration_status_str(state->client_state->status));
  1583. pjsip_regc_get_info(state->client_state->client, &info);
  1584. ast_str_append(&buf, 0, "NextReg: %d\r\n", info.next_reg);
  1585. ao2_ref(state, -1);
  1586. }
  1587. astman_append(ami->ami->s, "%s\r\n", ast_str_buffer(buf));
  1588. ast_free(buf);
  1589. return ast_sip_format_auths_ami(&ami->registration->outbound_auths, ami->ami);
  1590. }
  1591. static int ami_outbound_registration_detail(void *obj, void *arg, int flags)
  1592. {
  1593. struct sip_ami_outbound *ami = arg;
  1594. ami->registration = obj;
  1595. return ast_sip_push_task_wait_servant(NULL, ami_outbound_registration_task, ami);
  1596. }
  1597. static int ami_show_outbound_registrations(struct mansession *s,
  1598. const struct message *m)
  1599. {
  1600. struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
  1601. struct sip_ami_outbound ami_outbound = { .ami = &ami };
  1602. struct ao2_container *regs;
  1603. regs = get_registrations();
  1604. if (!regs) {
  1605. astman_send_error(s, m, "Unable to retrieve "
  1606. "outbound registrations\n");
  1607. return -1;
  1608. }
  1609. astman_send_listack(s, m, "Following are Events for each Outbound registration",
  1610. "start");
  1611. ao2_callback(regs, OBJ_NODATA, ami_outbound_registration_detail, &ami_outbound);
  1612. astman_send_list_complete_start(s, m, "OutboundRegistrationDetailComplete",
  1613. ami_outbound.registered + ami_outbound.not_registered);
  1614. astman_append(s,
  1615. "Registered: %d\r\n"
  1616. "NotRegistered: %d\r\n",
  1617. ami_outbound.registered,
  1618. ami_outbound.not_registered);
  1619. astman_send_list_complete_end(s);
  1620. ao2_ref(regs, -1);
  1621. return 0;
  1622. }
  1623. static struct ao2_container *cli_get_container(const char *regex)
  1624. {
  1625. RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
  1626. struct ao2_container *s_container;
  1627. container = ast_sorcery_retrieve_by_regex(ast_sip_get_sorcery(), "registration", regex);
  1628. if (!container) {
  1629. return NULL;
  1630. }
  1631. s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
  1632. ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
  1633. if (!s_container) {
  1634. return NULL;
  1635. }
  1636. if (ao2_container_dup(s_container, container, 0)) {
  1637. ao2_ref(s_container, -1);
  1638. return NULL;
  1639. }
  1640. return s_container;
  1641. }
  1642. static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
  1643. {
  1644. ao2_callback(container, OBJ_NODATA, callback, args);
  1645. return 0;
  1646. }
  1647. static void *cli_retrieve_by_id(const char *id)
  1648. {
  1649. struct ao2_container *states;
  1650. void *obj = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "registration", id);
  1651. if (!obj) {
  1652. /* if the object no longer exists then remove its state */
  1653. states = ao2_global_obj_ref(current_states);
  1654. if (states) {
  1655. ao2_find(states, id, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
  1656. ao2_ref(states, -1);
  1657. }
  1658. }
  1659. return obj;
  1660. }
  1661. static int cli_print_header(void *obj, void *arg, int flags)
  1662. {
  1663. struct ast_sip_cli_context *context = arg;
  1664. ast_assert(context->output_buffer != NULL);
  1665. ast_str_append(&context->output_buffer, 0,
  1666. " <Registration/ServerURI..............................> <Auth..........> <Status.......>\n");
  1667. return 0;
  1668. }
  1669. static int cli_print_body(void *obj, void *arg, int flags)
  1670. {
  1671. struct sip_outbound_registration *registration = obj;
  1672. struct ast_sip_cli_context *context = arg;
  1673. const char *id = ast_sorcery_object_get_id(registration);
  1674. struct sip_outbound_registration_state *state = get_state(id);
  1675. #define REGISTRATION_URI_FIELD_LEN 53
  1676. ast_assert(context->output_buffer != NULL);
  1677. ast_str_append(&context->output_buffer, 0, " %-s/%-*.*s %-16s %-16s\n",
  1678. id,
  1679. (int) (REGISTRATION_URI_FIELD_LEN - strlen(id)),
  1680. (int) (REGISTRATION_URI_FIELD_LEN - strlen(id)),
  1681. registration->server_uri,
  1682. AST_VECTOR_SIZE(&registration->outbound_auths)
  1683. ? AST_VECTOR_GET(&registration->outbound_auths, 0)
  1684. : "n/a",
  1685. (state ? sip_outbound_registration_status_str(state->client_state->status) : "Unregistered"));
  1686. ao2_cleanup(state);
  1687. if (context->show_details
  1688. || (context->show_details_only_level_0 && context->indent_level == 0)) {
  1689. ast_str_append(&context->output_buffer, 0, "\n");
  1690. ast_sip_cli_print_sorcery_objectset(registration, context, 0);
  1691. }
  1692. return 0;
  1693. }
  1694. /*
  1695. * A function pointer to callback needs to be within the
  1696. * module in order to avoid problems with an undefined
  1697. * symbol when the module is loaded.
  1698. */
  1699. static char *my_cli_traverse_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1700. {
  1701. return ast_sip_cli_traverse_objects(e, cmd, a);
  1702. }
  1703. static struct ast_cli_entry cli_outbound_registration[] = {
  1704. AST_CLI_DEFINE(cli_unregister, "Unregisters outbound registration target"),
  1705. AST_CLI_DEFINE(cli_register, "Registers an outbound registration target"),
  1706. AST_CLI_DEFINE(my_cli_traverse_objects, "List PJSIP Registrations",
  1707. .command = "pjsip list registrations",
  1708. .usage = "Usage: pjsip list registrations [ like <pattern> ]\n"
  1709. " List the configured PJSIP Registrations\n"
  1710. " Optional regular expression pattern is used to filter the list.\n"),
  1711. AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Registrations",
  1712. .command = "pjsip show registrations",
  1713. .usage = "Usage: pjsip show registrations [ like <pattern> ]\n"
  1714. " Show the configured PJSIP Registrations\n"
  1715. " Optional regular expression pattern is used to filter the list.\n"),
  1716. AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Registration",
  1717. .command = "pjsip show registration",
  1718. .usage = "Usage: pjsip show registration <id>\n"
  1719. " Show the configured PJSIP Registration\n"),
  1720. };
  1721. static struct ast_sip_cli_formatter_entry *cli_formatter;
  1722. static void auth_observer(const char *type)
  1723. {
  1724. struct sip_outbound_registration *registration;
  1725. struct sip_outbound_registration_state *state;
  1726. struct ao2_container *regs;
  1727. const char *registration_id;
  1728. struct ao2_iterator i;
  1729. ast_debug(4, "Auths updated. Checking for any outbound registrations that are in permanent rejected state so they can be retried\n");
  1730. regs = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
  1731. AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
  1732. if (!regs || ao2_container_count(regs) == 0) {
  1733. ao2_cleanup(regs);
  1734. return;
  1735. }
  1736. i = ao2_iterator_init(regs, 0);
  1737. for (; (registration = ao2_iterator_next(&i)); ao2_ref(registration, -1)) {
  1738. registration_id = ast_sorcery_object_get_id(registration);
  1739. state = get_state(registration_id);
  1740. if (state && state->client_state->status == SIP_REGISTRATION_REJECTED_PERMANENT) {
  1741. ast_debug(4, "Trying outbound registration '%s' again\n", registration_id);
  1742. if (ast_sip_push_task(state->client_state->serializer,
  1743. sip_outbound_registration_perform, ao2_bump(state))) {
  1744. ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n", registration_id);
  1745. ao2_ref(state, -1);
  1746. }
  1747. }
  1748. ao2_cleanup(state);
  1749. }
  1750. ao2_iterator_destroy(&i);
  1751. ao2_cleanup(regs);
  1752. }
  1753. static const struct ast_sorcery_observer observer_callbacks_auth = {
  1754. .loaded = auth_observer,
  1755. };
  1756. static int check_state(void *obj, void *arg, int flags)
  1757. {
  1758. struct sip_outbound_registration_state *state = obj;
  1759. struct sip_outbound_registration *registration;
  1760. registration = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "registration",
  1761. ast_sorcery_object_get_id(state->registration));
  1762. if (!registration) {
  1763. /* This is a dead registration */
  1764. return CMP_MATCH;
  1765. }
  1766. ao2_ref(registration, -1);
  1767. return 0;
  1768. }
  1769. /*!
  1770. * \internal
  1771. * \brief Observer to purge dead registration states.
  1772. *
  1773. * \param name Module name owning the sorcery instance.
  1774. * \param sorcery Instance being observed.
  1775. * \param object_type Name of object being observed.
  1776. * \param reloaded Non-zero if the object is being reloaded.
  1777. *
  1778. * \return Nothing
  1779. */
  1780. static void registration_loaded_observer(const char *name, const struct ast_sorcery *sorcery, const char *object_type, int reloaded)
  1781. {
  1782. struct ao2_container *states;
  1783. if (strcmp(object_type, "registration")) {
  1784. /* Not interested */
  1785. return;
  1786. }
  1787. states = ao2_global_obj_ref(current_states);
  1788. if (!states) {
  1789. /* Global container has gone. Likely shutting down. */
  1790. return;
  1791. }
  1792. /*
  1793. * Refresh the current configured registrations. We don't need to hold
  1794. * onto the objects, as the apply handler will cause their states to
  1795. * be created appropriately.
  1796. */
  1797. ao2_cleanup(get_registrations());
  1798. /* Now to purge dead registrations. */
  1799. ao2_callback(states, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, check_state, NULL);
  1800. ao2_ref(states, -1);
  1801. }
  1802. static const struct ast_sorcery_instance_observer observer_callbacks_registrations = {
  1803. .object_type_loaded = registration_loaded_observer,
  1804. };
  1805. static void registration_deleted_observer(const void *obj)
  1806. {
  1807. const struct sip_outbound_registration *registration = obj;
  1808. struct ao2_container *states;
  1809. states = ao2_global_obj_ref(current_states);
  1810. if (!states) {
  1811. /* Global container has gone. Likely shutting down. */
  1812. return;
  1813. }
  1814. ao2_find(states, ast_sorcery_object_get_id(registration), OBJ_UNLINK | OBJ_NODATA | OBJ_SEARCH_KEY);
  1815. ao2_ref(states, -1);
  1816. }
  1817. static const struct ast_sorcery_observer registration_observer = {
  1818. .deleted = registration_deleted_observer,
  1819. };
  1820. static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
  1821. {
  1822. /* This callback is only concerned with network change messages from the system topic. */
  1823. if (stasis_message_type(message) != ast_network_change_type()) {
  1824. return;
  1825. }
  1826. ast_debug(3, "Received network change event\n");
  1827. reregister_all();
  1828. }
  1829. static int unload_module(void)
  1830. {
  1831. int remaining;
  1832. network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
  1833. ast_manager_unregister("PJSIPShowRegistrationsOutbound");
  1834. ast_manager_unregister("PJSIPUnregister");
  1835. ast_manager_unregister("PJSIPRegister");
  1836. ast_cli_unregister_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
  1837. ast_sip_unregister_cli_formatter(cli_formatter);
  1838. cli_formatter = NULL;
  1839. ast_sip_unregister_endpoint_identifier(&line_identifier);
  1840. ast_sorcery_observer_remove(ast_sip_get_sorcery(), "auth", &observer_callbacks_auth);
  1841. ast_sorcery_instance_observer_remove(ast_sip_get_sorcery(), &observer_callbacks_registrations);
  1842. ast_sorcery_object_unregister(ast_sip_get_sorcery(), "registration");
  1843. ao2_global_obj_release(current_states);
  1844. ast_sip_transport_monitor_unregister_all(registration_transport_shutdown_cb, NULL, NULL);
  1845. /* Wait for registration serializers to get destroyed. */
  1846. ast_debug(2, "Waiting for registration transactions to complete for unload.\n");
  1847. remaining = ast_serializer_shutdown_group_join(shutdown_group, MAX_UNLOAD_TIMEOUT_TIME);
  1848. if (remaining) {
  1849. /*
  1850. * NOTE: We probably have a sip_outbound_registration_client_state
  1851. * ref leak if the remaining count cannot reach zero after a few
  1852. * minutes of trying to unload.
  1853. */
  1854. ast_log(LOG_WARNING, "Unload incomplete. Could not stop %d outbound registrations. Try again later.\n",
  1855. remaining);
  1856. return -1;
  1857. }
  1858. ast_debug(2, "Successful shutdown.\n");
  1859. ao2_cleanup(shutdown_group);
  1860. shutdown_group = NULL;
  1861. return 0;
  1862. }
  1863. static int load_module(void)
  1864. {
  1865. struct ao2_container *new_states;
  1866. CHECK_PJSIP_MODULE_LOADED();
  1867. shutdown_group = ast_serializer_shutdown_group_alloc();
  1868. if (!shutdown_group) {
  1869. return AST_MODULE_LOAD_DECLINE;
  1870. }
  1871. /* Create outbound registration states container. */
  1872. new_states = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
  1873. DEFAULT_STATE_BUCKETS, registration_state_hash, NULL, registration_state_cmp);
  1874. if (!new_states) {
  1875. ast_log(LOG_ERROR, "Unable to allocate registration states container\n");
  1876. unload_module();
  1877. return AST_MODULE_LOAD_DECLINE;
  1878. }
  1879. ao2_global_obj_replace_unref(current_states, new_states);
  1880. ao2_ref(new_states, -1);
  1881. /*
  1882. * Register sorcery object descriptions.
  1883. */
  1884. ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_outbound_registration");
  1885. ast_sorcery_apply_default(ast_sip_get_sorcery(), "registration", "config", "pjsip.conf,criteria=type=registration");
  1886. if (ast_sorcery_object_register(ast_sip_get_sorcery(), "registration", sip_outbound_registration_alloc, NULL, sip_outbound_registration_apply)) {
  1887. unload_module();
  1888. return AST_MODULE_LOAD_DECLINE;
  1889. }
  1890. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "type", "", OPT_NOOP_T, 0, 0);
  1891. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "server_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, server_uri));
  1892. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "client_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, client_uri));
  1893. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "contact_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, contact_user));
  1894. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, transport));
  1895. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, outbound_proxy));
  1896. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "expiration", "3600", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, expiration));
  1897. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "retry_interval", "60", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, retry_interval));
  1898. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "forbidden_retry_interval", "0", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, forbidden_retry_interval));
  1899. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "fatal_retry_interval", "0", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, fatal_retry_interval));
  1900. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "max_retries", "10", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, max_retries));
  1901. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "auth_rejection_permanent", "yes", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, auth_rejection_permanent));
  1902. ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "registration", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, outbound_auths_to_var_list, 0, 0);
  1903. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "support_path", "no", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, support_path));
  1904. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "line", "no", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, line));
  1905. ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, endpoint));
  1906. /*
  1907. * Register sorcery observers.
  1908. */
  1909. if (ast_sorcery_instance_observer_add(ast_sip_get_sorcery(),
  1910. &observer_callbacks_registrations)
  1911. || ast_sorcery_observer_add(ast_sip_get_sorcery(), "auth",
  1912. &observer_callbacks_auth)
  1913. || ast_sorcery_observer_add(ast_sip_get_sorcery(), "registration",
  1914. &registration_observer)) {
  1915. ast_log(LOG_ERROR, "Unable to register observers.\n");
  1916. unload_module();
  1917. return AST_MODULE_LOAD_DECLINE;
  1918. }
  1919. /* Register how this module identifies endpoints. */
  1920. ast_sip_register_endpoint_identifier(&line_identifier);
  1921. /* Register CLI commands. */
  1922. cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
  1923. if (!cli_formatter) {
  1924. ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
  1925. unload_module();
  1926. return AST_MODULE_LOAD_DECLINE;
  1927. }
  1928. cli_formatter->name = "registration";
  1929. cli_formatter->print_header = cli_print_header;
  1930. cli_formatter->print_body = cli_print_body;
  1931. cli_formatter->get_container = cli_get_container;
  1932. cli_formatter->iterate = cli_iterator;
  1933. cli_formatter->get_id = ast_sorcery_object_get_id;
  1934. cli_formatter->retrieve_by_id = cli_retrieve_by_id;
  1935. ast_sip_register_cli_formatter(cli_formatter);
  1936. ast_cli_register_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
  1937. /* Register AMI actions. */
  1938. ast_manager_register_xml("PJSIPUnregister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_unregister);
  1939. ast_manager_register_xml("PJSIPRegister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_register);
  1940. ast_manager_register_xml("PJSIPShowRegistrationsOutbound", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_show_outbound_registrations);
  1941. /* Clear any previous statsd gauges in case we weren't shutdown cleanly */
  1942. ast_statsd_log("PJSIP.registrations.count", AST_STATSD_GAUGE, 0);
  1943. ast_statsd_log("PJSIP.registrations.state.Registered", AST_STATSD_GAUGE, 0);
  1944. ast_statsd_log("PJSIP.registrations.state.Unregistered", AST_STATSD_GAUGE, 0);
  1945. ast_statsd_log("PJSIP.registrations.state.Rejected", AST_STATSD_GAUGE, 0);
  1946. /* Load configuration objects */
  1947. ast_sorcery_load_object(ast_sip_get_sorcery(), "registration");
  1948. network_change_sub = stasis_subscribe(ast_system_topic(),
  1949. network_change_stasis_cb, NULL);
  1950. stasis_subscription_accept_message_type(network_change_sub, ast_network_change_type());
  1951. stasis_subscription_set_filter(network_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
  1952. return AST_MODULE_LOAD_SUCCESS;
  1953. }
  1954. static int reload_module(void)
  1955. {
  1956. ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
  1957. return 0;
  1958. }
  1959. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Outbound Registration Support",
  1960. .support_level = AST_MODULE_SUPPORT_CORE,
  1961. .load = load_module,
  1962. .reload = reload_module,
  1963. .unload = unload_module,
  1964. .load_pri = AST_MODPRI_APP_DEPEND,
  1965. );