app.c 84 KB

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