app.c 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402
  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. case AST_RECORD_IF_EXISTS_ERROR:
  1291. ast_assert(0);
  1292. break;
  1293. }
  1294. if (silencethreshold < 0) {
  1295. silencethreshold = global_silence_threshold;
  1296. }
  1297. if (maxsilence < 0) {
  1298. maxsilence = global_maxsilence;
  1299. }
  1300. /* barf if no pointer passed to store duration in */
  1301. if (!duration) {
  1302. ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
  1303. return -1;
  1304. }
  1305. ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
  1306. snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
  1307. if (playfile || beep) {
  1308. if (!beep) {
  1309. d = ast_play_and_wait(chan, playfile);
  1310. }
  1311. if (d > -1) {
  1312. d = ast_stream_and_wait(chan, "beep", "");
  1313. }
  1314. if (d < 0) {
  1315. return -1;
  1316. }
  1317. }
  1318. if (prepend) {
  1319. ast_copy_string(prependfile, recordfile, sizeof(prependfile));
  1320. strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
  1321. }
  1322. fmts = ast_strdupa(fmt);
  1323. stringp = fmts;
  1324. strsep(&stringp, "|");
  1325. ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
  1326. sfmt[0] = ast_strdupa(fmts);
  1327. while ((fmt = strsep(&stringp, "|"))) {
  1328. if (fmtcnt > AST_MAX_FORMATS - 1) {
  1329. ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
  1330. break;
  1331. }
  1332. sfmt[fmtcnt++] = ast_strdupa(fmt);
  1333. }
  1334. end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
  1335. for (x = 0; x < fmtcnt; x++) {
  1336. others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, ioflags, 0, AST_FILE_MODE);
  1337. ast_verb(3, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
  1338. if (!others[x]) {
  1339. break;
  1340. }
  1341. }
  1342. if (path) {
  1343. ast_unlock_path(path);
  1344. }
  1345. if (maxsilence > 0) {
  1346. sildet = ast_dsp_new(); /* Create the silence detector */
  1347. if (!sildet) {
  1348. ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
  1349. return -1;
  1350. }
  1351. ast_dsp_set_threshold(sildet, silencethreshold);
  1352. res = set_read_to_slin(chan, &rfmt);
  1353. if (res < 0) {
  1354. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  1355. ast_dsp_free(sildet);
  1356. ao2_cleanup(rfmt);
  1357. return -1;
  1358. }
  1359. }
  1360. if (!prepend) {
  1361. /* Request a video update */
  1362. ast_indicate(chan, AST_CONTROL_VIDUPDATE);
  1363. if (ast_opt_transmit_silence) {
  1364. silgen = ast_channel_start_silence_generator(chan);
  1365. }
  1366. }
  1367. if (x == fmtcnt) {
  1368. /* Loop, writing the packets we read to the writer(s), until
  1369. * we have reason to stop. */
  1370. struct ast_frame *f;
  1371. int paused = 0;
  1372. int muted = 0;
  1373. time_t pause_start = 0;
  1374. int paused_secs = 0;
  1375. int pausedsilence = 0;
  1376. for (;;) {
  1377. if (!(res = ast_waitfor(chan, 2000))) {
  1378. ast_debug(1, "One waitfor failed, trying another\n");
  1379. /* Try one more time in case of masq */
  1380. if (!(res = ast_waitfor(chan, 2000))) {
  1381. ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
  1382. res = -1;
  1383. }
  1384. }
  1385. if (res < 0) {
  1386. f = NULL;
  1387. break;
  1388. }
  1389. if (!(f = ast_read(chan))) {
  1390. break;
  1391. }
  1392. if (f->frametype == AST_FRAME_VOICE) {
  1393. /* write each format */
  1394. if (paused) {
  1395. /* It's all good */
  1396. res = 0;
  1397. } else {
  1398. RAII_VAR(struct ast_frame *, silence, NULL, ast_frame_dtor);
  1399. struct ast_frame *orig = f;
  1400. if (muted) {
  1401. silence = make_silence(orig);
  1402. if (!silence) {
  1403. ast_log(LOG_WARNING,
  1404. "Error creating silence\n");
  1405. break;
  1406. }
  1407. f = silence;
  1408. }
  1409. for (x = 0; x < fmtcnt; x++) {
  1410. if (prepend && !others[x]) {
  1411. break;
  1412. }
  1413. res = ast_writestream(others[x], f);
  1414. }
  1415. f = orig;
  1416. }
  1417. /* Silence Detection */
  1418. if (maxsilence > 0) {
  1419. dspsilence = 0;
  1420. ast_dsp_silence(sildet, f, &dspsilence);
  1421. if (olddspsilence > dspsilence) {
  1422. totalsilence += olddspsilence;
  1423. }
  1424. olddspsilence = dspsilence;
  1425. if (paused) {
  1426. /* record how much silence there was while we are paused */
  1427. pausedsilence = dspsilence;
  1428. } else if (dspsilence > pausedsilence) {
  1429. /* ignore the paused silence */
  1430. dspsilence -= pausedsilence;
  1431. } else {
  1432. /* dspsilence has reset, reset pausedsilence */
  1433. pausedsilence = 0;
  1434. }
  1435. if (dspsilence > maxsilence) {
  1436. /* Ended happily with silence */
  1437. ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
  1438. res = 'S';
  1439. outmsg = 2;
  1440. break;
  1441. }
  1442. }
  1443. /* Exit on any error */
  1444. if (res) {
  1445. ast_log(LOG_WARNING, "Error writing frame\n");
  1446. break;
  1447. }
  1448. } else if (f->frametype == AST_FRAME_VIDEO) {
  1449. /* Write only once */
  1450. ast_writestream(others[0], f);
  1451. } else if (f->frametype == AST_FRAME_DTMF) {
  1452. if (prepend) {
  1453. /* stop recording with any digit */
  1454. ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
  1455. res = 't';
  1456. outmsg = 2;
  1457. break;
  1458. }
  1459. if (strchr(acceptdtmf, f->subclass.integer)) {
  1460. ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
  1461. res = f->subclass.integer;
  1462. outmsg = 2;
  1463. break;
  1464. }
  1465. if (strchr(canceldtmf, f->subclass.integer)) {
  1466. ast_verb(3, "User canceled message by pressing %c\n", f->subclass.integer);
  1467. res = f->subclass.integer;
  1468. outmsg = 0;
  1469. break;
  1470. }
  1471. } else if (f->frametype == AST_FRAME_CONTROL) {
  1472. if (f->subclass.integer == AST_CONTROL_RECORD_CANCEL) {
  1473. ast_verb(3, "Message canceled by control\n");
  1474. outmsg = 0; /* cancels the recording */
  1475. res = 0;
  1476. break;
  1477. } else if (f->subclass.integer == AST_CONTROL_RECORD_STOP) {
  1478. ast_verb(3, "Message ended by control\n");
  1479. res = 0;
  1480. break;
  1481. } else if (f->subclass.integer == AST_CONTROL_RECORD_SUSPEND) {
  1482. paused = !paused;
  1483. ast_verb(3, "Message %spaused by control\n",
  1484. paused ? "" : "un");
  1485. if (paused) {
  1486. pause_start = time(NULL);
  1487. } else {
  1488. paused_secs += time(NULL) - pause_start;
  1489. }
  1490. } else if (f->subclass.integer == AST_CONTROL_RECORD_MUTE) {
  1491. muted = !muted;
  1492. ast_verb(3, "Message %smuted by control\n",
  1493. muted ? "" : "un");
  1494. /* We can only silence slin frames, so
  1495. * set the mode, if we haven't already
  1496. * for sildet
  1497. */
  1498. if (muted && !rfmt) {
  1499. ast_verb(3, "Setting read format to linear mode\n");
  1500. res = set_read_to_slin(chan, &rfmt);
  1501. if (res < 0) {
  1502. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  1503. break;
  1504. }
  1505. }
  1506. }
  1507. }
  1508. if (maxtime && !paused) {
  1509. end = time(NULL);
  1510. if (maxtime < (end - start - paused_secs)) {
  1511. ast_verb(3, "Took too long, cutting it short...\n");
  1512. res = 't';
  1513. outmsg = 2;
  1514. break;
  1515. }
  1516. }
  1517. ast_frfree(f);
  1518. }
  1519. if (!f) {
  1520. ast_verb(3, "User hung up\n");
  1521. res = -1;
  1522. outmsg = 1;
  1523. } else {
  1524. ast_frfree(f);
  1525. }
  1526. } else {
  1527. ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
  1528. }
  1529. if (!prepend) {
  1530. if (silgen) {
  1531. ast_channel_stop_silence_generator(chan, silgen);
  1532. }
  1533. }
  1534. /*!\note
  1535. * Instead of asking how much time passed (end - start), calculate the number
  1536. * of seconds of audio which actually went into the file. This fixes a
  1537. * problem where audio is stopped up on the network and never gets to us.
  1538. *
  1539. * Note that we still want to use the number of seconds passed for the max
  1540. * message, otherwise we could get a situation where this stream is never
  1541. * closed (which would create a resource leak).
  1542. */
  1543. *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
  1544. if (sound_duration) {
  1545. *sound_duration = *duration;
  1546. }
  1547. if (!prepend) {
  1548. /* Reduce duration by a total silence amount */
  1549. if (olddspsilence <= dspsilence) {
  1550. totalsilence += dspsilence;
  1551. }
  1552. if (sound_duration) {
  1553. if (totalsilence > 0) {
  1554. *sound_duration -= (totalsilence - 200) / 1000;
  1555. }
  1556. if (*sound_duration < 0) {
  1557. *sound_duration = 0;
  1558. }
  1559. }
  1560. if (dspsilence > 0) {
  1561. *duration -= (dspsilence - 200) / 1000;
  1562. }
  1563. if (*duration < 0) {
  1564. *duration = 0;
  1565. }
  1566. for (x = 0; x < fmtcnt; x++) {
  1567. if (!others[x]) {
  1568. break;
  1569. }
  1570. /*!\note
  1571. * If we ended with silence, trim all but the first 200ms of silence
  1572. * off the recording. However, if we ended with '#', we don't want
  1573. * to trim ANY part of the recording.
  1574. */
  1575. if (res > 0 && dspsilence) {
  1576. /* rewind only the trailing silence */
  1577. ast_stream_rewind(others[x], dspsilence - 200);
  1578. }
  1579. ast_truncstream(others[x]);
  1580. ast_closestream(others[x]);
  1581. }
  1582. } else if (prepend && outmsg) {
  1583. struct ast_filestream *realfiles[AST_MAX_FORMATS];
  1584. struct ast_frame *fr;
  1585. for (x = 0; x < fmtcnt; x++) {
  1586. snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
  1587. realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
  1588. if (!others[x]) {
  1589. break;
  1590. }
  1591. if (!realfiles[x]) {
  1592. ast_closestream(others[x]);
  1593. continue;
  1594. }
  1595. /*!\note Same logic as above. */
  1596. if (dspsilence) {
  1597. ast_stream_rewind(others[x], dspsilence - 200);
  1598. }
  1599. ast_truncstream(others[x]);
  1600. /* add the original file too */
  1601. while ((fr = ast_readframe(realfiles[x]))) {
  1602. ast_writestream(others[x], fr);
  1603. ast_frfree(fr);
  1604. }
  1605. ast_closestream(others[x]);
  1606. ast_closestream(realfiles[x]);
  1607. ast_filerename(prependfile, recordfile, sfmt[x]);
  1608. ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
  1609. ast_filedelete(prependfile, sfmt[x]);
  1610. }
  1611. } else {
  1612. for (x = 0; x < fmtcnt; x++) {
  1613. if (!others[x]) {
  1614. break;
  1615. }
  1616. ast_closestream(others[x]);
  1617. }
  1618. }
  1619. if (rfmt && ast_set_read_format(chan, rfmt)) {
  1620. ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_format_get_name(rfmt), ast_channel_name(chan));
  1621. }
  1622. ao2_cleanup(rfmt);
  1623. if ((outmsg == 2) && (!skip_confirmation_sound)) {
  1624. ast_stream_and_wait(chan, "auth-thankyou", "");
  1625. }
  1626. if (sildet) {
  1627. ast_dsp_free(sildet);
  1628. }
  1629. return res;
  1630. }
  1631. static const char default_acceptdtmf[] = "#";
  1632. static const char default_canceldtmf[] = "";
  1633. 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)
  1634. {
  1635. 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);
  1636. }
  1637. 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)
  1638. {
  1639. 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);
  1640. }
  1641. 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)
  1642. {
  1643. 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);
  1644. }
  1645. /* Channel group core functions */
  1646. int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
  1647. {
  1648. int res = 0;
  1649. char tmp[256];
  1650. char *grp = NULL, *cat = NULL;
  1651. if (!ast_strlen_zero(data)) {
  1652. ast_copy_string(tmp, data, sizeof(tmp));
  1653. grp = tmp;
  1654. if ((cat = strchr(tmp, '@'))) {
  1655. *cat++ = '\0';
  1656. }
  1657. }
  1658. if (!ast_strlen_zero(grp)) {
  1659. ast_copy_string(group, grp, group_max);
  1660. } else {
  1661. *group = '\0';
  1662. }
  1663. if (!ast_strlen_zero(cat)) {
  1664. ast_copy_string(category, cat, category_max);
  1665. }
  1666. return res;
  1667. }
  1668. int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
  1669. {
  1670. int res = 0;
  1671. char group[80] = "", category[80] = "";
  1672. struct ast_group_info *gi = NULL;
  1673. size_t len = 0;
  1674. if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
  1675. return -1;
  1676. }
  1677. /* Calculate memory we will need if this is new */
  1678. len = sizeof(*gi) + strlen(group) + 1;
  1679. if (!ast_strlen_zero(category)) {
  1680. len += strlen(category) + 1;
  1681. }
  1682. AST_RWLIST_WRLOCK(&groups);
  1683. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1684. if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
  1685. AST_RWLIST_REMOVE_CURRENT(group_list);
  1686. free(gi);
  1687. break;
  1688. }
  1689. }
  1690. AST_RWLIST_TRAVERSE_SAFE_END;
  1691. if (ast_strlen_zero(group)) {
  1692. /* Enable unsetting the group */
  1693. } else if ((gi = calloc(1, len))) {
  1694. gi->chan = chan;
  1695. gi->group = (char *) gi + sizeof(*gi);
  1696. strcpy(gi->group, group);
  1697. if (!ast_strlen_zero(category)) {
  1698. gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
  1699. strcpy(gi->category, category);
  1700. }
  1701. AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
  1702. } else {
  1703. res = -1;
  1704. }
  1705. AST_RWLIST_UNLOCK(&groups);
  1706. return res;
  1707. }
  1708. int ast_app_group_get_count(const char *group, const char *category)
  1709. {
  1710. struct ast_group_info *gi = NULL;
  1711. int count = 0;
  1712. if (ast_strlen_zero(group)) {
  1713. return 0;
  1714. }
  1715. AST_RWLIST_RDLOCK(&groups);
  1716. AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
  1717. if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
  1718. count++;
  1719. }
  1720. }
  1721. AST_RWLIST_UNLOCK(&groups);
  1722. return count;
  1723. }
  1724. int ast_app_group_match_get_count(const char *groupmatch, const char *category)
  1725. {
  1726. struct ast_group_info *gi = NULL;
  1727. regex_t regexbuf_group;
  1728. regex_t regexbuf_category;
  1729. int count = 0;
  1730. if (ast_strlen_zero(groupmatch)) {
  1731. ast_log(LOG_NOTICE, "groupmatch empty\n");
  1732. return 0;
  1733. }
  1734. /* if regex compilation fails, return zero matches */
  1735. if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
  1736. ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
  1737. return 0;
  1738. }
  1739. if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
  1740. ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
  1741. regfree(&regexbuf_group);
  1742. return 0;
  1743. }
  1744. AST_RWLIST_RDLOCK(&groups);
  1745. AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
  1746. 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)))) {
  1747. count++;
  1748. }
  1749. }
  1750. AST_RWLIST_UNLOCK(&groups);
  1751. regfree(&regexbuf_group);
  1752. if (!ast_strlen_zero(category)) {
  1753. regfree(&regexbuf_category);
  1754. }
  1755. return count;
  1756. }
  1757. int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
  1758. {
  1759. struct ast_group_info *gi = NULL;
  1760. AST_RWLIST_WRLOCK(&groups);
  1761. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1762. if (gi->chan == old) {
  1763. gi->chan = new;
  1764. } else if (gi->chan == new) {
  1765. AST_RWLIST_REMOVE_CURRENT(group_list);
  1766. ast_free(gi);
  1767. }
  1768. }
  1769. AST_RWLIST_TRAVERSE_SAFE_END;
  1770. AST_RWLIST_UNLOCK(&groups);
  1771. return 0;
  1772. }
  1773. int ast_app_group_discard(struct ast_channel *chan)
  1774. {
  1775. struct ast_group_info *gi = NULL;
  1776. AST_RWLIST_WRLOCK(&groups);
  1777. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1778. if (gi->chan == chan) {
  1779. AST_RWLIST_REMOVE_CURRENT(group_list);
  1780. ast_free(gi);
  1781. }
  1782. }
  1783. AST_RWLIST_TRAVERSE_SAFE_END;
  1784. AST_RWLIST_UNLOCK(&groups);
  1785. return 0;
  1786. }
  1787. int ast_app_group_list_wrlock(void)
  1788. {
  1789. return AST_RWLIST_WRLOCK(&groups);
  1790. }
  1791. int ast_app_group_list_rdlock(void)
  1792. {
  1793. return AST_RWLIST_RDLOCK(&groups);
  1794. }
  1795. struct ast_group_info *ast_app_group_list_head(void)
  1796. {
  1797. return AST_RWLIST_FIRST(&groups);
  1798. }
  1799. int ast_app_group_list_unlock(void)
  1800. {
  1801. return AST_RWLIST_UNLOCK(&groups);
  1802. }
  1803. #undef ast_app_separate_args
  1804. unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
  1805. unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
  1806. {
  1807. int argc;
  1808. char *scan, *wasdelim = NULL;
  1809. int paren = 0, quote = 0, bracket = 0;
  1810. if (!array || !arraylen) {
  1811. return 0;
  1812. }
  1813. memset(array, 0, arraylen * sizeof(*array));
  1814. if (!buf) {
  1815. return 0;
  1816. }
  1817. scan = buf;
  1818. for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
  1819. array[argc] = scan;
  1820. for (; *scan; scan++) {
  1821. if (*scan == '(') {
  1822. paren++;
  1823. } else if (*scan == ')') {
  1824. if (paren) {
  1825. paren--;
  1826. }
  1827. } else if (*scan == '[') {
  1828. bracket++;
  1829. } else if (*scan == ']') {
  1830. if (bracket) {
  1831. bracket--;
  1832. }
  1833. } else if (*scan == '"' && delim != '"') {
  1834. quote = quote ? 0 : 1;
  1835. if (remove_chars) {
  1836. /* Remove quote character from argument */
  1837. memmove(scan, scan + 1, strlen(scan));
  1838. scan--;
  1839. }
  1840. } else if (*scan == '\\') {
  1841. if (remove_chars) {
  1842. /* Literal character, don't parse */
  1843. memmove(scan, scan + 1, strlen(scan));
  1844. } else {
  1845. scan++;
  1846. }
  1847. } else if ((*scan == delim) && !paren && !quote && !bracket) {
  1848. wasdelim = scan;
  1849. *scan++ = '\0';
  1850. break;
  1851. }
  1852. }
  1853. }
  1854. /* If the last character in the original string was the delimiter, then
  1855. * there is one additional argument. */
  1856. if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
  1857. array[argc++] = scan;
  1858. }
  1859. return argc;
  1860. }
  1861. /* ABI compatible function */
  1862. unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
  1863. {
  1864. return __ast_app_separate_args(buf, delim, 1, array, arraylen);
  1865. }
  1866. static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
  1867. {
  1868. char *s;
  1869. char *fs;
  1870. int res;
  1871. int fd;
  1872. int lp = strlen(path);
  1873. time_t start;
  1874. s = ast_alloca(lp + 10);
  1875. fs = ast_alloca(lp + 20);
  1876. snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, (unsigned long)ast_random());
  1877. fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
  1878. if (fd < 0) {
  1879. ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
  1880. return AST_LOCK_PATH_NOT_FOUND;
  1881. }
  1882. close(fd);
  1883. snprintf(s, strlen(path) + 9, "%s/.lock", path);
  1884. start = time(NULL);
  1885. while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
  1886. sched_yield();
  1887. }
  1888. unlink(fs);
  1889. if (res) {
  1890. ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
  1891. return AST_LOCK_TIMEOUT;
  1892. } else {
  1893. ast_debug(1, "Locked path '%s'\n", path);
  1894. return AST_LOCK_SUCCESS;
  1895. }
  1896. }
  1897. static int ast_unlock_path_lockfile(const char *path)
  1898. {
  1899. char *s;
  1900. int res;
  1901. s = ast_alloca(strlen(path) + 10);
  1902. snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
  1903. if ((res = unlink(s))) {
  1904. ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
  1905. } else {
  1906. ast_debug(1, "Unlocked path '%s'\n", path);
  1907. }
  1908. return res;
  1909. }
  1910. struct path_lock {
  1911. AST_LIST_ENTRY(path_lock) le;
  1912. int fd;
  1913. char *path;
  1914. };
  1915. static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
  1916. static void path_lock_destroy(struct path_lock *obj)
  1917. {
  1918. if (obj->fd >= 0) {
  1919. close(obj->fd);
  1920. }
  1921. if (obj->path) {
  1922. free(obj->path);
  1923. }
  1924. free(obj);
  1925. }
  1926. static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
  1927. {
  1928. char *fs;
  1929. int res;
  1930. int fd;
  1931. time_t start;
  1932. struct path_lock *pl;
  1933. struct stat st, ost;
  1934. fs = ast_alloca(strlen(path) + 20);
  1935. snprintf(fs, strlen(path) + 19, "%s/lock", path);
  1936. if (lstat(fs, &st) == 0) {
  1937. if ((st.st_mode & S_IFMT) == S_IFLNK) {
  1938. ast_log(LOG_WARNING, "Unable to create lock file "
  1939. "'%s': it's already a symbolic link\n",
  1940. fs);
  1941. return AST_LOCK_FAILURE;
  1942. }
  1943. if (st.st_nlink > 1) {
  1944. ast_log(LOG_WARNING, "Unable to create lock file "
  1945. "'%s': %u hard links exist\n",
  1946. fs, (unsigned int) st.st_nlink);
  1947. return AST_LOCK_FAILURE;
  1948. }
  1949. }
  1950. if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
  1951. ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
  1952. fs, strerror(errno));
  1953. return AST_LOCK_PATH_NOT_FOUND;
  1954. }
  1955. if (!(pl = ast_calloc(1, sizeof(*pl)))) {
  1956. /* We don't unlink the lock file here, on the possibility that
  1957. * someone else created it - better to leave a little mess
  1958. * than create a big one by destroying someone else's lock
  1959. * and causing something to be corrupted.
  1960. */
  1961. close(fd);
  1962. return AST_LOCK_FAILURE;
  1963. }
  1964. pl->fd = fd;
  1965. pl->path = strdup(path);
  1966. time(&start);
  1967. while (
  1968. #ifdef SOLARIS
  1969. ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
  1970. #else
  1971. ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
  1972. #endif
  1973. (errno == EWOULDBLOCK) &&
  1974. (time(NULL) - start < 5))
  1975. usleep(1000);
  1976. if (res) {
  1977. ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
  1978. path, strerror(errno));
  1979. /* No unlinking of lock done, since we tried and failed to
  1980. * flock() it.
  1981. */
  1982. path_lock_destroy(pl);
  1983. return AST_LOCK_TIMEOUT;
  1984. }
  1985. /* Check for the race where the file is recreated or deleted out from
  1986. * underneath us.
  1987. */
  1988. if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
  1989. st.st_dev != ost.st_dev &&
  1990. st.st_ino != ost.st_ino) {
  1991. ast_log(LOG_WARNING, "Unable to create lock file '%s': "
  1992. "file changed underneath us\n", fs);
  1993. path_lock_destroy(pl);
  1994. return AST_LOCK_FAILURE;
  1995. }
  1996. /* Success: file created, flocked, and is the one we started with */
  1997. AST_LIST_LOCK(&path_lock_list);
  1998. AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
  1999. AST_LIST_UNLOCK(&path_lock_list);
  2000. ast_debug(1, "Locked path '%s'\n", path);
  2001. return AST_LOCK_SUCCESS;
  2002. }
  2003. static int ast_unlock_path_flock(const char *path)
  2004. {
  2005. char *s;
  2006. struct path_lock *p;
  2007. s = ast_alloca(strlen(path) + 20);
  2008. AST_LIST_LOCK(&path_lock_list);
  2009. AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
  2010. if (!strcmp(p->path, path)) {
  2011. AST_LIST_REMOVE_CURRENT(le);
  2012. break;
  2013. }
  2014. }
  2015. AST_LIST_TRAVERSE_SAFE_END;
  2016. AST_LIST_UNLOCK(&path_lock_list);
  2017. if (p) {
  2018. snprintf(s, strlen(path) + 19, "%s/lock", path);
  2019. unlink(s);
  2020. path_lock_destroy(p);
  2021. ast_debug(1, "Unlocked path '%s'\n", path);
  2022. } else {
  2023. ast_debug(1, "Failed to unlock path '%s': "
  2024. "lock not found\n", path);
  2025. }
  2026. return 0;
  2027. }
  2028. void ast_set_lock_type(enum AST_LOCK_TYPE type)
  2029. {
  2030. ast_lock_type = type;
  2031. }
  2032. enum AST_LOCK_RESULT ast_lock_path(const char *path)
  2033. {
  2034. enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
  2035. switch (ast_lock_type) {
  2036. case AST_LOCK_TYPE_LOCKFILE:
  2037. r = ast_lock_path_lockfile(path);
  2038. break;
  2039. case AST_LOCK_TYPE_FLOCK:
  2040. r = ast_lock_path_flock(path);
  2041. break;
  2042. }
  2043. return r;
  2044. }
  2045. int ast_unlock_path(const char *path)
  2046. {
  2047. int r = 0;
  2048. switch (ast_lock_type) {
  2049. case AST_LOCK_TYPE_LOCKFILE:
  2050. r = ast_unlock_path_lockfile(path);
  2051. break;
  2052. case AST_LOCK_TYPE_FLOCK:
  2053. r = ast_unlock_path_flock(path);
  2054. break;
  2055. }
  2056. return r;
  2057. }
  2058. int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
  2059. {
  2060. int silencethreshold;
  2061. int maxsilence = 0;
  2062. int res = 0;
  2063. int cmd = 0;
  2064. int max_attempts = 3;
  2065. int attempts = 0;
  2066. int recorded = 0;
  2067. int message_exists = 0;
  2068. /* Note that urgent and private are for flagging messages as such in the future */
  2069. /* barf if no pointer passed to store duration in */
  2070. if (!duration) {
  2071. ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
  2072. return -1;
  2073. }
  2074. cmd = '3'; /* Want to start by recording */
  2075. silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
  2076. while ((cmd >= 0) && (cmd != 't')) {
  2077. switch (cmd) {
  2078. case '1':
  2079. if (!message_exists) {
  2080. /* In this case, 1 is to record a message */
  2081. cmd = '3';
  2082. break;
  2083. } else {
  2084. ast_stream_and_wait(chan, "vm-msgsaved", "");
  2085. cmd = 't';
  2086. return res;
  2087. }
  2088. case '2':
  2089. /* Review */
  2090. ast_verb(3, "Reviewing the recording\n");
  2091. cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
  2092. break;
  2093. case '3':
  2094. message_exists = 0;
  2095. /* Record */
  2096. ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
  2097. recorded = 1;
  2098. if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
  2099. /* User has hung up, no options to give */
  2100. return cmd;
  2101. }
  2102. if (cmd == '0') {
  2103. break;
  2104. } else if (cmd == '*') {
  2105. break;
  2106. } else {
  2107. /* If all is well, a message exists */
  2108. message_exists = 1;
  2109. cmd = 0;
  2110. }
  2111. break;
  2112. case '4':
  2113. case '5':
  2114. case '6':
  2115. case '7':
  2116. case '8':
  2117. case '9':
  2118. case '*':
  2119. case '#':
  2120. cmd = ast_play_and_wait(chan, "vm-sorry");
  2121. break;
  2122. default:
  2123. if (message_exists) {
  2124. cmd = ast_play_and_wait(chan, "vm-review");
  2125. } else {
  2126. if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
  2127. cmd = ast_waitfordigit(chan, 600);
  2128. }
  2129. }
  2130. if (!cmd) {
  2131. cmd = ast_waitfordigit(chan, 6000);
  2132. }
  2133. if (!cmd) {
  2134. attempts++;
  2135. }
  2136. if (attempts > max_attempts) {
  2137. cmd = 't';
  2138. }
  2139. }
  2140. }
  2141. if (cmd == 't') {
  2142. cmd = 0;
  2143. }
  2144. return cmd;
  2145. }
  2146. #define RES_UPONE (1 << 16)
  2147. #define RES_EXIT (1 << 17)
  2148. #define RES_REPEAT (1 << 18)
  2149. #define RES_RESTART ((1 << 19) | RES_REPEAT)
  2150. static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
  2151. static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
  2152. {
  2153. int res;
  2154. int (*ivr_func)(struct ast_channel *, void *);
  2155. char *c;
  2156. char *n;
  2157. switch (option->action) {
  2158. case AST_ACTION_UPONE:
  2159. return RES_UPONE;
  2160. case AST_ACTION_EXIT:
  2161. return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
  2162. case AST_ACTION_REPEAT:
  2163. return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
  2164. case AST_ACTION_RESTART:
  2165. return RES_RESTART ;
  2166. case AST_ACTION_NOOP:
  2167. return 0;
  2168. case AST_ACTION_BACKGROUND:
  2169. res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
  2170. if (res < 0) {
  2171. ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
  2172. res = 0;
  2173. }
  2174. return res;
  2175. case AST_ACTION_PLAYBACK:
  2176. res = ast_stream_and_wait(chan, (char *)option->adata, "");
  2177. if (res < 0) {
  2178. ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
  2179. res = 0;
  2180. }
  2181. return res;
  2182. case AST_ACTION_MENU:
  2183. if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
  2184. /* Do not pass entry errors back up, treat as though it was an "UPONE" */
  2185. res = 0;
  2186. }
  2187. return res;
  2188. case AST_ACTION_WAITOPTION:
  2189. if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
  2190. return 't';
  2191. }
  2192. return res;
  2193. case AST_ACTION_CALLBACK:
  2194. ivr_func = option->adata;
  2195. res = ivr_func(chan, cbdata);
  2196. return res;
  2197. case AST_ACTION_TRANSFER:
  2198. res = ast_parseable_goto(chan, option->adata);
  2199. return 0;
  2200. case AST_ACTION_PLAYLIST:
  2201. case AST_ACTION_BACKLIST:
  2202. res = 0;
  2203. c = ast_strdupa(option->adata);
  2204. while ((n = strsep(&c, ";"))) {
  2205. if ((res = ast_stream_and_wait(chan, n,
  2206. (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
  2207. break;
  2208. }
  2209. }
  2210. ast_stopstream(chan);
  2211. return res;
  2212. default:
  2213. ast_log(LOG_NOTICE, "Unknown dispatch function %u, ignoring!\n", option->action);
  2214. return 0;
  2215. }
  2216. return -1;
  2217. }
  2218. static int option_exists(struct ast_ivr_menu *menu, char *option)
  2219. {
  2220. int x;
  2221. for (x = 0; menu->options[x].option; x++) {
  2222. if (!strcasecmp(menu->options[x].option, option)) {
  2223. return x;
  2224. }
  2225. }
  2226. return -1;
  2227. }
  2228. static int option_matchmore(struct ast_ivr_menu *menu, char *option)
  2229. {
  2230. int x;
  2231. for (x = 0; menu->options[x].option; x++) {
  2232. if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
  2233. (menu->options[x].option[strlen(option)])) {
  2234. return x;
  2235. }
  2236. }
  2237. return -1;
  2238. }
  2239. static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
  2240. {
  2241. int res = 0;
  2242. int ms;
  2243. while (option_matchmore(menu, exten)) {
  2244. ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
  2245. if (strlen(exten) >= maxexten - 1) {
  2246. break;
  2247. }
  2248. if ((res = ast_waitfordigit(chan, ms)) < 1) {
  2249. break;
  2250. }
  2251. exten[strlen(exten) + 1] = '\0';
  2252. exten[strlen(exten)] = res;
  2253. }
  2254. return res > 0 ? 0 : res;
  2255. }
  2256. static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
  2257. {
  2258. /* Execute an IVR menu structure */
  2259. int res = 0;
  2260. int pos = 0;
  2261. int retries = 0;
  2262. char exten[AST_MAX_EXTENSION] = "s";
  2263. if (option_exists(menu, "s") < 0) {
  2264. strcpy(exten, "g");
  2265. if (option_exists(menu, "g") < 0) {
  2266. ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
  2267. return -1;
  2268. }
  2269. }
  2270. while (!res) {
  2271. while (menu->options[pos].option) {
  2272. if (!strcasecmp(menu->options[pos].option, exten)) {
  2273. res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
  2274. ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
  2275. if (res < 0) {
  2276. break;
  2277. } else if (res & RES_UPONE) {
  2278. return 0;
  2279. } else if (res & RES_EXIT) {
  2280. return res;
  2281. } else if (res & RES_REPEAT) {
  2282. int maxretries = res & 0xffff;
  2283. if ((res & RES_RESTART) == RES_RESTART) {
  2284. retries = 0;
  2285. } else {
  2286. retries++;
  2287. }
  2288. if (!maxretries) {
  2289. maxretries = 3;
  2290. }
  2291. if ((maxretries > 0) && (retries >= maxretries)) {
  2292. ast_debug(1, "Max retries %d exceeded\n", maxretries);
  2293. return -2;
  2294. } else {
  2295. if (option_exists(menu, "g") > -1) {
  2296. strcpy(exten, "g");
  2297. } else if (option_exists(menu, "s") > -1) {
  2298. strcpy(exten, "s");
  2299. }
  2300. }
  2301. pos = 0;
  2302. continue;
  2303. } else if (res && strchr(AST_DIGIT_ANY, res)) {
  2304. ast_debug(1, "Got start of extension, %c\n", res);
  2305. exten[1] = '\0';
  2306. exten[0] = res;
  2307. if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
  2308. break;
  2309. }
  2310. if (option_exists(menu, exten) < 0) {
  2311. if (option_exists(menu, "i")) {
  2312. ast_debug(1, "Invalid extension entered, going to 'i'!\n");
  2313. strcpy(exten, "i");
  2314. pos = 0;
  2315. continue;
  2316. } else {
  2317. ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
  2318. res = -2;
  2319. break;
  2320. }
  2321. } else {
  2322. ast_debug(1, "New existing extension: %s\n", exten);
  2323. pos = 0;
  2324. continue;
  2325. }
  2326. }
  2327. }
  2328. pos++;
  2329. }
  2330. ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
  2331. pos = 0;
  2332. if (!strcasecmp(exten, "s")) {
  2333. strcpy(exten, "g");
  2334. } else {
  2335. break;
  2336. }
  2337. }
  2338. return res;
  2339. }
  2340. int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
  2341. {
  2342. int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
  2343. /* Hide internal coding */
  2344. return res > 0 ? 0 : res;
  2345. }
  2346. char *ast_read_textfile(const char *filename)
  2347. {
  2348. int fd, count = 0, res;
  2349. char *output = NULL;
  2350. struct stat filesize;
  2351. if (stat(filename, &filesize) == -1) {
  2352. ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
  2353. return NULL;
  2354. }
  2355. count = filesize.st_size + 1;
  2356. if ((fd = open(filename, O_RDONLY)) < 0) {
  2357. ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
  2358. return NULL;
  2359. }
  2360. if ((output = ast_malloc(count))) {
  2361. res = read(fd, output, count - 1);
  2362. if (res == count - 1) {
  2363. output[res] = '\0';
  2364. } else {
  2365. ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
  2366. ast_free(output);
  2367. output = NULL;
  2368. }
  2369. }
  2370. close(fd);
  2371. return output;
  2372. }
  2373. static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
  2374. {
  2375. char *s, *arg;
  2376. int curarg, res = 0;
  2377. unsigned int argloc;
  2378. struct ast_flags *flags = _flags;
  2379. struct ast_flags64 *flags64 = _flags;
  2380. if (flaglen == 32) {
  2381. ast_clear_flag(flags, AST_FLAGS_ALL);
  2382. } else {
  2383. flags64->flags = 0;
  2384. }
  2385. if (!optstr) {
  2386. return 0;
  2387. }
  2388. s = optstr;
  2389. while (*s) {
  2390. curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
  2391. argloc = options[curarg].arg_index;
  2392. if (*s == '(') {
  2393. int paren = 1, quote = 0;
  2394. int parsequotes = (s[1] == '"') ? 1 : 0;
  2395. /* Has argument */
  2396. arg = ++s;
  2397. for (; *s; s++) {
  2398. if (*s == '(' && !quote) {
  2399. paren++;
  2400. } else if (*s == ')' && !quote) {
  2401. /* Count parentheses, unless they're within quotes (or backslashed, below) */
  2402. paren--;
  2403. } else if (*s == '"' && parsequotes) {
  2404. /* Leave embedded quotes alone, unless they are the first character */
  2405. quote = quote ? 0 : 1;
  2406. ast_copy_string(s, s + 1, INT_MAX);
  2407. s--;
  2408. } else if (*s == '\\') {
  2409. if (!quote) {
  2410. /* If a backslash is found outside of quotes, remove it */
  2411. ast_copy_string(s, s + 1, INT_MAX);
  2412. } else if (quote && s[1] == '"') {
  2413. /* Backslash for a quote character within quotes, remove the backslash */
  2414. ast_copy_string(s, s + 1, INT_MAX);
  2415. } else {
  2416. /* Backslash within quotes, keep both characters */
  2417. s++;
  2418. }
  2419. }
  2420. if (paren == 0) {
  2421. break;
  2422. }
  2423. }
  2424. /* This will find the closing paren we found above, or none, if the string ended before we found one. */
  2425. if ((s = strchr(s, ')'))) {
  2426. if (argloc) {
  2427. args[argloc - 1] = arg;
  2428. }
  2429. *s++ = '\0';
  2430. } else {
  2431. ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
  2432. res = -1;
  2433. break;
  2434. }
  2435. } else if (argloc) {
  2436. args[argloc - 1] = "";
  2437. }
  2438. if (flaglen == 32) {
  2439. ast_set_flag(flags, options[curarg].flag);
  2440. } else {
  2441. ast_set_flag64(flags64, options[curarg].flag);
  2442. }
  2443. }
  2444. return res;
  2445. }
  2446. int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
  2447. {
  2448. return parse_options(options, flags, args, optstr, 32);
  2449. }
  2450. int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
  2451. {
  2452. return parse_options(options, flags, args, optstr, 64);
  2453. }
  2454. void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
  2455. {
  2456. unsigned int i, found = 0;
  2457. for (i = 32; i < 128 && found < len; i++) {
  2458. if (ast_test_flag64(flags, options[i].flag)) {
  2459. buf[found++] = i;
  2460. }
  2461. }
  2462. buf[found] = '\0';
  2463. }
  2464. int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
  2465. {
  2466. int i;
  2467. *consumed = 1;
  2468. *result = 0;
  2469. if (ast_strlen_zero(stream)) {
  2470. *consumed = 0;
  2471. return -1;
  2472. }
  2473. if (*stream == '\\') {
  2474. *consumed = 2;
  2475. switch (*(stream + 1)) {
  2476. case 'n':
  2477. *result = '\n';
  2478. break;
  2479. case 'r':
  2480. *result = '\r';
  2481. break;
  2482. case 't':
  2483. *result = '\t';
  2484. break;
  2485. case 'x':
  2486. /* Hexadecimal */
  2487. if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
  2488. *consumed = 3;
  2489. if (*(stream + 2) <= '9') {
  2490. *result = *(stream + 2) - '0';
  2491. } else if (*(stream + 2) <= 'F') {
  2492. *result = *(stream + 2) - 'A' + 10;
  2493. } else {
  2494. *result = *(stream + 2) - 'a' + 10;
  2495. }
  2496. } else {
  2497. ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
  2498. return -1;
  2499. }
  2500. if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
  2501. *consumed = 4;
  2502. *result <<= 4;
  2503. if (*(stream + 3) <= '9') {
  2504. *result += *(stream + 3) - '0';
  2505. } else if (*(stream + 3) <= 'F') {
  2506. *result += *(stream + 3) - 'A' + 10;
  2507. } else {
  2508. *result += *(stream + 3) - 'a' + 10;
  2509. }
  2510. }
  2511. break;
  2512. case '0':
  2513. /* Octal */
  2514. *consumed = 2;
  2515. for (i = 2; ; i++) {
  2516. if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
  2517. (*consumed)++;
  2518. ast_debug(5, "result was %d, ", *result);
  2519. *result <<= 3;
  2520. *result += *(stream + i) - '0';
  2521. ast_debug(5, "is now %d\n", *result);
  2522. } else {
  2523. break;
  2524. }
  2525. }
  2526. break;
  2527. default:
  2528. *result = *(stream + 1);
  2529. }
  2530. } else {
  2531. *result = *stream;
  2532. *consumed = 1;
  2533. }
  2534. return 0;
  2535. }
  2536. char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
  2537. {
  2538. char *cur = result;
  2539. size_t consumed;
  2540. while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
  2541. cur++;
  2542. stream += consumed;
  2543. }
  2544. *cur = '\0';
  2545. return result;
  2546. }
  2547. int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
  2548. {
  2549. char next, *buf;
  2550. size_t offset = 0;
  2551. size_t consumed;
  2552. if (strchr(stream, '\\')) {
  2553. while (!ast_get_encoded_char(stream, &next, &consumed)) {
  2554. if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
  2555. ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
  2556. }
  2557. if (offset + 2 > ast_str_size(*str)) {
  2558. break;
  2559. }
  2560. buf = ast_str_buffer(*str);
  2561. buf[offset++] = next;
  2562. stream += consumed;
  2563. }
  2564. buf = ast_str_buffer(*str);
  2565. buf[offset++] = '\0';
  2566. ast_str_update(*str);
  2567. } else {
  2568. ast_str_set(str, maxlen, "%s", stream);
  2569. }
  2570. return 0;
  2571. }
  2572. void ast_close_fds_above_n(int n)
  2573. {
  2574. closefrom(n + 1);
  2575. }
  2576. int ast_safe_fork(int stop_reaper)
  2577. {
  2578. sigset_t signal_set, old_set;
  2579. int pid;
  2580. /* Don't let the default signal handler for children reap our status */
  2581. if (stop_reaper) {
  2582. ast_replace_sigchld();
  2583. }
  2584. /* GCC 4.9 gives a bogus "right-hand operand of comma expression has
  2585. * no effect" warning */
  2586. (void) sigfillset(&signal_set);
  2587. pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
  2588. pid = fork();
  2589. if (pid != 0) {
  2590. /* Fork failed or parent */
  2591. pthread_sigmask(SIG_SETMASK, &old_set, NULL);
  2592. if (!stop_reaper && pid > 0) {
  2593. struct zombie *cur = ast_calloc(1, sizeof(*cur));
  2594. if (cur) {
  2595. cur->pid = pid;
  2596. AST_LIST_LOCK(&zombies);
  2597. AST_LIST_INSERT_TAIL(&zombies, cur, list);
  2598. AST_LIST_UNLOCK(&zombies);
  2599. if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
  2600. if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
  2601. ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
  2602. shaun_of_the_dead_thread = AST_PTHREADT_NULL;
  2603. }
  2604. }
  2605. }
  2606. }
  2607. return pid;
  2608. } else {
  2609. /* Child */
  2610. #ifdef HAVE_CAP
  2611. cap_t cap = cap_from_text("cap_net_admin-eip");
  2612. if (cap_set_proc(cap)) {
  2613. ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
  2614. }
  2615. cap_free(cap);
  2616. #endif
  2617. /* Before we unblock our signals, return our trapped signals back to the defaults */
  2618. signal(SIGHUP, SIG_DFL);
  2619. signal(SIGCHLD, SIG_DFL);
  2620. signal(SIGINT, SIG_DFL);
  2621. signal(SIGURG, SIG_DFL);
  2622. signal(SIGTERM, SIG_DFL);
  2623. signal(SIGPIPE, SIG_DFL);
  2624. signal(SIGXFSZ, SIG_DFL);
  2625. /* unblock important signal handlers */
  2626. if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
  2627. ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
  2628. _exit(1);
  2629. }
  2630. return pid;
  2631. }
  2632. }
  2633. void ast_safe_fork_cleanup(void)
  2634. {
  2635. ast_unreplace_sigchld();
  2636. }
  2637. int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
  2638. {
  2639. int res;
  2640. char u[10];
  2641. #ifdef HAVE_LONG_DOUBLE_WIDER
  2642. long double amount;
  2643. #define FMT "%30Lf%9s"
  2644. #else
  2645. double amount;
  2646. #define FMT "%30lf%9s"
  2647. #endif
  2648. if (!timestr) {
  2649. return -1;
  2650. }
  2651. res = sscanf(timestr, FMT, &amount, u);
  2652. if (res == 0 || res == EOF) {
  2653. #undef FMT
  2654. return -1;
  2655. } else if (res == 2) {
  2656. switch (u[0]) {
  2657. case 'h':
  2658. case 'H':
  2659. unit = TIMELEN_HOURS;
  2660. break;
  2661. case 's':
  2662. case 'S':
  2663. unit = TIMELEN_SECONDS;
  2664. break;
  2665. case 'm':
  2666. case 'M':
  2667. if (toupper(u[1]) == 'S') {
  2668. unit = TIMELEN_MILLISECONDS;
  2669. } else if (u[1] == '\0') {
  2670. unit = TIMELEN_MINUTES;
  2671. }
  2672. break;
  2673. }
  2674. }
  2675. switch (unit) {
  2676. case TIMELEN_HOURS:
  2677. amount *= 60;
  2678. /* fall-through */
  2679. case TIMELEN_MINUTES:
  2680. amount *= 60;
  2681. /* fall-through */
  2682. case TIMELEN_SECONDS:
  2683. amount *= 1000;
  2684. /* fall-through */
  2685. case TIMELEN_MILLISECONDS:
  2686. ;
  2687. }
  2688. *result = amount > INT_MAX ? INT_MAX : (int) amount;
  2689. return 0;
  2690. }
  2691. static void mwi_state_dtor(void *obj)
  2692. {
  2693. struct ast_mwi_state *mwi_state = obj;
  2694. ast_string_field_free_memory(mwi_state);
  2695. ao2_cleanup(mwi_state->snapshot);
  2696. mwi_state->snapshot = NULL;
  2697. }
  2698. struct stasis_topic *ast_mwi_topic_all(void)
  2699. {
  2700. return mwi_topic_all;
  2701. }
  2702. struct stasis_cache *ast_mwi_state_cache(void)
  2703. {
  2704. return mwi_state_cache;
  2705. }
  2706. struct stasis_topic *ast_mwi_topic_cached(void)
  2707. {
  2708. return stasis_caching_get_topic(mwi_topic_cached);
  2709. }
  2710. struct stasis_topic *ast_mwi_topic(const char *uniqueid)
  2711. {
  2712. return stasis_topic_pool_get_topic(mwi_topic_pool, uniqueid);
  2713. }
  2714. struct ast_mwi_state *ast_mwi_create(const char *mailbox, const char *context)
  2715. {
  2716. RAII_VAR(struct ast_mwi_state *, mwi_state, NULL, ao2_cleanup);
  2717. ast_assert(!ast_strlen_zero(mailbox));
  2718. mwi_state = ao2_alloc(sizeof(*mwi_state), mwi_state_dtor);
  2719. if (!mwi_state) {
  2720. return NULL;
  2721. }
  2722. if (ast_string_field_init(mwi_state, 256)) {
  2723. return NULL;
  2724. }
  2725. if (!ast_strlen_zero(context)) {
  2726. ast_string_field_build(mwi_state, uniqueid, "%s@%s", mailbox, context);
  2727. } else {
  2728. ast_string_field_set(mwi_state, uniqueid, mailbox);
  2729. }
  2730. ao2_ref(mwi_state, +1);
  2731. return mwi_state;
  2732. }
  2733. /*!
  2734. * \internal
  2735. * \brief Create a MWI state snapshot message.
  2736. * \since 12.2.0
  2737. *
  2738. * \param[in] mailbox The mailbox identifier string.
  2739. * \param[in] context The context this mailbox resides in (NULL or "" if only using mailbox)
  2740. * \param[in] new_msgs The number of new messages in this mailbox
  2741. * \param[in] old_msgs The number of old messages in this mailbox
  2742. * \param[in] channel_id A unique identifier for a channel associated with this
  2743. * change in mailbox state
  2744. * \param[in] eid The EID of the server that originally published the message
  2745. *
  2746. * \retval message on success. Use ao2_cleanup() when done with it.
  2747. * \retval NULL on error.
  2748. */
  2749. static struct stasis_message *mwi_state_create_message(
  2750. const char *mailbox,
  2751. const char *context,
  2752. int new_msgs,
  2753. int old_msgs,
  2754. const char *channel_id,
  2755. struct ast_eid *eid)
  2756. {
  2757. struct ast_mwi_state *mwi_state;
  2758. struct stasis_message *message;
  2759. if (!ast_mwi_state_type()) {
  2760. return NULL;
  2761. }
  2762. mwi_state = ast_mwi_create(mailbox, context);
  2763. if (!mwi_state) {
  2764. return NULL;
  2765. }
  2766. mwi_state->new_msgs = new_msgs;
  2767. mwi_state->old_msgs = old_msgs;
  2768. if (!ast_strlen_zero(channel_id)) {
  2769. struct stasis_message *chan_message;
  2770. chan_message = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
  2771. channel_id);
  2772. if (chan_message) {
  2773. mwi_state->snapshot = stasis_message_data(chan_message);
  2774. ao2_ref(mwi_state->snapshot, +1);
  2775. }
  2776. ao2_cleanup(chan_message);
  2777. }
  2778. if (eid) {
  2779. mwi_state->eid = *eid;
  2780. } else {
  2781. mwi_state->eid = ast_eid_default;
  2782. }
  2783. /*
  2784. * XXX As far as stasis is concerned, all MWI events are local.
  2785. *
  2786. * We may in the future want to make MWI aggregate local/remote
  2787. * message counts similar to how device state aggregates state.
  2788. */
  2789. message = stasis_message_create_full(ast_mwi_state_type(), mwi_state, &ast_eid_default);
  2790. ao2_cleanup(mwi_state);
  2791. return message;
  2792. }
  2793. int ast_publish_mwi_state_full(
  2794. const char *mailbox,
  2795. const char *context,
  2796. int new_msgs,
  2797. int old_msgs,
  2798. const char *channel_id,
  2799. struct ast_eid *eid)
  2800. {
  2801. struct ast_mwi_state *mwi_state;
  2802. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  2803. struct stasis_topic *mailbox_specific_topic;
  2804. message = mwi_state_create_message(mailbox, context, new_msgs, old_msgs, channel_id, eid);
  2805. if (!message) {
  2806. return -1;
  2807. }
  2808. mwi_state = stasis_message_data(message);
  2809. mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
  2810. if (!mailbox_specific_topic) {
  2811. return -1;
  2812. }
  2813. stasis_publish(mailbox_specific_topic, message);
  2814. return 0;
  2815. }
  2816. int ast_delete_mwi_state_full(const char *mailbox, const char *context, struct ast_eid *eid)
  2817. {
  2818. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  2819. struct stasis_message *cached_msg;
  2820. struct stasis_message *clear_msg;
  2821. struct ast_mwi_state *mwi_state;
  2822. struct stasis_topic *mailbox_specific_topic;
  2823. msg = mwi_state_create_message(mailbox, context, 0, 0, NULL, eid);
  2824. if (!msg) {
  2825. return -1;
  2826. }
  2827. mwi_state = stasis_message_data(msg);
  2828. /*
  2829. * XXX As far as stasis is concerned, all MWI events are local.
  2830. *
  2831. * For now, it is assumed that there is only one entity
  2832. * maintaining the state of a particular mailbox.
  2833. *
  2834. * If we ever have multiple MWI event entities maintaining
  2835. * the same mailbox that wish to delete their cached entry
  2836. * we will need to do something about the race condition
  2837. * potential between checking the cache and removing the
  2838. * cache entry.
  2839. */
  2840. cached_msg = stasis_cache_get_by_eid(ast_mwi_state_cache(),
  2841. ast_mwi_state_type(), mwi_state->uniqueid, &ast_eid_default);
  2842. if (!cached_msg) {
  2843. /* Nothing to clear */
  2844. return -1;
  2845. }
  2846. ao2_cleanup(cached_msg);
  2847. mailbox_specific_topic = ast_mwi_topic(mwi_state->uniqueid);
  2848. if (!mailbox_specific_topic) {
  2849. return -1;
  2850. }
  2851. clear_msg = stasis_cache_clear_create(msg);
  2852. if (clear_msg) {
  2853. stasis_publish(mailbox_specific_topic, clear_msg);
  2854. }
  2855. ao2_cleanup(clear_msg);
  2856. return 0;
  2857. }
  2858. static const char *mwi_state_get_id(struct stasis_message *message)
  2859. {
  2860. if (ast_mwi_state_type() == stasis_message_type(message)) {
  2861. struct ast_mwi_state *mwi_state = stasis_message_data(message);
  2862. return mwi_state->uniqueid;
  2863. } else if (stasis_subscription_change_type() == stasis_message_type(message)) {
  2864. struct stasis_subscription_change *change = stasis_message_data(message);
  2865. return change->uniqueid;
  2866. }
  2867. return NULL;
  2868. }
  2869. static void mwi_blob_dtor(void *obj)
  2870. {
  2871. struct ast_mwi_blob *mwi_blob = obj;
  2872. ao2_cleanup(mwi_blob->mwi_state);
  2873. ast_json_unref(mwi_blob->blob);
  2874. }
  2875. struct stasis_message *ast_mwi_blob_create(struct ast_mwi_state *mwi_state,
  2876. struct stasis_message_type *message_type,
  2877. struct ast_json *blob)
  2878. {
  2879. RAII_VAR(struct ast_mwi_blob *, obj, NULL, ao2_cleanup);
  2880. RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
  2881. ast_assert(blob != NULL);
  2882. if (!message_type) {
  2883. return NULL;
  2884. }
  2885. obj = ao2_alloc(sizeof(*obj), mwi_blob_dtor);
  2886. if (!obj) {
  2887. return NULL;
  2888. }
  2889. obj->mwi_state = mwi_state;
  2890. ao2_ref(obj->mwi_state, +1);
  2891. obj->blob = ast_json_ref(blob);
  2892. /* This is not a normal MWI event. Only used by the MinivmNotify app. */
  2893. msg = stasis_message_create(message_type, obj);
  2894. if (!msg) {
  2895. return NULL;
  2896. }
  2897. ao2_ref(msg, +1);
  2898. return msg;
  2899. }
  2900. struct stasis_topic *ast_queue_topic_all(void)
  2901. {
  2902. return queue_topic_all;
  2903. }
  2904. struct stasis_topic *ast_queue_topic(const char *queuename)
  2905. {
  2906. return stasis_topic_pool_get_topic(queue_topic_pool, queuename);
  2907. }
  2908. static void app_cleanup(void)
  2909. {
  2910. ao2_cleanup(queue_topic_pool);
  2911. queue_topic_pool = NULL;
  2912. ao2_cleanup(queue_topic_all);
  2913. queue_topic_all = NULL;
  2914. ao2_cleanup(mwi_topic_pool);
  2915. mwi_topic_pool = NULL;
  2916. ao2_cleanup(mwi_topic_all);
  2917. mwi_topic_all = NULL;
  2918. ao2_cleanup(mwi_state_cache);
  2919. mwi_state_cache = NULL;
  2920. mwi_topic_cached = stasis_caching_unsubscribe_and_join(mwi_topic_cached);
  2921. STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_state_type);
  2922. STASIS_MESSAGE_TYPE_CLEANUP(ast_mwi_vm_app_type);
  2923. }
  2924. int app_init(void)
  2925. {
  2926. ast_register_cleanup(app_cleanup);
  2927. if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_state_type) != 0) {
  2928. return -1;
  2929. }
  2930. if (STASIS_MESSAGE_TYPE_INIT(ast_mwi_vm_app_type) != 0) {
  2931. return -1;
  2932. }
  2933. mwi_topic_all = stasis_topic_create("stasis_mwi_topic");
  2934. if (!mwi_topic_all) {
  2935. return -1;
  2936. }
  2937. mwi_state_cache = stasis_cache_create(mwi_state_get_id);
  2938. if (!mwi_state_cache) {
  2939. return -1;
  2940. }
  2941. mwi_topic_cached = stasis_caching_topic_create(mwi_topic_all, mwi_state_cache);
  2942. if (!mwi_topic_cached) {
  2943. return -1;
  2944. }
  2945. mwi_topic_pool = stasis_topic_pool_create(mwi_topic_all);
  2946. if (!mwi_topic_pool) {
  2947. return -1;
  2948. }
  2949. queue_topic_all = stasis_topic_create("stasis_queue_topic");
  2950. if (!queue_topic_all) {
  2951. return -1;
  2952. }
  2953. queue_topic_pool = stasis_topic_pool_create(queue_topic_all);
  2954. if (!queue_topic_pool) {
  2955. return -1;
  2956. }
  2957. return 0;
  2958. }