udptl.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  1. /*
  2. * Asterisk -- A telephony toolkit for Linux.
  3. *
  4. * UDPTL support for T.38
  5. *
  6. * Copyright (C) 2005, Steve Underwood, partly based on RTP code which is
  7. * Copyright (C) 1999-2009, Digium, Inc.
  8. *
  9. * Steve Underwood <steveu@coppice.org>
  10. * Kevin P. Fleming <kpfleming@digium.com>
  11. *
  12. * See http://www.asterisk.org for more information about
  13. * the Asterisk project. Please do not directly contact
  14. * any of the maintainers of this project for assistance;
  15. * the project provides a web site, mailing lists and IRC
  16. * channels for your use.
  17. *
  18. * This program is free software, distributed under the terms of
  19. * the GNU General Public License Version 2. See the LICENSE file
  20. * at the top of the source tree.
  21. *
  22. * A license has been granted to Digium (via disclaimer) for the use of
  23. * this code.
  24. */
  25. /*!
  26. * \file
  27. *
  28. * \brief UDPTL support for T.38 faxing
  29. *
  30. *
  31. * \author Mark Spencer <markster@digium.com>
  32. * \author Steve Underwood <steveu@coppice.org>
  33. * \author Kevin P. Fleming <kpfleming@digium.com>
  34. *
  35. * \page T38fax_udptl T.38 support :: UDPTL
  36. *
  37. * Asterisk supports T.38 fax passthrough, origination and termination. It does
  38. * not support gateway operation. The only channel driver that supports T.38 at
  39. * this time is chan_sip.
  40. *
  41. * UDPTL is handled very much like RTP. It can be reinvited to go directly between
  42. * the endpoints, without involving Asterisk in the media stream.
  43. *
  44. * \b References:
  45. * - chan_sip.c
  46. * - udptl.c
  47. * - app_fax.c
  48. */
  49. /*** MODULEINFO
  50. <support_level>core</support_level>
  51. ***/
  52. #include "asterisk.h"
  53. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  54. #include <sys/time.h>
  55. #include <signal.h>
  56. #include <fcntl.h>
  57. #include "asterisk/udptl.h"
  58. #include "asterisk/frame.h"
  59. #include "asterisk/channel.h"
  60. #include "asterisk/acl.h"
  61. #include "asterisk/config_options.h"
  62. #include "asterisk/lock.h"
  63. #include "asterisk/utils.h"
  64. #include "asterisk/netsock2.h"
  65. #include "asterisk/cli.h"
  66. #include "asterisk/unaligned.h"
  67. #define UDPTL_MTU 1200
  68. #if !defined(FALSE)
  69. #define FALSE 0
  70. #endif
  71. #if !defined(TRUE)
  72. #define TRUE (!FALSE)
  73. #endif
  74. #define LOG_TAG(u) S_OR(u->tag, "no tag")
  75. #define DEFAULT_UDPTLSTART 4000
  76. #define DEFAULT_UDPTLEND 4999
  77. static int udptldebug; /*!< Are we debugging? */
  78. static struct ast_sockaddr udptldebugaddr; /*!< Debug packets to/from this host */
  79. #define LOCAL_FAX_MAX_DATAGRAM 1400
  80. #define DEFAULT_FAX_MAX_DATAGRAM 400
  81. #define FAX_MAX_DATAGRAM_LIMIT 1400
  82. #define MAX_FEC_ENTRIES 5
  83. #define MAX_FEC_SPAN 5
  84. #define UDPTL_BUF_MASK 15
  85. typedef struct {
  86. int buf_len;
  87. uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
  88. } udptl_fec_tx_buffer_t;
  89. typedef struct {
  90. int buf_len;
  91. uint8_t buf[LOCAL_FAX_MAX_DATAGRAM];
  92. unsigned int fec_len[MAX_FEC_ENTRIES];
  93. uint8_t fec[MAX_FEC_ENTRIES][LOCAL_FAX_MAX_DATAGRAM];
  94. unsigned int fec_span;
  95. unsigned int fec_entries;
  96. } udptl_fec_rx_buffer_t;
  97. /*! \brief Structure for an UDPTL session */
  98. struct ast_udptl {
  99. int fd;
  100. char resp;
  101. struct ast_frame f[16];
  102. unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
  103. unsigned int lasteventseqn;
  104. int nat;
  105. int flags;
  106. struct ast_sockaddr us;
  107. struct ast_sockaddr them;
  108. int *ioid;
  109. struct ast_sched_context *sched;
  110. struct io_context *io;
  111. void *data;
  112. char *tag;
  113. ast_udptl_callback callback;
  114. /*! This option indicates the error correction scheme used in transmitted UDPTL
  115. * packets and expected in received UDPTL packets.
  116. */
  117. enum ast_t38_ec_modes error_correction_scheme;
  118. /*! This option indicates the number of error correction entries transmitted in
  119. * UDPTL packets and expected in received UDPTL packets.
  120. */
  121. unsigned int error_correction_entries;
  122. /*! This option indicates the span of the error correction entries in transmitted
  123. * UDPTL packets (FEC only).
  124. */
  125. unsigned int error_correction_span;
  126. /*! The maximum size UDPTL packet that can be accepted by
  127. * the remote device.
  128. */
  129. int far_max_datagram;
  130. /*! The maximum size UDPTL packet that we are prepared to
  131. * accept, or -1 if it hasn't been calculated since the last
  132. * changes were applied to the UDPTL structure.
  133. */
  134. int local_max_datagram;
  135. /*! The maximum IFP that can be submitted for sending
  136. * to the remote device. Calculated from far_max_datagram,
  137. * error_correction_scheme and error_correction_entries,
  138. * or -1 if it hasn't been calculated since the last
  139. * changes were applied to the UDPTL structure.
  140. */
  141. int far_max_ifp;
  142. /*! The maximum IFP that the local endpoint is prepared
  143. * to accept. Along with error_correction_scheme and
  144. * error_correction_entries, used to calculate local_max_datagram.
  145. */
  146. int local_max_ifp;
  147. unsigned int tx_seq_no;
  148. unsigned int rx_seq_no;
  149. udptl_fec_tx_buffer_t tx[UDPTL_BUF_MASK + 1];
  150. udptl_fec_rx_buffer_t rx[UDPTL_BUF_MASK + 1];
  151. };
  152. static AST_RWLIST_HEAD_STATIC(protos, ast_udptl_protocol);
  153. struct udptl_global_options {
  154. unsigned int start; /*< The UDPTL start port */
  155. unsigned int end; /*< The UDPTL end port */
  156. unsigned int fecentries;
  157. unsigned int fecspan;
  158. unsigned int nochecksums;
  159. unsigned int use_even_ports;
  160. };
  161. static AO2_GLOBAL_OBJ_STATIC(globals);
  162. struct udptl_config {
  163. struct udptl_global_options *general;
  164. };
  165. static void *udptl_snapshot_alloc(void);
  166. static int udptl_pre_apply_config(void);
  167. static struct aco_type general_option = {
  168. .type = ACO_GLOBAL,
  169. .category_match = ACO_WHITELIST,
  170. .item_offset = offsetof(struct udptl_config, general),
  171. .category = "^general$",
  172. };
  173. static struct aco_type *general_options[] = ACO_TYPES(&general_option);
  174. static struct aco_file udptl_conf = {
  175. .filename = "udptl.conf",
  176. .types = ACO_TYPES(&general_option),
  177. };
  178. CONFIG_INFO_STANDARD(cfg_info, globals, udptl_snapshot_alloc,
  179. .files = ACO_FILES(&udptl_conf),
  180. .pre_apply_config = udptl_pre_apply_config,
  181. );
  182. static inline int udptl_debug_test_addr(const struct ast_sockaddr *addr)
  183. {
  184. if (udptldebug == 0)
  185. return 0;
  186. if (ast_sockaddr_isnull(&udptldebugaddr)) {
  187. return 1;
  188. }
  189. if (ast_sockaddr_port(&udptldebugaddr)) {
  190. return !ast_sockaddr_cmp(&udptldebugaddr, addr);
  191. } else {
  192. return !ast_sockaddr_cmp_addr(&udptldebugaddr, addr);
  193. }
  194. }
  195. static int decode_length(uint8_t *buf, unsigned int limit, unsigned int *len, unsigned int *pvalue)
  196. {
  197. if (*len >= limit)
  198. return -1;
  199. if ((buf[*len] & 0x80) == 0) {
  200. *pvalue = buf[*len];
  201. (*len)++;
  202. return 0;
  203. }
  204. if ((buf[*len] & 0x40) == 0) {
  205. if (*len == limit - 1)
  206. return -1;
  207. *pvalue = (buf[*len] & 0x3F) << 8;
  208. (*len)++;
  209. *pvalue |= buf[*len];
  210. (*len)++;
  211. return 0;
  212. }
  213. *pvalue = (buf[*len] & 0x3F) << 14;
  214. (*len)++;
  215. /* We have a fragment. Currently we don't process fragments. */
  216. ast_debug(1, "UDPTL packet with length greater than 16K received, decoding will fail\n");
  217. return 1;
  218. }
  219. /*- End of function --------------------------------------------------------*/
  220. static int decode_open_type(uint8_t *buf, unsigned int limit, unsigned int *len, const uint8_t **p_object, unsigned int *p_num_octets)
  221. {
  222. unsigned int octet_cnt = 0;
  223. if (decode_length(buf, limit, len, &octet_cnt) != 0)
  224. return -1;
  225. if (octet_cnt > 0) {
  226. /* Make sure the buffer contains at least the number of bits requested */
  227. if ((*len + octet_cnt) > limit)
  228. return -1;
  229. *p_num_octets = octet_cnt;
  230. *p_object = &buf[*len];
  231. *len += octet_cnt;
  232. }
  233. return 0;
  234. }
  235. /*- End of function --------------------------------------------------------*/
  236. static unsigned int encode_length(uint8_t *buf, unsigned int *len, unsigned int value)
  237. {
  238. unsigned int multiplier;
  239. if (value < 0x80) {
  240. /* 1 octet */
  241. buf[*len] = value;
  242. (*len)++;
  243. return value;
  244. }
  245. if (value < 0x4000) {
  246. /* 2 octets */
  247. /* Set the first bit of the first octet */
  248. buf[*len] = ((0x8000 | value) >> 8) & 0xFF;
  249. (*len)++;
  250. buf[*len] = value & 0xFF;
  251. (*len)++;
  252. return value;
  253. }
  254. /* Fragmentation */
  255. multiplier = (value < 0x10000) ? (value >> 14) : 4;
  256. /* Set the first 2 bits of the octet */
  257. buf[*len] = 0xC0 | multiplier;
  258. (*len)++;
  259. return multiplier << 14;
  260. }
  261. /*- End of function --------------------------------------------------------*/
  262. static int encode_open_type(const struct ast_udptl *udptl, uint8_t *buf, unsigned int buflen,
  263. unsigned int *len, const uint8_t *data, unsigned int num_octets)
  264. {
  265. unsigned int enclen;
  266. unsigned int octet_idx;
  267. uint8_t zero_byte;
  268. /* If open type is of zero length, add a single zero byte (10.1) */
  269. if (num_octets == 0) {
  270. zero_byte = 0;
  271. data = &zero_byte;
  272. num_octets = 1;
  273. }
  274. /* Encode the open type */
  275. for (octet_idx = 0; ; num_octets -= enclen, octet_idx += enclen) {
  276. enclen = encode_length(buf, len, num_octets);
  277. if (enclen + *len > buflen) {
  278. ast_log(LOG_ERROR, "UDPTL (%s): Buffer overflow detected (%u + %u > %u)\n",
  279. LOG_TAG(udptl), enclen, *len, buflen);
  280. return -1;
  281. }
  282. if (enclen > 0) {
  283. memcpy(&buf[*len], &data[octet_idx], enclen);
  284. *len += enclen;
  285. }
  286. if (enclen >= num_octets)
  287. break;
  288. }
  289. return 0;
  290. }
  291. /*- End of function --------------------------------------------------------*/
  292. static int udptl_rx_packet(struct ast_udptl *s, uint8_t *buf, unsigned int len)
  293. {
  294. int stat1;
  295. int stat2;
  296. int i;
  297. unsigned int ptr; /* an index that keeps track of how much of the UDPTL packet has been processed */
  298. int seq_no;
  299. const uint8_t *ifp = NULL;
  300. const uint8_t *data = NULL;
  301. unsigned int ifp_len = 0;
  302. int repaired[16];
  303. const uint8_t *bufs[ARRAY_LEN(s->f) - 1];
  304. unsigned int lengths[ARRAY_LEN(s->f) - 1];
  305. int span;
  306. int entries;
  307. int ifp_no;
  308. ptr = 0;
  309. ifp_no = 0;
  310. memset(&s->f[0], 0, sizeof(s->f[0]));
  311. /* Decode seq_number */
  312. if (ptr + 2 > len)
  313. return -1;
  314. seq_no = (buf[0] << 8) | buf[1];
  315. ptr += 2;
  316. /* Break out the primary packet */
  317. if ((stat1 = decode_open_type(buf, len, &ptr, &ifp, &ifp_len)) != 0)
  318. return -1;
  319. /* Decode error_recovery */
  320. if (ptr + 1 > len)
  321. return -1;
  322. if ((buf[ptr++] & 0x80) == 0) {
  323. /* Secondary packet mode for error recovery */
  324. if (seq_no > s->rx_seq_no) {
  325. /* We received a later packet than we expected, so we need to check if we can fill in the gap from the
  326. secondary packets. */
  327. int total_count = 0;
  328. do {
  329. unsigned int count;
  330. if ((stat2 = decode_length(buf, len, &ptr, &count)) < 0)
  331. return -1;
  332. for (i = 0; i < count && total_count + i < ARRAY_LEN(bufs); i++) {
  333. if ((stat1 = decode_open_type(buf, len, &ptr, &bufs[total_count + i], &lengths[total_count + i])) != 0) {
  334. return -1;
  335. }
  336. /* valid secondaries can contain zero-length packets that should be ignored */
  337. if (!bufs[total_count + i] || !lengths[total_count + i]) {
  338. /* drop the count of items to process and reuse the buffers that were just set */
  339. i--;
  340. count--;
  341. }
  342. }
  343. total_count += i;
  344. }
  345. while (stat2 > 0 && total_count < ARRAY_LEN(bufs));
  346. /* Step through in reverse order, so we go oldest to newest */
  347. for (i = total_count; i > 0; i--) {
  348. if (seq_no - i >= s->rx_seq_no) {
  349. /* This one wasn't seen before */
  350. /* Decode the secondary IFP packet */
  351. ast_debug(3, "Recovering lost packet via secondary %d, len %u\n", seq_no - i, lengths[i - 1]);
  352. s->f[ifp_no].frametype = AST_FRAME_MODEM;
  353. s->f[ifp_no].subclass.integer = AST_MODEM_T38;
  354. s->f[ifp_no].mallocd = 0;
  355. s->f[ifp_no].seqno = seq_no - i;
  356. s->f[ifp_no].datalen = lengths[i - 1];
  357. s->f[ifp_no].data.ptr = (uint8_t *) bufs[i - 1];
  358. s->f[ifp_no].offset = 0;
  359. s->f[ifp_no].src = "UDPTL";
  360. if (ifp_no > 0)
  361. AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
  362. AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
  363. ifp_no++;
  364. }
  365. }
  366. }
  367. }
  368. else
  369. {
  370. int j;
  371. int l;
  372. int x;
  373. /* FEC mode for error recovery */
  374. /* Our buffers cannot tolerate overlength IFP packets in FEC mode */
  375. if (ifp_len > LOCAL_FAX_MAX_DATAGRAM)
  376. return -1;
  377. /* Update any missed slots in the buffer */
  378. for ( ; seq_no > s->rx_seq_no; s->rx_seq_no++) {
  379. x = s->rx_seq_no & UDPTL_BUF_MASK;
  380. s->rx[x].buf_len = -1;
  381. s->rx[x].fec_len[0] = 0;
  382. s->rx[x].fec_span = 0;
  383. s->rx[x].fec_entries = 0;
  384. }
  385. x = seq_no & UDPTL_BUF_MASK;
  386. memset(repaired, 0, sizeof(repaired));
  387. /* Save the new IFP packet */
  388. memcpy(s->rx[x].buf, ifp, ifp_len);
  389. s->rx[x].buf_len = ifp_len;
  390. repaired[x] = TRUE;
  391. /* Decode the FEC packets */
  392. /* The span is defined as an unconstrained integer, but will never be more
  393. than a small value. */
  394. if (ptr + 2 > len)
  395. return -1;
  396. if (buf[ptr++] != 1)
  397. return -1;
  398. span = buf[ptr++];
  399. s->rx[x].fec_span = span;
  400. /* The number of entries is defined as a length, but will only ever be a small
  401. value. Treat it as such. */
  402. if (ptr + 1 > len)
  403. return -1;
  404. entries = buf[ptr++];
  405. if (entries > MAX_FEC_ENTRIES) {
  406. return -1;
  407. }
  408. s->rx[x].fec_entries = entries;
  409. /* Decode the elements */
  410. for (i = 0; i < entries; i++) {
  411. if ((stat1 = decode_open_type(buf, len, &ptr, &data, &s->rx[x].fec_len[i])) != 0)
  412. return -1;
  413. if (s->rx[x].fec_len[i] > LOCAL_FAX_MAX_DATAGRAM)
  414. return -1;
  415. /* Save the new FEC data */
  416. memcpy(s->rx[x].fec[i], data, s->rx[x].fec_len[i]);
  417. #if 0
  418. fprintf(stderr, "FEC: ");
  419. for (j = 0; j < s->rx[x].fec_len[i]; j++)
  420. fprintf(stderr, "%02hhX ", data[j]);
  421. fprintf(stderr, "\n");
  422. #endif
  423. }
  424. /* See if we can reconstruct anything which is missing */
  425. /* TODO: this does not comprehensively hunt back and repair everything that is possible */
  426. for (l = x; l != ((x - (16 - span*entries)) & UDPTL_BUF_MASK); l = (l - 1) & UDPTL_BUF_MASK) {
  427. int m;
  428. if (s->rx[l].fec_len[0] <= 0)
  429. continue;
  430. for (m = 0; m < s->rx[l].fec_entries; m++) {
  431. int k;
  432. int which;
  433. int limit = (l + m) & UDPTL_BUF_MASK;
  434. /* only repair buffers that actually exist! */
  435. if (seq_no <= (s->rx[l].fec_span * s->rx[l].fec_entries) - m) {
  436. continue;
  437. }
  438. for (which = -1, k = (limit - s->rx[l].fec_span * s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK) {
  439. if (s->rx[k].buf_len <= 0)
  440. which = (which == -1) ? k : -2;
  441. }
  442. if (which >= 0) {
  443. /* Repairable */
  444. for (j = 0; j < s->rx[l].fec_len[m]; j++) {
  445. s->rx[which].buf[j] = s->rx[l].fec[m][j];
  446. for (k = (limit - s->rx[l].fec_span * s->rx[l].fec_entries) & UDPTL_BUF_MASK; k != limit; k = (k + s->rx[l].fec_entries) & UDPTL_BUF_MASK)
  447. s->rx[which].buf[j] ^= (s->rx[k].buf_len > j) ? s->rx[k].buf[j] : 0;
  448. }
  449. s->rx[which].buf_len = s->rx[l].fec_len[m];
  450. repaired[which] = TRUE;
  451. }
  452. }
  453. }
  454. /* Now play any new packets forwards in time */
  455. for (l = (x + 1) & UDPTL_BUF_MASK, j = seq_no - UDPTL_BUF_MASK; l != x; l = (l + 1) & UDPTL_BUF_MASK, j++) {
  456. if (repaired[l]) {
  457. //fprintf(stderr, "Fixed packet %d, len %d\n", j, l);
  458. s->f[ifp_no].frametype = AST_FRAME_MODEM;
  459. s->f[ifp_no].subclass.integer = AST_MODEM_T38;
  460. s->f[ifp_no].mallocd = 0;
  461. s->f[ifp_no].seqno = j;
  462. s->f[ifp_no].datalen = s->rx[l].buf_len;
  463. s->f[ifp_no].data.ptr = s->rx[l].buf;
  464. s->f[ifp_no].offset = 0;
  465. s->f[ifp_no].src = "UDPTL";
  466. if (ifp_no > 0)
  467. AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
  468. AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
  469. ifp_no++;
  470. }
  471. }
  472. }
  473. /* If packets are received out of sequence, we may have already processed this packet from the error
  474. recovery information in a packet already received. */
  475. if (seq_no >= s->rx_seq_no) {
  476. /* Decode the primary IFP packet */
  477. s->f[ifp_no].frametype = AST_FRAME_MODEM;
  478. s->f[ifp_no].subclass.integer = AST_MODEM_T38;
  479. s->f[ifp_no].mallocd = 0;
  480. s->f[ifp_no].seqno = seq_no;
  481. s->f[ifp_no].datalen = ifp_len;
  482. s->f[ifp_no].data.ptr = (uint8_t *) ifp;
  483. s->f[ifp_no].offset = 0;
  484. s->f[ifp_no].src = "UDPTL";
  485. if (ifp_no > 0)
  486. AST_LIST_NEXT(&s->f[ifp_no - 1], frame_list) = &s->f[ifp_no];
  487. AST_LIST_NEXT(&s->f[ifp_no], frame_list) = NULL;
  488. ifp_no++;
  489. }
  490. s->rx_seq_no = seq_no + 1;
  491. return ifp_no;
  492. }
  493. /*- End of function --------------------------------------------------------*/
  494. static int udptl_build_packet(struct ast_udptl *s, uint8_t *buf, unsigned int buflen, uint8_t *ifp, unsigned int ifp_len)
  495. {
  496. uint8_t fec[LOCAL_FAX_MAX_DATAGRAM * 2] = { 0, };
  497. int i;
  498. int j;
  499. int seq;
  500. int entry;
  501. int entries;
  502. int span;
  503. int m;
  504. unsigned int len;
  505. int limit;
  506. int high_tide;
  507. seq = s->tx_seq_no & 0xFFFF;
  508. /* Map the sequence number to an entry in the circular buffer */
  509. entry = seq & UDPTL_BUF_MASK;
  510. /* We save the message in a circular buffer, for generating FEC or
  511. redundancy sets later on. */
  512. s->tx[entry].buf_len = ifp_len;
  513. memcpy(s->tx[entry].buf, ifp, ifp_len);
  514. /* Build the UDPTLPacket */
  515. len = 0;
  516. /* Encode the sequence number */
  517. buf[len++] = (seq >> 8) & 0xFF;
  518. buf[len++] = seq & 0xFF;
  519. /* Encode the primary IFP packet */
  520. if (encode_open_type(s, buf, buflen, &len, ifp, ifp_len) < 0)
  521. return -1;
  522. /* Encode the appropriate type of error recovery information */
  523. switch (s->error_correction_scheme)
  524. {
  525. case UDPTL_ERROR_CORRECTION_NONE:
  526. /* Encode the error recovery type */
  527. buf[len++] = 0x00;
  528. /* The number of entries will always be zero, so it is pointless allowing
  529. for the fragmented case here. */
  530. encode_length(buf, &len, 0);
  531. break;
  532. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  533. /* Encode the error recovery type */
  534. buf[len++] = 0x00;
  535. if (s->tx_seq_no > s->error_correction_entries)
  536. entries = s->error_correction_entries;
  537. else
  538. entries = s->tx_seq_no;
  539. /* The number of entries will always be small, so it is pointless allowing
  540. for the fragmented case here. */
  541. encode_length(buf, &len, entries);
  542. /* Encode the elements */
  543. for (i = 0; i < entries; i++) {
  544. j = (entry - i - 1) & UDPTL_BUF_MASK;
  545. if (encode_open_type(s, buf, buflen, &len, s->tx[j].buf, s->tx[j].buf_len) < 0) {
  546. ast_debug(1, "UDPTL (%s): Encoding failed at i=%d, j=%d\n",
  547. LOG_TAG(s), i, j);
  548. return -1;
  549. }
  550. }
  551. break;
  552. case UDPTL_ERROR_CORRECTION_FEC:
  553. span = s->error_correction_span;
  554. entries = s->error_correction_entries;
  555. if (seq < s->error_correction_span*s->error_correction_entries) {
  556. /* In the initial stages, wind up the FEC smoothly */
  557. entries = seq/s->error_correction_span;
  558. if (seq < s->error_correction_span)
  559. span = 0;
  560. }
  561. /* Encode the error recovery type */
  562. buf[len++] = 0x80;
  563. /* Span is defined as an inconstrained integer, which it dumb. It will only
  564. ever be a small value. Treat it as such. */
  565. buf[len++] = 1;
  566. buf[len++] = span;
  567. /* The number of entries is defined as a length, but will only ever be a small
  568. value. Treat it as such. */
  569. buf[len++] = entries;
  570. for (m = 0; m < entries; m++) {
  571. /* Make an XOR'ed entry the maximum length */
  572. limit = (entry + m) & UDPTL_BUF_MASK;
  573. high_tide = 0;
  574. for (i = (limit - span*entries) & UDPTL_BUF_MASK; i != limit; i = (i + entries) & UDPTL_BUF_MASK) {
  575. if (high_tide < s->tx[i].buf_len) {
  576. for (j = 0; j < high_tide; j++)
  577. fec[j] ^= s->tx[i].buf[j];
  578. for ( ; j < s->tx[i].buf_len; j++)
  579. fec[j] = s->tx[i].buf[j];
  580. high_tide = s->tx[i].buf_len;
  581. } else {
  582. for (j = 0; j < s->tx[i].buf_len; j++)
  583. fec[j] ^= s->tx[i].buf[j];
  584. }
  585. }
  586. if (encode_open_type(s, buf, buflen, &len, fec, high_tide) < 0)
  587. return -1;
  588. }
  589. break;
  590. }
  591. s->tx_seq_no++;
  592. return len;
  593. }
  594. int ast_udptl_fd(const struct ast_udptl *udptl)
  595. {
  596. return udptl->fd;
  597. }
  598. void ast_udptl_set_data(struct ast_udptl *udptl, void *data)
  599. {
  600. udptl->data = data;
  601. }
  602. void ast_udptl_set_callback(struct ast_udptl *udptl, ast_udptl_callback callback)
  603. {
  604. udptl->callback = callback;
  605. }
  606. void ast_udptl_setnat(struct ast_udptl *udptl, int nat)
  607. {
  608. udptl->nat = nat;
  609. }
  610. static int udptlread(int *id, int fd, short events, void *cbdata)
  611. {
  612. struct ast_udptl *udptl = cbdata;
  613. struct ast_frame *f;
  614. if ((f = ast_udptl_read(udptl))) {
  615. if (udptl->callback)
  616. udptl->callback(udptl, f, udptl->data);
  617. }
  618. return 1;
  619. }
  620. struct ast_frame *ast_udptl_read(struct ast_udptl *udptl)
  621. {
  622. int res;
  623. struct ast_sockaddr addr;
  624. uint8_t *buf;
  625. buf = udptl->rawdata + AST_FRIENDLY_OFFSET;
  626. /* Cache where the header will go */
  627. res = ast_recvfrom(udptl->fd,
  628. buf,
  629. sizeof(udptl->rawdata) - AST_FRIENDLY_OFFSET,
  630. 0,
  631. &addr);
  632. if (res < 0) {
  633. if (errno != EAGAIN)
  634. ast_log(LOG_WARNING, "UDPTL (%s): read error: %s\n",
  635. LOG_TAG(udptl), strerror(errno));
  636. ast_assert(errno != EBADF);
  637. return &ast_null_frame;
  638. }
  639. /* Ignore if the other side hasn't been given an address yet. */
  640. if (ast_sockaddr_isnull(&udptl->them)) {
  641. return &ast_null_frame;
  642. }
  643. if (udptl->nat) {
  644. /* Send to whoever sent to us */
  645. if (ast_sockaddr_cmp(&udptl->them, &addr)) {
  646. ast_sockaddr_copy(&udptl->them, &addr);
  647. ast_debug(1, "UDPTL (%s): NAT, Using address %s\n",
  648. LOG_TAG(udptl), ast_sockaddr_stringify(&udptl->them));
  649. }
  650. }
  651. if (udptl_debug_test_addr(&addr)) {
  652. int seq_no;
  653. /* Decode sequence number just for verbose message. */
  654. if (res < 2) {
  655. /* Short packet. */
  656. seq_no = -1;
  657. } else {
  658. seq_no = (buf[0] << 8) | buf[1];
  659. }
  660. ast_verb(1, "UDPTL (%s): packet from %s (seq %d, len %d)\n",
  661. LOG_TAG(udptl), ast_sockaddr_stringify(&addr), seq_no, res);
  662. }
  663. if (udptl_rx_packet(udptl, buf, res) < 1) {
  664. return &ast_null_frame;
  665. }
  666. return &udptl->f[0];
  667. }
  668. static void calculate_local_max_datagram(struct ast_udptl *udptl)
  669. {
  670. unsigned int new_max = 0;
  671. if (udptl->local_max_ifp == -1) {
  672. ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate local_max_datagram before local_max_ifp has been set.\n",
  673. LOG_TAG(udptl));
  674. udptl->local_max_datagram = -1;
  675. return;
  676. }
  677. /* calculate the amount of space required to receive an IFP
  678. * of the maximum size supported by the application/endpoint
  679. * that we are delivering them to (local endpoint), and add
  680. * the amount of space required to support the selected
  681. * error correction mode
  682. */
  683. switch (udptl->error_correction_scheme) {
  684. case UDPTL_ERROR_CORRECTION_NONE:
  685. /* need room for sequence number, length indicator, redundancy
  686. * indicator and following length indicator
  687. */
  688. new_max = 5 + udptl->local_max_ifp;
  689. break;
  690. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  691. /* need room for sequence number, length indicators, plus
  692. * room for up to 3 redundancy packets
  693. */
  694. new_max = 5 + udptl->local_max_ifp + 2 + (3 * udptl->local_max_ifp);
  695. break;
  696. case UDPTL_ERROR_CORRECTION_FEC:
  697. /* need room for sequence number, length indicators and a
  698. * a single IFP of the maximum size expected
  699. */
  700. new_max = 5 + udptl->local_max_ifp + 4 + udptl->local_max_ifp;
  701. break;
  702. }
  703. /* add 5% extra space for insurance, but no larger than LOCAL_FAX_MAX_DATAGRAM */
  704. udptl->local_max_datagram = MIN(new_max * 1.05, LOCAL_FAX_MAX_DATAGRAM);
  705. }
  706. static void calculate_far_max_ifp(struct ast_udptl *udptl)
  707. {
  708. unsigned new_max = 0;
  709. if (udptl->far_max_datagram == -1) {
  710. ast_log(LOG_WARNING, "UDPTL (%s): Cannot calculate far_max_ifp before far_max_datagram has been set.\n",
  711. LOG_TAG(udptl));
  712. udptl->far_max_ifp = -1;
  713. return;
  714. }
  715. /* the goal here is to supply the local endpoint (application
  716. * or bridged channel) a maximum IFP value that will allow it
  717. * to effectively and efficiently transfer image data at its
  718. * selected bit rate, taking into account the selected error
  719. * correction mode, but without overrunning the far endpoint's
  720. * datagram buffer. this is complicated by the fact that some
  721. * far endpoints send us bogus (small) max datagram values,
  722. * which would result in either buffer overrun or no error
  723. * correction. we try to accomodate those, but if the supplied
  724. * value is too small to do so, we'll emit warning messages and
  725. * the user will have to use configuration options to override
  726. * the max datagram value supplied by the far endpoint.
  727. */
  728. switch (udptl->error_correction_scheme) {
  729. case UDPTL_ERROR_CORRECTION_NONE:
  730. /* need room for sequence number, length indicator, redundancy
  731. * indicator and following length indicator
  732. */
  733. new_max = udptl->far_max_datagram - 5;
  734. break;
  735. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  736. /* for this case, we'd like to send as many error correction entries
  737. * as possible (up to the number we're configured for), but we'll settle
  738. * for sending fewer if the configured number would cause the
  739. * calculated max IFP to be too small for effective operation
  740. *
  741. * need room for sequence number, length indicators and the
  742. * configured number of redundant packets
  743. *
  744. * note: we purposely don't allow error_correction_entries to drop to
  745. * zero in this loop; we'd rather send smaller IFPs (and thus reduce
  746. * the image data transfer rate) than sacrifice redundancy completely
  747. */
  748. for (;;) {
  749. new_max = (udptl->far_max_datagram - 8) / (udptl->error_correction_entries + 1);
  750. if ((new_max < 80) && (udptl->error_correction_entries > 1)) {
  751. /* the max ifp is not large enough, subtract an
  752. * error correction entry and calculate again
  753. * */
  754. --udptl->error_correction_entries;
  755. } else {
  756. break;
  757. }
  758. }
  759. break;
  760. case UDPTL_ERROR_CORRECTION_FEC:
  761. /* need room for sequence number, length indicators and a
  762. * a single IFP of the maximum size expected
  763. */
  764. new_max = (udptl->far_max_datagram - 10) / 2;
  765. break;
  766. }
  767. /* subtract 5% of space for insurance */
  768. udptl->far_max_ifp = new_max * 0.95;
  769. }
  770. enum ast_t38_ec_modes ast_udptl_get_error_correction_scheme(const struct ast_udptl *udptl)
  771. {
  772. return udptl->error_correction_scheme;
  773. }
  774. void ast_udptl_set_error_correction_scheme(struct ast_udptl *udptl, enum ast_t38_ec_modes ec)
  775. {
  776. udptl->error_correction_scheme = ec;
  777. switch (ec) {
  778. case UDPTL_ERROR_CORRECTION_FEC:
  779. udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_FEC;
  780. if (udptl->error_correction_entries == 0) {
  781. udptl->error_correction_entries = 3;
  782. }
  783. if (udptl->error_correction_span == 0) {
  784. udptl->error_correction_span = 3;
  785. }
  786. break;
  787. case UDPTL_ERROR_CORRECTION_REDUNDANCY:
  788. udptl->error_correction_scheme = UDPTL_ERROR_CORRECTION_REDUNDANCY;
  789. if (udptl->error_correction_entries == 0) {
  790. udptl->error_correction_entries = 3;
  791. }
  792. break;
  793. default:
  794. /* nothing to do */
  795. break;
  796. };
  797. /* reset calculated values so they'll be computed again */
  798. udptl->local_max_datagram = -1;
  799. udptl->far_max_ifp = -1;
  800. }
  801. void ast_udptl_set_local_max_ifp(struct ast_udptl *udptl, unsigned int max_ifp)
  802. {
  803. /* make sure max_ifp is a positive value since a cast will take place when
  804. * when setting local_max_ifp */
  805. if ((signed int) max_ifp > 0) {
  806. udptl->local_max_ifp = max_ifp;
  807. /* reset calculated values so they'll be computed again */
  808. udptl->local_max_datagram = -1;
  809. }
  810. }
  811. unsigned int ast_udptl_get_local_max_datagram(struct ast_udptl *udptl)
  812. {
  813. if (udptl->local_max_datagram == -1) {
  814. calculate_local_max_datagram(udptl);
  815. }
  816. /* this function expects a unsigned value in return. */
  817. if (udptl->local_max_datagram < 0) {
  818. return 0;
  819. }
  820. return udptl->local_max_datagram;
  821. }
  822. void ast_udptl_set_far_max_datagram(struct ast_udptl *udptl, unsigned int max_datagram)
  823. {
  824. if (!max_datagram || (max_datagram > FAX_MAX_DATAGRAM_LIMIT)) {
  825. udptl->far_max_datagram = DEFAULT_FAX_MAX_DATAGRAM;
  826. } else {
  827. udptl->far_max_datagram = max_datagram;
  828. }
  829. /* reset calculated values so they'll be computed again */
  830. udptl->far_max_ifp = -1;
  831. }
  832. unsigned int ast_udptl_get_far_max_datagram(const struct ast_udptl *udptl)
  833. {
  834. if (udptl->far_max_datagram < 0) {
  835. return 0;
  836. }
  837. return udptl->far_max_datagram;
  838. }
  839. unsigned int ast_udptl_get_far_max_ifp(struct ast_udptl *udptl)
  840. {
  841. if (udptl->far_max_ifp == -1) {
  842. calculate_far_max_ifp(udptl);
  843. }
  844. if (udptl->far_max_ifp < 0) {
  845. return 0;
  846. }
  847. return udptl->far_max_ifp;
  848. }
  849. struct ast_udptl *ast_udptl_new_with_bindaddr(struct ast_sched_context *sched, struct io_context *io, int callbackmode, struct ast_sockaddr *addr)
  850. {
  851. struct ast_udptl *udptl;
  852. int x;
  853. int startplace;
  854. int i;
  855. long int flags;
  856. RAII_VAR(struct udptl_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
  857. if (!cfg || !cfg->general) {
  858. ast_log(LOG_ERROR, "Could not access global udptl options!\n");
  859. return NULL;
  860. }
  861. if (!(udptl = ast_calloc(1, sizeof(*udptl)))) {
  862. return NULL;
  863. }
  864. udptl->error_correction_span = cfg->general->fecspan;
  865. udptl->error_correction_entries = cfg->general->fecentries;
  866. udptl->far_max_datagram = -1;
  867. udptl->far_max_ifp = -1;
  868. udptl->local_max_ifp = -1;
  869. udptl->local_max_datagram = -1;
  870. for (i = 0; i <= UDPTL_BUF_MASK; i++) {
  871. udptl->rx[i].buf_len = -1;
  872. udptl->tx[i].buf_len = -1;
  873. }
  874. if ((udptl->fd = socket(ast_sockaddr_is_ipv6(addr) ?
  875. AF_INET6 : AF_INET, SOCK_DGRAM, 0)) < 0) {
  876. ast_free(udptl);
  877. ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
  878. return NULL;
  879. }
  880. flags = fcntl(udptl->fd, F_GETFL);
  881. fcntl(udptl->fd, F_SETFL, flags | O_NONBLOCK);
  882. #ifdef SO_NO_CHECK
  883. if (cfg->general->nochecksums)
  884. setsockopt(udptl->fd, SOL_SOCKET, SO_NO_CHECK, &cfg->general->nochecksums, sizeof(cfg->general->nochecksums));
  885. #endif
  886. /* Find us a place */
  887. x = (cfg->general->start == cfg->general->end) ? cfg->general->start : (ast_random() % (cfg->general->end - cfg->general->start)) + cfg->general->start;
  888. if (cfg->general->use_even_ports && (x & 1)) {
  889. ++x;
  890. }
  891. startplace = x;
  892. for (;;) {
  893. ast_sockaddr_copy(&udptl->us, addr);
  894. ast_sockaddr_set_port(&udptl->us, x);
  895. if (ast_bind(udptl->fd, &udptl->us) == 0) {
  896. break;
  897. }
  898. if (errno != EADDRINUSE && errno != EACCES) {
  899. ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
  900. close(udptl->fd);
  901. ast_free(udptl);
  902. return NULL;
  903. }
  904. if (cfg->general->use_even_ports) {
  905. x += 2;
  906. } else {
  907. ++x;
  908. }
  909. if (x > cfg->general->end)
  910. x = cfg->general->start;
  911. if (x == startplace) {
  912. ast_log(LOG_WARNING, "No UDPTL ports remaining\n");
  913. close(udptl->fd);
  914. ast_free(udptl);
  915. return NULL;
  916. }
  917. }
  918. if (io && sched && callbackmode) {
  919. /* Operate this one in a callback mode */
  920. udptl->sched = sched;
  921. udptl->io = io;
  922. udptl->ioid = ast_io_add(udptl->io, udptl->fd, udptlread, AST_IO_IN, udptl);
  923. }
  924. return udptl;
  925. }
  926. void ast_udptl_set_tag(struct ast_udptl *udptl, const char *format, ...)
  927. {
  928. va_list ap;
  929. ast_free(udptl->tag);
  930. udptl->tag = NULL;
  931. va_start(ap, format);
  932. if (ast_vasprintf(&udptl->tag, format, ap) == -1) {
  933. udptl->tag = NULL;
  934. }
  935. va_end(ap);
  936. }
  937. int ast_udptl_setqos(struct ast_udptl *udptl, unsigned int tos, unsigned int cos)
  938. {
  939. return ast_set_qos(udptl->fd, tos, cos, "UDPTL");
  940. }
  941. void ast_udptl_set_peer(struct ast_udptl *udptl, const struct ast_sockaddr *them)
  942. {
  943. ast_sockaddr_copy(&udptl->them, them);
  944. }
  945. void ast_udptl_get_peer(const struct ast_udptl *udptl, struct ast_sockaddr *them)
  946. {
  947. ast_sockaddr_copy(them, &udptl->them);
  948. }
  949. void ast_udptl_get_us(const struct ast_udptl *udptl, struct ast_sockaddr *us)
  950. {
  951. ast_sockaddr_copy(us, &udptl->us);
  952. }
  953. void ast_udptl_stop(struct ast_udptl *udptl)
  954. {
  955. ast_sockaddr_setnull(&udptl->them);
  956. }
  957. void ast_udptl_destroy(struct ast_udptl *udptl)
  958. {
  959. if (udptl->ioid)
  960. ast_io_remove(udptl->io, udptl->ioid);
  961. if (udptl->fd > -1)
  962. close(udptl->fd);
  963. if (udptl->tag)
  964. ast_free(udptl->tag);
  965. ast_free(udptl);
  966. }
  967. int ast_udptl_write(struct ast_udptl *s, struct ast_frame *f)
  968. {
  969. unsigned int seq;
  970. unsigned int len = f->datalen;
  971. /* if no max datagram size is provided, use default value */
  972. const int bufsize = (s->far_max_datagram > 0) ? s->far_max_datagram : DEFAULT_FAX_MAX_DATAGRAM;
  973. uint8_t buf[bufsize];
  974. memset(buf, 0, sizeof(buf));
  975. /* If we have no peer, return immediately */
  976. if (ast_sockaddr_isnull(&s->them)) {
  977. return 0;
  978. }
  979. /* If there is no data length, return immediately */
  980. if (f->datalen == 0)
  981. return 0;
  982. if ((f->frametype != AST_FRAME_MODEM) ||
  983. (f->subclass.integer != AST_MODEM_T38)) {
  984. ast_log(LOG_WARNING, "UDPTL (%s): UDPTL can only send T.38 data.\n",
  985. LOG_TAG(s));
  986. return -1;
  987. }
  988. if (len > s->far_max_ifp) {
  989. ast_log(LOG_WARNING,
  990. "UDPTL (%s): UDPTL asked to send %u bytes of IFP when far end only prepared to accept %d bytes; data loss will occur."
  991. "You may need to override the T38FaxMaxDatagram value for this endpoint in the channel driver configuration.\n",
  992. LOG_TAG(s), len, s->far_max_ifp);
  993. len = s->far_max_ifp;
  994. }
  995. /* Save seq_no for debug output because udptl_build_packet increments it */
  996. seq = s->tx_seq_no & 0xFFFF;
  997. /* Cook up the UDPTL packet, with the relevant EC info. */
  998. len = udptl_build_packet(s, buf, sizeof(buf), f->data.ptr, len);
  999. if ((signed int) len > 0 && !ast_sockaddr_isnull(&s->them)) {
  1000. if (ast_sendto(s->fd, buf, len, 0, &s->them) < 0) {
  1001. ast_log(LOG_NOTICE, "UDPTL (%s): Transmission error to %s: %s\n",
  1002. LOG_TAG(s), ast_sockaddr_stringify(&s->them), strerror(errno));
  1003. }
  1004. if (udptl_debug_test_addr(&s->them)) {
  1005. ast_verb(1, "UDPTL (%s): packet to %s (seq %u, len %u)\n",
  1006. LOG_TAG(s), ast_sockaddr_stringify(&s->them), seq, len);
  1007. }
  1008. }
  1009. return 0;
  1010. }
  1011. void ast_udptl_proto_unregister(struct ast_udptl_protocol *proto)
  1012. {
  1013. AST_RWLIST_WRLOCK(&protos);
  1014. AST_RWLIST_REMOVE(&protos, proto, list);
  1015. AST_RWLIST_UNLOCK(&protos);
  1016. }
  1017. int ast_udptl_proto_register(struct ast_udptl_protocol *proto)
  1018. {
  1019. struct ast_udptl_protocol *cur;
  1020. AST_RWLIST_WRLOCK(&protos);
  1021. AST_RWLIST_TRAVERSE(&protos, cur, list) {
  1022. if (cur->type == proto->type) {
  1023. ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
  1024. AST_RWLIST_UNLOCK(&protos);
  1025. return -1;
  1026. }
  1027. }
  1028. AST_RWLIST_INSERT_TAIL(&protos, proto, list);
  1029. AST_RWLIST_UNLOCK(&protos);
  1030. return 0;
  1031. }
  1032. static struct ast_udptl_protocol *get_proto(struct ast_channel *chan)
  1033. {
  1034. struct ast_udptl_protocol *cur = NULL;
  1035. AST_RWLIST_RDLOCK(&protos);
  1036. AST_RWLIST_TRAVERSE(&protos, cur, list) {
  1037. if (cur->type == ast_channel_tech(chan)->type)
  1038. break;
  1039. }
  1040. AST_RWLIST_UNLOCK(&protos);
  1041. return cur;
  1042. }
  1043. int ast_udptl_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
  1044. {
  1045. struct ast_frame *f;
  1046. struct ast_channel *who;
  1047. struct ast_channel *cs[3];
  1048. struct ast_udptl *p0;
  1049. struct ast_udptl *p1;
  1050. struct ast_udptl_protocol *pr0;
  1051. struct ast_udptl_protocol *pr1;
  1052. struct ast_sockaddr ac0;
  1053. struct ast_sockaddr ac1;
  1054. struct ast_sockaddr t0;
  1055. struct ast_sockaddr t1;
  1056. void *pvt0;
  1057. void *pvt1;
  1058. int to;
  1059. ast_channel_lock(c0);
  1060. while (ast_channel_trylock(c1)) {
  1061. ast_channel_unlock(c0);
  1062. usleep(1);
  1063. ast_channel_lock(c0);
  1064. }
  1065. pr0 = get_proto(c0);
  1066. pr1 = get_proto(c1);
  1067. if (!pr0) {
  1068. ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", ast_channel_name(c0));
  1069. ast_channel_unlock(c0);
  1070. ast_channel_unlock(c1);
  1071. return -1;
  1072. }
  1073. if (!pr1) {
  1074. ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", ast_channel_name(c1));
  1075. ast_channel_unlock(c0);
  1076. ast_channel_unlock(c1);
  1077. return -1;
  1078. }
  1079. pvt0 = ast_channel_tech_pvt(c0);
  1080. pvt1 = ast_channel_tech_pvt(c1);
  1081. p0 = pr0->get_udptl_info(c0);
  1082. p1 = pr1->get_udptl_info(c1);
  1083. if (!p0 || !p1) {
  1084. /* Somebody doesn't want to play... */
  1085. ast_channel_unlock(c0);
  1086. ast_channel_unlock(c1);
  1087. return -2;
  1088. }
  1089. if (pr0->set_udptl_peer(c0, p1)) {
  1090. ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", ast_channel_name(c0), ast_channel_name(c1));
  1091. memset(&ac1, 0, sizeof(ac1));
  1092. } else {
  1093. /* Store UDPTL peer */
  1094. ast_udptl_get_peer(p1, &ac1);
  1095. }
  1096. if (pr1->set_udptl_peer(c1, p0)) {
  1097. ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", ast_channel_name(c1), ast_channel_name(c0));
  1098. memset(&ac0, 0, sizeof(ac0));
  1099. } else {
  1100. /* Store UDPTL peer */
  1101. ast_udptl_get_peer(p0, &ac0);
  1102. }
  1103. ast_channel_unlock(c0);
  1104. ast_channel_unlock(c1);
  1105. cs[0] = c0;
  1106. cs[1] = c1;
  1107. cs[2] = NULL;
  1108. for (;;) {
  1109. if ((ast_channel_tech_pvt(c0) != pvt0) ||
  1110. (ast_channel_tech_pvt(c1) != pvt1) ||
  1111. (ast_channel_masq(c0) || ast_channel_masqr(c0) || ast_channel_masq(c1) || ast_channel_masqr(c1))) {
  1112. ast_debug(1, "Oooh, something is weird, backing out\n");
  1113. /* Tell it to try again later */
  1114. return -3;
  1115. }
  1116. to = -1;
  1117. ast_udptl_get_peer(p1, &t1);
  1118. ast_udptl_get_peer(p0, &t0);
  1119. if (ast_sockaddr_cmp(&t1, &ac1)) {
  1120. ast_debug(1, "Oooh, '%s' changed end address to %s\n",
  1121. ast_channel_name(c1), ast_sockaddr_stringify(&t1));
  1122. ast_debug(1, "Oooh, '%s' was %s\n",
  1123. ast_channel_name(c1), ast_sockaddr_stringify(&ac1));
  1124. ast_sockaddr_copy(&ac1, &t1);
  1125. }
  1126. if (ast_sockaddr_cmp(&t0, &ac0)) {
  1127. ast_debug(1, "Oooh, '%s' changed end address to %s\n",
  1128. ast_channel_name(c0), ast_sockaddr_stringify(&t0));
  1129. ast_debug(1, "Oooh, '%s' was %s\n",
  1130. ast_channel_name(c0), ast_sockaddr_stringify(&ac0));
  1131. ast_sockaddr_copy(&ac0, &t0);
  1132. }
  1133. who = ast_waitfor_n(cs, 2, &to);
  1134. if (!who) {
  1135. ast_debug(1, "Ooh, empty read...\n");
  1136. /* check for hangup / whentohangup */
  1137. if (ast_check_hangup(c0) || ast_check_hangup(c1))
  1138. break;
  1139. continue;
  1140. }
  1141. f = ast_read(who);
  1142. if (!f) {
  1143. *fo = f;
  1144. *rc = who;
  1145. ast_debug(1, "Oooh, got a %s\n", f ? "digit" : "hangup");
  1146. /* That's all we needed */
  1147. return 0;
  1148. } else {
  1149. if (f->frametype == AST_FRAME_MODEM) {
  1150. /* Forward T.38 frames if they happen upon us */
  1151. if (who == c0) {
  1152. ast_write(c1, f);
  1153. } else if (who == c1) {
  1154. ast_write(c0, f);
  1155. }
  1156. }
  1157. ast_frfree(f);
  1158. }
  1159. /* Swap priority. Not that it's a big deal at this point */
  1160. cs[2] = cs[0];
  1161. cs[0] = cs[1];
  1162. cs[1] = cs[2];
  1163. }
  1164. return -1;
  1165. }
  1166. static char *handle_cli_udptl_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1167. {
  1168. switch (cmd) {
  1169. case CLI_INIT:
  1170. e->command = "udptl set debug {on|off|ip}";
  1171. e->usage =
  1172. "Usage: udptl set debug {on|off|ip host[:port]}\n"
  1173. " Enable or disable dumping of UDPTL packets.\n"
  1174. " If ip is specified, limit the dumped packets to those to and from\n"
  1175. " the specified 'host' with optional port.\n";
  1176. return NULL;
  1177. case CLI_GENERATE:
  1178. return NULL;
  1179. }
  1180. if (a->argc < 4 || a->argc > 5)
  1181. return CLI_SHOWUSAGE;
  1182. if (a->argc == 4) {
  1183. if (!strncasecmp(a->argv[3], "on", 2)) {
  1184. udptldebug = 1;
  1185. memset(&udptldebugaddr, 0, sizeof(udptldebugaddr));
  1186. ast_cli(a->fd, "UDPTL Debugging Enabled\n");
  1187. } else if (!strncasecmp(a->argv[3], "off", 3)) {
  1188. udptldebug = 0;
  1189. ast_cli(a->fd, "UDPTL Debugging Disabled\n");
  1190. } else {
  1191. return CLI_SHOWUSAGE;
  1192. }
  1193. } else {
  1194. struct ast_sockaddr *addrs;
  1195. if (strncasecmp(a->argv[3], "ip", 2))
  1196. return CLI_SHOWUSAGE;
  1197. if (!ast_sockaddr_resolve(&addrs, a->argv[4], 0, 0)) {
  1198. return CLI_SHOWUSAGE;
  1199. }
  1200. ast_sockaddr_copy(&udptldebugaddr, &addrs[0]);
  1201. ast_cli(a->fd, "UDPTL Debugging Enabled for IP: %s\n", ast_sockaddr_stringify(&udptldebugaddr));
  1202. udptldebug = 1;
  1203. ast_free(addrs);
  1204. }
  1205. return CLI_SUCCESS;
  1206. }
  1207. static char *handle_cli_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1208. {
  1209. RAII_VAR(struct udptl_config *, cfg, NULL, ao2_cleanup);
  1210. switch (cmd) {
  1211. case CLI_INIT:
  1212. e->command = "udptl show config";
  1213. e->usage =
  1214. "Usage: udptl show config\n"
  1215. " Display UDPTL configuration options\n";
  1216. return NULL;
  1217. case CLI_GENERATE:
  1218. return NULL;
  1219. }
  1220. if (!(cfg = ao2_global_obj_ref(globals))) {
  1221. return CLI_FAILURE;
  1222. }
  1223. ast_cli(a->fd, "UDPTL Global options\n");
  1224. ast_cli(a->fd, "--------------------\n");
  1225. ast_cli(a->fd, "udptlstart: %u\n", cfg->general->start);
  1226. ast_cli(a->fd, "udptlend: %u\n", cfg->general->end);
  1227. ast_cli(a->fd, "udptlfecentries: %u\n", cfg->general->fecentries);
  1228. ast_cli(a->fd, "udptlfecspan: %u\n", cfg->general->fecspan);
  1229. ast_cli(a->fd, "use_even_ports: %s\n", AST_CLI_YESNO(cfg->general->use_even_ports));
  1230. ast_cli(a->fd, "udptlchecksums: %s\n", AST_CLI_YESNO(!cfg->general->nochecksums));
  1231. return CLI_SUCCESS;
  1232. }
  1233. static struct ast_cli_entry cli_udptl[] = {
  1234. AST_CLI_DEFINE(handle_cli_udptl_set_debug, "Enable/Disable UDPTL debugging"),
  1235. AST_CLI_DEFINE(handle_cli_show_config, "Show UDPTL config options"),
  1236. };
  1237. static void udptl_config_destructor(void *obj)
  1238. {
  1239. struct udptl_config *cfg = obj;
  1240. ao2_cleanup(cfg->general);
  1241. }
  1242. static void *udptl_snapshot_alloc(void)
  1243. {
  1244. struct udptl_config *cfg;
  1245. if (!(cfg = ao2_alloc(sizeof(*cfg), udptl_config_destructor))) {
  1246. return NULL;
  1247. }
  1248. if (!(cfg->general = ao2_alloc(sizeof(*cfg->general), NULL))) {
  1249. ao2_ref(cfg, -1);
  1250. return NULL;
  1251. }
  1252. return cfg;
  1253. }
  1254. static int removed_options_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
  1255. {
  1256. if (!strcasecmp(var->name, "t38faxudpec")) {
  1257. ast_log(LOG_WARNING, "t38faxudpec in udptl.conf is no longer supported; use the t38pt_udptl configuration option in sip.conf instead.\n");
  1258. } else if (!strcasecmp(var->name, "t38faxmaxdatagram")) {
  1259. ast_log(LOG_WARNING, "t38faxmaxdatagram in udptl.conf is no longer supported; value is now supplied by T.38 applications.\n");
  1260. }
  1261. return 0;
  1262. }
  1263. static void __ast_udptl_reload(int reload)
  1264. {
  1265. if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
  1266. if (!reload) {
  1267. RAII_VAR(struct udptl_config *, udptl_cfg, udptl_snapshot_alloc(), ao2_cleanup);
  1268. if (aco_set_defaults(&general_option, "general", udptl_cfg->general)) {
  1269. ast_log(LOG_ERROR, "Failed to load udptl.conf and failed to initialize defaults.\n");
  1270. return;
  1271. }
  1272. ast_log(LOG_NOTICE, "Could not load udptl config; using defaults\n");
  1273. ao2_global_obj_replace_unref(globals, udptl_cfg);
  1274. }
  1275. }
  1276. }
  1277. static int udptl_pre_apply_config(void) {
  1278. struct udptl_config *cfg = aco_pending_config(&cfg_info);
  1279. if (!cfg->general) {
  1280. return -1;
  1281. }
  1282. #ifndef SO_NO_CHECK
  1283. if (cfg->general->nochecksums) {
  1284. ast_log(LOG_WARNING, "Disabling UDPTL checksums is not supported on this operating system!\n");
  1285. cfg->general->nochecksums = 0;
  1286. }
  1287. #endif
  1288. /* Fix up any global config values that we can handle before replacing the config */
  1289. if (cfg->general->use_even_ports && (cfg->general->start & 1)) {
  1290. ++cfg->general->start;
  1291. ast_log(LOG_NOTICE, "Odd numbered udptlstart specified but use_even_ports enabled. udptlstart is now %u\n", cfg->general->start);
  1292. }
  1293. if (cfg->general->start > cfg->general->end) {
  1294. ast_log(LOG_WARNING, "Unreasonable values for UDPTL start/end ports; defaulting to %s-%s.\n", __stringify(DEFAULT_UDPTLSTART), __stringify(DEFAULT_UDPTLEND));
  1295. cfg->general->start = DEFAULT_UDPTLSTART;
  1296. cfg->general->end = DEFAULT_UDPTLEND;
  1297. }
  1298. if (cfg->general->use_even_ports && (cfg->general->end & 1)) {
  1299. --cfg->general->end;
  1300. ast_log(LOG_NOTICE, "Odd numbered udptlend specified but use_even_ports enabled. udptlend is now %u\n", cfg->general->end);
  1301. }
  1302. return 0;
  1303. }
  1304. int ast_udptl_reload(void)
  1305. {
  1306. __ast_udptl_reload(1);
  1307. return 0;
  1308. }
  1309. /*!
  1310. * \internal
  1311. * \brief Clean up resources on Asterisk shutdown
  1312. */
  1313. static void udptl_shutdown(void)
  1314. {
  1315. ast_cli_unregister_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
  1316. ao2_t_global_obj_release(globals, "Unref udptl global container in shutdown");
  1317. aco_info_destroy(&cfg_info);
  1318. }
  1319. void ast_udptl_init(void)
  1320. {
  1321. if (aco_info_init(&cfg_info)) {
  1322. return;
  1323. }
  1324. aco_option_register(&cfg_info, "udptlstart", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLSTART),
  1325. OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
  1326. FLDSET(struct udptl_global_options, start), DEFAULT_UDPTLSTART, 1024, 65535);
  1327. aco_option_register(&cfg_info, "udptlend", ACO_EXACT, general_options, __stringify(DEFAULT_UDPTLEND),
  1328. OPT_UINT_T, PARSE_IN_RANGE | PARSE_DEFAULT,
  1329. FLDSET(struct udptl_global_options, end), DEFAULT_UDPTLEND, 1024, 65535);
  1330. aco_option_register(&cfg_info, "udptlfecentries", ACO_EXACT, general_options, NULL,
  1331. OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
  1332. FLDSET(struct udptl_global_options, fecentries), 1, MAX_FEC_ENTRIES);
  1333. aco_option_register(&cfg_info, "udptlfecspan", ACO_EXACT, general_options, NULL,
  1334. OPT_UINT_T, PARSE_IN_RANGE | PARSE_RANGE_DEFAULTS,
  1335. FLDSET(struct udptl_global_options, fecspan), 1, MAX_FEC_SPAN);
  1336. aco_option_register(&cfg_info, "udptlchecksums", ACO_EXACT, general_options, "yes",
  1337. OPT_BOOL_T, 0, FLDSET(struct udptl_global_options, nochecksums));
  1338. aco_option_register(&cfg_info, "use_even_ports", ACO_EXACT, general_options, "no",
  1339. OPT_BOOL_T, 1, FLDSET(struct udptl_global_options, use_even_ports));
  1340. aco_option_register_custom(&cfg_info, "t38faxudpec", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
  1341. aco_option_register_custom(&cfg_info, "t38faxmaxdatagram", ACO_EXACT, general_options, NULL, removed_options_handler, 0);
  1342. __ast_udptl_reload(0);
  1343. ast_cli_register_multiple(cli_udptl, ARRAY_LEN(cli_udptl));
  1344. ast_register_cleanup(udptl_shutdown);
  1345. }