app.c 86 KB

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