app.c 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2005, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Convenient Application Routines
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. /** \example
  25. * \par This is an example of how to develop an app.
  26. * Application Skeleton is an example of creating an application for Asterisk.
  27. * \verbinclude app_skel.c
  28. */
  29. /*** MODULEINFO
  30. <support_level>core</support_level>
  31. ***/
  32. #include "asterisk.h"
  33. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  34. #ifdef HAVE_SYS_STAT_H
  35. #include <sys/stat.h>
  36. #endif
  37. #include <regex.h> /* for regcomp(3) */
  38. #include <sys/file.h> /* for flock(2) */
  39. #include <signal.h> /* for pthread_sigmask(3) */
  40. #include <stdlib.h> /* for closefrom(3) */
  41. #include <sys/types.h>
  42. #include <sys/wait.h> /* for waitpid(2) */
  43. #ifndef HAVE_CLOSEFROM
  44. #include <dirent.h> /* for opendir(3) */
  45. #endif
  46. #ifdef HAVE_CAP
  47. #include <sys/capability.h>
  48. #endif /* HAVE_CAP */
  49. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  50. #include "asterisk/channel.h"
  51. #include "asterisk/pbx.h"
  52. #include "asterisk/file.h"
  53. #include "asterisk/app.h"
  54. #include "asterisk/dsp.h"
  55. #include "asterisk/utils.h"
  56. #include "asterisk/lock.h"
  57. #include "asterisk/indications.h"
  58. #include "asterisk/linkedlists.h"
  59. #include "asterisk/threadstorage.h"
  60. #include "asterisk/test.h"
  61. #include "asterisk/module.h"
  62. #include "asterisk/astobj2.h"
  63. #include "asterisk/stasis.h"
  64. #include "asterisk/stasis_channels.h"
  65. #include "asterisk/json.h"
  66. #include "asterisk/format_cache.h"
  67. #define MWI_TOPIC_BUCKETS 57
  68. AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
  69. static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
  70. struct zombie {
  71. pid_t pid;
  72. AST_LIST_ENTRY(zombie) list;
  73. };
  74. static AST_LIST_HEAD_STATIC(zombies, zombie);
  75. /*
  76. * @{ \brief Define \ref stasis topic objects
  77. */
  78. static struct stasis_topic *mwi_topic_all;
  79. static struct stasis_cache *mwi_state_cache;
  80. static struct stasis_caching_topic *mwi_topic_cached;
  81. static struct stasis_topic_pool *mwi_topic_pool;
  82. static struct stasis_topic *queue_topic_all;
  83. static struct stasis_topic_pool *queue_topic_pool;
  84. /* @} */
  85. /*! \brief Convert a MWI \ref stasis_message to a \ref ast_event */
  86. static struct ast_event *mwi_to_event(struct stasis_message *message)
  87. {
  88. struct ast_event *event;
  89. struct ast_mwi_state *mwi_state;
  90. char *mailbox;
  91. char *context;
  92. if (!message) {
  93. return NULL;
  94. }
  95. mwi_state = stasis_message_data(message);
  96. /* Strip off @context */
  97. context = mailbox = ast_strdupa(mwi_state->uniqueid);
  98. strsep(&context, "@");
  99. if (ast_strlen_zero(context)) {
  100. context = "default";
  101. }
  102. event = ast_event_new(AST_EVENT_MWI,
  103. AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
  104. AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
  105. AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, mwi_state->new_msgs,
  106. AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, mwi_state->old_msgs,
  107. AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, &mwi_state->eid, sizeof(mwi_state->eid),
  108. AST_EVENT_IE_END);
  109. return event;
  110. }
  111. /*
  112. * @{ \brief Define \ref stasis message types for MWI
  113. */
  114. STASIS_MESSAGE_TYPE_DEFN(ast_mwi_state_type,
  115. .to_event = mwi_to_event, );
  116. STASIS_MESSAGE_TYPE_DEFN(ast_mwi_vm_app_type);
  117. /* @} */
  118. static void *shaun_of_the_dead(void *data)
  119. {
  120. struct zombie *cur;
  121. int status;
  122. for (;;) {
  123. if (!AST_LIST_EMPTY(&zombies)) {
  124. /* Don't allow cancellation while we have a lock. */
  125. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  126. AST_LIST_LOCK(&zombies);
  127. AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
  128. if (waitpid(cur->pid, &status, WNOHANG) != 0) {
  129. AST_LIST_REMOVE_CURRENT(list);
  130. ast_free(cur);
  131. }
  132. }
  133. AST_LIST_TRAVERSE_SAFE_END
  134. AST_LIST_UNLOCK(&zombies);
  135. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  136. }
  137. pthread_testcancel();
  138. /* Wait for 60 seconds, without engaging in a busy loop. */
  139. ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
  140. }
  141. return NULL;
  142. }
  143. #define AST_MAX_FORMATS 10
  144. static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
  145. /*!
  146. * \brief This function presents a dialtone and reads an extension into 'collect'
  147. * which must be a pointer to a **pre-initialized** array of char having a
  148. * size of 'size' suitable for writing to. It will collect no more than the smaller
  149. * of 'maxlen' or 'size' minus the original strlen() of collect digits.
  150. * \param chan struct.
  151. * \param context
  152. * \param collect
  153. * \param size
  154. * \param maxlen
  155. * \param timeout timeout in milliseconds
  156. *
  157. * \return 0 if extension does not exist, 1 if extension exists
  158. */
  159. int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
  160. {
  161. struct ast_tone_zone_sound *ts;
  162. int res = 0, x = 0;
  163. if (maxlen > size) {
  164. maxlen = size;
  165. }
  166. if (!timeout) {
  167. if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
  168. timeout = ast_channel_pbx(chan)->dtimeoutms;
  169. } else {
  170. timeout = 5000;
  171. }
  172. }
  173. if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
  174. res = ast_playtones_start(chan, 0, ts->data, 0);
  175. ts = ast_tone_zone_sound_unref(ts);
  176. } else {
  177. ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
  178. }
  179. for (x = strlen(collect); x < maxlen; ) {
  180. res = ast_waitfordigit(chan, timeout);
  181. if (!ast_ignore_pattern(context, collect)) {
  182. ast_playtones_stop(chan);
  183. }
  184. if (res < 1) {
  185. break;
  186. }
  187. if (res == '#') {
  188. break;
  189. }
  190. collect[x++] = res;
  191. if (!ast_matchmore_extension(chan, context, collect, 1,
  192. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
  193. break;
  194. }
  195. }
  196. if (res >= 0) {
  197. res = ast_exists_extension(chan, context, collect, 1,
  198. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
  199. }
  200. return res;
  201. }
  202. /*!
  203. * \brief ast_app_getdata
  204. * \param c The channel to read from
  205. * \param prompt The file to stream to the channel
  206. * \param s The string to read in to. Must be at least the size of your length
  207. * \param maxlen How many digits to read (maximum)
  208. * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
  209. * "ludicrous time" (essentially never times out) */
  210. enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
  211. {
  212. int res = 0, to, fto;
  213. char *front, *filename;
  214. /* XXX Merge with full version? XXX */
  215. if (maxlen)
  216. s[0] = '\0';
  217. if (!prompt)
  218. prompt = "";
  219. filename = ast_strdupa(prompt);
  220. while ((front = strsep(&filename, "&"))) {
  221. if (!ast_strlen_zero(front)) {
  222. res = ast_streamfile(c, front, ast_channel_language(c));
  223. if (res)
  224. continue;
  225. }
  226. if (ast_strlen_zero(filename)) {
  227. /* set timeouts for the last prompt */
  228. fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
  229. to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
  230. if (timeout > 0) {
  231. fto = to = timeout;
  232. }
  233. if (timeout < 0) {
  234. fto = to = 1000000000;
  235. }
  236. } else {
  237. /* there is more than one prompt, so
  238. * get rid of the long timeout between
  239. * prompts, and make it 50ms */
  240. fto = 50;
  241. to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
  242. }
  243. res = ast_readstring(c, s, maxlen, to, fto, "#");
  244. if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
  245. return res;
  246. }
  247. if (!ast_strlen_zero(s)) {
  248. return res;
  249. }
  250. }
  251. return res;
  252. }
  253. /* The lock type used by ast_lock_path() / ast_unlock_path() */
  254. static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
  255. int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
  256. {
  257. int res, to = 2000, fto = 6000;
  258. if (!ast_strlen_zero(prompt)) {
  259. res = ast_streamfile(c, prompt, ast_channel_language(c));
  260. if (res < 0) {
  261. return res;
  262. }
  263. }
  264. if (timeout > 0) {
  265. fto = to = timeout;
  266. }
  267. if (timeout < 0) {
  268. fto = to = 1000000000;
  269. }
  270. res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
  271. return res;
  272. }
  273. int ast_app_exec_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_args)
  274. {
  275. struct ast_app *macro_app;
  276. int res;
  277. macro_app = pbx_findapp("Macro");
  278. if (!macro_app) {
  279. ast_log(LOG_WARNING,
  280. "Cannot run 'Macro(%s)'. The application is not available.\n", macro_args);
  281. return -1;
  282. }
  283. if (autoservice_chan) {
  284. ast_autoservice_start(autoservice_chan);
  285. }
  286. ast_debug(4, "%s Original location: %s,%s,%d\n", ast_channel_name(macro_chan),
  287. ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
  288. ast_channel_priority(macro_chan));
  289. res = pbx_exec(macro_chan, macro_app, macro_args);
  290. ast_debug(4, "Macro exited with status %d\n", res);
  291. /*
  292. * Assume anything negative from Macro is an error.
  293. * Anything else is success.
  294. */
  295. if (res < 0) {
  296. res = -1;
  297. } else {
  298. res = 0;
  299. }
  300. ast_debug(4, "%s Ending location: %s,%s,%d\n", ast_channel_name(macro_chan),
  301. ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
  302. ast_channel_priority(macro_chan));
  303. if (autoservice_chan) {
  304. ast_autoservice_stop(autoservice_chan);
  305. }
  306. return res;
  307. }
  308. int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_name, const char *macro_args)
  309. {
  310. int res;
  311. char *args_str;
  312. size_t args_len;
  313. if (ast_strlen_zero(macro_args)) {
  314. return ast_app_exec_macro(autoservice_chan, macro_chan, macro_name);
  315. }
  316. /* Create the Macro application argument string. */
  317. args_len = strlen(macro_name) + strlen(macro_args) + 2;
  318. args_str = ast_malloc(args_len);
  319. if (!args_str) {
  320. return -1;
  321. }
  322. snprintf(args_str, args_len, "%s,%s", macro_name, macro_args);
  323. res = ast_app_exec_macro(autoservice_chan, macro_chan, args_str);
  324. ast_free(args_str);
  325. return res;
  326. }
  327. static const struct ast_app_stack_funcs *app_stack_callbacks;
  328. void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
  329. {
  330. app_stack_callbacks = funcs;
  331. }
  332. const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
  333. {
  334. const struct ast_app_stack_funcs *funcs;
  335. const char *new_args;
  336. funcs = app_stack_callbacks;
  337. if (!funcs || !funcs->expand_sub_args) {
  338. ast_log(LOG_WARNING,
  339. "Cannot expand 'Gosub(%s)' arguments. The app_stack module is not available.\n",
  340. args);
  341. return NULL;
  342. }
  343. ast_module_ref(funcs->module);
  344. new_args = funcs->expand_sub_args(chan, args);
  345. ast_module_unref(funcs->module);
  346. return new_args;
  347. }
  348. int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
  349. {
  350. const struct ast_app_stack_funcs *funcs;
  351. int res;
  352. funcs = app_stack_callbacks;
  353. if (!funcs || !funcs->run_sub) {
  354. ast_log(LOG_WARNING,
  355. "Cannot run 'Gosub(%s)'. The app_stack module is not available.\n",
  356. sub_args);
  357. return -1;
  358. }
  359. ast_module_ref(funcs->module);
  360. if (autoservice_chan) {
  361. ast_autoservice_start(autoservice_chan);
  362. }
  363. res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
  364. ast_module_unref(funcs->module);
  365. if (autoservice_chan) {
  366. ast_autoservice_stop(autoservice_chan);
  367. }
  368. return res;
  369. }
  370. int ast_app_run_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_location, const char *sub_args, int ignore_hangup)
  371. {
  372. int res;
  373. char *args_str;
  374. size_t args_len;
  375. if (ast_strlen_zero(sub_args)) {
  376. return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
  377. }
  378. /* Create the Gosub application argument string. */
  379. args_len = strlen(sub_location) + strlen(sub_args) + 3;
  380. args_str = ast_malloc(args_len);
  381. if (!args_str) {
  382. return -1;
  383. }
  384. snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
  385. res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
  386. ast_free(args_str);
  387. return res;
  388. }
  389. /*! \brief The container for the voicemail provider */
  390. static AO2_GLOBAL_OBJ_STATIC(vm_provider);
  391. /*! Voicemail not registered warning */
  392. static int vm_warnings;
  393. int ast_vm_is_registered(void)
  394. {
  395. struct ast_vm_functions *table;
  396. int is_registered;
  397. table = ao2_global_obj_ref(vm_provider);
  398. is_registered = table ? 1 : 0;
  399. ao2_cleanup(table);
  400. return is_registered;
  401. }
  402. int __ast_vm_register(const struct ast_vm_functions *vm_table, struct ast_module *module)
  403. {
  404. RAII_VAR(struct ast_vm_functions *, table, NULL, ao2_cleanup);
  405. if (!vm_table->module_name) {
  406. ast_log(LOG_ERROR, "Voicemail provider missing required information.\n");
  407. return -1;
  408. }
  409. if (vm_table->module_version != VM_MODULE_VERSION) {
  410. ast_log(LOG_ERROR, "Voicemail provider '%s' has incorrect version\n",
  411. vm_table->module_name);
  412. return -1;
  413. }
  414. table = ao2_global_obj_ref(vm_provider);
  415. if (table) {
  416. ast_log(LOG_WARNING, "Voicemail provider already registered by %s.\n",
  417. table->module_name);
  418. return -1;
  419. }
  420. table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
  421. if (!table) {
  422. return -1;
  423. }
  424. *table = *vm_table;
  425. table->module = module;
  426. ao2_global_obj_replace_unref(vm_provider, table);
  427. return 0;
  428. }
  429. void ast_vm_unregister(const char *module_name)
  430. {
  431. struct ast_vm_functions *table;
  432. table = ao2_global_obj_ref(vm_provider);
  433. if (table && !strcmp(table->module_name, module_name)) {
  434. ao2_global_obj_release(vm_provider);
  435. }
  436. ao2_cleanup(table);
  437. }
  438. #ifdef TEST_FRAMEWORK
  439. /*! \brief Holding container for the voicemail provider used while testing */
  440. static AO2_GLOBAL_OBJ_STATIC(vm_provider_holder);
  441. static int provider_is_swapped = 0;
  442. void ast_vm_test_swap_table_in(const struct ast_vm_functions *vm_table)
  443. {
  444. RAII_VAR(struct ast_vm_functions *, holding_table, NULL, ao2_cleanup);
  445. RAII_VAR(struct ast_vm_functions *, new_table, NULL, ao2_cleanup);
  446. if (provider_is_swapped) {
  447. ast_log(LOG_ERROR, "Attempted to swap in test function table without swapping out old test table.\n");
  448. return;
  449. }
  450. holding_table = ao2_global_obj_ref(vm_provider);
  451. if (holding_table) {
  452. ao2_global_obj_replace_unref(vm_provider_holder, holding_table);
  453. }
  454. new_table = ao2_alloc_options(sizeof(*new_table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
  455. if (!new_table) {
  456. return;
  457. }
  458. *new_table = *vm_table;
  459. ao2_global_obj_replace_unref(vm_provider, new_table);
  460. provider_is_swapped = 1;
  461. }
  462. void ast_vm_test_swap_table_out(void)
  463. {
  464. RAII_VAR(struct ast_vm_functions *, held_table, NULL, ao2_cleanup);
  465. if (!provider_is_swapped) {
  466. ast_log(LOG_ERROR, "Attempted to swap out test function table, but none is currently installed.\n");
  467. return;
  468. }
  469. held_table = ao2_global_obj_ref(vm_provider_holder);
  470. if (!held_table) {
  471. return;
  472. }
  473. ao2_global_obj_replace_unref(vm_provider, held_table);
  474. ao2_global_obj_release(vm_provider_holder);
  475. provider_is_swapped = 0;
  476. }
  477. #endif
  478. /*! \brief The container for the voicemail greeter provider */
  479. static AO2_GLOBAL_OBJ_STATIC(vm_greeter_provider);
  480. /*! Voicemail greeter not registered warning */
  481. static int vm_greeter_warnings;
  482. int ast_vm_greeter_is_registered(void)
  483. {
  484. struct ast_vm_greeter_functions *table;
  485. int is_registered;
  486. table = ao2_global_obj_ref(vm_greeter_provider);
  487. is_registered = table ? 1 : 0;
  488. ao2_cleanup(table);
  489. return is_registered;
  490. }
  491. int __ast_vm_greeter_register(const struct ast_vm_greeter_functions *vm_table, struct ast_module *module)
  492. {
  493. RAII_VAR(struct ast_vm_greeter_functions *, table, NULL, ao2_cleanup);
  494. if (!vm_table->module_name) {
  495. ast_log(LOG_ERROR, "Voicemail greeter provider missing required information.\n");
  496. return -1;
  497. }
  498. if (vm_table->module_version != VM_GREETER_MODULE_VERSION) {
  499. ast_log(LOG_ERROR, "Voicemail greeter provider '%s' has incorrect version\n",
  500. vm_table->module_name);
  501. return -1;
  502. }
  503. table = ao2_global_obj_ref(vm_greeter_provider);
  504. if (table) {
  505. ast_log(LOG_WARNING, "Voicemail greeter provider already registered by %s.\n",
  506. table->module_name);
  507. return -1;
  508. }
  509. table = ao2_alloc_options(sizeof(*table), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
  510. if (!table) {
  511. return -1;
  512. }
  513. *table = *vm_table;
  514. table->module = module;
  515. ao2_global_obj_replace_unref(vm_greeter_provider, table);
  516. return 0;
  517. }
  518. void ast_vm_greeter_unregister(const char *module_name)
  519. {
  520. struct ast_vm_greeter_functions *table;
  521. table = ao2_global_obj_ref(vm_greeter_provider);
  522. if (table && !strcmp(table->module_name, module_name)) {
  523. ao2_global_obj_release(vm_greeter_provider);
  524. }
  525. ao2_cleanup(table);
  526. }
  527. #ifdef TEST_FRAMEWORK
  528. static ast_vm_test_create_user_fn *ast_vm_test_create_user_func = NULL;
  529. static ast_vm_test_destroy_user_fn *ast_vm_test_destroy_user_func = NULL;
  530. void ast_install_vm_test_functions(ast_vm_test_create_user_fn *vm_test_create_user_func,
  531. ast_vm_test_destroy_user_fn *vm_test_destroy_user_func)
  532. {
  533. ast_vm_test_create_user_func = vm_test_create_user_func;
  534. ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
  535. }
  536. void ast_uninstall_vm_test_functions(void)
  537. {
  538. ast_vm_test_create_user_func = NULL;
  539. ast_vm_test_destroy_user_func = NULL;
  540. }
  541. #endif
  542. static void vm_warn_no_provider(void)
  543. {
  544. if (vm_warnings++ % 10 == 0) {
  545. ast_verb(3, "No voicemail provider registered.\n");
  546. }
  547. }
  548. #define VM_API_CALL(res, api_call, api_parms) \
  549. do { \
  550. struct ast_vm_functions *table; \
  551. table = ao2_global_obj_ref(vm_provider); \
  552. if (!table) { \
  553. vm_warn_no_provider(); \
  554. } else if (table->api_call) { \
  555. ast_module_ref(table->module); \
  556. (res) = table->api_call api_parms; \
  557. ast_module_unref(table->module); \
  558. } \
  559. ao2_cleanup(table); \
  560. } while (0)
  561. static void vm_greeter_warn_no_provider(void)
  562. {
  563. if (vm_greeter_warnings++ % 10 == 0) {
  564. ast_verb(3, "No voicemail greeter provider registered.\n");
  565. }
  566. }
  567. #define VM_GREETER_API_CALL(res, api_call, api_parms) \
  568. do { \
  569. struct ast_vm_greeter_functions *table; \
  570. table = ao2_global_obj_ref(vm_greeter_provider); \
  571. if (!table) { \
  572. vm_greeter_warn_no_provider(); \
  573. } else if (table->api_call) { \
  574. ast_module_ref(table->module); \
  575. (res) = table->api_call api_parms; \
  576. ast_module_unref(table->module); \
  577. } \
  578. ao2_cleanup(table); \
  579. } while (0)
  580. int ast_app_has_voicemail(const char *mailboxes, const char *folder)
  581. {
  582. int res = 0;
  583. VM_API_CALL(res, has_voicemail, (mailboxes, folder));
  584. return res;
  585. }
  586. /*!
  587. * \internal
  588. * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
  589. * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
  590. * to figure out what the name of the recipient was supposed to be
  591. */
  592. int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
  593. {
  594. int res = -1;
  595. VM_API_CALL(res, copy_recording_to_vm, (vm_rec_data));
  596. return res;
  597. }
  598. int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
  599. {
  600. int res = 0;
  601. if (newmsgs) {
  602. *newmsgs = 0;
  603. }
  604. if (oldmsgs) {
  605. *oldmsgs = 0;
  606. }
  607. VM_API_CALL(res, inboxcount, (mailboxes, newmsgs, oldmsgs));
  608. return res;
  609. }
  610. int ast_app_inboxcount2(const char *mailboxes, int *urgentmsgs, int *newmsgs, int *oldmsgs)
  611. {
  612. int res = 0;
  613. if (newmsgs) {
  614. *newmsgs = 0;
  615. }
  616. if (oldmsgs) {
  617. *oldmsgs = 0;
  618. }
  619. if (urgentmsgs) {
  620. *urgentmsgs = 0;
  621. }
  622. VM_API_CALL(res, inboxcount2, (mailboxes, urgentmsgs, newmsgs, oldmsgs));
  623. return res;
  624. }
  625. int ast_app_sayname(struct ast_channel *chan, const char *mailbox_id)
  626. {
  627. int res = -1;
  628. VM_GREETER_API_CALL(res, sayname, (chan, mailbox_id));
  629. return res;
  630. }
  631. int ast_app_messagecount(const char *mailbox_id, const char *folder)
  632. {
  633. int res = 0;
  634. VM_API_CALL(res, messagecount, (mailbox_id, folder));
  635. return res;
  636. }
  637. const char *ast_vm_index_to_foldername(int id)
  638. {
  639. const char *res = NULL;
  640. VM_API_CALL(res, index_to_foldername, (id));
  641. return res;
  642. }
  643. struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
  644. const char *context,
  645. const char *folder,
  646. int descending,
  647. enum ast_vm_snapshot_sort_val sort_val,
  648. int combine_INBOX_and_OLD)
  649. {
  650. struct ast_vm_mailbox_snapshot *res = NULL;
  651. VM_API_CALL(res, mailbox_snapshot_create, (mailbox, context, folder, descending,
  652. sort_val, combine_INBOX_and_OLD));
  653. return res;
  654. }
  655. struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
  656. {
  657. struct ast_vm_mailbox_snapshot *res = NULL;
  658. VM_API_CALL(res, mailbox_snapshot_destroy, (mailbox_snapshot));
  659. return res;
  660. }
  661. int ast_vm_msg_move(const char *mailbox,
  662. const char *context,
  663. size_t num_msgs,
  664. const char *oldfolder,
  665. const char *old_msg_ids[],
  666. const char *newfolder)
  667. {
  668. int res = 0;
  669. VM_API_CALL(res, msg_move, (mailbox, context, num_msgs, oldfolder, old_msg_ids,
  670. newfolder));
  671. return res;
  672. }
  673. int ast_vm_msg_remove(const char *mailbox,
  674. const char *context,
  675. size_t num_msgs,
  676. const char *folder,
  677. const char *msgs[])
  678. {
  679. int res = 0;
  680. VM_API_CALL(res, msg_remove, (mailbox, context, num_msgs, folder, msgs));
  681. return res;
  682. }
  683. int ast_vm_msg_forward(const char *from_mailbox,
  684. const char *from_context,
  685. const char *from_folder,
  686. const char *to_mailbox,
  687. const char *to_context,
  688. const char *to_folder,
  689. size_t num_msgs,
  690. const char *msg_ids[],
  691. int delete_old)
  692. {
  693. int res = 0;
  694. VM_API_CALL(res, msg_forward, (from_mailbox, from_context, from_folder, to_mailbox,
  695. to_context, to_folder, num_msgs, msg_ids, delete_old));
  696. return res;
  697. }
  698. int ast_vm_msg_play(struct ast_channel *chan,
  699. const char *mailbox,
  700. const char *context,
  701. const char *folder,
  702. const char *msg_num,
  703. ast_vm_msg_play_cb *cb)
  704. {
  705. int res = 0;
  706. VM_API_CALL(res, msg_play, (chan, mailbox, context, folder, msg_num, cb));
  707. return res;
  708. }
  709. #ifdef TEST_FRAMEWORK
  710. int ast_vm_test_create_user(const char *context, const char *mailbox)
  711. {
  712. if (ast_vm_test_create_user_func) {
  713. return ast_vm_test_create_user_func(context, mailbox);
  714. }
  715. return 0;
  716. }
  717. int ast_vm_test_destroy_user(const char *context, const char *mailbox)
  718. {
  719. if (ast_vm_test_destroy_user_func) {
  720. return ast_vm_test_destroy_user_func(context, mailbox);
  721. }
  722. return 0;
  723. }
  724. #endif
  725. int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
  726. {
  727. const char *ptr;
  728. int res;
  729. struct ast_silence_generator *silgen = NULL;
  730. if (!between) {
  731. between = 100;
  732. }
  733. if (peer && ast_autoservice_start(peer)) {
  734. return -1;
  735. }
  736. /* Need a quiet time before sending digits. */
  737. if (ast_opt_transmit_silence) {
  738. silgen = ast_channel_start_silence_generator(chan);
  739. }
  740. res = ast_safe_sleep(chan, 100);
  741. if (res) {
  742. goto dtmf_stream_cleanup;
  743. }
  744. for (ptr = digits; *ptr; ptr++) {
  745. if (*ptr == 'w') {
  746. /* 'w' -- wait half a second */
  747. if ((res = ast_safe_sleep(chan, 500))) {
  748. break;
  749. }
  750. } else if (*ptr == 'W') {
  751. /* 'W' -- wait a second */
  752. if ((res = ast_safe_sleep(chan, 1000))) {
  753. break;
  754. }
  755. } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
  756. if (*ptr == 'f' || *ptr == 'F') {
  757. /* ignore return values if not supported by channel */
  758. ast_indicate(chan, AST_CONTROL_FLASH);
  759. } else {
  760. /* Character represents valid DTMF */
  761. ast_senddigit(chan, *ptr, duration);
  762. }
  763. /* pause between digits */
  764. if ((res = ast_safe_sleep(chan, between))) {
  765. break;
  766. }
  767. } else {
  768. ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
  769. }
  770. }
  771. dtmf_stream_cleanup:
  772. if (silgen) {
  773. ast_channel_stop_silence_generator(chan, silgen);
  774. }
  775. if (peer && ast_autoservice_stop(peer)) {
  776. res = -1;
  777. }
  778. return res;
  779. }
  780. struct linear_state {
  781. int fd;
  782. int autoclose;
  783. int allowoverride;
  784. struct ast_format *origwfmt;
  785. };
  786. static void linear_release(struct ast_channel *chan, void *params)
  787. {
  788. struct linear_state *ls = params;
  789. if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
  790. ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n",
  791. ast_channel_name(chan), ast_format_get_name(ls->origwfmt));
  792. }
  793. ao2_cleanup(ls->origwfmt);
  794. if (ls->autoclose) {
  795. close(ls->fd);
  796. }
  797. ast_free(params);
  798. }
  799. static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
  800. {
  801. short buf[2048 + AST_FRIENDLY_OFFSET / 2];
  802. struct linear_state *ls = data;
  803. struct ast_frame f = {
  804. .frametype = AST_FRAME_VOICE,
  805. .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
  806. .offset = AST_FRIENDLY_OFFSET,
  807. };
  808. int res;
  809. f.subclass.format = ast_format_slin;
  810. len = samples * 2;
  811. if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
  812. ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
  813. len = sizeof(buf) - AST_FRIENDLY_OFFSET;
  814. }
  815. res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
  816. if (res > 0) {
  817. f.datalen = res;
  818. f.samples = res / 2;
  819. ast_write(chan, &f);
  820. if (res == len) {
  821. return 0;
  822. }
  823. }
  824. return -1;
  825. }
  826. static void *linear_alloc(struct ast_channel *chan, void *params)
  827. {
  828. struct linear_state *ls = params;
  829. if (!params) {
  830. return NULL;
  831. }
  832. /* In this case, params is already malloc'd */
  833. if (ls->allowoverride) {
  834. ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
  835. } else {
  836. ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
  837. }
  838. ls->origwfmt = ao2_bump(ast_channel_writeformat(chan));
  839. if (ast_set_write_format(chan, ast_format_slin)) {
  840. ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
  841. ao2_cleanup(ls->origwfmt);
  842. ast_free(ls);
  843. ls = params = NULL;
  844. }
  845. return params;
  846. }
  847. static struct ast_generator linearstream =
  848. {
  849. .alloc = linear_alloc,
  850. .release = linear_release,
  851. .generate = linear_generator,
  852. };
  853. int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
  854. {
  855. struct linear_state *lin;
  856. char tmpf[256];
  857. int res = -1;
  858. int autoclose = 0;
  859. if (fd < 0) {
  860. if (ast_strlen_zero(filename)) {
  861. return -1;
  862. }
  863. autoclose = 1;
  864. if (filename[0] == '/') {
  865. ast_copy_string(tmpf, filename, sizeof(tmpf));
  866. } else {
  867. snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
  868. }
  869. if ((fd = open(tmpf, O_RDONLY)) < 0) {
  870. ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
  871. return -1;
  872. }
  873. }
  874. if ((lin = ast_calloc(1, sizeof(*lin)))) {
  875. lin->fd = fd;
  876. lin->allowoverride = allowoverride;
  877. lin->autoclose = autoclose;
  878. res = ast_activate_generator(chan, &linearstream, lin);
  879. }
  880. return res;
  881. }
  882. static int control_streamfile(struct ast_channel *chan,
  883. const char *file,
  884. const char *fwd,
  885. const char *rev,
  886. const char *stop,
  887. const char *suspend,
  888. const char *restart,
  889. int skipms,
  890. long *offsetms,
  891. const char *lang,
  892. ast_waitstream_fr_cb cb)
  893. {
  894. char *breaks = NULL;
  895. char *end = NULL;
  896. int blen = 2;
  897. int res;
  898. long pause_restart_point = 0;
  899. long offset = 0;
  900. if (!file) {
  901. return -1;
  902. }
  903. if (offsetms) {
  904. offset = *offsetms * 8; /* XXX Assumes 8kHz */
  905. }
  906. if (lang == NULL) {
  907. lang = ast_channel_language(chan);
  908. }
  909. if (stop) {
  910. blen += strlen(stop);
  911. }
  912. if (suspend) {
  913. blen += strlen(suspend);
  914. }
  915. if (restart) {
  916. blen += strlen(restart);
  917. }
  918. if (blen > 2) {
  919. breaks = ast_alloca(blen + 1);
  920. breaks[0] = '\0';
  921. if (stop) {
  922. strcat(breaks, stop);
  923. }
  924. if (suspend) {
  925. strcat(breaks, suspend);
  926. }
  927. if (restart) {
  928. strcat(breaks, restart);
  929. }
  930. }
  931. if ((end = strchr(file, ':'))) {
  932. if (!strcasecmp(end, ":end")) {
  933. *end = '\0';
  934. end++;
  935. }
  936. }
  937. for (;;) {
  938. ast_stopstream(chan);
  939. res = ast_streamfile(chan, file, lang);
  940. if (!res) {
  941. if (pause_restart_point) {
  942. ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
  943. pause_restart_point = 0;
  944. }
  945. else if (end || offset < 0) {
  946. if (offset == -8) {
  947. offset = 0;
  948. }
  949. ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
  950. ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
  951. end = NULL;
  952. offset = 0;
  953. } else if (offset) {
  954. ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
  955. ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
  956. offset = 0;
  957. }
  958. if (cb) {
  959. res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
  960. } else {
  961. res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
  962. }
  963. }
  964. if (res < 1) {
  965. break;
  966. }
  967. /* We go at next loop if we got the restart char */
  968. if ((restart && strchr(restart, res)) || res == AST_CONTROL_STREAM_RESTART) {
  969. ast_debug(1, "we'll restart the stream here at next loop\n");
  970. pause_restart_point = 0;
  971. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  972. "Control: %s\r\n",
  973. ast_channel_name(chan),
  974. "Restart");
  975. continue;
  976. }
  977. if ((suspend && strchr(suspend, res)) || res == AST_CONTROL_STREAM_SUSPEND) {
  978. pause_restart_point = ast_tellstream(ast_channel_stream(chan));
  979. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  980. "Control: %s\r\n",
  981. ast_channel_name(chan),
  982. "Pause");
  983. for (;;) {
  984. ast_stopstream(chan);
  985. if (!(res = ast_waitfordigit(chan, 1000))) {
  986. continue;
  987. } else if (res == -1 || (suspend && strchr(suspend, res)) || (stop && strchr(stop, res))
  988. || res == AST_CONTROL_STREAM_SUSPEND || res == AST_CONTROL_STREAM_STOP) {
  989. break;
  990. }
  991. }
  992. if ((suspend && (res == *suspend)) || res == AST_CONTROL_STREAM_SUSPEND) {
  993. res = 0;
  994. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  995. "Control: %s\r\n",
  996. ast_channel_name(chan),
  997. "Unpause");
  998. continue;
  999. }
  1000. }
  1001. if (res == -1) {
  1002. break;
  1003. }
  1004. /* if we get one of our stop chars, return it to the calling function */
  1005. if ((stop && strchr(stop, res)) || res == AST_CONTROL_STREAM_STOP) {
  1006. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1007. "Control: %s\r\n",
  1008. ast_channel_name(chan),
  1009. "Stop");
  1010. break;
  1011. }
  1012. }
  1013. if (pause_restart_point) {
  1014. offset = pause_restart_point;
  1015. } else {
  1016. if (ast_channel_stream(chan)) {
  1017. offset = ast_tellstream(ast_channel_stream(chan));
  1018. } else {
  1019. offset = -8; /* indicate end of file */
  1020. }
  1021. }
  1022. if (offsetms) {
  1023. *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
  1024. }
  1025. ast_stopstream(chan);
  1026. return res;
  1027. }
  1028. int ast_control_streamfile_w_cb(struct ast_channel *chan,
  1029. const char *file,
  1030. const char *fwd,
  1031. const char *rev,
  1032. const char *stop,
  1033. const char *suspend,
  1034. const char *restart,
  1035. int skipms,
  1036. long *offsetms,
  1037. ast_waitstream_fr_cb cb)
  1038. {
  1039. return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, cb);
  1040. }
  1041. int ast_control_streamfile(struct ast_channel *chan, const char *file,
  1042. const char *fwd, const char *rev,
  1043. const char *stop, const char *suspend,
  1044. const char *restart, int skipms, long *offsetms)
  1045. {
  1046. return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, NULL);
  1047. }
  1048. int ast_control_streamfile_lang(struct ast_channel *chan, const char *file,
  1049. const char *fwd, const char *rev, const char *stop, const char *suspend,
  1050. const char *restart, int skipms, const char *lang, long *offsetms)
  1051. {
  1052. return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, lang, NULL);
  1053. }
  1054. enum control_tone_frame_response_result {
  1055. CONTROL_TONE_RESPONSE_FAILED = -1,
  1056. CONTROL_TONE_RESPONSE_NORMAL = 0,
  1057. CONTROL_TONE_RESPONSE_FINISHED = 1,
  1058. };
  1059. static enum control_tone_frame_response_result control_tone_frame_response(struct ast_channel *chan, struct ast_frame *fr, struct ast_tone_zone_sound *ts, const char *tone, int *paused)
  1060. {
  1061. switch (fr->subclass.integer) {
  1062. case AST_CONTROL_STREAM_STOP:
  1063. ast_playtones_stop(chan);
  1064. return CONTROL_TONE_RESPONSE_FINISHED;
  1065. case AST_CONTROL_STREAM_SUSPEND:
  1066. if (*paused) {
  1067. *paused = 0;
  1068. if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
  1069. return CONTROL_TONE_RESPONSE_FAILED;
  1070. }
  1071. } else {
  1072. *paused = 1;
  1073. ast_playtones_stop(chan);
  1074. }
  1075. return CONTROL_TONE_RESPONSE_NORMAL;
  1076. case AST_CONTROL_STREAM_RESTART:
  1077. ast_playtones_stop(chan);
  1078. if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
  1079. return CONTROL_TONE_RESPONSE_FAILED;
  1080. }
  1081. return CONTROL_TONE_RESPONSE_NORMAL;
  1082. case AST_CONTROL_STREAM_REVERSE:
  1083. ast_log(LOG_NOTICE, "Media control operation 'reverse' not supported for media type 'tone'\n");
  1084. return CONTROL_TONE_RESPONSE_NORMAL;
  1085. case AST_CONTROL_STREAM_FORWARD:
  1086. ast_log(LOG_NOTICE, "Media control operation 'forward' not supported for media type 'tone'\n");
  1087. return CONTROL_TONE_RESPONSE_NORMAL;
  1088. case AST_CONTROL_HANGUP:
  1089. case AST_CONTROL_BUSY:
  1090. case AST_CONTROL_CONGESTION:
  1091. return CONTROL_TONE_RESPONSE_FINISHED;
  1092. }
  1093. return CONTROL_TONE_RESPONSE_NORMAL;
  1094. }
  1095. static int parse_tone_uri(char *tone_parser,
  1096. const char **tone_indication,
  1097. const char **tone_zone)
  1098. {
  1099. *tone_indication = strsep(&tone_parser, ";");
  1100. if (ast_strlen_zero(tone_parser)) {
  1101. /* Only the indication is included */
  1102. return 0;
  1103. }
  1104. if (!(strncmp(tone_parser, "tonezone=", 9))) {
  1105. *tone_zone = tone_parser + 9;
  1106. } else {
  1107. ast_log(LOG_ERROR, "Unexpected Tone URI component: %s\n", tone_parser);
  1108. return -1;
  1109. }
  1110. return 0;
  1111. }
  1112. int ast_control_tone(struct ast_channel *chan, const char *tone)
  1113. {
  1114. struct ast_tone_zone *zone = NULL;
  1115. struct ast_tone_zone_sound *ts;
  1116. int paused = 0;
  1117. int res = 0;
  1118. const char *tone_indication = NULL;
  1119. const char *tone_zone = NULL;
  1120. char *tone_uri_parser;
  1121. if (ast_strlen_zero(tone)) {
  1122. return -1;
  1123. }
  1124. tone_uri_parser = ast_strdupa(tone);
  1125. if (parse_tone_uri(tone_uri_parser, &tone_indication, &tone_zone)) {
  1126. return -1;
  1127. }
  1128. if (tone_zone) {
  1129. zone = ast_get_indication_zone(tone_zone);
  1130. }
  1131. ts = ast_get_indication_tone(zone ? zone : ast_channel_zone(chan), tone_indication);
  1132. if (ast_playtones_start(chan, 0, ts ? ts->data : tone_indication, 0)) {
  1133. return -1;
  1134. }
  1135. for (;;) {
  1136. struct ast_frame *fr;
  1137. if (ast_waitfor(chan, -1) < 0) {
  1138. res = -1;
  1139. break;
  1140. }
  1141. fr = ast_read_noaudio(chan);
  1142. if (!fr) {
  1143. res = -1;
  1144. break;
  1145. }
  1146. if (fr->frametype != AST_FRAME_CONTROL) {
  1147. continue;
  1148. }
  1149. res = control_tone_frame_response(chan, fr, ts, tone_indication, &paused);
  1150. if (res == CONTROL_TONE_RESPONSE_FINISHED) {
  1151. res = 0;
  1152. break;
  1153. } else if (res == CONTROL_TONE_RESPONSE_FAILED) {
  1154. res = -1;
  1155. break;
  1156. }
  1157. }
  1158. if (ts) {
  1159. ast_tone_zone_sound_unref(ts);
  1160. }
  1161. if (zone) {
  1162. ast_tone_zone_unref(zone);
  1163. }
  1164. return res;
  1165. }
  1166. int ast_play_and_wait(struct ast_channel *chan, const char *fn)
  1167. {
  1168. int d = 0;
  1169. if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
  1170. return d;
  1171. }
  1172. d = ast_waitstream(chan, AST_DIGIT_ANY);
  1173. ast_stopstream(chan);
  1174. return d;
  1175. }
  1176. /*!
  1177. * \brief Construct a silence frame of the same duration as \a orig.
  1178. *
  1179. * The \a orig frame must be \ref AST_FORMAT_SLINEAR.
  1180. *
  1181. * \param orig Frame as basis for silence to generate.
  1182. * \return New frame of silence; free with ast_frfree().
  1183. * \return \c NULL on error.
  1184. */
  1185. static struct ast_frame *make_silence(const struct ast_frame *orig)
  1186. {
  1187. struct ast_frame *silence;
  1188. size_t size;
  1189. size_t datalen;
  1190. size_t samples = 0;
  1191. struct ast_frame *next;
  1192. if (!orig) {
  1193. return NULL;
  1194. }
  1195. if (ast_format_cmp(orig->subclass.format, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
  1196. ast_log(LOG_WARNING, "Attempting to silence non-slin frame\n");
  1197. return NULL;
  1198. }
  1199. for (next = AST_LIST_NEXT(orig, frame_list);
  1200. orig;
  1201. orig = next, next = orig ? AST_LIST_NEXT(orig, frame_list) : NULL) {
  1202. samples += orig->samples;
  1203. }
  1204. ast_verb(4, "Silencing %zu samples\n", samples);
  1205. datalen = sizeof(short) * samples;
  1206. size = sizeof(*silence) + datalen;
  1207. silence = ast_calloc(1, size);
  1208. if (!silence) {
  1209. return NULL;
  1210. }
  1211. silence->mallocd = AST_MALLOCD_HDR;
  1212. silence->frametype = AST_FRAME_VOICE;
  1213. silence->data.ptr = (void *)(silence + 1);
  1214. silence->samples = samples;
  1215. silence->datalen = datalen;
  1216. silence->subclass.format = ast_format_slin;
  1217. return silence;
  1218. }
  1219. /*!
  1220. * \brief Sets a channel's read format to \ref AST_FORMAT_SLINEAR, recording
  1221. * its original format.
  1222. *
  1223. * \param chan Channel to modify.
  1224. * \param[out] orig_format Output variable to store channel's original read
  1225. * format.
  1226. * \return 0 on success.
  1227. * \return -1 on error.
  1228. */
  1229. static int set_read_to_slin(struct ast_channel *chan, struct ast_format **orig_format)
  1230. {
  1231. if (!chan || !orig_format) {
  1232. return -1;
  1233. }
  1234. *orig_format = ao2_bump(ast_channel_readformat(chan));
  1235. return ast_set_read_format(chan, ast_format_slin);
  1236. }
  1237. static int global_silence_threshold = 128;
  1238. static int global_maxsilence = 0;
  1239. /*! Optionally play a sound file or a beep, then record audio and video from the channel.
  1240. * \param chan Channel to playback to/record from.
  1241. * \param playfile Filename of sound to play before recording begins.
  1242. * \param recordfile Filename to record to.
  1243. * \param maxtime Maximum length of recording (in seconds).
  1244. * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
  1245. * \param duration Where to store actual length of the recorded message (in milliseconds).
  1246. * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
  1247. * \param beep Whether to play a beep before starting to record.
  1248. * \param silencethreshold
  1249. * \param maxsilence Length of silence that will end a recording (in milliseconds).
  1250. * \param path Optional filesystem path to unlock.
  1251. * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
  1252. * \param acceptdtmf DTMF digits that will end the recording.
  1253. * \param canceldtmf DTMF digits that will cancel the recording.
  1254. * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
  1255. *
  1256. * \retval -1 failure or hangup
  1257. * \retval 'S' Recording ended from silence timeout
  1258. * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
  1259. * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
  1260. */
  1261. static int __ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence, const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf, int skip_confirmation_sound, enum ast_record_if_exists if_exists)
  1262. {
  1263. int d = 0;
  1264. char *fmts;
  1265. char comment[256];
  1266. int x, fmtcnt = 1, res = -1, outmsg = 0;
  1267. struct ast_filestream *others[AST_MAX_FORMATS];
  1268. char *sfmt[AST_MAX_FORMATS];
  1269. char *stringp = NULL;
  1270. time_t start, end;
  1271. struct ast_dsp *sildet = NULL; /* silence detector dsp */
  1272. int totalsilence = 0;
  1273. int dspsilence = 0;
  1274. int olddspsilence = 0;
  1275. struct ast_format *rfmt = NULL;
  1276. struct ast_silence_generator *silgen = NULL;
  1277. char prependfile[PATH_MAX];
  1278. int ioflags; /* IO flags for writing output file */
  1279. ioflags = O_CREAT|O_WRONLY;
  1280. switch (if_exists) {
  1281. case AST_RECORD_IF_EXISTS_FAIL:
  1282. ioflags |= O_EXCL;
  1283. break;
  1284. case AST_RECORD_IF_EXISTS_OVERWRITE:
  1285. ioflags |= O_TRUNC;
  1286. break;
  1287. case AST_RECORD_IF_EXISTS_APPEND:
  1288. ioflags |= O_APPEND;
  1289. break;
  1290. }
  1291. if (silencethreshold < 0) {
  1292. silencethreshold = global_silence_threshold;
  1293. }
  1294. if (maxsilence < 0) {
  1295. maxsilence = global_maxsilence;
  1296. }
  1297. /* barf if no pointer passed to store duration in */
  1298. if (!duration) {
  1299. ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
  1300. return -1;
  1301. }
  1302. ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
  1303. snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
  1304. if (playfile || beep) {
  1305. if (!beep) {
  1306. d = ast_play_and_wait(chan, playfile);
  1307. }
  1308. if (d > -1) {
  1309. d = ast_stream_and_wait(chan, "beep", "");
  1310. }
  1311. if (d < 0) {
  1312. return -1;
  1313. }
  1314. }
  1315. if (prepend) {
  1316. ast_copy_string(prependfile, recordfile, sizeof(prependfile));
  1317. strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
  1318. }
  1319. fmts = ast_strdupa(fmt);
  1320. stringp = fmts;
  1321. strsep(&stringp, "|");
  1322. ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
  1323. sfmt[0] = ast_strdupa(fmts);
  1324. while ((fmt = strsep(&stringp, "|"))) {
  1325. if (fmtcnt > AST_MAX_FORMATS - 1) {
  1326. ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
  1327. break;
  1328. }
  1329. sfmt[fmtcnt++] = ast_strdupa(fmt);
  1330. }
  1331. end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
  1332. for (x = 0; x < fmtcnt; x++) {
  1333. others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, ioflags, 0, AST_FILE_MODE);
  1334. ast_verb(3, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
  1335. if (!others[x]) {
  1336. break;
  1337. }
  1338. }
  1339. if (path) {
  1340. ast_unlock_path(path);
  1341. }
  1342. if (maxsilence > 0) {
  1343. sildet = ast_dsp_new(); /* Create the silence detector */
  1344. if (!sildet) {
  1345. ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
  1346. return -1;
  1347. }
  1348. ast_dsp_set_threshold(sildet, silencethreshold);
  1349. res = set_read_to_slin(chan, &rfmt);
  1350. if (res < 0) {
  1351. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  1352. ast_dsp_free(sildet);
  1353. ao2_cleanup(rfmt);
  1354. return -1;
  1355. }
  1356. }
  1357. if (!prepend) {
  1358. /* Request a video update */
  1359. ast_indicate(chan, AST_CONTROL_VIDUPDATE);
  1360. if (ast_opt_transmit_silence) {
  1361. silgen = ast_channel_start_silence_generator(chan);
  1362. }
  1363. }
  1364. if (x == fmtcnt) {
  1365. /* Loop, writing the packets we read to the writer(s), until
  1366. * we have reason to stop. */
  1367. struct ast_frame *f;
  1368. int paused = 0;
  1369. int muted = 0;
  1370. time_t pause_start = 0;
  1371. int paused_secs = 0;
  1372. int pausedsilence = 0;
  1373. for (;;) {
  1374. if (!(res = ast_waitfor(chan, 2000))) {
  1375. ast_debug(1, "One waitfor failed, trying another\n");
  1376. /* Try one more time in case of masq */
  1377. if (!(res = ast_waitfor(chan, 2000))) {
  1378. ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
  1379. res = -1;
  1380. }
  1381. }
  1382. if (res < 0) {
  1383. f = NULL;
  1384. break;
  1385. }
  1386. if (!(f = ast_read(chan))) {
  1387. break;
  1388. }
  1389. if (f->frametype == AST_FRAME_VOICE) {
  1390. /* write each format */
  1391. if (paused) {
  1392. /* It's all good */
  1393. res = 0;
  1394. } else {
  1395. RAII_VAR(struct ast_frame *, silence, NULL, ast_frame_dtor);
  1396. struct ast_frame *orig = f;
  1397. if (muted) {
  1398. silence = make_silence(orig);
  1399. if (!silence) {
  1400. ast_log(LOG_WARNING,
  1401. "Error creating silence\n");
  1402. break;
  1403. }
  1404. f = silence;
  1405. }
  1406. for (x = 0; x < fmtcnt; x++) {
  1407. if (prepend && !others[x]) {
  1408. break;
  1409. }
  1410. res = ast_writestream(others[x], f);
  1411. }
  1412. f = orig;
  1413. }
  1414. /* Silence Detection */
  1415. if (maxsilence > 0) {
  1416. dspsilence = 0;
  1417. ast_dsp_silence(sildet, f, &dspsilence);
  1418. if (olddspsilence > dspsilence) {
  1419. totalsilence += olddspsilence;
  1420. }
  1421. olddspsilence = dspsilence;
  1422. if (paused) {
  1423. /* record how much silence there was while we are paused */
  1424. pausedsilence = dspsilence;
  1425. } else if (dspsilence > pausedsilence) {
  1426. /* ignore the paused silence */
  1427. dspsilence -= pausedsilence;
  1428. } else {
  1429. /* dspsilence has reset, reset pausedsilence */
  1430. pausedsilence = 0;
  1431. }
  1432. if (dspsilence > maxsilence) {
  1433. /* Ended happily with silence */
  1434. ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
  1435. res = 'S';
  1436. outmsg = 2;
  1437. break;
  1438. }
  1439. }
  1440. /* Exit on any error */
  1441. if (res) {
  1442. ast_log(LOG_WARNING, "Error writing frame\n");
  1443. break;
  1444. }
  1445. } else if (f->frametype == AST_FRAME_VIDEO) {
  1446. /* Write only once */
  1447. ast_writestream(others[0], f);
  1448. } else if (f->frametype == AST_FRAME_DTMF) {
  1449. if (prepend) {
  1450. /* stop recording with any digit */
  1451. ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
  1452. res = 't';
  1453. outmsg = 2;
  1454. break;
  1455. }
  1456. if (strchr(acceptdtmf, f->subclass.integer)) {
  1457. ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
  1458. res = f->subclass.integer;
  1459. outmsg = 2;
  1460. break;
  1461. }
  1462. if (strchr(canceldtmf, f->subclass.integer)) {
  1463. ast_verb(3, "User canceled message by pressing %c\n", f->subclass.integer);
  1464. res = f->subclass.integer;
  1465. outmsg = 0;
  1466. break;
  1467. }
  1468. } else if (f->frametype == AST_FRAME_CONTROL) {
  1469. if (f->subclass.integer == AST_CONTROL_RECORD_CANCEL) {
  1470. ast_verb(3, "Message canceled by control\n");
  1471. outmsg = 0; /* cancels the recording */
  1472. res = 0;
  1473. break;
  1474. } else if (f->subclass.integer == AST_CONTROL_RECORD_STOP) {
  1475. ast_verb(3, "Message ended by control\n");
  1476. res = 0;
  1477. break;
  1478. } else if (f->subclass.integer == AST_CONTROL_RECORD_SUSPEND) {
  1479. paused = !paused;
  1480. ast_verb(3, "Message %spaused by control\n",
  1481. paused ? "" : "un");
  1482. if (paused) {
  1483. pause_start = time(NULL);
  1484. } else {
  1485. paused_secs += time(NULL) - pause_start;
  1486. }
  1487. } else if (f->subclass.integer == AST_CONTROL_RECORD_MUTE) {
  1488. muted = !muted;
  1489. ast_verb(3, "Message %smuted by control\n",
  1490. muted ? "" : "un");
  1491. /* We can only silence slin frames, so
  1492. * set the mode, if we haven't already
  1493. * for sildet
  1494. */
  1495. if (muted && !rfmt) {
  1496. ast_verb(3, "Setting read format to linear mode\n");
  1497. res = set_read_to_slin(chan, &rfmt);
  1498. if (res < 0) {
  1499. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  1500. break;
  1501. }
  1502. }
  1503. }
  1504. }
  1505. if (maxtime && !paused) {
  1506. end = time(NULL);
  1507. if (maxtime < (end - start - paused_secs)) {
  1508. ast_verb(3, "Took too long, cutting it short...\n");
  1509. res = 't';
  1510. outmsg = 2;
  1511. break;
  1512. }
  1513. }
  1514. ast_frfree(f);
  1515. }
  1516. if (!f) {
  1517. ast_verb(3, "User hung up\n");
  1518. res = -1;
  1519. outmsg = 1;
  1520. } else {
  1521. ast_frfree(f);
  1522. }
  1523. } else {
  1524. ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
  1525. }
  1526. if (!prepend) {
  1527. if (silgen) {
  1528. ast_channel_stop_silence_generator(chan, silgen);
  1529. }
  1530. }
  1531. /*!\note
  1532. * Instead of asking how much time passed (end - start), calculate the number
  1533. * of seconds of audio which actually went into the file. This fixes a
  1534. * problem where audio is stopped up on the network and never gets to us.
  1535. *
  1536. * Note that we still want to use the number of seconds passed for the max
  1537. * message, otherwise we could get a situation where this stream is never
  1538. * closed (which would create a resource leak).
  1539. */
  1540. *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
  1541. if (sound_duration) {
  1542. *sound_duration = *duration;
  1543. }
  1544. if (!prepend) {
  1545. /* Reduce duration by a total silence amount */
  1546. if (olddspsilence <= dspsilence) {
  1547. totalsilence += dspsilence;
  1548. }
  1549. if (sound_duration) {
  1550. if (totalsilence > 0) {
  1551. *sound_duration -= (totalsilence - 200) / 1000;
  1552. }
  1553. if (*sound_duration < 0) {
  1554. *sound_duration = 0;
  1555. }
  1556. }
  1557. if (dspsilence > 0) {
  1558. *duration -= (dspsilence - 200) / 1000;
  1559. }
  1560. if (*duration < 0) {
  1561. *duration = 0;
  1562. }
  1563. for (x = 0; x < fmtcnt; x++) {
  1564. if (!others[x]) {
  1565. break;
  1566. }
  1567. /*!\note
  1568. * If we ended with silence, trim all but the first 200ms of silence
  1569. * off the recording. However, if we ended with '#', we don't want
  1570. * to trim ANY part of the recording.
  1571. */
  1572. if (res > 0 && dspsilence) {
  1573. /* rewind only the trailing silence */
  1574. ast_stream_rewind(others[x], dspsilence - 200);
  1575. }
  1576. ast_truncstream(others[x]);
  1577. ast_closestream(others[x]);
  1578. }
  1579. } else if (prepend && outmsg) {
  1580. struct ast_filestream *realfiles[AST_MAX_FORMATS];
  1581. struct ast_frame *fr;
  1582. for (x = 0; x < fmtcnt; x++) {
  1583. snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
  1584. realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
  1585. if (!others[x]) {
  1586. break;
  1587. }
  1588. if (!realfiles[x]) {
  1589. ast_closestream(others[x]);
  1590. continue;
  1591. }
  1592. /*!\note Same logic as above. */
  1593. if (dspsilence) {
  1594. ast_stream_rewind(others[x], dspsilence - 200);
  1595. }
  1596. ast_truncstream(others[x]);
  1597. /* add the original file too */
  1598. while ((fr = ast_readframe(realfiles[x]))) {
  1599. ast_writestream(others[x], fr);
  1600. ast_frfree(fr);
  1601. }
  1602. ast_closestream(others[x]);
  1603. ast_closestream(realfiles[x]);
  1604. ast_filerename(prependfile, recordfile, sfmt[x]);
  1605. ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
  1606. ast_filedelete(prependfile, sfmt[x]);
  1607. }
  1608. } else {
  1609. for (x = 0; x < fmtcnt; x++) {
  1610. if (!others[x]) {
  1611. break;
  1612. }
  1613. ast_closestream(others[x]);
  1614. }
  1615. }
  1616. if (rfmt && ast_set_read_format(chan, rfmt)) {
  1617. ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_format_get_name(rfmt), ast_channel_name(chan));
  1618. }
  1619. ao2_cleanup(rfmt);
  1620. if ((outmsg == 2) && (!skip_confirmation_sound)) {
  1621. ast_stream_and_wait(chan, "auth-thankyou", "");
  1622. }
  1623. if (sildet) {
  1624. ast_dsp_free(sildet);
  1625. }
  1626. return res;
  1627. }
  1628. static const char default_acceptdtmf[] = "#";
  1629. static const char default_canceldtmf[] = "";
  1630. int ast_play_and_record_full(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf, int skip_confirmation_sound, enum ast_record_if_exists if_exists)
  1631. {
  1632. return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, ""), S_OR(canceldtmf, default_canceldtmf), skip_confirmation_sound, if_exists);
  1633. }
  1634. int ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int silencethreshold, int maxsilence, const char *path)
  1635. {
  1636. return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf, 0, AST_RECORD_IF_EXISTS_OVERWRITE);
  1637. }
  1638. int ast_play_and_prepend(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence)
  1639. {
  1640. return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf, 1, AST_RECORD_IF_EXISTS_OVERWRITE);
  1641. }
  1642. /* Channel group core functions */
  1643. int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
  1644. {
  1645. int res = 0;
  1646. char tmp[256];
  1647. char *grp = NULL, *cat = NULL;
  1648. if (!ast_strlen_zero(data)) {
  1649. ast_copy_string(tmp, data, sizeof(tmp));
  1650. grp = tmp;
  1651. if ((cat = strchr(tmp, '@'))) {
  1652. *cat++ = '\0';
  1653. }
  1654. }
  1655. if (!ast_strlen_zero(grp)) {
  1656. ast_copy_string(group, grp, group_max);
  1657. } else {
  1658. *group = '\0';
  1659. }
  1660. if (!ast_strlen_zero(cat)) {
  1661. ast_copy_string(category, cat, category_max);
  1662. }
  1663. return res;
  1664. }
  1665. int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
  1666. {
  1667. int res = 0;
  1668. char group[80] = "", category[80] = "";
  1669. struct ast_group_info *gi = NULL;
  1670. size_t len = 0;
  1671. if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
  1672. return -1;
  1673. }
  1674. /* Calculate memory we will need if this is new */
  1675. len = sizeof(*gi) + strlen(group) + 1;
  1676. if (!ast_strlen_zero(category)) {
  1677. len += strlen(category) + 1;
  1678. }
  1679. AST_RWLIST_WRLOCK(&groups);
  1680. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1681. if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
  1682. AST_RWLIST_REMOVE_CURRENT(group_list);
  1683. ast_free(gi);
  1684. break;
  1685. }
  1686. }
  1687. AST_RWLIST_TRAVERSE_SAFE_END;
  1688. if (ast_strlen_zero(group)) {
  1689. /* Enable unsetting the group */
  1690. } else if ((gi = ast_calloc(1, len))) {
  1691. gi->chan = chan;
  1692. gi->group = (char *) gi + sizeof(*gi);
  1693. strcpy(gi->group, group);
  1694. if (!ast_strlen_zero(category)) {
  1695. gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
  1696. strcpy(gi->category, category);
  1697. }
  1698. AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
  1699. } else {
  1700. res = -1;
  1701. }
  1702. AST_RWLIST_UNLOCK(&groups);
  1703. return res;
  1704. }
  1705. int ast_app_group_get_count(const char *group, const char *category)
  1706. {
  1707. struct ast_group_info *gi = NULL;
  1708. int count = 0;
  1709. if (ast_strlen_zero(group)) {
  1710. return 0;
  1711. }
  1712. AST_RWLIST_RDLOCK(&groups);
  1713. AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
  1714. if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
  1715. count++;
  1716. }
  1717. }
  1718. AST_RWLIST_UNLOCK(&groups);
  1719. return count;
  1720. }
  1721. int ast_app_group_match_get_count(const char *groupmatch, const char *category)
  1722. {
  1723. struct ast_group_info *gi = NULL;
  1724. regex_t regexbuf_group;
  1725. regex_t regexbuf_category;
  1726. int count = 0;
  1727. if (ast_strlen_zero(groupmatch)) {
  1728. ast_log(LOG_NOTICE, "groupmatch empty\n");
  1729. return 0;
  1730. }
  1731. /* if regex compilation fails, return zero matches */
  1732. if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
  1733. ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
  1734. return 0;
  1735. }
  1736. if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
  1737. ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
  1738. regfree(&regexbuf_group);
  1739. return 0;
  1740. }
  1741. AST_RWLIST_RDLOCK(&groups);
  1742. AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
  1743. if (!regexec(&regexbuf_group, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !regexec(&regexbuf_category, gi->category, 0, NULL, 0)))) {
  1744. count++;
  1745. }
  1746. }
  1747. AST_RWLIST_UNLOCK(&groups);
  1748. regfree(&regexbuf_group);
  1749. if (!ast_strlen_zero(category)) {
  1750. regfree(&regexbuf_category);
  1751. }
  1752. return count;
  1753. }
  1754. int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
  1755. {
  1756. struct ast_group_info *gi = NULL;
  1757. AST_RWLIST_WRLOCK(&groups);
  1758. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1759. if (gi->chan == old) {
  1760. gi->chan = new;
  1761. } else if (gi->chan == new) {
  1762. AST_RWLIST_REMOVE_CURRENT(group_list);
  1763. ast_free(gi);
  1764. }
  1765. }
  1766. AST_RWLIST_TRAVERSE_SAFE_END;
  1767. AST_RWLIST_UNLOCK(&groups);
  1768. return 0;
  1769. }
  1770. int ast_app_group_discard(struct ast_channel *chan)
  1771. {
  1772. struct ast_group_info *gi = NULL;
  1773. AST_RWLIST_WRLOCK(&groups);
  1774. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1775. if (gi->chan == chan) {
  1776. AST_RWLIST_REMOVE_CURRENT(group_list);
  1777. ast_free(gi);
  1778. }
  1779. }
  1780. AST_RWLIST_TRAVERSE_SAFE_END;
  1781. AST_RWLIST_UNLOCK(&groups);
  1782. return 0;
  1783. }
  1784. int ast_app_group_list_wrlock(void)
  1785. {
  1786. return AST_RWLIST_WRLOCK(&groups);
  1787. }
  1788. int ast_app_group_list_rdlock(void)
  1789. {
  1790. return AST_RWLIST_RDLOCK(&groups);
  1791. }
  1792. struct ast_group_info *ast_app_group_list_head(void)
  1793. {
  1794. return AST_RWLIST_FIRST(&groups);
  1795. }
  1796. int ast_app_group_list_unlock(void)
  1797. {
  1798. return AST_RWLIST_UNLOCK(&groups);
  1799. }
  1800. #undef ast_app_separate_args
  1801. unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
  1802. unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
  1803. {
  1804. int argc;
  1805. char *scan, *wasdelim = NULL;
  1806. int paren = 0, quote = 0, bracket = 0;
  1807. if (!array || !arraylen) {
  1808. return 0;
  1809. }
  1810. memset(array, 0, arraylen * sizeof(*array));
  1811. if (!buf) {
  1812. return 0;
  1813. }
  1814. scan = buf;
  1815. for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
  1816. array[argc] = scan;
  1817. for (; *scan; scan++) {
  1818. if (*scan == '(') {
  1819. paren++;
  1820. } else if (*scan == ')') {
  1821. if (paren) {
  1822. paren--;
  1823. }
  1824. } else if (*scan == '[') {
  1825. bracket++;
  1826. } else if (*scan == ']') {
  1827. if (bracket) {
  1828. bracket--;
  1829. }
  1830. } else if (*scan == '"' && delim != '"') {
  1831. quote = quote ? 0 : 1;
  1832. if (remove_chars) {
  1833. /* Remove quote character from argument */
  1834. memmove(scan, scan + 1, strlen(scan));
  1835. scan--;
  1836. }
  1837. } else if (*scan == '\\') {
  1838. if (remove_chars) {
  1839. /* Literal character, don't parse */
  1840. memmove(scan, scan + 1, strlen(scan));
  1841. } else {
  1842. scan++;
  1843. }
  1844. } else if ((*scan == delim) && !paren && !quote && !bracket) {
  1845. wasdelim = scan;
  1846. *scan++ = '\0';
  1847. break;
  1848. }
  1849. }
  1850. }
  1851. /* If the last character in the original string was the delimiter, then
  1852. * there is one additional argument. */
  1853. if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
  1854. array[argc++] = scan;
  1855. }
  1856. return argc;
  1857. }
  1858. /* ABI compatible function */
  1859. unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
  1860. {
  1861. return __ast_app_separate_args(buf, delim, 1, array, arraylen);
  1862. }
  1863. static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
  1864. {
  1865. char *s;
  1866. char *fs;
  1867. int res;
  1868. int fd;
  1869. int lp = strlen(path);
  1870. time_t start;
  1871. s = ast_alloca(lp + 10);
  1872. fs = ast_alloca(lp + 20);
  1873. snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, (unsigned long)ast_random());
  1874. fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
  1875. if (fd < 0) {
  1876. ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
  1877. return AST_LOCK_PATH_NOT_FOUND;
  1878. }
  1879. close(fd);
  1880. snprintf(s, strlen(path) + 9, "%s/.lock", path);
  1881. start = time(NULL);
  1882. while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
  1883. sched_yield();
  1884. }
  1885. unlink(fs);
  1886. if (res) {
  1887. ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
  1888. return AST_LOCK_TIMEOUT;
  1889. } else {
  1890. ast_debug(1, "Locked path '%s'\n", path);
  1891. return AST_LOCK_SUCCESS;
  1892. }
  1893. }
  1894. static int ast_unlock_path_lockfile(const char *path)
  1895. {
  1896. char *s;
  1897. int res;
  1898. s = ast_alloca(strlen(path) + 10);
  1899. snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
  1900. if ((res = unlink(s))) {
  1901. ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
  1902. } else {
  1903. ast_debug(1, "Unlocked path '%s'\n", path);
  1904. }
  1905. return res;
  1906. }
  1907. struct path_lock {
  1908. AST_LIST_ENTRY(path_lock) le;
  1909. int fd;
  1910. char *path;
  1911. };
  1912. static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
  1913. static void path_lock_destroy(struct path_lock *obj)
  1914. {
  1915. if (obj->fd >= 0) {
  1916. close(obj->fd);
  1917. }
  1918. if (obj->path) {
  1919. ast_free(obj->path);
  1920. }
  1921. ast_free(obj);
  1922. }
  1923. static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
  1924. {
  1925. char *fs;
  1926. int res;
  1927. int fd;
  1928. time_t start;
  1929. struct path_lock *pl;
  1930. struct stat st, ost;
  1931. fs = ast_alloca(strlen(path) + 20);
  1932. snprintf(fs, strlen(path) + 19, "%s/lock", path);
  1933. if (lstat(fs, &st) == 0) {
  1934. if ((st.st_mode & S_IFMT) == S_IFLNK) {
  1935. ast_log(LOG_WARNING, "Unable to create lock file "
  1936. "'%s': it's already a symbolic link\n",
  1937. fs);
  1938. return AST_LOCK_FAILURE;
  1939. }
  1940. if (st.st_nlink > 1) {
  1941. ast_log(LOG_WARNING, "Unable to create lock file "
  1942. "'%s': %u hard links exist\n",
  1943. fs, (unsigned int) st.st_nlink);
  1944. return AST_LOCK_FAILURE;
  1945. }
  1946. }
  1947. if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
  1948. ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
  1949. fs, strerror(errno));
  1950. return AST_LOCK_PATH_NOT_FOUND;
  1951. }
  1952. if (!(pl = ast_calloc(1, sizeof(*pl)))) {
  1953. /* We don't unlink the lock file here, on the possibility that
  1954. * someone else created it - better to leave a little mess
  1955. * than create a big one by destroying someone else's lock
  1956. * and causing something to be corrupted.
  1957. */
  1958. close(fd);
  1959. return AST_LOCK_FAILURE;
  1960. }
  1961. pl->fd = fd;
  1962. pl->path = ast_strdup(path);
  1963. time(&start);
  1964. while (
  1965. #ifdef SOLARIS
  1966. ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
  1967. #else
  1968. ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
  1969. #endif
  1970. (errno == EWOULDBLOCK) &&
  1971. (time(NULL) - start < 5))
  1972. usleep(1000);
  1973. if (res) {
  1974. ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
  1975. path, strerror(errno));
  1976. /* No unlinking of lock done, since we tried and failed to
  1977. * flock() it.
  1978. */
  1979. path_lock_destroy(pl);
  1980. return AST_LOCK_TIMEOUT;
  1981. }
  1982. /* Check for the race where the file is recreated or deleted out from
  1983. * underneath us.
  1984. */
  1985. if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
  1986. st.st_dev != ost.st_dev &&
  1987. st.st_ino != ost.st_ino) {
  1988. ast_log(LOG_WARNING, "Unable to create lock file '%s': "
  1989. "file changed underneath us\n", fs);
  1990. path_lock_destroy(pl);
  1991. return AST_LOCK_FAILURE;
  1992. }
  1993. /* Success: file created, flocked, and is the one we started with */
  1994. AST_LIST_LOCK(&path_lock_list);
  1995. AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
  1996. AST_LIST_UNLOCK(&path_lock_list);
  1997. ast_debug(1, "Locked path '%s'\n", path);
  1998. return AST_LOCK_SUCCESS;
  1999. }
  2000. static int ast_unlock_path_flock(const char *path)
  2001. {
  2002. char *s;
  2003. struct path_lock *p;
  2004. s = ast_alloca(strlen(path) + 20);
  2005. AST_LIST_LOCK(&path_lock_list);
  2006. AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
  2007. if (!strcmp(p->path, path)) {
  2008. AST_LIST_REMOVE_CURRENT(le);
  2009. break;
  2010. }
  2011. }
  2012. AST_LIST_TRAVERSE_SAFE_END;
  2013. AST_LIST_UNLOCK(&path_lock_list);
  2014. if (p) {
  2015. snprintf(s, strlen(path) + 19, "%s/lock", path);
  2016. unlink(s);
  2017. path_lock_destroy(p);
  2018. ast_debug(1, "Unlocked path '%s'\n", path);
  2019. } else {
  2020. ast_debug(1, "Failed to unlock path '%s': "
  2021. "lock not found\n", path);
  2022. }
  2023. return 0;
  2024. }
  2025. void ast_set_lock_type(enum AST_LOCK_TYPE type)
  2026. {
  2027. ast_lock_type = type;
  2028. }
  2029. enum AST_LOCK_RESULT ast_lock_path(const char *path)
  2030. {
  2031. enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
  2032. switch (ast_lock_type) {
  2033. case AST_LOCK_TYPE_LOCKFILE:
  2034. r = ast_lock_path_lockfile(path);
  2035. break;
  2036. case AST_LOCK_TYPE_FLOCK:
  2037. r = ast_lock_path_flock(path);
  2038. break;
  2039. }
  2040. return r;
  2041. }
  2042. int ast_unlock_path(const char *path)
  2043. {
  2044. int r = 0;
  2045. switch (ast_lock_type) {
  2046. case AST_LOCK_TYPE_LOCKFILE:
  2047. r = ast_unlock_path_lockfile(path);
  2048. break;
  2049. case AST_LOCK_TYPE_FLOCK:
  2050. r = ast_unlock_path_flock(path);
  2051. break;
  2052. }
  2053. return r;
  2054. }
  2055. int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
  2056. {
  2057. int silencethreshold;
  2058. int maxsilence = 0;
  2059. int res = 0;
  2060. int cmd = 0;
  2061. int max_attempts = 3;
  2062. int attempts = 0;
  2063. int recorded = 0;
  2064. int message_exists = 0;
  2065. /* Note that urgent and private are for flagging messages as such in the future */
  2066. /* barf if no pointer passed to store duration in */
  2067. if (!duration) {
  2068. ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
  2069. return -1;
  2070. }
  2071. cmd = '3'; /* Want to start by recording */
  2072. silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
  2073. while ((cmd >= 0) && (cmd != 't')) {
  2074. switch (cmd) {
  2075. case '1':
  2076. if (!message_exists) {
  2077. /* In this case, 1 is to record a message */
  2078. cmd = '3';
  2079. break;
  2080. } else {
  2081. ast_stream_and_wait(chan, "vm-msgsaved", "");
  2082. cmd = 't';
  2083. return res;
  2084. }
  2085. case '2':
  2086. /* Review */
  2087. ast_verb(3, "Reviewing the recording\n");
  2088. cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
  2089. break;
  2090. case '3':
  2091. message_exists = 0;
  2092. /* Record */
  2093. ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
  2094. recorded = 1;
  2095. if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
  2096. /* User has hung up, no options to give */
  2097. return cmd;
  2098. }
  2099. if (cmd == '0') {
  2100. break;
  2101. } else if (cmd == '*') {
  2102. break;
  2103. } else {
  2104. /* If all is well, a message exists */
  2105. message_exists = 1;
  2106. cmd = 0;
  2107. }
  2108. break;
  2109. case '4':
  2110. case '5':
  2111. case '6':
  2112. case '7':
  2113. case '8':
  2114. case '9':
  2115. case '*':
  2116. case '#':
  2117. cmd = ast_play_and_wait(chan, "vm-sorry");
  2118. break;
  2119. default:
  2120. if (message_exists) {
  2121. cmd = ast_play_and_wait(chan, "vm-review");
  2122. } else {
  2123. if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
  2124. cmd = ast_waitfordigit(chan, 600);
  2125. }
  2126. }
  2127. if (!cmd) {
  2128. cmd = ast_waitfordigit(chan, 6000);
  2129. }
  2130. if (!cmd) {
  2131. attempts++;
  2132. }
  2133. if (attempts > max_attempts) {
  2134. cmd = 't';
  2135. }
  2136. }
  2137. }
  2138. if (cmd == 't') {
  2139. cmd = 0;
  2140. }
  2141. return cmd;
  2142. }
  2143. #define RES_UPONE (1 << 16)
  2144. #define RES_EXIT (1 << 17)
  2145. #define RES_REPEAT (1 << 18)
  2146. #define RES_RESTART ((1 << 19) | RES_REPEAT)
  2147. static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
  2148. static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
  2149. {
  2150. int res;
  2151. int (*ivr_func)(struct ast_channel *, void *);
  2152. char *c;
  2153. char *n;
  2154. switch (option->action) {
  2155. case AST_ACTION_UPONE:
  2156. return RES_UPONE;
  2157. case AST_ACTION_EXIT:
  2158. return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
  2159. case AST_ACTION_REPEAT:
  2160. return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
  2161. case AST_ACTION_RESTART:
  2162. return RES_RESTART ;
  2163. case AST_ACTION_NOOP:
  2164. return 0;
  2165. case AST_ACTION_BACKGROUND:
  2166. res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
  2167. if (res < 0) {
  2168. ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
  2169. res = 0;
  2170. }
  2171. return res;
  2172. case AST_ACTION_PLAYBACK:
  2173. res = ast_stream_and_wait(chan, (char *)option->adata, "");
  2174. if (res < 0) {
  2175. ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
  2176. res = 0;
  2177. }
  2178. return res;
  2179. case AST_ACTION_MENU:
  2180. if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
  2181. /* Do not pass entry errors back up, treat as though it was an "UPONE" */
  2182. res = 0;
  2183. }
  2184. return res;
  2185. case AST_ACTION_WAITOPTION:
  2186. if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
  2187. return 't';
  2188. }
  2189. return res;
  2190. case AST_ACTION_CALLBACK:
  2191. ivr_func = option->adata;
  2192. res = ivr_func(chan, cbdata);
  2193. return res;
  2194. case AST_ACTION_TRANSFER:
  2195. res = ast_parseable_goto(chan, option->adata);
  2196. return 0;
  2197. case AST_ACTION_PLAYLIST:
  2198. case AST_ACTION_BACKLIST:
  2199. res = 0;
  2200. c = ast_strdupa(option->adata);
  2201. while ((n = strsep(&c, ";"))) {
  2202. if ((res = ast_stream_and_wait(chan, n,
  2203. (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
  2204. break;
  2205. }
  2206. }
  2207. ast_stopstream(chan);
  2208. return res;
  2209. default:
  2210. ast_log(LOG_NOTICE, "Unknown dispatch function %u, ignoring!\n", option->action);
  2211. return 0;
  2212. }
  2213. return -1;
  2214. }
  2215. static int option_exists(struct ast_ivr_menu *menu, char *option)
  2216. {
  2217. int x;
  2218. for (x = 0; menu->options[x].option; x++) {
  2219. if (!strcasecmp(menu->options[x].option, option)) {
  2220. return x;
  2221. }
  2222. }
  2223. return -1;
  2224. }
  2225. static int option_matchmore(struct ast_ivr_menu *menu, char *option)
  2226. {
  2227. int x;
  2228. for (x = 0; menu->options[x].option; x++) {
  2229. if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
  2230. (menu->options[x].option[strlen(option)])) {
  2231. return x;
  2232. }
  2233. }
  2234. return -1;
  2235. }
  2236. static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
  2237. {
  2238. int res = 0;
  2239. int ms;
  2240. while (option_matchmore(menu, exten)) {
  2241. ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
  2242. if (strlen(exten) >= maxexten - 1) {
  2243. break;
  2244. }
  2245. if ((res = ast_waitfordigit(chan, ms)) < 1) {
  2246. break;
  2247. }
  2248. exten[strlen(exten) + 1] = '\0';
  2249. exten[strlen(exten)] = res;
  2250. }
  2251. return res > 0 ? 0 : res;
  2252. }
  2253. static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
  2254. {
  2255. /* Execute an IVR menu structure */
  2256. int res = 0;
  2257. int pos = 0;
  2258. int retries = 0;
  2259. char exten[AST_MAX_EXTENSION] = "s";
  2260. if (option_exists(menu, "s") < 0) {
  2261. strcpy(exten, "g");
  2262. if (option_exists(menu, "g") < 0) {
  2263. ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
  2264. return -1;
  2265. }
  2266. }
  2267. while (!res) {
  2268. while (menu->options[pos].option) {
  2269. if (!strcasecmp(menu->options[pos].option, exten)) {
  2270. res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
  2271. ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
  2272. if (res < 0) {
  2273. break;
  2274. } else if (res & RES_UPONE) {
  2275. return 0;
  2276. } else if (res & RES_EXIT) {
  2277. return res;
  2278. } else if (res & RES_REPEAT) {
  2279. int maxretries = res & 0xffff;
  2280. if ((res & RES_RESTART) == RES_RESTART) {
  2281. retries = 0;
  2282. } else {
  2283. retries++;
  2284. }
  2285. if (!maxretries) {
  2286. maxretries = 3;
  2287. }
  2288. if ((maxretries > 0) && (retries >= maxretries)) {
  2289. ast_debug(1, "Max retries %d exceeded\n", maxretries);
  2290. return -2;
  2291. } else {
  2292. if (option_exists(menu, "g") > -1) {
  2293. strcpy(exten, "g");
  2294. } else if (option_exists(menu, "s") > -1) {
  2295. strcpy(exten, "s");
  2296. }
  2297. }
  2298. pos = 0;
  2299. continue;
  2300. } else if (res && strchr(AST_DIGIT_ANY, res)) {
  2301. ast_debug(1, "Got start of extension, %c\n", res);
  2302. exten[1] = '\0';
  2303. exten[0] = res;
  2304. if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
  2305. break;
  2306. }
  2307. if (option_exists(menu, exten) < 0) {
  2308. if (option_exists(menu, "i")) {
  2309. ast_debug(1, "Invalid extension entered, going to 'i'!\n");
  2310. strcpy(exten, "i");
  2311. pos = 0;
  2312. continue;
  2313. } else {
  2314. ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
  2315. res = -2;
  2316. break;
  2317. }
  2318. } else {
  2319. ast_debug(1, "New existing extension: %s\n", exten);
  2320. pos = 0;
  2321. continue;
  2322. }
  2323. }
  2324. }
  2325. pos++;
  2326. }
  2327. ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
  2328. pos = 0;
  2329. if (!strcasecmp(exten, "s")) {
  2330. strcpy(exten, "g");
  2331. } else {
  2332. break;
  2333. }
  2334. }
  2335. return res;
  2336. }
  2337. int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
  2338. {
  2339. int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
  2340. /* Hide internal coding */
  2341. return res > 0 ? 0 : res;
  2342. }
  2343. char *ast_read_textfile(const char *filename)
  2344. {
  2345. int fd, count = 0, res;
  2346. char *output = NULL;
  2347. struct stat filesize;
  2348. if (stat(filename, &filesize) == -1) {
  2349. ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
  2350. return NULL;
  2351. }
  2352. count = filesize.st_size + 1;
  2353. if ((fd = open(filename, O_RDONLY)) < 0) {
  2354. ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
  2355. return NULL;
  2356. }
  2357. if ((output = ast_malloc(count))) {
  2358. res = read(fd, output, count - 1);
  2359. if (res == count - 1) {
  2360. output[res] = '\0';
  2361. } else {
  2362. ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
  2363. ast_free(output);
  2364. output = NULL;
  2365. }
  2366. }
  2367. close(fd);
  2368. return output;
  2369. }
  2370. static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
  2371. {
  2372. char *s, *arg;
  2373. int curarg, res = 0;
  2374. unsigned int argloc;
  2375. struct ast_flags *flags = _flags;
  2376. struct ast_flags64 *flags64 = _flags;
  2377. if (flaglen == 32) {
  2378. ast_clear_flag(flags, AST_FLAGS_ALL);
  2379. } else {
  2380. flags64->flags = 0;
  2381. }
  2382. if (!optstr) {
  2383. return 0;
  2384. }
  2385. s = optstr;
  2386. while (*s) {
  2387. curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
  2388. argloc = options[curarg].arg_index;
  2389. if (*s == '(') {
  2390. int paren = 1, quote = 0;
  2391. int parsequotes = (s[1] == '"') ? 1 : 0;
  2392. /* Has argument */
  2393. arg = ++s;
  2394. for (; *s; s++) {
  2395. if (*s == '(' && !quote) {
  2396. paren++;
  2397. } else if (*s == ')' && !quote) {
  2398. /* Count parentheses, unless they're within quotes (or backslashed, below) */
  2399. paren--;
  2400. } else if (*s == '"' && parsequotes) {
  2401. /* Leave embedded quotes alone, unless they are the first character */
  2402. quote = quote ? 0 : 1;
  2403. ast_copy_string(s, s + 1, INT_MAX);
  2404. s--;
  2405. } else if (*s == '\\') {
  2406. if (!quote) {
  2407. /* If a backslash is found outside of quotes, remove it */
  2408. ast_copy_string(s, s + 1, INT_MAX);
  2409. } else if (quote && s[1] == '"') {
  2410. /* Backslash for a quote character within quotes, remove the backslash */
  2411. ast_copy_string(s, s + 1, INT_MAX);
  2412. } else {
  2413. /* Backslash within quotes, keep both characters */
  2414. s++;
  2415. }
  2416. }
  2417. if (paren == 0) {
  2418. break;
  2419. }
  2420. }
  2421. /* This will find the closing paren we found above, or none, if the string ended before we found one. */
  2422. if ((s = strchr(s, ')'))) {
  2423. if (argloc) {
  2424. args[argloc - 1] = arg;
  2425. }
  2426. *s++ = '\0';
  2427. } else {
  2428. ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
  2429. res = -1;
  2430. break;
  2431. }
  2432. } else if (argloc) {
  2433. args[argloc - 1] = "";
  2434. }
  2435. if (flaglen == 32) {
  2436. ast_set_flag(flags, options[curarg].flag);
  2437. } else {
  2438. ast_set_flag64(flags64, options[curarg].flag);
  2439. }
  2440. }
  2441. return res;
  2442. }
  2443. int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
  2444. {
  2445. return parse_options(options, flags, args, optstr, 32);
  2446. }
  2447. int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
  2448. {
  2449. return parse_options(options, flags, args, optstr, 64);
  2450. }
  2451. void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
  2452. {
  2453. unsigned int i, found = 0;
  2454. for (i = 32; i < 128 && found < len; i++) {
  2455. if (ast_test_flag64(flags, options[i].flag)) {
  2456. buf[found++] = i;
  2457. }
  2458. }
  2459. buf[found] = '\0';
  2460. }
  2461. int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
  2462. {
  2463. int i;
  2464. *consumed = 1;
  2465. *result = 0;
  2466. if (ast_strlen_zero(stream)) {
  2467. *consumed = 0;
  2468. return -1;
  2469. }
  2470. if (*stream == '\\') {
  2471. *consumed = 2;
  2472. switch (*(stream + 1)) {
  2473. case 'n':
  2474. *result = '\n';
  2475. break;
  2476. case 'r':
  2477. *result = '\r';
  2478. break;
  2479. case 't':
  2480. *result = '\t';
  2481. break;
  2482. case 'x':
  2483. /* Hexadecimal */
  2484. if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
  2485. *consumed = 3;
  2486. if (*(stream + 2) <= '9') {
  2487. *result = *(stream + 2) - '0';
  2488. } else if (*(stream + 2) <= 'F') {
  2489. *result = *(stream + 2) - 'A' + 10;
  2490. } else {
  2491. *result = *(stream + 2) - 'a' + 10;
  2492. }
  2493. } else {
  2494. ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
  2495. return -1;
  2496. }
  2497. if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
  2498. *consumed = 4;
  2499. *result <<= 4;
  2500. if (*(stream + 3) <= '9') {
  2501. *result += *(stream + 3) - '0';
  2502. } else if (*(stream + 3) <= 'F') {
  2503. *result += *(stream + 3) - 'A' + 10;
  2504. } else {
  2505. *result += *(stream + 3) - 'a' + 10;
  2506. }
  2507. }
  2508. break;
  2509. case '0':
  2510. /* Octal */
  2511. *consumed = 2;
  2512. for (i = 2; ; i++) {
  2513. if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
  2514. (*consumed)++;
  2515. ast_debug(5, "result was %d, ", *result);
  2516. *result <<= 3;
  2517. *result += *(stream + i) - '0';
  2518. ast_debug(5, "is now %d\n", *result);
  2519. } else {
  2520. break;
  2521. }
  2522. }
  2523. break;
  2524. default:
  2525. *result = *(stream + 1);
  2526. }
  2527. } else {
  2528. *result = *stream;
  2529. *consumed = 1;
  2530. }
  2531. return 0;
  2532. }
  2533. char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
  2534. {
  2535. char *cur = result;
  2536. size_t consumed;
  2537. while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
  2538. cur++;
  2539. stream += consumed;
  2540. }
  2541. *cur = '\0';
  2542. return result;
  2543. }
  2544. int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
  2545. {
  2546. char next, *buf;
  2547. size_t offset = 0;
  2548. size_t consumed;
  2549. if (strchr(stream, '\\')) {
  2550. while (!ast_get_encoded_char(stream, &next, &consumed)) {
  2551. if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
  2552. ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
  2553. }
  2554. if (offset + 2 > ast_str_size(*str)) {
  2555. break;
  2556. }
  2557. buf = ast_str_buffer(*str);
  2558. buf[offset++] = next;
  2559. stream += consumed;
  2560. }
  2561. buf = ast_str_buffer(*str);
  2562. buf[offset++] = '\0';
  2563. ast_str_update(*str);
  2564. } else {
  2565. ast_str_set(str, maxlen, "%s", stream);
  2566. }
  2567. return 0;
  2568. }
  2569. void ast_close_fds_above_n(int n)
  2570. {
  2571. closefrom(n + 1);
  2572. }
  2573. int ast_safe_fork(int stop_reaper)
  2574. {
  2575. sigset_t signal_set, old_set;
  2576. int pid;
  2577. /* Don't let the default signal handler for children reap our status */
  2578. if (stop_reaper) {
  2579. ast_replace_sigchld();
  2580. }
  2581. /* GCC 4.9 gives a bogus "right-hand operand of comma expression has
  2582. * no effect" warning */
  2583. (void) sigfillset(&signal_set);
  2584. pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
  2585. pid = fork();
  2586. if (pid != 0) {
  2587. /* Fork failed or parent */
  2588. pthread_sigmask(SIG_SETMASK, &old_set, NULL);
  2589. if (!stop_reaper && pid > 0) {
  2590. struct zombie *cur = ast_calloc(1, sizeof(*cur));
  2591. if (cur) {
  2592. cur->pid = pid;
  2593. AST_LIST_LOCK(&zombies);
  2594. AST_LIST_INSERT_TAIL(&zombies, cur, list);
  2595. AST_LIST_UNLOCK(&zombies);
  2596. if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
  2597. if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
  2598. ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
  2599. shaun_of_the_dead_thread = AST_PTHREADT_NULL;
  2600. }
  2601. }
  2602. }
  2603. }
  2604. return pid;
  2605. } else {
  2606. /* Child */
  2607. #ifdef HAVE_CAP
  2608. cap_t cap = cap_from_text("cap_net_admin-eip");
  2609. if (cap_set_proc(cap)) {
  2610. ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
  2611. }
  2612. cap_free(cap);
  2613. #endif
  2614. /* Before we unblock our signals, return our trapped signals back to the defaults */
  2615. signal(SIGHUP, SIG_DFL);
  2616. signal(SIGCHLD, SIG_DFL);
  2617. signal(SIGINT, SIG_DFL);
  2618. signal(SIGURG, SIG_DFL);
  2619. signal(SIGTERM, SIG_DFL);
  2620. signal(SIGPIPE, SIG_DFL);
  2621. signal(SIGXFSZ, SIG_DFL);
  2622. /* unblock important signal handlers */
  2623. if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
  2624. ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
  2625. _exit(1);
  2626. }
  2627. return pid;
  2628. }
  2629. }
  2630. void ast_safe_fork_cleanup(void)
  2631. {
  2632. ast_unreplace_sigchld();
  2633. }
  2634. int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
  2635. {
  2636. int res;
  2637. char u[10];
  2638. #ifdef HAVE_LONG_DOUBLE_WIDER
  2639. long double amount;
  2640. #define FMT "%30Lf%9s"
  2641. #else
  2642. double amount;
  2643. #define FMT "%30lf%9s"
  2644. #endif
  2645. if (!timestr) {
  2646. return -1;
  2647. }
  2648. res = sscanf(timestr, FMT, &amount, u);
  2649. if (res == 0 || res == EOF) {
  2650. #undef FMT
  2651. return -1;
  2652. } else if (res == 2) {
  2653. switch (u[0]) {
  2654. case 'h':
  2655. case 'H':
  2656. unit = TIMELEN_HOURS;
  2657. break;
  2658. case 's':
  2659. case 'S':
  2660. unit = TIMELEN_SECONDS;
  2661. break;
  2662. case 'm':
  2663. case 'M':
  2664. if (toupper(u[1]) == 'S') {
  2665. unit = TIMELEN_MILLISECONDS;
  2666. } else if (u[1] == '\0') {
  2667. unit = TIMELEN_MINUTES;
  2668. }
  2669. break;
  2670. }
  2671. }
  2672. switch (unit) {
  2673. case TIMELEN_HOURS:
  2674. amount *= 60;
  2675. /* fall-through */
  2676. case TIMELEN_MINUTES:
  2677. amount *= 60;
  2678. /* fall-through */
  2679. case TIMELEN_SECONDS:
  2680. amount *= 1000;
  2681. /* fall-through */
  2682. case TIMELEN_MILLISECONDS:
  2683. ;
  2684. }
  2685. *result = amount > INT_MAX ? INT_MAX : (int) amount;
  2686. return 0;
  2687. }
  2688. static void mwi_state_dtor(void *obj)
  2689. {
  2690. struct ast_mwi_state *mwi_state = obj;
  2691. ast_string_field_free_memory(mwi_state);
  2692. ao2_cleanup(mwi_state->snapshot);
  2693. mwi_state->snapshot = NULL;
  2694. }
  2695. struct stasis_topic *ast_mwi_topic_all(void)
  2696. {
  2697. return mwi_topic_all;
  2698. }
  2699. struct stasis_cache *ast_mwi_state_cache(void)
  2700. {
  2701. return mwi_state_cache;
  2702. }
  2703. struct stasis_topic *ast_mwi_topic_cached(void)
  2704. {
  2705. return stasis_caching_get_topic(mwi_topic_cached);
  2706. }
  2707. struct stasis_topic *ast_mwi_topic(const char *uniqueid)
  2708. {
  2709. return stasis_topic_pool_get_topic(mwi_topic_pool, uniqueid);
  2710. }
  2711. struct ast_mwi_state *ast_mwi_create(const char *mailbox, const char *context)
  2712. {
  2713. RAII_VAR(struct ast_mwi_state *, mwi_state, NULL, ao2_cleanup);
  2714. ast_assert(!ast_strlen_zero(mailbox));
  2715. mwi_state = ao2_alloc(sizeof(*mwi_state), mwi_state_dtor);
  2716. if (!mwi_state) {
  2717. return NULL;
  2718. }
  2719. if (ast_string_field_init(mwi_state, 256)) {
  2720. return NULL;
  2721. }
  2722. if (!ast_strlen_zero(context)) {
  2723. ast_string_field_build(mwi_state, uniqueid, "%s@%s", mailbox, context);
  2724. } else {
  2725. ast_string_field_set(mwi_state, uniqueid, mailbox);
  2726. }
  2727. ao2_ref(mwi_state, +1);
  2728. return mwi_state;
  2729. }
  2730. /*!
  2731. * \internal
  2732. * \brief Create a MWI state snapshot message.
  2733. * \since 12.2.0
  2734. *
  2735. * \param[in] mailbox The mailbox identifier string.
  2736. * \param[in] context The context this mailbox resides in (NULL or "" if only using mailbox)
  2737. * \param[in] new_msgs The number of new messages in this mailbox
  2738. * \param[in] old_msgs The number of old messages in this mailbox
  2739. * \param[in] channel_id A unique identifier for a channel associated with this
  2740. * change in mailbox state
  2741. * \param[in] eid The EID of the server that originally published the message
  2742. *
  2743. * \retval message on success. Use ao2_cleanup() when done with it.
  2744. * \retval NULL on error.
  2745. */
  2746. static struct stasis_message *mwi_state_create_message(
  2747. const char *mailbox,
  2748. const char *context,
  2749. int new_msgs,
  2750. int old_msgs,
  2751. const char *channel_id,
  2752. struct ast_eid *eid)
  2753. {
  2754. struct ast_mwi_state *mwi_state;
  2755. struct stasis_message *message;
  2756. if (!ast_mwi_state_type()) {
  2757. return NULL;
  2758. }
  2759. mwi_state = ast_mwi_create(mailbox, context);
  2760. if (!mwi_state) {
  2761. return NULL;
  2762. }
  2763. mwi_state->new_msgs = new_msgs;
  2764. mwi_state->old_msgs = old_msgs;
  2765. if (!ast_strlen_zero(channel_id)) {
  2766. struct stasis_message *chan_message;
  2767. chan_message = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
  2768. channel_id);
  2769. if (chan_message) {
  2770. mwi_state->snapshot = stasis_message_data(chan_message);
  2771. ao2_ref(mwi_state->snapshot, +1);
  2772. }
  2773. ao2_cleanup(chan_message);
  2774. }
  2775. if (eid) {
  2776. mwi_state->eid = *eid;
  2777. } else {
  2778. mwi_state->eid = ast_eid_default;
  2779. }
  2780. /*
  2781. * XXX As far as stasis is concerned, all MWI events are local.
  2782. *
  2783. * We may in the future want to make MWI aggregate local/remote
  2784. * message counts similar to how device state aggregates state.
  2785. */
  2786. message = stasis_message_create_full(ast_mwi_state_type(), mwi_state, &ast_eid_default);
  2787. ao2_cleanup(mwi_state);
  2788. return message;
  2789. }
  2790. int ast_publish_mwi_state_full(
  2791. const char *mailbox,
  2792. const char *context,
  2793. int new_msgs,
  2794. int old_msgs,
  2795. const char *channel_id,
  2796. struct ast_eid *eid)
  2797. {
  2798. struct ast_mwi_state *mwi_state;
  2799. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  2800. struct stasis_topic *mailbox_specific_topic;
  2801. message = mwi_state_create_message(mailbox, context, new_msgs, old_msgs, channel_id, eid);
  2802. if (!message) {
  2803. return -1;
  2804. }
  2805. mwi_state = stasis_message_data(message);
  2806. mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
  2807. if (!mailbox_specific_topic) {
  2808. return -1;
  2809. }
  2810. stasis_publish(mailbox_specific_topic, message);
  2811. return 0;
  2812. }
  2813. int ast_delete_mwi_state_full(const char *mailbox, const char *context, struct ast_eid *eid)
  2814. {
  2815. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  2816. struct stasis_message *cached_msg;
  2817. struct stasis_message *clear_msg;
  2818. struct ast_mwi_state *mwi_state;
  2819. struct stasis_topic *mailbox_specific_topic;
  2820. msg = mwi_state_create_message(mailbox, context, 0, 0, NULL, eid);
  2821. if (!msg) {
  2822. return -1;
  2823. }
  2824. mwi_state = stasis_message_data(msg);
  2825. /*
  2826. * XXX As far as stasis is concerned, all MWI events are local.
  2827. *
  2828. * For now, it is assumed that there is only one entity
  2829. * maintaining the state of a particular mailbox.
  2830. *
  2831. * If we ever have multiple MWI event entities maintaining
  2832. * the same mailbox that wish to delete their cached entry
  2833. * we will need to do something about the race condition
  2834. * potential between checking the cache and removing the
  2835. * cache entry.
  2836. */
  2837. cached_msg = stasis_cache_get_by_eid(ast_mwi_state_cache(),
  2838. ast_mwi_state_type(), mwi_state->uniqueid, &ast_eid_default);
  2839. if (!cached_msg) {
  2840. /* Nothing to clear */
  2841. return -1;
  2842. }
  2843. ao2_cleanup(cached_msg);
  2844. mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
  2845. if (!mailbox_specific_topic) {
  2846. return -1;
  2847. }
  2848. clear_msg = stasis_cache_clear_create(msg);
  2849. if (clear_msg) {
  2850. stasis_publish(mailbox_specific_topic, clear_msg);
  2851. }
  2852. ao2_cleanup(clear_msg);
  2853. return 0;
  2854. }
  2855. static const char *mwi_state_get_id(struct stasis_message *message)
  2856. {
  2857. if (ast_mwi_state_type() == stasis_message_type(message)) {
  2858. struct ast_mwi_state *mwi_state = stasis_message_data(message);
  2859. return mwi_state->uniqueid;
  2860. } else if (stasis_subscription_change_type() == stasis_message_type(message)) {
  2861. struct stasis_subscription_change *change = stasis_message_data(message);
  2862. return change->uniqueid;
  2863. }
  2864. return NULL;
  2865. }
  2866. static void mwi_blob_dtor(void *obj)
  2867. {
  2868. struct ast_mwi_blob *mwi_blob = obj;
  2869. ao2_cleanup(mwi_blob->mwi_state);
  2870. ast_json_unref(mwi_blob->blob);
  2871. }
  2872. struct stasis_message *ast_mwi_blob_create(struct ast_mwi_state *mwi_state,
  2873. struct stasis_message_type *message_type,
  2874. struct ast_json *blob)
  2875. {
  2876. RAII_VAR(struct ast_mwi_blob *, obj, NULL, ao2_cleanup);
  2877. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  2878. ast_assert(blob != NULL);
  2879. if (!message_type) {
  2880. return NULL;
  2881. }
  2882. obj = ao2_alloc(sizeof(*obj), mwi_blob_dtor);
  2883. if (!obj) {
  2884. return NULL;
  2885. }
  2886. obj->mwi_state = mwi_state;
  2887. ao2_ref(obj->mwi_state, +1);
  2888. obj->blob = ast_json_ref(blob);
  2889. /* This is not a normal MWI event. Only used by the MinivmNotify app. */
  2890. msg = stasis_message_create(message_type, obj);
  2891. if (!msg) {
  2892. return NULL;
  2893. }
  2894. ao2_ref(msg, +1);
  2895. return msg;
  2896. }
  2897. struct stasis_topic *ast_queue_topic_all(void)
  2898. {
  2899. return queue_topic_all;
  2900. }
  2901. struct stasis_topic *ast_queue_topic(const char *queuename)
  2902. {
  2903. return stasis_topic_pool_get_topic(queue_topic_pool, queuename);
  2904. }
  2905. static void app_cleanup(void)
  2906. {
  2907. ao2_cleanup(queue_topic_pool);
  2908. queue_topic_pool = NULL;
  2909. ao2_cleanup(queue_topic_all);
  2910. queue_topic_all = NULL;
  2911. ao2_cleanup(mwi_topic_pool);
  2912. mwi_topic_pool = NULL;
  2913. ao2_cleanup(mwi_topic_all);
  2914. mwi_topic_all = NULL;
  2915. ao2_cleanup(mwi_state_cache);
  2916. mwi_state_cache = NULL;
  2917. mwi_topic_cached = stasis_caching_unsubscribe_and_join(mwi_topic_cached);
  2918. STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_state_type);
  2919. STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_vm_app_type);
  2920. }
  2921. int app_init(void)
  2922. {
  2923. ast_register_cleanup(app_cleanup);
  2924. if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_state_type) != 0) {
  2925. return -1;
  2926. }
  2927. if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_vm_app_type) != 0) {
  2928. return -1;
  2929. }
  2930. mwi_topic_all = stasis_topic_create("stasis_mwi_topic");
  2931. if (!mwi_topic_all) {
  2932. return -1;
  2933. }
  2934. mwi_state_cache = stasis_cache_create(mwi_state_get_id);
  2935. if (!mwi_state_cache) {
  2936. return -1;
  2937. }
  2938. mwi_topic_cached = stasis_caching_topic_create(mwi_topic_all, mwi_state_cache);
  2939. if (!mwi_topic_cached) {
  2940. return -1;
  2941. }
  2942. mwi_topic_pool = stasis_topic_pool_create(mwi_topic_all);
  2943. if (!mwi_topic_pool) {
  2944. return -1;
  2945. }
  2946. queue_topic_all = stasis_topic_create("stasis_queue_topic");
  2947. if (!queue_topic_all) {
  2948. return -1;
  2949. }
  2950. queue_topic_pool = stasis_topic_pool_create(queue_topic_all);
  2951. if (!queue_topic_pool) {
  2952. return -1;
  2953. }
  2954. return 0;
  2955. }