app_sms.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2004 - 2005, Adrian Kennard, rights assigned to Digium
  5. *
  6. * See http://www.asterisk.org for more information about
  7. * the Asterisk project. Please do not directly contact
  8. * any of the maintainers of this project for assistance;
  9. * the project provides a web site, mailing lists and IRC
  10. * channels for your use.
  11. *
  12. * This program is free software, distributed under the terms of
  13. * the GNU General Public License Version 2. See the LICENSE file
  14. * at the top of the source tree.
  15. */
  16. /*! \file
  17. *
  18. * \brief SMS application - ETSI ES 201 912 protocol 1 implementation
  19. *
  20. * \par Development notes
  21. * \note The ETSI standards are available free of charge from ETSI at
  22. * http://pda.etsi.org/pda/queryform.asp
  23. * Among the relevant documents here we have:
  24. *
  25. * ES 201 912 SMS for PSTN/ISDN
  26. * TS 123 040 Technical realization of SMS
  27. *
  28. *
  29. * \ingroup applications
  30. *
  31. * \author Adrian Kennard (for the original protocol 1 code)
  32. * \author Filippo Grassilli (Hyppo) - protocol 2 support
  33. * Not fully tested, under development
  34. */
  35. /*** MODULEINFO
  36. <support_level>extended</support_level>
  37. ***/
  38. #include "asterisk.h"
  39. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  40. #include <dirent.h>
  41. #include <ctype.h>
  42. #include <sys/stat.h>
  43. #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR and LOG_DIR */
  44. #include "asterisk/lock.h"
  45. #include "asterisk/file.h"
  46. #include "asterisk/channel.h"
  47. #include "asterisk/pbx.h"
  48. #include "asterisk/module.h"
  49. #include "asterisk/alaw.h"
  50. #include "asterisk/callerid.h"
  51. #include "asterisk/utils.h"
  52. #include "asterisk/app.h"
  53. /*** DOCUMENTATION
  54. <application name="SMS" language="en_US">
  55. <synopsis>
  56. Communicates with SMS service centres and SMS capable analogue phones.
  57. </synopsis>
  58. <syntax>
  59. <parameter name="name" required="true">
  60. <para>The name of the queue used in <filename>/var/spool/asterisk/sms</filename></para>
  61. </parameter>
  62. <parameter name="options">
  63. <optionlist>
  64. <option name="a">
  65. <para>Answer, i.e. send initial FSK packet.</para>
  66. </option>
  67. <option name="s">
  68. <para>Act as service centre talking to a phone.</para>
  69. </option>
  70. <option name="t">
  71. <para>Use protocol 2 (default used is protocol 1).</para>
  72. </option>
  73. <option name="p">
  74. <para>Set the initial delay to N ms (default is <literal>300</literal>).
  75. addr and body are a deprecated format to send messages out.</para>
  76. </option>
  77. <option name="r">
  78. <para>Set the Status Report Request (SRR) bit.</para>
  79. </option>
  80. <option name="o">
  81. <para>The body should be coded as octets not 7-bit symbols.</para>
  82. </option>
  83. </optionlist>
  84. </parameter>
  85. <parameter name="addr" />
  86. <parameter name="body" />
  87. </syntax>
  88. <description>
  89. <para>SMS handles exchange of SMS data with a call to/from SMS capable phone or SMS PSTN service center.
  90. Can send and/or receive SMS messages. Works to ETSI ES 201 912; compatible with BT SMS PSTN service in
  91. UK and Telecom Italia in Italy.</para>
  92. <para>Typical usage is to use to handle calls from the SMS service centre CLI, or to set up a call using
  93. <literal>outgoing</literal> or manager interface to connect service centre to SMS().</para>
  94. <para>"Messages are processed as per text file message queues. smsq (a separate software) is a command to
  95. generate message queues and send messages.</para>
  96. <note><para>The protocol has tight delay bounds. Please use short frames and disable/keep short the
  97. jitter buffer on the ATA to make sure that respones (ACK etc.) are received in time.</para></note>
  98. </description>
  99. </application>
  100. ***/
  101. /* #define OUTALAW */ /* enable this to output Alaw rather than linear */
  102. /* ToDo */
  103. /* Add full VP support */
  104. /* Handle status report messages (generation and reception) */
  105. /* Time zones on time stamps */
  106. /* user ref field */
  107. static volatile unsigned char message_ref; /* arbitary message ref */
  108. static volatile unsigned int seq; /* arbitrary message sequence number for unqiue files */
  109. static char log_file[255];
  110. static char *app = "SMS";
  111. /*
  112. * 80 samples of a single period of the wave. At 8000 Hz, it means these
  113. * are the samples of a 100 Hz signal.
  114. * To pick the two carriers (1300Hz for '1' and 2100 Hz for '0') used by
  115. * the modulation, we should take one every 13 and 21 samples respectively.
  116. */
  117. static const signed short wave[] = {
  118. 0, 392, 782, 1167, 1545, 1913, 2270, 2612, 2939, 3247, 3536, 3802, 4045, 4263, 4455, 4619, 4755, 4862, 4938, 4985,
  119. 5000, 4985, 4938, 4862, 4755, 4619, 4455, 4263, 4045, 3802, 3536, 3247, 2939, 2612, 2270, 1913, 1545, 1167, 782, 392,
  120. 0, -392, -782, -1167,
  121. -1545, -1913, -2270, -2612, -2939, -3247, -3536, -3802, -4045, -4263, -4455, -4619, -4755, -4862, -4938, -4985, -5000,
  122. -4985, -4938, -4862,
  123. -4755, -4619, -4455, -4263, -4045, -3802, -3536, -3247, -2939, -2612, -2270, -1913, -1545, -1167, -782, -392
  124. };
  125. #ifdef OUTALAW
  126. static unsigned char wavea[80];
  127. typedef unsigned char output_t;
  128. static const output_t *wave_out = wavea; /* outgoing samples */
  129. #define __OUT_FMT AST_FORMAT_ALAW;
  130. #else
  131. typedef signed short output_t;
  132. static const output_t *wave_out = wave; /* outgoing samples */
  133. #define __OUT_FMT AST_FORMAT_SLINEAR
  134. #endif
  135. #define OSYNC_BITS 80 /* initial sync bits */
  136. /*!
  137. * The SMS spec ETSI ES 201 912 defines two protocols with different message types.
  138. * Also note that the high bit is used to indicate whether the message
  139. * is complete or not, but in two opposite ways:
  140. * for Protocol 1, 0x80 means that the message is complete;
  141. * for Protocol 2, 0x00 means that the message is complete;
  142. */
  143. enum message_types {
  144. DLL_SMS_MASK = 0x7f, /* mask for the valid bits */
  145. /* Protocol 1 values */
  146. DLL1_SMS_DATA = 0x11, /* data packet */
  147. DLL1_SMS_ERROR = 0x12,
  148. DLL1_SMS_EST = 0x13, /* start the connection */
  149. DLL1_SMS_REL = 0x14, /* end the connection */
  150. DLL1_SMS_ACK = 0x15,
  151. DLL1_SMS_NACK = 0x16,
  152. DLL1_SMS_COMPLETE = 0x80, /* packet is complete */
  153. DLL1_SMS_MORE = 0x00, /* more data to follow */
  154. /* Protocol 2 values */
  155. DLL2_SMS_EST = 0x7f, /* magic number. No message body */
  156. DLL2_SMS_INFO_MO = 0x10,
  157. DLL2_SMS_INFO_MT = 0x11,
  158. DLL2_SMS_INFO_STA = 0x12,
  159. DLL2_SMS_NACK = 0x13,
  160. DLL2_SMS_ACK0 = 0x14, /* ack even-numbered frame */
  161. DLL2_SMS_ACK1 = 0x15, /* ack odd-numbered frame */
  162. DLL2_SMS_ENQ = 0x16,
  163. DLL2_SMS_REL = 0x17, /* end the connection */
  164. DLL2_SMS_COMPLETE = 0x00, /* packet is complete */
  165. DLL2_SMS_MORE = 0x80, /* more data to follow */
  166. };
  167. /* SMS 7 bit character mapping to UCS-2 */
  168. static const unsigned short defaultalphabet[] = {
  169. 0x0040, 0x00A3, 0x0024, 0x00A5, 0x00E8, 0x00E9, 0x00F9, 0x00EC,
  170. 0x00F2, 0x00E7, 0x000A, 0x00D8, 0x00F8, 0x000D, 0x00C5, 0x00E5,
  171. 0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0, 0x03A8,
  172. 0x03A3, 0x0398, 0x039E, 0x00A0, 0x00C6, 0x00E6, 0x00DF, 0x00C9,
  173. ' ', '!', '"', '#', 164, '%', '&', 39, '(', ')', '*', '+', ',', '-', '.', '/',
  174. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
  175. 161, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  176. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 196, 214, 209, 220, 167,
  177. 191, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  178. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 228, 246, 241, 252, 224,
  179. };
  180. static const unsigned short escapes[] = {
  181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x000C, 0, 0, 0, 0, 0,
  182. 0, 0, 0, 0, 0x005E, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  183. 0, 0, 0, 0, 0, 0, 0, 0, 0x007B, 0x007D, 0, 0, 0, 0, 0, 0x005C,
  184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x005B, 0x007E, 0x005D, 0,
  185. 0x007C, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  187. 0, 0, 0, 0, 0, 0x20AC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  189. };
  190. #define SMSLEN 160 /*!< max SMS length */
  191. #define SMSLEN_8 140 /*!< max SMS length for 8-bit char */
  192. typedef struct sms_s {
  193. unsigned char hangup; /*!< we are done... */
  194. unsigned char err; /*!< set for any errors */
  195. unsigned char smsc:1; /*!< we are SMSC */
  196. unsigned char rx:1; /*!< this is a received message */
  197. char queue[30]; /*!< queue name */
  198. char oa[20]; /*!< originating address */
  199. char da[20]; /*!< destination address */
  200. struct timeval scts; /*!< time stamp, UTC */
  201. unsigned char pid; /*!< protocol ID */
  202. unsigned char dcs; /*!< data coding scheme */
  203. short mr; /*!< message reference - actually a byte, but use -1 for not set */
  204. int udl; /*!< user data length */
  205. int udhl; /*!< user data header length */
  206. unsigned char srr:1; /*!< Status Report request */
  207. unsigned char udhi:1; /*!< User Data Header required, even if length 0 */
  208. unsigned char rp:1; /*!< Reply Path */
  209. unsigned int vp; /*!< validity period in minutes, 0 for not set */
  210. unsigned short ud[SMSLEN]; /*!< user data (message), UCS-2 coded */
  211. unsigned char udh[SMSLEN]; /*!< user data header */
  212. char cli[20]; /*!< caller ID */
  213. unsigned char ophase; /*!< phase (0-79) for 0 and 1 frequencies (1300Hz and 2100Hz) */
  214. unsigned char ophasep; /*!< phase (0-79) for 1200 bps */
  215. unsigned char obyte; /*!< byte being sent */
  216. unsigned int opause; /*!< silent pause before sending (in sample periods) */
  217. unsigned char obitp; /*!< bit in byte */
  218. unsigned char osync; /*!< sync bits to send */
  219. unsigned char obytep; /*!< byte in data */
  220. unsigned char obyten; /*!< bytes in data */
  221. unsigned char omsg[256]; /*!< data buffer (out) */
  222. unsigned char imsg[250]; /*!< data buffer (in) */
  223. signed long long ims0,
  224. imc0,
  225. ims1,
  226. imc1; /*!< magnitude averages sin/cos 0/1 */
  227. unsigned int idle;
  228. unsigned short imag; /*!< signal level */
  229. unsigned char ips0; /*!< phase sin for bit 0, start at 0 inc by 21 mod 80 */
  230. unsigned char ips1; /*!< phase cos for bit 0, start at 20 inc by 21 mod 80 */
  231. unsigned char ipc0; /*!< phase sin for bit 1, start at 0 inc by 13 mod 80 */
  232. unsigned char ipc1; /*!< phase cos for bit 1, start at 20 inc by 13 mod 80 */
  233. unsigned char ibitl; /*!< last bit */
  234. unsigned char ibitc; /*!< bit run length count */
  235. unsigned char iphasep; /*!< bit phase (0-79) for 1200 bps */
  236. unsigned char ibitn; /*!< bit number in byte being received */
  237. unsigned char ibytev; /*!< byte value being received */
  238. unsigned char ibytep; /*!< byte pointer in message */
  239. unsigned char ibytec; /*!< byte checksum for message */
  240. unsigned char ierr; /*!< error flag */
  241. unsigned char ibith; /*!< history of last bits */
  242. unsigned char ibitt; /*!< total of 1's in last 3 bytes */
  243. /* more to go here */
  244. int opause_0; /*!< initial delay in ms, p() option */
  245. int protocol; /*!< ETSI SMS protocol to use (passed at app call) */
  246. int oseizure; /*!< protocol 2: channel seizure bits to send */
  247. int framenumber; /*!< protocol 2: frame number (for sending ACK0 or ACK1) */
  248. char udtxt[SMSLEN]; /*!< user data (message), PLAIN text */
  249. } sms_t;
  250. /* different types of encoding */
  251. #define is7bit(dcs) ( ((dcs) & 0xC0) ? (!((dcs) & 4) ) : (((dcs) & 0xc) == 0) )
  252. #define is8bit(dcs) ( ((dcs) & 0xC0) ? ( ((dcs) & 4) ) : (((dcs) & 0xc) == 4) )
  253. #define is16bit(dcs) ( ((dcs) & 0xC0) ? 0 : (((dcs) & 0xc) == 8) )
  254. static void sms_messagetx(sms_t *h);
  255. /*! \brief copy number, skipping non digits apart from leading + */
  256. static void numcpy(char *d, char *s)
  257. {
  258. if (*s == '+') {
  259. *d++ = *s++;
  260. }
  261. while (*s) {
  262. if (isdigit(*s)) {
  263. *d++ = *s;
  264. }
  265. s++;
  266. }
  267. *d = 0;
  268. }
  269. /*! \brief static, return a date/time in ISO format */
  270. static char *isodate(time_t t, char *buf, int len)
  271. {
  272. struct ast_tm tm;
  273. struct timeval local = { t, 0 };
  274. ast_localtime(&local, &tm, NULL);
  275. ast_strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
  276. return buf;
  277. }
  278. /*! \brief Reads next UCS character from NUL terminated UTF-8 string and advance pointer */
  279. /* for non valid UTF-8 sequences, returns character as is */
  280. /* Does not advance pointer for null termination */
  281. static long utf8decode(unsigned char **pp)
  282. {
  283. unsigned char *p = *pp;
  284. if (!*p) {
  285. return 0; /* null termination of string */
  286. }
  287. (*pp)++;
  288. if (*p < 0xC0) {
  289. return *p; /* ascii or continuation character */
  290. }
  291. if (*p < 0xE0) {
  292. if (*p < 0xC2 || (p[1] & 0xC0) != 0x80) {
  293. return *p; /* not valid UTF-8 */
  294. }
  295. (*pp)++;
  296. return ((*p & 0x1F) << 6) + (p[1] & 0x3F);
  297. }
  298. if (*p < 0xF0) {
  299. if ((*p == 0xE0 && p[1] < 0xA0) || (p[1] & 0xC0) != 0x80 || (p[2] & 0xC0) != 0x80) {
  300. return *p; /* not valid UTF-8 */
  301. }
  302. (*pp) += 2;
  303. return ((*p & 0x0F) << 12) + ((p[1] & 0x3F) << 6) + (p[2] & 0x3F);
  304. }
  305. if (*p < 0xF8) {
  306. if ((*p == 0xF0 && p[1] < 0x90) || (p[1] & 0xC0) != 0x80 || (p[2] & 0xC0) != 0x80 || (p[3] & 0xC0) != 0x80) {
  307. return *p; /* not valid UTF-8 */
  308. }
  309. (*pp) += 3;
  310. return ((*p & 0x07) << 18) + ((p[1] & 0x3F) << 12) + ((p[2] & 0x3F) << 6) + (p[3] & 0x3F);
  311. }
  312. if (*p < 0xFC) {
  313. if ((*p == 0xF8 && p[1] < 0x88) || (p[1] & 0xC0) != 0x80 || (p[2] & 0xC0) != 0x80 || (p[3] & 0xC0) != 0x80
  314. || (p[4] & 0xC0) != 0x80) {
  315. return *p; /* not valid UTF-8 */
  316. }
  317. (*pp) += 4;
  318. return ((*p & 0x03) << 24) + ((p[1] & 0x3F) << 18) + ((p[2] & 0x3F) << 12) + ((p[3] & 0x3F) << 6) + (p[4] & 0x3F);
  319. }
  320. if (*p < 0xFE) {
  321. if ((*p == 0xFC && p[1] < 0x84) || (p[1] & 0xC0) != 0x80 || (p[2] & 0xC0) != 0x80 || (p[3] & 0xC0) != 0x80
  322. || (p[4] & 0xC0) != 0x80 || (p[5] & 0xC0) != 0x80) {
  323. return *p; /* not valid UTF-8 */
  324. }
  325. (*pp) += 5;
  326. return ((*p & 0x01) << 30) + ((p[1] & 0x3F) << 24) + ((p[2] & 0x3F) << 18) + ((p[3] & 0x3F) << 12) + ((p[4] & 0x3F) << 6) + (p[5] & 0x3F);
  327. }
  328. return *p; /* not sensible */
  329. }
  330. /*! \brief takes a binary header (udhl bytes at udh) and UCS-2 message (udl characters at ud) and packs in to o using SMS 7 bit character codes */
  331. /* The return value is the number of septets packed in to o, which is internally limited to SMSLEN */
  332. /* o can be null, in which case this is used to validate or count only */
  333. /* if the input contains invalid characters then the return value is -1 */
  334. static int packsms7(unsigned char *o, int udhl, unsigned char *udh, int udl, unsigned short *ud)
  335. {
  336. unsigned char p = 0; /* output pointer (bytes) */
  337. unsigned char b = 0; /* bit position */
  338. unsigned char n = 0; /* output character count */
  339. unsigned char dummy[SMSLEN];
  340. if (o == NULL) { /* output to a dummy buffer if o not set */
  341. o = dummy;
  342. }
  343. if (udhl) { /* header */
  344. o[p++] = udhl;
  345. b = 1;
  346. n = 1;
  347. while (udhl--) {
  348. o[p++] = *udh++;
  349. b += 8;
  350. while (b >= 7) {
  351. b -= 7;
  352. n++;
  353. }
  354. if (n >= SMSLEN)
  355. return n;
  356. }
  357. if (b) {
  358. b = 7 - b;
  359. if (++n >= SMSLEN)
  360. return n;
  361. } /* filling to septet boundary */
  362. }
  363. o[p] = 0;
  364. /* message */
  365. while (udl--) {
  366. long u;
  367. unsigned char v;
  368. u = *ud++;
  369. /* XXX 0 is invalid ? */
  370. /* look up in defaultalphabet[]. If found, v is the 7-bit code */
  371. for (v = 0; v < 128 && defaultalphabet[v] != u; v++);
  372. if (v == 128 /* not found */ && u && n + 1 < SMSLEN) {
  373. /* if not found, look in the escapes table (we need 2 bytes) */
  374. for (v = 0; v < 128 && escapes[v] != u; v++);
  375. if (v < 128) { /* escaped sequence, esc + v */
  376. /* store the low (8-b) bits in o[p], the remaining bits in o[p+1] */
  377. o[p] |= (27 << b); /* the low bits go into o[p] */
  378. b += 7;
  379. if (b >= 8) {
  380. b -= 8;
  381. p++;
  382. o[p] = (27 >> (7 - b));
  383. }
  384. n++;
  385. }
  386. }
  387. if (v == 128)
  388. return -1; /* invalid character */
  389. /* store, same as above */
  390. o[p] |= (v << b);
  391. b += 7;
  392. if (b >= 8) {
  393. b -= 8;
  394. p++;
  395. o[p] = (v >> (7 - b));
  396. }
  397. if (++n >= SMSLEN)
  398. return n;
  399. }
  400. return n;
  401. }
  402. /*! \brief takes a binary header (udhl bytes at udh) and UCS-2 message (udl characters at ud)
  403. * and packs in to o using 8 bit character codes.
  404. * The return value is the number of bytes packed in to o, which is internally limited to 140.
  405. * o can be null, in which case this is used to validate or count only.
  406. * if the input contains invalid characters then the return value is -1
  407. */
  408. static int packsms8(unsigned char *o, int udhl, unsigned char *udh, int udl, unsigned short *ud)
  409. {
  410. unsigned char p = 0;
  411. unsigned char dummy[SMSLEN_8];
  412. if (o == NULL)
  413. o = dummy;
  414. /* header - no encoding */
  415. if (udhl) {
  416. o[p++] = udhl;
  417. while (udhl--) {
  418. o[p++] = *udh++;
  419. if (p >= SMSLEN_8) {
  420. return p;
  421. }
  422. }
  423. }
  424. while (udl--) {
  425. long u;
  426. u = *ud++;
  427. if (u < 0 || u > 0xFF) {
  428. return -1; /* not valid */
  429. }
  430. o[p++] = u;
  431. if (p >= SMSLEN_8) {
  432. return p;
  433. }
  434. }
  435. return p;
  436. }
  437. /*! \brief takes a binary header (udhl bytes at udh) and UCS-2
  438. message (udl characters at ud) and packs in to o using 16 bit
  439. UCS-2 character codes
  440. The return value is the number of bytes packed in to o, which is
  441. internally limited to 140
  442. o can be null, in which case this is used to validate or count
  443. only if the input contains invalid characters then
  444. the return value is -1 */
  445. static int packsms16(unsigned char *o, int udhl, unsigned char *udh, int udl, unsigned short *ud)
  446. {
  447. unsigned char p = 0;
  448. unsigned char dummy[SMSLEN_8];
  449. if (o == NULL) {
  450. o = dummy;
  451. }
  452. /* header - no encoding */
  453. if (udhl) {
  454. o[p++] = udhl;
  455. while (udhl--) {
  456. o[p++] = *udh++;
  457. if (p >= SMSLEN_8) {
  458. return p;
  459. }
  460. }
  461. }
  462. while (udl--) {
  463. long u;
  464. u = *ud++;
  465. o[p++] = (u >> 8);
  466. if (p >= SMSLEN_8) {
  467. return p - 1; /* could not fit last character */
  468. }
  469. o[p++] = u;
  470. if (p >= SMSLEN_8) {
  471. return p;
  472. }
  473. }
  474. return p;
  475. }
  476. /*! \brief general pack, with length and data,
  477. returns number of bytes of target used */
  478. static int packsms(unsigned char dcs, unsigned char *base, unsigned int udhl, unsigned char *udh, int udl, unsigned short *ud)
  479. {
  480. unsigned char *p = base;
  481. if (udl == 0) {
  482. *p++ = 0; /* no user data */
  483. } else {
  484. int l = 0;
  485. if (is7bit(dcs)) { /* 7 bit */
  486. if ((l = packsms7(p + 1, udhl, udh, udl, ud)) < 0) {
  487. l = 0;
  488. }
  489. *p++ = l;
  490. p += (l * 7 + 7) / 8;
  491. } else if (is8bit(dcs)) { /* 8 bit */
  492. if ((l = packsms8(p + 1, udhl, udh, udl, ud)) < 0) {
  493. l = 0;
  494. }
  495. *p++ = l;
  496. p += l;
  497. } else { /* UCS-2 */
  498. if ((l = packsms16(p + 1, udhl, udh, udl, ud)) < 0) {
  499. l = 0;
  500. }
  501. *p++ = l;
  502. p += l;
  503. }
  504. }
  505. return p - base;
  506. }
  507. /*! \brief pack a date and return */
  508. static void packdate(unsigned char *o, time_t w)
  509. {
  510. struct ast_tm t;
  511. struct timeval topack = { w, 0 };
  512. int z;
  513. ast_localtime(&topack, &t, NULL);
  514. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined( __NetBSD__ ) || defined(__APPLE__) || defined(__CYGWIN__)
  515. z = -t.tm_gmtoff / 60 / 15;
  516. #else
  517. z = timezone / 60 / 15;
  518. #endif
  519. *o++ = ((t.tm_year % 10) << 4) + (t.tm_year % 100) / 10;
  520. *o++ = (((t.tm_mon + 1) % 10) << 4) + (t.tm_mon + 1) / 10;
  521. *o++ = ((t.tm_mday % 10) << 4) + t.tm_mday / 10;
  522. *o++ = ((t.tm_hour % 10) << 4) + t.tm_hour / 10;
  523. *o++ = ((t.tm_min % 10) << 4) + t.tm_min / 10;
  524. *o++ = ((t.tm_sec % 10) << 4) + t.tm_sec / 10;
  525. if (z < 0) {
  526. *o++ = (((-z) % 10) << 4) + (-z) / 10 + 0x08;
  527. } else {
  528. *o++ = ((z % 10) << 4) + z / 10;
  529. }
  530. }
  531. /*! \brief unpack a date and return */
  532. static struct timeval unpackdate(unsigned char *i)
  533. {
  534. struct ast_tm t;
  535. t.tm_year = 100 + (i[0] & 0xF) * 10 + (i[0] >> 4);
  536. t.tm_mon = (i[1] & 0xF) * 10 + (i[1] >> 4) - 1;
  537. t.tm_mday = (i[2] & 0xF) * 10 + (i[2] >> 4);
  538. t.tm_hour = (i[3] & 0xF) * 10 + (i[3] >> 4);
  539. t.tm_min = (i[4] & 0xF) * 10 + (i[4] >> 4);
  540. t.tm_sec = (i[5] & 0xF) * 10 + (i[5] >> 4);
  541. t.tm_isdst = 0;
  542. if (i[6] & 0x08) {
  543. t.tm_min += 15 * ((i[6] & 0x7) * 10 + (i[6] >> 4));
  544. } else {
  545. t.tm_min -= 15 * ((i[6] & 0x7) * 10 + (i[6] >> 4));
  546. }
  547. return ast_mktime(&t, NULL);
  548. }
  549. /*! \brief unpacks bytes (7 bit encoding) at i, len l septets,
  550. and places in udh and ud setting udhl and udl. udh not used
  551. if udhi not set */
  552. static void unpacksms7(unsigned char *i, unsigned char l, unsigned char *udh, int *udhl, unsigned short *ud, int *udl, char udhi)
  553. {
  554. unsigned char b = 0, p = 0;
  555. unsigned short *o = ud;
  556. *udhl = 0;
  557. if (udhi && l) { /* header */
  558. int h = i[p];
  559. *udhl = h;
  560. if (h) {
  561. b = 1;
  562. p++;
  563. l--;
  564. while (h-- && l) {
  565. *udh++ = i[p++];
  566. b += 8;
  567. while (b >= 7) {
  568. b -= 7;
  569. l--;
  570. if (!l) {
  571. break;
  572. }
  573. }
  574. }
  575. /* adjust for fill, septets */
  576. if (b) {
  577. b = 7 - b;
  578. l--;
  579. }
  580. }
  581. }
  582. while (l--) {
  583. unsigned char v;
  584. if (b < 2) {
  585. v = ((i[p] >> b) & 0x7F); /* everything in one byte */
  586. } else {
  587. v = ((((i[p] >> b) + (i[p + 1] << (8 - b)))) & 0x7F);
  588. }
  589. b += 7;
  590. if (b >= 8) {
  591. b -= 8;
  592. p++;
  593. }
  594. /* 0x00A0 is the encoding of ESC (27) in defaultalphabet */
  595. if (o > ud && o[-1] == 0x00A0 && escapes[v]) {
  596. o[-1] = escapes[v];
  597. } else {
  598. *o++ = defaultalphabet[v];
  599. }
  600. }
  601. *udl = (o - ud);
  602. }
  603. /*! \brief unpacks bytes (8 bit encoding) at i, len l septets,
  604. * and places in udh and ud setting udhl and udl. udh not used
  605. * if udhi not set.
  606. */
  607. static void unpacksms8(unsigned char *i, unsigned char l, unsigned char *udh, int *udhl, unsigned short *ud, int *udl, char udhi)
  608. {
  609. unsigned short *o = ud;
  610. *udhl = 0;
  611. if (udhi) {
  612. int n = *i;
  613. *udhl = n;
  614. if (n) {
  615. i++;
  616. l--;
  617. while (l && n) {
  618. l--;
  619. n--;
  620. *udh++ = *i++;
  621. }
  622. }
  623. }
  624. while (l--) {
  625. *o++ = *i++; /* not to UTF-8 as explicitly 8 bit coding in DCS */
  626. }
  627. *udl = (o - ud);
  628. }
  629. /*! \brief unpacks bytes (16 bit encoding) at i, len l septets,
  630. and places in udh and ud setting udhl and udl.
  631. udh not used if udhi not set */
  632. static void unpacksms16(unsigned char *i, unsigned char l, unsigned char *udh, int *udhl, unsigned short *ud, int *udl, char udhi)
  633. {
  634. unsigned short *o = ud;
  635. *udhl = 0;
  636. if (udhi) {
  637. int n = *i;
  638. *udhl = n;
  639. if (n) {
  640. i++;
  641. l--;
  642. while (l && n) {
  643. l--;
  644. n--;
  645. *udh++ = *i++;
  646. }
  647. }
  648. }
  649. while (l--) {
  650. int v = *i++;
  651. if (l--) {
  652. v = (v << 8) + *i++;
  653. }
  654. *o++ = v;
  655. }
  656. *udl = (o - ud);
  657. }
  658. /*! \brief general unpack - starts with length byte (octet or septet) and returns number of bytes used, inc length */
  659. static int unpacksms(unsigned char dcs, unsigned char *i, unsigned char *udh, int *udhl, unsigned short *ud, int *udl, char udhi)
  660. {
  661. int l = *i++;
  662. if (is7bit(dcs)) {
  663. unpacksms7(i, l, udh, udhl, ud, udl, udhi);
  664. l = (l * 7 + 7) / 8; /* adjust length to return */
  665. } else if (is8bit(dcs)) {
  666. unpacksms8(i, l, udh, udhl, ud, udl, udhi);
  667. } else {
  668. unpacksms16(i, l, udh, udhl, ud, udl, udhi);
  669. }
  670. return l + 1;
  671. }
  672. /*! \brief unpack an address from i, return byte length, unpack to o */
  673. static unsigned char unpackaddress(char *o, unsigned char *i)
  674. {
  675. unsigned char l = i[0], p;
  676. if (i[1] == 0x91) {
  677. *o++ = '+';
  678. }
  679. for (p = 0; p < l; p++) {
  680. if (p & 1) {
  681. *o++ = (i[2 + p / 2] >> 4) + '0';
  682. } else {
  683. *o++ = (i[2 + p / 2] & 0xF) + '0';
  684. }
  685. }
  686. *o = 0;
  687. return (l + 5) / 2;
  688. }
  689. /*! \brief store an address at o, and return number of bytes used */
  690. static unsigned char packaddress(unsigned char *o, char *i)
  691. {
  692. unsigned char p = 2;
  693. o[0] = 0; /* number of bytes */
  694. if (*i == '+') { /* record as bit 0 in byte 1 */
  695. i++;
  696. o[1] = 0x91;
  697. } else {
  698. o[1] = 0x81;
  699. }
  700. for ( ; *i ; i++) {
  701. if (!isdigit(*i)) { /* ignore non-digits */
  702. continue;
  703. }
  704. if (o[0] & 1) {
  705. o[p++] |= ((*i & 0xF) << 4);
  706. } else {
  707. o[p] = (*i & 0xF);
  708. }
  709. o[0]++;
  710. }
  711. if (o[0] & 1) {
  712. o[p++] |= 0xF0; /* pad */
  713. }
  714. return p;
  715. }
  716. /*! \brief Log the output, and remove file */
  717. static void sms_log(sms_t * h, char status)
  718. {
  719. int o;
  720. if (*h->oa == '\0' && *h->da == '\0') {
  721. return;
  722. }
  723. o = open(log_file, O_CREAT | O_APPEND | O_WRONLY, AST_FILE_MODE);
  724. if (o >= 0) {
  725. char line[1000], mrs[3] = "", *p;
  726. char buf[30];
  727. unsigned char n;
  728. if (h->mr >= 0) {
  729. snprintf(mrs, sizeof(mrs), "%02X", h->mr);
  730. }
  731. snprintf(line, sizeof(line), "%s %c%c%c%s %s %s %s ",
  732. isodate(time(NULL), buf, sizeof(buf)),
  733. status, h->rx ? 'I' : 'O', h->smsc ? 'S' : 'M', mrs, h->queue,
  734. S_OR(h->oa, "-"), S_OR(h->da, "-") );
  735. p = line + strlen(line);
  736. for (n = 0; n < h->udl; n++) {
  737. if (h->ud[n] == '\\') {
  738. *p++ = '\\';
  739. *p++ = '\\';
  740. } else if (h->ud[n] == '\n') {
  741. *p++ = '\\';
  742. *p++ = 'n';
  743. } else if (h->ud[n] == '\r') {
  744. *p++ = '\\';
  745. *p++ = 'r';
  746. } else if (h->ud[n] < 32 || h->ud[n] == 127) {
  747. *p++ = 191;
  748. } else {
  749. *p++ = h->ud[n];
  750. }
  751. }
  752. *p++ = '\n';
  753. *p = 0;
  754. if (write(o, line, strlen(line)) < 0) {
  755. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  756. }
  757. close(o);
  758. }
  759. *h->oa = *h->da = h->udl = 0;
  760. }
  761. /*! \brief parse and delete a file */
  762. static void sms_readfile(sms_t * h, char *fn)
  763. {
  764. char line[1000];
  765. FILE *s;
  766. char dcsset = 0; /* if DSC set */
  767. ast_log(LOG_NOTICE, "Sending %s\n", fn);
  768. h->rx = h->udl = *h->oa = *h->da = h->pid = h->srr = h->udhi = h->rp = h->vp = h->udhl = 0;
  769. h->mr = -1;
  770. h->dcs = 0xF1; /* normal messages class 1 */
  771. h->scts = ast_tvnow();
  772. s = fopen(fn, "r");
  773. if (s) {
  774. if (unlink(fn)) { /* concurrent access, we lost */
  775. fclose(s);
  776. return;
  777. }
  778. while (fgets (line, sizeof(line), s)) { /* process line in file */
  779. char *p;
  780. void *pp = &p;
  781. for (p = line; *p && *p != '\n' && *p != '\r'; p++);
  782. *p = 0; /* strip eoln */
  783. p = line;
  784. if (!*p || *p == ';') {
  785. continue; /* blank line or comment, ignore */
  786. }
  787. while (isalnum(*p)) {
  788. *p = tolower (*p);
  789. p++;
  790. }
  791. while (isspace (*p)) {
  792. *p++ = 0;
  793. }
  794. if (*p == '=') {
  795. *p++ = 0;
  796. if (!strcmp(line, "ud")) { /* parse message (UTF-8) */
  797. unsigned char o = 0;
  798. memcpy(h->udtxt, p, SMSLEN); /* for protocol 2 */
  799. while (*p && o < SMSLEN) {
  800. h->ud[o++] = utf8decode(pp);
  801. }
  802. h->udl = o;
  803. if (*p) {
  804. ast_log(LOG_WARNING, "UD too long in %s\n", fn);
  805. }
  806. } else {
  807. while (isspace (*p)) {
  808. p++;
  809. }
  810. if (!strcmp(line, "oa") && strlen(p) < sizeof(h->oa)) {
  811. numcpy (h->oa, p);
  812. } else if (!strcmp(line, "da") && strlen(p) < sizeof(h->oa)) {
  813. numcpy (h->da, p);
  814. } else if (!strcmp(line, "pid")) {
  815. h->pid = atoi(p);
  816. } else if (!strcmp(line, "dcs")) {
  817. h->dcs = atoi(p);
  818. dcsset = 1;
  819. } else if (!strcmp(line, "mr")) {
  820. h->mr = atoi(p);
  821. } else if (!strcmp(line, "srr")) {
  822. h->srr = (atoi(p) ? 1 : 0);
  823. } else if (!strcmp(line, "vp")) {
  824. h->vp = atoi(p);
  825. } else if (!strcmp(line, "rp")) {
  826. h->rp = (atoi(p) ? 1 : 0);
  827. } else if (!strcmp(line, "scts")) { /* get date/time */
  828. int Y, m, d, H, M, S;
  829. /* XXX Why aren't we using ast_strptime here? */
  830. if (sscanf(p, "%4d-%2d-%2dT%2d:%2d:%2d", &Y, &m, &d, &H, &M, &S) == 6) {
  831. struct ast_tm t = { 0, };
  832. t.tm_year = Y - 1900;
  833. t.tm_mon = m - 1;
  834. t.tm_mday = d;
  835. t.tm_hour = H;
  836. t.tm_min = M;
  837. t.tm_sec = S;
  838. t.tm_isdst = -1;
  839. h->scts = ast_mktime(&t, NULL);
  840. if (h->scts.tv_sec == 0) {
  841. ast_log(LOG_WARNING, "Bad date/timein %s: %s", fn, p);
  842. }
  843. }
  844. } else {
  845. ast_log(LOG_WARNING, "Cannot parse in %s: %s=%si\n", fn, line, p);
  846. }
  847. }
  848. } else if (*p == '#') { /* raw hex format */
  849. *p++ = 0;
  850. if (*p == '#') {
  851. p++;
  852. if (!strcmp(line, "ud")) { /* user data */
  853. int o = 0;
  854. while (*p && o < SMSLEN) {
  855. if (isxdigit(*p) && isxdigit(p[1]) && isxdigit(p[2]) && isxdigit(p[3])) {
  856. h->ud[o++] =
  857. (((isalpha(*p) ? 9 : 0) + (*p & 0xF)) << 12) +
  858. (((isalpha(p[1]) ? 9 : 0) + (p[1] & 0xF)) << 8) +
  859. (((isalpha(p[2]) ? 9 : 0) + (p[2] & 0xF)) << 4) + ((isalpha(p[3]) ? 9 : 0) + (p[3] & 0xF));
  860. p += 4;
  861. } else
  862. break;
  863. }
  864. h->udl = o;
  865. if (*p)
  866. ast_log(LOG_WARNING, "UD too long / invalid UCS-2 hex in %s\n", fn);
  867. } else
  868. ast_log(LOG_WARNING, "Only ud can use ## format, %s\n", fn);
  869. } else if (!strcmp(line, "ud")) { /* user data */
  870. int o = 0;
  871. while (*p && o < SMSLEN) {
  872. if (isxdigit(*p) && isxdigit(p[1])) {
  873. h->ud[o++] = (((isalpha(*p) ? 9 : 0) + (*p & 0xF)) << 4) + ((isalpha(p[1]) ? 9 : 0) + (p[1] & 0xF));
  874. p += 2;
  875. } else {
  876. break;
  877. }
  878. }
  879. h->udl = o;
  880. if (*p) {
  881. ast_log(LOG_WARNING, "UD too long / invalid UCS-1 hex in %s\n", fn);
  882. }
  883. } else if (!strcmp(line, "udh")) { /* user data header */
  884. unsigned char o = 0;
  885. h->udhi = 1;
  886. while (*p && o < SMSLEN) {
  887. if (isxdigit(*p) && isxdigit(p[1])) {
  888. h->udh[o] = (((isalpha(*p) ? 9 : 0) + (*p & 0xF)) << 4) + ((isalpha(p[1]) ? 9 : 0) + (p[1] & 0xF));
  889. o++;
  890. p += 2;
  891. } else {
  892. break;
  893. }
  894. }
  895. h->udhl = o;
  896. if (*p) {
  897. ast_log(LOG_WARNING, "UDH too long / invalid hex in %s\n", fn);
  898. }
  899. } else {
  900. ast_log(LOG_WARNING, "Only ud and udh can use # format, %s\n", fn);
  901. }
  902. } else {
  903. ast_log(LOG_WARNING, "Cannot parse in %s: %s\n", fn, line);
  904. }
  905. }
  906. fclose(s);
  907. if (!dcsset && packsms7(0, h->udhl, h->udh, h->udl, h->ud) < 0) {
  908. if (packsms8(0, h->udhl, h->udh, h->udl, h->ud) < 0) {
  909. if (packsms16(0, h->udhl, h->udh, h->udl, h->ud) < 0) {
  910. ast_log(LOG_WARNING, "Invalid UTF-8 message even for UCS-2 (%s)\n", fn);
  911. } else {
  912. h->dcs = 0x08; /* default to 16 bit */
  913. ast_log(LOG_WARNING, "Sending in 16 bit format(%s)\n", fn);
  914. }
  915. } else {
  916. h->dcs = 0xF5; /* default to 8 bit */
  917. ast_log(LOG_WARNING, "Sending in 8 bit format(%s)\n", fn);
  918. }
  919. }
  920. if (is7bit(h->dcs) && packsms7(0, h->udhl, h->udh, h->udl, h->ud) < 0) {
  921. ast_log(LOG_WARNING, "Invalid 7 bit GSM data %s\n", fn);
  922. }
  923. if (is8bit(h->dcs) && packsms8(0, h->udhl, h->udh, h->udl, h->ud) < 0) {
  924. ast_log(LOG_WARNING, "Invalid 8 bit data %s\n", fn);
  925. }
  926. if (is16bit(h->dcs) && packsms16(0, h->udhl, h->udh, h->udl, h->ud) < 0) {
  927. ast_log(LOG_WARNING, "Invalid 16 bit data %s\n", fn);
  928. }
  929. }
  930. }
  931. /*! \brief white a received text message to a file */
  932. static void sms_writefile(sms_t * h)
  933. {
  934. char fn[200] = "", fn2[200] = "";
  935. char buf[30];
  936. FILE *o;
  937. if (ast_tvzero(h->scts)) {
  938. h->scts = ast_tvnow();
  939. }
  940. snprintf(fn, sizeof(fn), "%s/sms/%s", ast_config_AST_SPOOL_DIR, h->smsc ? h->rx ? "morx" : "mttx" : h->rx ? "mtrx" : "motx");
  941. ast_mkdir(fn, 0777); /* ensure it exists */
  942. ast_copy_string(fn2, fn, sizeof(fn2));
  943. snprintf(fn2 + strlen(fn2), sizeof(fn2) - strlen(fn2), "/%s.%s-%d", h->queue, isodate(h->scts.tv_sec, buf, sizeof(buf)), seq++);
  944. snprintf(fn + strlen(fn), sizeof(fn) - strlen(fn), "/.%s", fn2 + strlen(fn) + 1);
  945. if ((o = fopen(fn, "w")) == NULL) {
  946. return;
  947. }
  948. if (*h->oa) {
  949. fprintf(o, "oa=%s\n", h->oa);
  950. }
  951. if (*h->da) {
  952. fprintf(o, "da=%s\n", h->da);
  953. }
  954. if (h->udhi) {
  955. unsigned int p;
  956. fprintf(o, "udh#");
  957. for (p = 0; p < h->udhl; p++) {
  958. fprintf(o, "%02X", h->udh[p]);
  959. }
  960. fprintf(o, "\n");
  961. }
  962. if (h->udl) {
  963. unsigned int p;
  964. for (p = 0; p < h->udl && h->ud[p] >= ' '; p++);
  965. if (p < h->udl) {
  966. fputc(';', o); /* cannot use ud=, but include as a comment for human readable */
  967. }
  968. fprintf(o, "ud=");
  969. for (p = 0; p < h->udl; p++) {
  970. unsigned short v = h->ud[p];
  971. if (v < 32) {
  972. fputc(191, o);
  973. } else if (v < 0x80) {
  974. fputc(v, o);
  975. } else if (v < 0x800) {
  976. fputc(0xC0 + (v >> 6), o);
  977. fputc(0x80 + (v & 0x3F), o);
  978. } else {
  979. fputc(0xE0 + (v >> 12), o);
  980. fputc(0x80 + ((v >> 6) & 0x3F), o);
  981. fputc(0x80 + (v & 0x3F), o);
  982. }
  983. }
  984. fprintf(o, "\n");
  985. for (p = 0; p < h->udl && h->ud[p] >= ' '; p++);
  986. if (p < h->udl) {
  987. for (p = 0; p < h->udl && h->ud[p] < 0x100; p++);
  988. if (p == h->udl) { /* can write in ucs-1 hex */
  989. fprintf(o, "ud#");
  990. for (p = 0; p < h->udl; p++) {
  991. fprintf(o, "%02X", h->ud[p]);
  992. }
  993. fprintf(o, "\n");
  994. } else { /* write in UCS-2 */
  995. fprintf(o, "ud##");
  996. for (p = 0; p < h->udl; p++) {
  997. fprintf(o, "%04X", h->ud[p]);
  998. }
  999. fprintf(o, "\n");
  1000. }
  1001. }
  1002. }
  1003. if (h->scts.tv_sec) {
  1004. char datebuf[30];
  1005. fprintf(o, "scts=%s\n", isodate(h->scts.tv_sec, datebuf, sizeof(datebuf)));
  1006. }
  1007. if (h->pid) {
  1008. fprintf(o, "pid=%d\n", h->pid);
  1009. }
  1010. if (h->dcs != 0xF1) {
  1011. fprintf(o, "dcs=%d\n", h->dcs);
  1012. }
  1013. if (h->vp) {
  1014. fprintf(o, "vp=%d\n", h->vp);
  1015. }
  1016. if (h->srr) {
  1017. fprintf(o, "srr=1\n");
  1018. }
  1019. if (h->mr >= 0) {
  1020. fprintf(o, "mr=%d\n", h->mr);
  1021. }
  1022. if (h->rp) {
  1023. fprintf(o, "rp=1\n");
  1024. }
  1025. fclose(o);
  1026. if (rename(fn, fn2)) {
  1027. unlink(fn);
  1028. } else {
  1029. ast_log(LOG_NOTICE, "Received to %s\n", fn2);
  1030. }
  1031. }
  1032. /*! \brief read dir skipping dot files... */
  1033. static struct dirent *readdirqueue(DIR *d, char *queue)
  1034. {
  1035. struct dirent *f;
  1036. do {
  1037. f = readdir(d);
  1038. } while (f && (*f->d_name == '.' || strncmp(f->d_name, queue, strlen(queue)) || f->d_name[strlen(queue)] != '.'));
  1039. return f;
  1040. }
  1041. /*! \brief handle the incoming message */
  1042. static unsigned char sms_handleincoming (sms_t * h)
  1043. {
  1044. unsigned char p = 3;
  1045. if (h->smsc) { /* SMSC */
  1046. if ((h->imsg[2] & 3) == 1) { /* SMS-SUBMIT */
  1047. h->udhl = h->udl = 0;
  1048. h->vp = 0;
  1049. h->srr = ((h->imsg[2] & 0x20) ? 1 : 0);
  1050. h->udhi = ((h->imsg[2] & 0x40) ? 1 : 0);
  1051. h->rp = ((h->imsg[2] & 0x80) ? 1 : 0);
  1052. ast_copy_string(h->oa, h->cli, sizeof(h->oa));
  1053. h->scts = ast_tvnow();
  1054. h->mr = h->imsg[p++];
  1055. p += unpackaddress(h->da, h->imsg + p);
  1056. h->pid = h->imsg[p++];
  1057. h->dcs = h->imsg[p++];
  1058. if ((h->imsg[2] & 0x18) == 0x10) { /* relative VP */
  1059. if (h->imsg[p] < 144) {
  1060. h->vp = (h->imsg[p] + 1) * 5;
  1061. } else if (h->imsg[p] < 168) {
  1062. h->vp = 720 + (h->imsg[p] - 143) * 30;
  1063. } else if (h->imsg[p] < 197) {
  1064. h->vp = (h->imsg[p] - 166) * 1440;
  1065. } else {
  1066. h->vp = (h->imsg[p] - 192) * 10080;
  1067. }
  1068. p++;
  1069. } else if (h->imsg[2] & 0x18) {
  1070. p += 7; /* ignore enhanced / absolute VP */
  1071. }
  1072. p += unpacksms(h->dcs, h->imsg + p, h->udh, &h->udhl, h->ud, &h->udl, h->udhi);
  1073. h->rx = 1; /* received message */
  1074. sms_writefile(h); /* write the file */
  1075. if (p != h->imsg[1] + 2) {
  1076. ast_log(LOG_WARNING, "Mismatch receive unpacking %d/%d\n", p, h->imsg[1] + 2);
  1077. return 0xFF; /* duh! */
  1078. }
  1079. } else {
  1080. ast_log(LOG_WARNING, "Unknown message type %02X\n", h->imsg[2]);
  1081. return 0xFF;
  1082. }
  1083. } else { /* client */
  1084. if (!(h->imsg[2] & 3)) { /* SMS-DELIVER */
  1085. *h->da = h->srr = h->rp = h->vp = h->udhi = h->udhl = h->udl = 0;
  1086. h->srr = ((h->imsg[2] & 0x20) ? 1 : 0);
  1087. h->udhi = ((h->imsg[2] & 0x40) ? 1 : 0);
  1088. h->rp = ((h->imsg[2] & 0x80) ? 1 : 0);
  1089. h->mr = -1;
  1090. p += unpackaddress(h->oa, h->imsg + p);
  1091. h->pid = h->imsg[p++];
  1092. h->dcs = h->imsg[p++];
  1093. h->scts = unpackdate(h->imsg + p);
  1094. p += 7;
  1095. p += unpacksms(h->dcs, h->imsg + p, h->udh, &h->udhl, h->ud, &h->udl, h->udhi);
  1096. h->rx = 1; /* received message */
  1097. sms_writefile(h); /* write the file */
  1098. if (p != h->imsg[1] + 2) {
  1099. ast_log(LOG_WARNING, "Mismatch receive unpacking %d/%d\n", p, h->imsg[1] + 2);
  1100. return 0xFF; /* duh! */
  1101. }
  1102. } else {
  1103. ast_log(LOG_WARNING, "Unknown message type %02X\n", h->imsg[2]);
  1104. return 0xFF;
  1105. }
  1106. }
  1107. return 0; /* no error */
  1108. }
  1109. #ifdef SOLARIS
  1110. #define NAME_MAX 1024
  1111. #endif
  1112. /*!
  1113. * Add data to a protocol 2 message.
  1114. * Use the length field (h->omsg[1]) as a pointer to the next free position.
  1115. */
  1116. static void adddata_proto2(sms_t *h, unsigned char msg, char *data, int size)
  1117. {
  1118. int x = h->omsg[1] + 2; /* Get current position */
  1119. if (x == 2) {
  1120. x += 2; /* First: skip Payload length (set later) */
  1121. }
  1122. h->omsg[x++] = msg; /* Message code */
  1123. h->omsg[x++] = (unsigned char)size; /* Data size Low */
  1124. h->omsg[x++] = 0; /* Data size Hi */
  1125. for (; size > 0 ; size--) {
  1126. h->omsg[x++] = *data++;
  1127. }
  1128. h->omsg[1] = x - 2; /* Frame size */
  1129. h->omsg[2] = x - 4; /* Payload length (Lo) */
  1130. h->omsg[3] = 0; /* Payload length (Hi) */
  1131. }
  1132. static void putdummydata_proto2(sms_t *h)
  1133. {
  1134. adddata_proto2(h, 0x10, "\0", 1); /* Media Identifier > SMS */
  1135. adddata_proto2(h, 0x11, "\0\0\0\0\0\0", 6); /* Firmware version */
  1136. adddata_proto2(h, 0x12, "\2\0\4", 3); /* SMS provider ID */
  1137. adddata_proto2(h, 0x13, h->udtxt, h->udl); /* Body */
  1138. }
  1139. static void sms_compose2(sms_t *h, int more)
  1140. {
  1141. struct ast_tm tm;
  1142. struct timeval now = h->scts;
  1143. char stm[9];
  1144. h->omsg[0] = 0x00; /* set later... */
  1145. h->omsg[1] = 0;
  1146. putdummydata_proto2(h);
  1147. if (h->smsc) { /* deliver */
  1148. h->omsg[0] = 0x11; /* SMS_DELIVERY */
  1149. /* Required: 10 11 12 13 14 15 17 (seems they must be ordered!) */
  1150. ast_localtime(&now, &tm, NULL);
  1151. sprintf(stm, "%02d%02d%02d%02d", tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min); /* Date mmddHHMM */
  1152. adddata_proto2(h, 0x14, stm, 8); /* Date */
  1153. if (*h->oa == 0) {
  1154. strcpy(h->oa, "00000000");
  1155. }
  1156. adddata_proto2(h, 0x15, h->oa, strlen(h->oa)); /* Originator */
  1157. adddata_proto2(h, 0x17, "\1", 1); /* Calling Terminal ID */
  1158. } else { /* submit */
  1159. h->omsg[0] = 0x10; /* SMS_SUBMIT */
  1160. /* Required: 10 11 12 13 17 18 1B 1C (seems they must be ordered!) */
  1161. adddata_proto2(h, 0x17, "\1", 1); /* Calling Terminal ID */
  1162. if (*h->da == 0) {
  1163. strcpy(h->da, "00000000");
  1164. }
  1165. adddata_proto2(h, 0x18, h->da, strlen(h->da)); /* Originator */
  1166. adddata_proto2(h, 0x1B, "\1", 1); /* Called Terminal ID */
  1167. adddata_proto2(h, 0x1C, "\0\0\0", 3); /* Notification */
  1168. }
  1169. }
  1170. static void putdummydata_proto2(sms_t *h);
  1171. #define MAX_DEBUG_LEN 300
  1172. static char *sms_hexdump(unsigned char buf[], int size, char *s /* destination */)
  1173. {
  1174. char *p;
  1175. int f;
  1176. for (p = s, f = 0; f < size && f < MAX_DEBUG_LEN; f++, p += 3) {
  1177. sprintf(p, "%02X ", (unsigned char)buf[f]);
  1178. }
  1179. return(s);
  1180. }
  1181. /*! \brief sms_handleincoming_proto2: handle the incoming message */
  1182. static int sms_handleincoming_proto2(sms_t *h)
  1183. {
  1184. int f, i, sz = 0;
  1185. int msg, msgsz;
  1186. struct ast_tm tm;
  1187. struct timeval now = { 0, 0 };
  1188. char debug_buf[MAX_DEBUG_LEN * 3 + 1];
  1189. sz = h->imsg[1] + 2;
  1190. /* ast_verb(3, "SMS-P2 Frame: %s\n", sms_hexdump(h->imsg, sz, debug_buf)); */
  1191. /* Parse message body (called payload) */
  1192. now = h->scts = ast_tvnow();
  1193. for (f = 4; f < sz; ) {
  1194. msg = h->imsg[f++];
  1195. msgsz = h->imsg[f++];
  1196. msgsz += (h->imsg[f++] * 256);
  1197. switch (msg) {
  1198. case 0x13: /* Body */
  1199. ast_verb(3, "SMS-P2 Body#%02X=[%.*s]\n", msg, msgsz, &h->imsg[f]);
  1200. if (msgsz >= sizeof(h->imsg)) {
  1201. msgsz = sizeof(h->imsg) - 1;
  1202. }
  1203. for (i = 0; i < msgsz; i++) {
  1204. h->ud[i] = h->imsg[f + i];
  1205. }
  1206. h->udl = msgsz;
  1207. break;
  1208. case 0x14: /* Date SCTS */
  1209. now = h->scts = ast_tvnow();
  1210. ast_localtime(&now, &tm, NULL);
  1211. tm.tm_mon = ( (h->imsg[f] * 10) + h->imsg[f + 1] ) - 1;
  1212. tm.tm_mday = ( (h->imsg[f + 2] * 10) + h->imsg[f + 3] );
  1213. tm.tm_hour = ( (h->imsg[f + 4] * 10) + h->imsg[f + 5] );
  1214. tm.tm_min = ( (h->imsg[f + 6] * 10) + h->imsg[f + 7] );
  1215. tm.tm_sec = 0;
  1216. h->scts = ast_mktime(&tm, NULL);
  1217. ast_verb(3, "SMS-P2 Date#%02X=%02d/%02d %02d:%02d\n", msg, tm.tm_mday, tm.tm_mon + 1, tm.tm_hour, tm.tm_min);
  1218. break;
  1219. case 0x15: /* Calling line (from SMSC) */
  1220. if (msgsz >= 20) {
  1221. msgsz = 20 - 1;
  1222. }
  1223. ast_verb(3, "SMS-P2 Origin#%02X=[%.*s]\n", msg, msgsz, &h->imsg[f]);
  1224. ast_copy_string(h->oa, (char *)(&h->imsg[f]), msgsz + 1);
  1225. break;
  1226. case 0x18: /* Destination(from TE/phone) */
  1227. if (msgsz >= 20) {
  1228. msgsz = 20 - 1;
  1229. }
  1230. ast_verb(3, "SMS-P2 Destination#%02X=[%.*s]\n", msg, msgsz, &h->imsg[f]);
  1231. ast_copy_string(h->da, (char *)(&h->imsg[f]), msgsz + 1);
  1232. break;
  1233. case 0x1C: /* Notify */
  1234. ast_verb(3, "SMS-P2 Notify#%02X=%s\n", msg, sms_hexdump(&h->imsg[f], 3, debug_buf));
  1235. break;
  1236. default:
  1237. ast_verb(3, "SMS-P2 Par#%02X [%d]: %s\n", msg, msgsz, sms_hexdump(&h->imsg[f], msgsz, debug_buf));
  1238. break;
  1239. }
  1240. f+=msgsz; /* Skip to next */
  1241. }
  1242. h->rx = 1; /* received message */
  1243. sms_writefile(h); /* write the file */
  1244. return 0; /* no error */
  1245. }
  1246. #if 0
  1247. static void smssend(sms_t *h, char *c)
  1248. {
  1249. int f, x;
  1250. for (f = 0; f < strlen(c); f++) {
  1251. sscanf(&c[f*3], "%x", &x);
  1252. h->omsg[f] = x;
  1253. }
  1254. sms_messagetx(h);
  1255. }
  1256. #endif
  1257. static void sms_nextoutgoing (sms_t *h);
  1258. static void sms_messagerx2(sms_t * h)
  1259. {
  1260. int p = h->imsg[0] & DLL_SMS_MASK ; /* mask the high bit */
  1261. int cause;
  1262. #define DLL2_ACK(h) ((h->framenumber & 1) ? DLL2_SMS_ACK1: DLL2_SMS_ACK1)
  1263. switch (p) {
  1264. case DLL2_SMS_EST: /* Protocol 2: Connection ready (fake): send message */
  1265. sms_nextoutgoing (h);
  1266. /* smssend(h,"11 29 27 00 10 01 00 00 11 06 00 00 00 00 00 00 00 12 03 00 02 00 04 13 01 00 41 14 08 00 30 39 31 35 30 02 30 02 15 02 00 39 30 "); */
  1267. break;
  1268. case DLL2_SMS_INFO_MO: /* transport SMS_SUBMIT */
  1269. case DLL2_SMS_INFO_MT: /* transport SMS_DELIVERY */
  1270. cause = sms_handleincoming_proto2(h);
  1271. if (!cause) { /* ACK */
  1272. sms_log(h, 'Y');
  1273. }
  1274. h->omsg[0] = DLL2_ACK(h);
  1275. h->omsg[1] = 0x06; /* msg len */
  1276. h->omsg[2] = 0x04; /* payload len */
  1277. h->omsg[3] = 0x00; /* payload len */
  1278. h->omsg[4] = 0x1f; /* Response type */
  1279. h->omsg[5] = 0x01; /* parameter len */
  1280. h->omsg[6] = 0x00; /* parameter len */
  1281. h->omsg[7] = cause; /* CONFIRM or error */
  1282. sms_messagetx(h);
  1283. break;
  1284. case DLL2_SMS_NACK: /* Protocol 2: SMS_NAK */
  1285. h->omsg[0] = DLL2_SMS_REL; /* SMS_REL */
  1286. h->omsg[1] = 0x00; /* msg len */
  1287. sms_messagetx(h);
  1288. break;
  1289. case DLL2_SMS_ACK0:
  1290. case DLL2_SMS_ACK1:
  1291. /* SMS_ACK also transport SMS_SUBMIT or SMS_DELIVERY */
  1292. if ( (h->omsg[0] & DLL_SMS_MASK) == DLL2_SMS_REL) {
  1293. /* a response to our Release, just hangup */
  1294. h->hangup = 1; /* hangup */
  1295. } else {
  1296. /* XXX depending on what we are.. */
  1297. ast_log(LOG_NOTICE, "SMS_SUBMIT or SMS_DELIVERY");
  1298. sms_nextoutgoing (h);
  1299. }
  1300. break;
  1301. case DLL2_SMS_REL: /* Protocol 2: SMS_REL (hangup req) */
  1302. h->omsg[0] = DLL2_ACK(h);
  1303. h->omsg[1] = 0;
  1304. sms_messagetx(h);
  1305. break;
  1306. }
  1307. }
  1308. /*! \brief compose a message for protocol 1 */
  1309. static void sms_compose1(sms_t *h, int more)
  1310. {
  1311. unsigned int p = 2; /* next byte to write. Skip type and len */
  1312. h->omsg[0] = 0x91; /* SMS_DATA */
  1313. if (h->smsc) { /* deliver */
  1314. h->omsg[p++] = (more ? 4 : 0) + ((h->udhl > 0) ? 0x40 : 0);
  1315. p += packaddress(h->omsg + p, h->oa);
  1316. h->omsg[p++] = h->pid;
  1317. h->omsg[p++] = h->dcs;
  1318. packdate(h->omsg + p, h->scts.tv_sec);
  1319. p += 7;
  1320. p += packsms(h->dcs, h->omsg + p, h->udhl, h->udh, h->udl, h->ud);
  1321. } else { /* submit */
  1322. h->omsg[p++] =
  1323. 0x01 + (more ? 4 : 0) + (h->srr ? 0x20 : 0) + (h->rp ? 0x80 : 0) + (h->vp ? 0x10 : 0) + (h->udhi ? 0x40 : 0);
  1324. if (h->mr < 0) {
  1325. h->mr = message_ref++;
  1326. }
  1327. h->omsg[p++] = h->mr;
  1328. p += packaddress(h->omsg + p, h->da);
  1329. h->omsg[p++] = h->pid;
  1330. h->omsg[p++] = h->dcs;
  1331. if (h->vp) { /* relative VP */
  1332. if (h->vp < 720) {
  1333. h->omsg[p++] = (h->vp + 4) / 5 - 1;
  1334. } else if (h->vp < 1440) {
  1335. h->omsg[p++] = (h->vp - 720 + 29) / 30 + 143;
  1336. } else if (h->vp < 43200) {
  1337. h->omsg[p++] = (h->vp + 1439) / 1440 + 166;
  1338. } else if (h->vp < 635040) {
  1339. h->omsg[p++] = (h->vp + 10079) / 10080 + 192;
  1340. } else {
  1341. h->omsg[p++] = 255; /* max */
  1342. }
  1343. }
  1344. p += packsms(h->dcs, h->omsg + p, h->udhl, h->udh, h->udl, h->ud);
  1345. }
  1346. h->omsg[1] = p - 2;
  1347. }
  1348. /*! \brief find and fill in next message, or send a REL if none waiting */
  1349. static void sms_nextoutgoing (sms_t * h)
  1350. {
  1351. char fn[100 + NAME_MAX] = "";
  1352. DIR *d;
  1353. char more = 0;
  1354. *h->da = *h->oa = '\0'; /* clear destinations */
  1355. h->rx = 0; /* outgoing message */
  1356. snprintf(fn, sizeof(fn), "%s/sms/%s", ast_config_AST_SPOOL_DIR, h->smsc ? "mttx" : "motx");
  1357. ast_mkdir(fn, 0777); /* ensure it exists */
  1358. d = opendir(fn);
  1359. if (d) {
  1360. struct dirent *f = readdirqueue(d, h->queue);
  1361. if (f) {
  1362. snprintf(fn + strlen(fn), sizeof(fn) - strlen(fn), "/%s", f->d_name);
  1363. sms_readfile(h, fn);
  1364. if (readdirqueue(d, h->queue)) {
  1365. more = 1; /* more to send */
  1366. }
  1367. }
  1368. closedir(d);
  1369. }
  1370. if (*h->da || *h->oa) { /* message to send */
  1371. if (h->protocol == 2) {
  1372. sms_compose2(h, more);
  1373. } else {
  1374. sms_compose1(h, more);
  1375. }
  1376. } else { /* no message */
  1377. if (h->protocol == 2) {
  1378. h->omsg[0] = 0x17; /* SMS_REL */
  1379. h->omsg[1] = 0;
  1380. } else {
  1381. h->omsg[0] = 0x94; /* SMS_REL */
  1382. h->omsg[1] = 0;
  1383. }
  1384. }
  1385. sms_messagetx(h);
  1386. }
  1387. #define DIR_RX 1
  1388. #define DIR_TX 2
  1389. static void sms_debug (int dir, sms_t *h)
  1390. {
  1391. char txt[259 * 3 + 1];
  1392. char *p = txt; /* always long enough */
  1393. unsigned char *msg = (dir == DIR_RX) ? h->imsg : h->omsg;
  1394. int n = (dir == DIR_RX) ? h->ibytep : msg[1] + 2;
  1395. int q = 0;
  1396. while (q < n && q < 30) {
  1397. sprintf(p, " %02X", msg[q++]);
  1398. p += 3;
  1399. }
  1400. if (q < n) {
  1401. sprintf(p, "...");
  1402. }
  1403. ast_verb(3, "SMS %s%s\n", dir == DIR_RX ? "RX" : "TX", txt);
  1404. }
  1405. static void sms_messagerx(sms_t * h)
  1406. {
  1407. int cause;
  1408. sms_debug (DIR_RX, h);
  1409. if (h->protocol == 2) {
  1410. sms_messagerx2(h);
  1411. return;
  1412. }
  1413. /* parse incoming message for Protocol 1 */
  1414. switch (h->imsg[0]) {
  1415. case 0x91: /* SMS_DATA */
  1416. cause = sms_handleincoming (h);
  1417. if (!cause) {
  1418. sms_log(h, 'Y');
  1419. h->omsg[0] = 0x95; /* SMS_ACK */
  1420. h->omsg[1] = 0x02;
  1421. h->omsg[2] = 0x00; /* deliver report */
  1422. h->omsg[3] = 0x00; /* no parameters */
  1423. } else { /* NACK */
  1424. sms_log(h, 'N');
  1425. h->omsg[0] = 0x96; /* SMS_NACK */
  1426. h->omsg[1] = 3;
  1427. h->omsg[2] = 0; /* delivery report */
  1428. h->omsg[3] = cause; /* cause */
  1429. h->omsg[4] = 0; /* no parameters */
  1430. }
  1431. sms_messagetx(h);
  1432. break;
  1433. case 0x92: /* SMS_ERROR */
  1434. h->err = 1;
  1435. sms_messagetx(h); /* send whatever we sent again */
  1436. break;
  1437. case 0x93: /* SMS_EST */
  1438. sms_nextoutgoing (h);
  1439. break;
  1440. case 0x94: /* SMS_REL */
  1441. h->hangup = 1; /* hangup */
  1442. break;
  1443. case 0x95: /* SMS_ACK */
  1444. sms_log(h, 'Y');
  1445. sms_nextoutgoing (h);
  1446. break;
  1447. case 0x96: /* SMS_NACK */
  1448. h->err = 1;
  1449. sms_log(h, 'N');
  1450. sms_nextoutgoing (h);
  1451. break;
  1452. default: /* Unknown */
  1453. h->omsg[0] = 0x92; /* SMS_ERROR */
  1454. h->omsg[1] = 1;
  1455. h->omsg[2] = 3; /* unknown message type */
  1456. sms_messagetx(h);
  1457. break;
  1458. }
  1459. }
  1460. static void sms_messagetx(sms_t * h)
  1461. {
  1462. unsigned char c = 0, p;
  1463. int len = h->omsg[1] + 2; /* total message length excluding checksum */
  1464. for (p = 0; p < len; p++) { /* compute checksum */
  1465. c += h->omsg[p];
  1466. }
  1467. h->omsg[len] = 0 - c; /* actually, (256 - (c & 0fxx)) & 0xff) */
  1468. sms_debug(DIR_TX, h);
  1469. h->framenumber++; /* Proto 2 */
  1470. h->obytep = 0;
  1471. h->obitp = 0;
  1472. if (h->protocol == 2) { /* Proto 2: */
  1473. h->oseizure = 300; /* 300bits (or more ?) */
  1474. h->obyte = 0; /* Seizure starts with space (0) */
  1475. if (h->omsg[0] == 0x7F) {
  1476. h->opause = 8 * h->opause_0; /* initial message delay */
  1477. } else {
  1478. h->opause = 400;
  1479. }
  1480. } else { /* Proto 1: */
  1481. h->oseizure = 0; /* No seizure */
  1482. h->obyte = 1; /* send mark ('1') at the beginning */
  1483. /* Change the initial message delay. BT requires 300ms,
  1484. * but for others this might be way too much and the phone
  1485. * could time out. XXX make it configurable.
  1486. */
  1487. if (h->omsg[0] == 0x93) {
  1488. h->opause = 8 * h->opause_0; /* initial message delay */
  1489. } else {
  1490. h->opause = 200;
  1491. }
  1492. }
  1493. /* Note - setting osync triggers the generator */
  1494. h->osync = OSYNC_BITS; /* 80 sync bits */
  1495. h->obyten = len + 1; /* bytes to send (including checksum) */
  1496. }
  1497. /*!
  1498. * outgoing data are produced by this generator function, that reads from
  1499. * the descriptor whether it has data to send and which ones.
  1500. */
  1501. static int sms_generate(struct ast_channel *chan, void *data, int len, int samples)
  1502. {
  1503. struct ast_frame f = { 0 };
  1504. #define MAXSAMPLES (800)
  1505. output_t *buf;
  1506. sms_t *h = data;
  1507. int i;
  1508. if (samples > MAXSAMPLES) {
  1509. ast_log(LOG_WARNING, "Only doing %d samples (%d requested)\n",
  1510. MAXSAMPLES, samples);
  1511. samples = MAXSAMPLES;
  1512. }
  1513. len = samples * sizeof(*buf) + AST_FRIENDLY_OFFSET;
  1514. buf = alloca(len);
  1515. f.frametype = AST_FRAME_VOICE;
  1516. ast_format_set(&f.subclass.format, __OUT_FMT, 0);
  1517. f.datalen = samples * sizeof(*buf);
  1518. f.offset = AST_FRIENDLY_OFFSET;
  1519. f.mallocd = 0;
  1520. f.data.ptr = buf;
  1521. f.samples = samples;
  1522. f.src = "app_sms";
  1523. /* create a buffer containing the digital sms pattern */
  1524. for (i = 0; i < samples; i++) {
  1525. buf[i] = wave_out[0]; /* default is silence */
  1526. if (h->opause) {
  1527. h->opause--;
  1528. } else if (h->obyten || h->osync) { /* sending data */
  1529. buf[i] = wave_out[h->ophase];
  1530. h->ophase += (h->obyte & 1) ? 13 : 21; /* compute next phase */
  1531. if (h->ophase >= 80)
  1532. h->ophase -= 80;
  1533. if ((h->ophasep += 12) >= 80) { /* time to send the next bit */
  1534. h->ophasep -= 80;
  1535. if (h->oseizure > 0) { /* sending channel seizure (proto 2) */
  1536. h->oseizure--;
  1537. h->obyte ^= 1; /* toggle low bit */
  1538. } else if (h->osync) {
  1539. h->obyte = 1; /* send mark as sync bit */
  1540. h->osync--; /* sending sync bits */
  1541. if (h->osync == 0 && h->protocol == 2 && h->omsg[0] == DLL2_SMS_EST) {
  1542. h->obytep = h->obyten = 0; /* we are done */
  1543. }
  1544. } else {
  1545. h->obitp++;
  1546. if (h->obitp == 1) {
  1547. h->obyte = 0; /* start bit; */
  1548. } else if (h->obitp == 2) {
  1549. h->obyte = h->omsg[h->obytep];
  1550. } else if (h->obitp == 10) {
  1551. h->obyte = 1; /* stop bit */
  1552. h->obitp = 0;
  1553. h->obytep++;
  1554. if (h->obytep == h->obyten) {
  1555. h->obytep = h->obyten = 0; /* sent */
  1556. h->osync = 10; /* trailing marks */
  1557. }
  1558. } else {
  1559. h->obyte >>= 1;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. }
  1565. if (ast_write(chan, &f) < 0) {
  1566. ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", chan->name, strerror(errno));
  1567. return -1;
  1568. }
  1569. return 0;
  1570. #undef MAXSAMPLES
  1571. }
  1572. /*!
  1573. * Just return the pointer to the descriptor that we received.
  1574. */
  1575. static void *sms_alloc(struct ast_channel *chan, void *sms_t_ptr)
  1576. {
  1577. return sms_t_ptr;
  1578. }
  1579. static void sms_release(struct ast_channel *chan, void *data)
  1580. {
  1581. return; /* nothing to do here. */
  1582. }
  1583. static struct ast_generator smsgen = {
  1584. .alloc = sms_alloc,
  1585. .release = sms_release,
  1586. .generate = sms_generate,
  1587. };
  1588. /*!
  1589. * Process an incoming frame, trying to detect the carrier and
  1590. * decode the message. The two frequencies are 1300 and 2100 Hz.
  1591. * The decoder detects the amplitude of the signal over the last
  1592. * few samples, filtering the absolute values with a lowpass filter.
  1593. * If the magnitude (h->imag) is large enough, multiply the signal
  1594. * by the two carriers, and compute the amplitudes m0 and m1.
  1595. * Record the current sample as '0' or '1' depending on which one is greater.
  1596. * The last 3 bits are stored in h->ibith, with the count of '1'
  1597. * bits in h->ibitt.
  1598. * XXX the rest is to be determined.
  1599. */
  1600. static void sms_process(sms_t * h, int samples, signed short *data)
  1601. {
  1602. int bit;
  1603. /*
  1604. * Ignore incoming audio while a packet is being transmitted,
  1605. * the protocol is half-duplex.
  1606. * Unfortunately this means that if the outbound and incoming
  1607. * transmission overlap (which is an error condition anyways),
  1608. * we may miss some data and this makes debugging harder.
  1609. */
  1610. if (h->obyten || h->osync) {
  1611. return;
  1612. }
  1613. for ( ; samples-- ; data++) {
  1614. unsigned long long m0, m1;
  1615. if (abs(*data) > h->imag) {
  1616. h->imag = abs(*data);
  1617. } else {
  1618. h->imag = h->imag * 7 / 8;
  1619. }
  1620. if (h->imag <= 500) { /* below [arbitrary] threahold: lost carrier */
  1621. if (h->idle++ == 80000) { /* nothing happening */
  1622. ast_log(LOG_NOTICE, "No data, hanging up\n");
  1623. h->hangup = 1;
  1624. h->err = 1;
  1625. }
  1626. if (h->ierr) { /* error */
  1627. ast_log(LOG_NOTICE, "Error %d, hanging up\n", h->ierr);
  1628. /* Protocol 1 */
  1629. h->err = 1;
  1630. h->omsg[0] = 0x92; /* error */
  1631. h->omsg[1] = 1;
  1632. h->omsg[2] = h->ierr;
  1633. sms_messagetx(h); /* send error */
  1634. }
  1635. h->ierr = h->ibitn = h->ibytep = h->ibytec = 0;
  1636. continue;
  1637. }
  1638. h->idle = 0;
  1639. /* multiply signal by the two carriers. */
  1640. h->ims0 = (h->ims0 * 6 + *data * wave[h->ips0]) / 7;
  1641. h->imc0 = (h->imc0 * 6 + *data * wave[h->ipc0]) / 7;
  1642. h->ims1 = (h->ims1 * 6 + *data * wave[h->ips1]) / 7;
  1643. h->imc1 = (h->imc1 * 6 + *data * wave[h->ipc1]) / 7;
  1644. /* compute the amplitudes */
  1645. m0 = h->ims0 * h->ims0 + h->imc0 * h->imc0;
  1646. m1 = h->ims1 * h->ims1 + h->imc1 * h->imc1;
  1647. /* advance the sin/cos pointers */
  1648. if ((h->ips0 += 21) >= 80) {
  1649. h->ips0 -= 80;
  1650. }
  1651. if ((h->ipc0 += 21) >= 80) {
  1652. h->ipc0 -= 80;
  1653. }
  1654. if ((h->ips1 += 13) >= 80) {
  1655. h->ips1 -= 80;
  1656. }
  1657. if ((h->ipc1 += 13) >= 80) {
  1658. h->ipc1 -= 80;
  1659. }
  1660. /* set new bit to 1 or 0 depending on which value is stronger */
  1661. h->ibith <<= 1;
  1662. if (m1 > m0) {
  1663. h->ibith |= 1;
  1664. }
  1665. if (h->ibith & 8) {
  1666. h->ibitt--;
  1667. }
  1668. if (h->ibith & 1) {
  1669. h->ibitt++;
  1670. }
  1671. bit = ((h->ibitt > 1) ? 1 : 0);
  1672. if (bit != h->ibitl) {
  1673. h->ibitc = 1;
  1674. } else {
  1675. h->ibitc++;
  1676. }
  1677. h->ibitl = bit;
  1678. if (!h->ibitn && h->ibitc == 4 && !bit) {
  1679. h->ibitn = 1;
  1680. h->iphasep = 0;
  1681. }
  1682. if (bit && h->ibitc == 200) { /* sync, restart message */
  1683. /* Protocol 2: empty connection ready (I am master) */
  1684. if (h->framenumber < 0 && h->ibytec >= 160 && !memcmp(h->imsg, "UUUUUUUUUUUUUUUUUUUU", 20)) {
  1685. h->framenumber = 1;
  1686. ast_verb(3, "SMS protocol 2 detected\n");
  1687. h->protocol = 2;
  1688. h->imsg[0] = 0xff; /* special message (fake) */
  1689. h->imsg[1] = h->imsg[2] = 0x00;
  1690. h->ierr = h->ibitn = h->ibytep = h->ibytec = 0;
  1691. sms_messagerx(h);
  1692. }
  1693. h->ierr = h->ibitn = h->ibytep = h->ibytec = 0;
  1694. }
  1695. if (h->ibitn) {
  1696. h->iphasep += 12;
  1697. if (h->iphasep >= 80) { /* next bit */
  1698. h->iphasep -= 80;
  1699. if (h->ibitn++ == 9) { /* end of byte */
  1700. if (!bit) { /* bad stop bit */
  1701. ast_log(LOG_NOTICE, "bad stop bit");
  1702. h->ierr = 0xFF; /* unknown error */
  1703. } else {
  1704. if (h->ibytep < sizeof(h->imsg)) {
  1705. h->imsg[h->ibytep] = h->ibytev;
  1706. h->ibytec += h->ibytev;
  1707. h->ibytep++;
  1708. } else if (h->ibytep == sizeof(h->imsg)) {
  1709. ast_log(LOG_NOTICE, "msg too large");
  1710. h->ierr = 2; /* bad message length */
  1711. }
  1712. if (h->ibytep > 1 && h->ibytep == 3 + h->imsg[1] && !h->ierr) {
  1713. if (!h->ibytec) {
  1714. sms_messagerx(h);
  1715. } else {
  1716. ast_log(LOG_NOTICE, "bad checksum");
  1717. h->ierr = 1; /* bad checksum */
  1718. }
  1719. }
  1720. }
  1721. h->ibitn = 0;
  1722. }
  1723. h->ibytev = (h->ibytev >> 1) + (bit ? 0x80 : 0);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. /*
  1729. * Standard argument parsing:
  1730. * - one enum for the flags we recognise,
  1731. * - one enum for argument indexes
  1732. * - AST_APP_OPTIONS() to drive the parsing routine
  1733. * - in the function, AST_DECLARE_APP_ARGS(...) for the arguments.
  1734. */
  1735. enum sms_flags {
  1736. OPTION_BE_SMSC = (1 << 0), /* act as sms center */
  1737. OPTION_ANSWER = (1 << 1), /* answer on incoming calls */
  1738. OPTION_TWO = (1 << 2), /* Use Protocol Two */
  1739. OPTION_PAUSE = (1 << 3), /* pause before sending data, in ms */
  1740. OPTION_SRR = (1 << 4), /* set srr */
  1741. OPTION_DCS = (1 << 5), /* set dcs */
  1742. };
  1743. enum sms_opt_args {
  1744. OPTION_ARG_PAUSE = 0,
  1745. OPTION_ARG_ARRAY_SIZE
  1746. };
  1747. AST_APP_OPTIONS(sms_options, {
  1748. AST_APP_OPTION('s', OPTION_BE_SMSC),
  1749. AST_APP_OPTION('a', OPTION_ANSWER),
  1750. AST_APP_OPTION('t', OPTION_TWO),
  1751. AST_APP_OPTION('r', OPTION_SRR),
  1752. AST_APP_OPTION('o', OPTION_DCS),
  1753. AST_APP_OPTION_ARG('p', OPTION_PAUSE, OPTION_ARG_PAUSE),
  1754. } );
  1755. static int sms_exec(struct ast_channel *chan, const char *data)
  1756. {
  1757. int res = -1;
  1758. sms_t h = { 0 };
  1759. /* argument parsing support */
  1760. struct ast_flags flags;
  1761. char *parse, *sms_opts[OPTION_ARG_ARRAY_SIZE] = { 0, };
  1762. char *p;
  1763. AST_DECLARE_APP_ARGS(sms_args,
  1764. AST_APP_ARG(queue);
  1765. AST_APP_ARG(options);
  1766. AST_APP_ARG(addr);
  1767. AST_APP_ARG(body);
  1768. );
  1769. if (!data) {
  1770. ast_log(LOG_ERROR, "Requires queue name at least\n");
  1771. return -1;
  1772. }
  1773. parse = ast_strdupa(data); /* create a local copy */
  1774. AST_STANDARD_APP_ARGS(sms_args, parse);
  1775. if (sms_args.argc > 1) {
  1776. ast_app_parse_options(sms_options, &flags, sms_opts, sms_args.options);
  1777. }
  1778. ast_verb(1, "sms argc %d queue <%s> opts <%s> addr <%s> body <%s>\n",
  1779. sms_args.argc, S_OR(sms_args.queue, ""),
  1780. S_OR(sms_args.options, ""),
  1781. S_OR(sms_args.addr, ""),
  1782. S_OR(sms_args.body, "") );
  1783. h.ipc0 = h.ipc1 = 20; /* phase for cosine */
  1784. h.dcs = 0xF1; /* default */
  1785. ast_copy_string(h.cli,
  1786. S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""),
  1787. sizeof(h.cli));
  1788. if (ast_strlen_zero(sms_args.queue)) {
  1789. ast_log(LOG_ERROR, "Requires queue name\n");
  1790. goto done;
  1791. }
  1792. if (strlen(sms_args.queue) >= sizeof(h.queue)) {
  1793. ast_log(LOG_ERROR, "Queue name too long\n");
  1794. goto done;
  1795. }
  1796. ast_copy_string(h.queue, sms_args.queue, sizeof(h.queue));
  1797. for (p = h.queue; *p; p++) {
  1798. if (!isalnum(*p)) {
  1799. *p = '-'; /* make very safe for filenames */
  1800. }
  1801. }
  1802. h.smsc = ast_test_flag(&flags, OPTION_BE_SMSC);
  1803. h.protocol = ast_test_flag(&flags, OPTION_TWO) ? 2 : 1;
  1804. if (!ast_strlen_zero(sms_opts[OPTION_ARG_PAUSE])) {
  1805. h.opause_0 = atoi(sms_opts[OPTION_ARG_PAUSE]);
  1806. }
  1807. if (h.opause_0 < 25 || h.opause_0 > 2000) {
  1808. h.opause_0 = 300; /* default 300ms */
  1809. }
  1810. ast_verb(1, "initial delay %dms\n", h.opause_0);
  1811. /* the following apply if there is an arg3/4 and apply to the created message file */
  1812. if (ast_test_flag(&flags, OPTION_SRR)) {
  1813. h.srr = 1;
  1814. }
  1815. if (ast_test_flag(&flags, OPTION_DCS)) {
  1816. h.dcs = 1;
  1817. }
  1818. #if 0
  1819. case '1':
  1820. case '2':
  1821. case '3':
  1822. case '4':
  1823. case '5':
  1824. case '6':
  1825. case '7': /* set the pid for saved local message */
  1826. h.pid = 0x40 + (*d & 0xF);
  1827. break;
  1828. }
  1829. #endif
  1830. if (sms_args.argc > 2) {
  1831. unsigned char *up;
  1832. /* submitting a message, not taking call. */
  1833. /* deprecated, use smsq instead */
  1834. h.scts = ast_tvnow();
  1835. if (ast_strlen_zero(sms_args.addr) || strlen(sms_args.addr) >= sizeof(h.oa)) {
  1836. ast_log(LOG_ERROR, "Address too long %s\n", sms_args.addr);
  1837. goto done;
  1838. }
  1839. if (h.smsc) {
  1840. ast_copy_string(h.oa, sms_args.addr, sizeof(h.oa));
  1841. } else {
  1842. ast_copy_string(h.da, sms_args.addr, sizeof(h.da));
  1843. ast_copy_string(h.oa, h.cli, sizeof(h.oa));
  1844. }
  1845. h.udl = 0;
  1846. if (ast_strlen_zero(sms_args.body)) {
  1847. ast_log(LOG_ERROR, "Missing body for %s\n", sms_args.addr);
  1848. goto done;
  1849. }
  1850. up = (unsigned char *)sms_args.body;
  1851. while (*up && h.udl < SMSLEN) {
  1852. h.ud[h.udl++] = utf8decode(&up);
  1853. }
  1854. if (is7bit(h.dcs) && packsms7(0, h.udhl, h.udh, h.udl, h.ud) < 0) {
  1855. ast_log(LOG_WARNING, "Invalid 7 bit GSM data\n");
  1856. goto done;
  1857. }
  1858. if (is8bit(h.dcs) && packsms8(0, h.udhl, h.udh, h.udl, h.ud) < 0) {
  1859. ast_log(LOG_WARNING, "Invalid 8 bit data\n");
  1860. goto done;
  1861. }
  1862. if (is16bit(h.dcs) && packsms16(0, h.udhl, h.udh, h.udl, h.ud) < 0) {
  1863. ast_log(LOG_WARNING, "Invalid 16 bit data\n");
  1864. goto done;
  1865. }
  1866. h.rx = 0; /* sent message */
  1867. h.mr = -1;
  1868. sms_writefile(&h);
  1869. res = h.err;
  1870. goto done;
  1871. }
  1872. if (chan->_state != AST_STATE_UP) { /* make sure channel is answered before any TX */
  1873. ast_answer(chan);
  1874. }
  1875. if (ast_test_flag(&flags, OPTION_ANSWER)) {
  1876. h.framenumber = 1; /* Proto 2 */
  1877. /* set up SMS_EST initial message */
  1878. if (h.protocol == 2) {
  1879. h.omsg[0] = DLL2_SMS_EST;
  1880. h.omsg[1] = 0;
  1881. } else {
  1882. h.omsg[0] = DLL1_SMS_EST | DLL1_SMS_COMPLETE;
  1883. h.omsg[1] = 0;
  1884. }
  1885. sms_messagetx(&h);
  1886. }
  1887. res = ast_set_write_format_by_id(chan, __OUT_FMT);
  1888. if (res >= 0) {
  1889. res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
  1890. }
  1891. if (res < 0) {
  1892. ast_log(LOG_ERROR, "Unable to set to linear mode, giving up\n");
  1893. goto done;
  1894. }
  1895. if ( (res = ast_activate_generator(chan, &smsgen, &h)) < 0) {
  1896. ast_log(LOG_ERROR, "Failed to activate generator on '%s'\n", chan->name);
  1897. goto done;
  1898. }
  1899. /* Do our thing here */
  1900. for (;;) {
  1901. struct ast_frame *f;
  1902. int i = ast_waitfor(chan, -1);
  1903. if (i < 0) {
  1904. ast_log(LOG_NOTICE, "waitfor failed\n");
  1905. break;
  1906. }
  1907. if (h.hangup) {
  1908. ast_log(LOG_NOTICE, "channel hangup\n");
  1909. break;
  1910. }
  1911. f = ast_read(chan);
  1912. if (!f) {
  1913. ast_log(LOG_NOTICE, "ast_read failed\n");
  1914. break;
  1915. }
  1916. if (f->frametype == AST_FRAME_VOICE) {
  1917. sms_process(&h, f->samples, f->data.ptr);
  1918. }
  1919. ast_frfree(f);
  1920. }
  1921. res = h.err; /* XXX */
  1922. /*
  1923. * The SMS generator data is on the stack. We _MUST_ make sure the generator
  1924. * is stopped before returning from this function.
  1925. */
  1926. ast_deactivate_generator(chan);
  1927. sms_log(&h, '?'); /* log incomplete message */
  1928. done:
  1929. return (res);
  1930. }
  1931. static int unload_module(void)
  1932. {
  1933. return ast_unregister_application(app);
  1934. }
  1935. static int load_module(void)
  1936. {
  1937. #ifdef OUTALAW
  1938. int p;
  1939. for (p = 0; p < 80; p++) {
  1940. wavea[p] = AST_LIN2A(wave[p]);
  1941. }
  1942. #endif
  1943. snprintf(log_file, sizeof(log_file), "%s/sms", ast_config_AST_LOG_DIR);
  1944. return ast_register_application_xml(app, sms_exec);
  1945. }
  1946. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "SMS/PSTN handler");