app.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633
  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. /*** MODULEINFO
  25. <support_level>core</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #ifdef HAVE_SYS_STAT_H
  30. #include <sys/stat.h>
  31. #endif
  32. #include <regex.h> /* for regcomp(3) */
  33. #include <sys/file.h> /* for flock(2) */
  34. #include <signal.h> /* for pthread_sigmask(3) */
  35. #include <stdlib.h> /* for closefrom(3) */
  36. #include <sys/types.h>
  37. #include <sys/wait.h> /* for waitpid(2) */
  38. #ifndef HAVE_CLOSEFROM
  39. #include <dirent.h> /* for opendir(3) */
  40. #endif
  41. #ifdef HAVE_CAP
  42. #include <sys/capability.h>
  43. #endif /* HAVE_CAP */
  44. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  45. #include "asterisk/channel.h"
  46. #include "asterisk/pbx.h"
  47. #include "asterisk/file.h"
  48. #include "asterisk/app.h"
  49. #include "asterisk/dsp.h"
  50. #include "asterisk/utils.h"
  51. #include "asterisk/lock.h"
  52. #include "asterisk/indications.h"
  53. #include "asterisk/linkedlists.h"
  54. #include "asterisk/threadstorage.h"
  55. #include "asterisk/test.h"
  56. #include "asterisk/module.h"
  57. AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
  58. static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
  59. struct zombie {
  60. pid_t pid;
  61. AST_LIST_ENTRY(zombie) list;
  62. };
  63. static AST_LIST_HEAD_STATIC(zombies, zombie);
  64. static void *shaun_of_the_dead(void *data)
  65. {
  66. struct zombie *cur;
  67. int status;
  68. for (;;) {
  69. if (!AST_LIST_EMPTY(&zombies)) {
  70. /* Don't allow cancellation while we have a lock. */
  71. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  72. AST_LIST_LOCK(&zombies);
  73. AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
  74. if (waitpid(cur->pid, &status, WNOHANG) != 0) {
  75. AST_LIST_REMOVE_CURRENT(list);
  76. ast_free(cur);
  77. }
  78. }
  79. AST_LIST_TRAVERSE_SAFE_END
  80. AST_LIST_UNLOCK(&zombies);
  81. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  82. }
  83. pthread_testcancel();
  84. /* Wait for 60 seconds, without engaging in a busy loop. */
  85. ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
  86. }
  87. return NULL;
  88. }
  89. #define AST_MAX_FORMATS 10
  90. static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
  91. /*!
  92. * \brief This function presents a dialtone and reads an extension into 'collect'
  93. * which must be a pointer to a **pre-initialized** array of char having a
  94. * size of 'size' suitable for writing to. It will collect no more than the smaller
  95. * of 'maxlen' or 'size' minus the original strlen() of collect digits.
  96. * \param chan struct.
  97. * \param context
  98. * \param collect
  99. * \param size
  100. * \param maxlen
  101. * \param timeout timeout in milliseconds
  102. *
  103. * \return 0 if extension does not exist, 1 if extension exists
  104. */
  105. int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
  106. {
  107. struct ast_tone_zone_sound *ts;
  108. int res = 0, x = 0;
  109. if (maxlen > size) {
  110. maxlen = size;
  111. }
  112. if (!timeout) {
  113. if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
  114. timeout = ast_channel_pbx(chan)->dtimeoutms;
  115. } else {
  116. timeout = 5000;
  117. }
  118. }
  119. if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
  120. res = ast_playtones_start(chan, 0, ts->data, 0);
  121. ts = ast_tone_zone_sound_unref(ts);
  122. } else {
  123. ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
  124. }
  125. for (x = strlen(collect); x < maxlen; ) {
  126. res = ast_waitfordigit(chan, timeout);
  127. if (!ast_ignore_pattern(context, collect)) {
  128. ast_playtones_stop(chan);
  129. }
  130. if (res < 1) {
  131. break;
  132. }
  133. if (res == '#') {
  134. break;
  135. }
  136. collect[x++] = res;
  137. if (!ast_matchmore_extension(chan, context, collect, 1,
  138. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
  139. break;
  140. }
  141. }
  142. if (res >= 0) {
  143. res = ast_exists_extension(chan, context, collect, 1,
  144. S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
  145. }
  146. return res;
  147. }
  148. /*!
  149. * \brief ast_app_getdata
  150. * \param c The channel to read from
  151. * \param prompt The file to stream to the channel
  152. * \param s The string to read in to. Must be at least the size of your length
  153. * \param maxlen How many digits to read (maximum)
  154. * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
  155. * "ludicrous time" (essentially never times out) */
  156. enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
  157. {
  158. int res = 0, to, fto;
  159. char *front, *filename;
  160. /* XXX Merge with full version? XXX */
  161. if (maxlen)
  162. s[0] = '\0';
  163. if (!prompt)
  164. prompt = "";
  165. filename = ast_strdupa(prompt);
  166. while ((front = strsep(&filename, "&"))) {
  167. if (!ast_strlen_zero(front)) {
  168. res = ast_streamfile(c, front, ast_channel_language(c));
  169. if (res)
  170. continue;
  171. }
  172. if (ast_strlen_zero(filename)) {
  173. /* set timeouts for the last prompt */
  174. fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
  175. to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
  176. if (timeout > 0) {
  177. fto = to = timeout;
  178. }
  179. if (timeout < 0) {
  180. fto = to = 1000000000;
  181. }
  182. } else {
  183. /* there is more than one prompt, so
  184. * get rid of the long timeout between
  185. * prompts, and make it 50ms */
  186. fto = 50;
  187. to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
  188. }
  189. res = ast_readstring(c, s, maxlen, to, fto, "#");
  190. if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
  191. return res;
  192. }
  193. if (!ast_strlen_zero(s)) {
  194. return res;
  195. }
  196. }
  197. return res;
  198. }
  199. /* The lock type used by ast_lock_path() / ast_unlock_path() */
  200. static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
  201. int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
  202. {
  203. int res, to = 2000, fto = 6000;
  204. if (!ast_strlen_zero(prompt)) {
  205. res = ast_streamfile(c, prompt, ast_channel_language(c));
  206. if (res < 0) {
  207. return res;
  208. }
  209. }
  210. if (timeout > 0) {
  211. fto = to = timeout;
  212. }
  213. if (timeout < 0) {
  214. fto = to = 1000000000;
  215. }
  216. res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
  217. return res;
  218. }
  219. int ast_app_exec_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_args)
  220. {
  221. struct ast_app *macro_app;
  222. int res;
  223. macro_app = pbx_findapp("Macro");
  224. if (!macro_app) {
  225. ast_log(LOG_WARNING,
  226. "Cannot run 'Macro(%s)'. The application is not available.\n", macro_args);
  227. return -1;
  228. }
  229. if (autoservice_chan) {
  230. ast_autoservice_start(autoservice_chan);
  231. }
  232. ast_debug(4, "%s Original location: %s,%s,%d\n", ast_channel_name(macro_chan),
  233. ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
  234. ast_channel_priority(macro_chan));
  235. res = pbx_exec(macro_chan, macro_app, macro_args);
  236. ast_debug(4, "Macro exited with status %d\n", res);
  237. /*
  238. * Assume anything negative from Macro is an error.
  239. * Anything else is success.
  240. */
  241. if (res < 0) {
  242. res = -1;
  243. } else {
  244. res = 0;
  245. }
  246. ast_debug(4, "%s Ending location: %s,%s,%d\n", ast_channel_name(macro_chan),
  247. ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
  248. ast_channel_priority(macro_chan));
  249. if (autoservice_chan) {
  250. ast_autoservice_stop(autoservice_chan);
  251. }
  252. return res;
  253. }
  254. int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_name, const char *macro_args)
  255. {
  256. int res;
  257. char *args_str;
  258. size_t args_len;
  259. if (ast_strlen_zero(macro_args)) {
  260. return ast_app_exec_macro(autoservice_chan, macro_chan, macro_name);
  261. }
  262. /* Create the Macro application argument string. */
  263. args_len = strlen(macro_name) + strlen(macro_args) + 2;
  264. args_str = ast_malloc(args_len);
  265. if (!args_str) {
  266. return -1;
  267. }
  268. snprintf(args_str, args_len, "%s,%s", macro_name, macro_args);
  269. res = ast_app_exec_macro(autoservice_chan, macro_chan, args_str);
  270. ast_free(args_str);
  271. return res;
  272. }
  273. static const struct ast_app_stack_funcs *app_stack_callbacks;
  274. void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
  275. {
  276. app_stack_callbacks = funcs;
  277. }
  278. const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
  279. {
  280. const struct ast_app_stack_funcs *funcs;
  281. const char *new_args;
  282. funcs = app_stack_callbacks;
  283. if (!funcs || !funcs->expand_sub_args) {
  284. ast_log(LOG_WARNING,
  285. "Cannot expand 'Gosub(%s)' arguments. The app_stack module is not available.\n",
  286. args);
  287. return NULL;
  288. }
  289. ast_module_ref(funcs->module);
  290. new_args = funcs->expand_sub_args(chan, args);
  291. ast_module_unref(funcs->module);
  292. return new_args;
  293. }
  294. int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
  295. {
  296. const struct ast_app_stack_funcs *funcs;
  297. int res;
  298. funcs = app_stack_callbacks;
  299. if (!funcs || !funcs->run_sub) {
  300. ast_log(LOG_WARNING,
  301. "Cannot run 'Gosub(%s)'. The app_stack module is not available.\n",
  302. sub_args);
  303. return -1;
  304. }
  305. ast_module_ref(funcs->module);
  306. if (autoservice_chan) {
  307. ast_autoservice_start(autoservice_chan);
  308. }
  309. res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
  310. ast_module_unref(funcs->module);
  311. if (autoservice_chan) {
  312. ast_autoservice_stop(autoservice_chan);
  313. }
  314. return res;
  315. }
  316. 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)
  317. {
  318. int res;
  319. char *args_str;
  320. size_t args_len;
  321. if (ast_strlen_zero(sub_args)) {
  322. return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
  323. }
  324. /* Create the Gosub application argument string. */
  325. args_len = strlen(sub_location) + strlen(sub_args) + 3;
  326. args_str = ast_malloc(args_len);
  327. if (!args_str) {
  328. return -1;
  329. }
  330. snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
  331. res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
  332. ast_free(args_str);
  333. return res;
  334. }
  335. static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
  336. static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
  337. static int (*ast_inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs) = NULL;
  338. static int (*ast_sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context) = NULL;
  339. static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
  340. static int (*ast_copy_recording_to_vm_func)(struct ast_vm_recording_data *vm_rec_data) = NULL;
  341. static const char *(*ast_vm_index_to_foldername_func)(int id) = NULL;
  342. static struct ast_vm_mailbox_snapshot *(*ast_vm_mailbox_snapshot_create_func)(const char *mailbox,
  343. const char *context,
  344. const char *folder,
  345. int descending,
  346. enum ast_vm_snapshot_sort_val sort_val,
  347. int combine_INBOX_and_OLD) = NULL;
  348. static struct ast_vm_mailbox_snapshot *(*ast_vm_mailbox_snapshot_destroy_func)(struct ast_vm_mailbox_snapshot *mailbox_snapshot) = NULL;
  349. static int (*ast_vm_msg_move_func)(const char *mailbox,
  350. const char *context,
  351. size_t num_msgs,
  352. const char *oldfolder,
  353. const char *old_msg_ids[],
  354. const char *newfolder) = NULL;
  355. static int (*ast_vm_msg_remove_func)(const char *mailbox,
  356. const char *context,
  357. size_t num_msgs,
  358. const char *folder,
  359. const char *msgs[]) = NULL;
  360. static int (*ast_vm_msg_forward_func)(const char *from_mailbox,
  361. const char *from_context,
  362. const char *from_folder,
  363. const char *to_mailbox,
  364. const char *to_context,
  365. const char *to_folder,
  366. size_t num_msgs,
  367. const char *msg_ids[],
  368. int delete_old) = NULL;
  369. static int (*ast_vm_msg_play_func)(struct ast_channel *chan,
  370. const char *mailbox,
  371. const char *context,
  372. const char *folder,
  373. const char *msg_num,
  374. ast_vm_msg_play_cb cb) = NULL;
  375. void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
  376. int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
  377. int (*inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs),
  378. int (*messagecount_func)(const char *context, const char *mailbox, const char *folder),
  379. int (*sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context),
  380. int (*copy_recording_to_vm_func)(struct ast_vm_recording_data *vm_rec_data),
  381. const char *vm_index_to_foldername_func(int id),
  382. struct ast_vm_mailbox_snapshot *(*vm_mailbox_snapshot_create_func)(const char *mailbox,
  383. const char *context,
  384. const char *folder,
  385. int descending,
  386. enum ast_vm_snapshot_sort_val sort_val,
  387. int combine_INBOX_and_OLD),
  388. struct ast_vm_mailbox_snapshot *(*vm_mailbox_snapshot_destroy_func)(struct ast_vm_mailbox_snapshot *mailbox_snapshot),
  389. int (*vm_msg_move_func)(const char *mailbox,
  390. const char *context,
  391. size_t num_msgs,
  392. const char *oldfolder,
  393. const char *old_msg_ids[],
  394. const char *newfolder),
  395. int (*vm_msg_remove_func)(const char *mailbox,
  396. const char *context,
  397. size_t num_msgs,
  398. const char *folder,
  399. const char *msgs[]),
  400. int (*vm_msg_forward_func)(const char *from_mailbox,
  401. const char *from_context,
  402. const char *from_folder,
  403. const char *to_mailbox,
  404. const char *to_context,
  405. const char *to_folder,
  406. size_t num_msgs,
  407. const char *msg_ids[],
  408. int delete_old),
  409. int (*vm_msg_play_func)(struct ast_channel *chan,
  410. const char *mailbox,
  411. const char *context,
  412. const char *folder,
  413. const char *msg_num,
  414. ast_vm_msg_play_cb cb))
  415. {
  416. ast_has_voicemail_func = has_voicemail_func;
  417. ast_inboxcount_func = inboxcount_func;
  418. ast_inboxcount2_func = inboxcount2_func;
  419. ast_messagecount_func = messagecount_func;
  420. ast_sayname_func = sayname_func;
  421. ast_copy_recording_to_vm_func = copy_recording_to_vm_func;
  422. ast_vm_index_to_foldername_func = vm_index_to_foldername_func;
  423. ast_vm_mailbox_snapshot_create_func = vm_mailbox_snapshot_create_func;
  424. ast_vm_mailbox_snapshot_destroy_func = vm_mailbox_snapshot_destroy_func;
  425. ast_vm_msg_move_func = vm_msg_move_func;
  426. ast_vm_msg_remove_func = vm_msg_remove_func;
  427. ast_vm_msg_forward_func = vm_msg_forward_func;
  428. ast_vm_msg_play_func = vm_msg_play_func;
  429. }
  430. void ast_uninstall_vm_functions(void)
  431. {
  432. ast_has_voicemail_func = NULL;
  433. ast_inboxcount_func = NULL;
  434. ast_inboxcount2_func = NULL;
  435. ast_messagecount_func = NULL;
  436. ast_sayname_func = NULL;
  437. ast_copy_recording_to_vm_func = NULL;
  438. ast_vm_index_to_foldername_func = NULL;
  439. ast_vm_mailbox_snapshot_create_func = NULL;
  440. ast_vm_mailbox_snapshot_destroy_func = NULL;
  441. ast_vm_msg_move_func = NULL;
  442. ast_vm_msg_remove_func = NULL;
  443. ast_vm_msg_forward_func = NULL;
  444. ast_vm_msg_play_func = NULL;
  445. }
  446. #ifdef TEST_FRAMEWORK
  447. int (*ast_vm_test_create_user_func)(const char *context, const char *mailbox) = NULL;
  448. int (*ast_vm_test_destroy_user_func)(const char *context, const char *mailbox) = NULL;
  449. void ast_install_vm_test_functions(int (*vm_test_create_user_func)(const char *context, const char *mailbox),
  450. int (*vm_test_destroy_user_func)(const char *context, const char *mailbox))
  451. {
  452. ast_vm_test_create_user_func = vm_test_create_user_func;
  453. ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
  454. }
  455. void ast_uninstall_vm_test_functions(void)
  456. {
  457. ast_vm_test_create_user_func = NULL;
  458. ast_vm_test_destroy_user_func = NULL;
  459. }
  460. #endif
  461. int ast_app_has_voicemail(const char *mailbox, const char *folder)
  462. {
  463. static int warned = 0;
  464. if (ast_has_voicemail_func) {
  465. return ast_has_voicemail_func(mailbox, folder);
  466. }
  467. if (warned++ % 10 == 0) {
  468. ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
  469. }
  470. return 0;
  471. }
  472. /*!
  473. * \internal
  474. * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
  475. * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
  476. * to figure out what the name of the recipient was supposed to be
  477. */
  478. int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
  479. {
  480. static int warned = 0;
  481. if (ast_copy_recording_to_vm_func) {
  482. return ast_copy_recording_to_vm_func(vm_rec_data);
  483. }
  484. if (warned++ % 10 == 0) {
  485. ast_verb(3, "copy recording to voicemail called to copy %s.%s to %s@%s, but voicemail not loaded.\n",
  486. vm_rec_data->recording_file, vm_rec_data->recording_ext,
  487. vm_rec_data->mailbox, vm_rec_data->context);
  488. }
  489. return -1;
  490. }
  491. int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
  492. {
  493. static int warned = 0;
  494. if (newmsgs) {
  495. *newmsgs = 0;
  496. }
  497. if (oldmsgs) {
  498. *oldmsgs = 0;
  499. }
  500. if (ast_inboxcount_func) {
  501. return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
  502. }
  503. if (warned++ % 10 == 0) {
  504. ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
  505. }
  506. return 0;
  507. }
  508. int ast_app_inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
  509. {
  510. static int warned = 0;
  511. if (newmsgs) {
  512. *newmsgs = 0;
  513. }
  514. if (oldmsgs) {
  515. *oldmsgs = 0;
  516. }
  517. if (urgentmsgs) {
  518. *urgentmsgs = 0;
  519. }
  520. if (ast_inboxcount2_func) {
  521. return ast_inboxcount2_func(mailbox, urgentmsgs, newmsgs, oldmsgs);
  522. }
  523. if (warned++ % 10 == 0) {
  524. ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
  525. }
  526. return 0;
  527. }
  528. int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
  529. {
  530. if (ast_sayname_func) {
  531. return ast_sayname_func(chan, mailbox, context);
  532. }
  533. return -1;
  534. }
  535. int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
  536. {
  537. static int warned = 0;
  538. if (ast_messagecount_func) {
  539. return ast_messagecount_func(context, mailbox, folder);
  540. }
  541. if (!warned) {
  542. warned++;
  543. ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
  544. }
  545. return 0;
  546. }
  547. const char *ast_vm_index_to_foldername(int id)
  548. {
  549. if (ast_vm_index_to_foldername_func) {
  550. return ast_vm_index_to_foldername_func(id);
  551. }
  552. return NULL;
  553. }
  554. struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
  555. const char *context,
  556. const char *folder,
  557. int descending,
  558. enum ast_vm_snapshot_sort_val sort_val,
  559. int combine_INBOX_and_OLD)
  560. {
  561. if (ast_vm_mailbox_snapshot_create_func) {
  562. return ast_vm_mailbox_snapshot_create_func(mailbox, context, folder, descending, sort_val, combine_INBOX_and_OLD);
  563. }
  564. return NULL;
  565. }
  566. struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
  567. {
  568. if (ast_vm_mailbox_snapshot_destroy_func) {
  569. return ast_vm_mailbox_snapshot_destroy_func(mailbox_snapshot);
  570. }
  571. return NULL;
  572. }
  573. int ast_vm_msg_move(const char *mailbox,
  574. const char *context,
  575. size_t num_msgs,
  576. const char *oldfolder,
  577. const char *old_msg_ids[],
  578. const char *newfolder)
  579. {
  580. if (ast_vm_msg_move_func) {
  581. return ast_vm_msg_move_func(mailbox, context, num_msgs, oldfolder, old_msg_ids, newfolder);
  582. }
  583. return 0;
  584. }
  585. int ast_vm_msg_remove(const char *mailbox,
  586. const char *context,
  587. size_t num_msgs,
  588. const char *folder,
  589. const char *msgs[])
  590. {
  591. if (ast_vm_msg_remove_func) {
  592. return ast_vm_msg_remove_func(mailbox, context, num_msgs, folder, msgs);
  593. }
  594. return 0;
  595. }
  596. int ast_vm_msg_forward(const char *from_mailbox,
  597. const char *from_context,
  598. const char *from_folder,
  599. const char *to_mailbox,
  600. const char *to_context,
  601. const char *to_folder,
  602. size_t num_msgs,
  603. const char *msg_ids[],
  604. int delete_old)
  605. {
  606. if (ast_vm_msg_forward_func) {
  607. return ast_vm_msg_forward_func(from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder, num_msgs, msg_ids, delete_old);
  608. }
  609. return 0;
  610. }
  611. int ast_vm_msg_play(struct ast_channel *chan,
  612. const char *mailbox,
  613. const char *context,
  614. const char *folder,
  615. const char *msg_num,
  616. ast_vm_msg_play_cb cb)
  617. {
  618. if (ast_vm_msg_play_func) {
  619. return ast_vm_msg_play_func(chan, mailbox, context, folder, msg_num, cb);
  620. }
  621. return 0;
  622. }
  623. #ifdef TEST_FRAMEWORK
  624. int ast_vm_test_create_user(const char *context, const char *mailbox)
  625. {
  626. if (ast_vm_test_create_user_func) {
  627. return ast_vm_test_create_user_func(context, mailbox);
  628. }
  629. return 0;
  630. }
  631. int ast_vm_test_destroy_user(const char *context, const char *mailbox)
  632. {
  633. if (ast_vm_test_destroy_user_func) {
  634. return ast_vm_test_destroy_user_func(context, mailbox);
  635. }
  636. return 0;
  637. }
  638. #endif
  639. int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
  640. {
  641. const char *ptr;
  642. int res = 0;
  643. struct ast_silence_generator *silgen = NULL;
  644. if (!between) {
  645. between = 100;
  646. }
  647. if (peer) {
  648. res = ast_autoservice_start(peer);
  649. }
  650. if (!res) {
  651. res = ast_waitfor(chan, 100);
  652. }
  653. /* ast_waitfor will return the number of remaining ms on success */
  654. if (res < 0) {
  655. if (peer) {
  656. ast_autoservice_stop(peer);
  657. }
  658. return res;
  659. }
  660. if (ast_opt_transmit_silence) {
  661. silgen = ast_channel_start_silence_generator(chan);
  662. }
  663. for (ptr = digits; *ptr; ptr++) {
  664. if (*ptr == 'w') {
  665. /* 'w' -- wait half a second */
  666. if ((res = ast_safe_sleep(chan, 500))) {
  667. break;
  668. }
  669. } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
  670. /* Character represents valid DTMF */
  671. if (*ptr == 'f' || *ptr == 'F') {
  672. /* ignore return values if not supported by channel */
  673. ast_indicate(chan, AST_CONTROL_FLASH);
  674. } else {
  675. ast_senddigit(chan, *ptr, duration);
  676. }
  677. /* pause between digits */
  678. if ((res = ast_safe_sleep(chan, between))) {
  679. break;
  680. }
  681. } else {
  682. ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
  683. }
  684. }
  685. if (peer) {
  686. /* Stop autoservice on the peer channel, but don't overwrite any error condition
  687. that has occurred previously while acting on the primary channel */
  688. if (ast_autoservice_stop(peer) && !res) {
  689. res = -1;
  690. }
  691. }
  692. if (silgen) {
  693. ast_channel_stop_silence_generator(chan, silgen);
  694. }
  695. return res;
  696. }
  697. struct linear_state {
  698. int fd;
  699. int autoclose;
  700. int allowoverride;
  701. struct ast_format origwfmt;
  702. };
  703. static void linear_release(struct ast_channel *chan, void *params)
  704. {
  705. struct linear_state *ls = params;
  706. if (ls->origwfmt.id && ast_set_write_format(chan, &ls->origwfmt)) {
  707. ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%u'\n", ast_channel_name(chan), ls->origwfmt.id);
  708. }
  709. if (ls->autoclose) {
  710. close(ls->fd);
  711. }
  712. ast_free(params);
  713. }
  714. static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
  715. {
  716. short buf[2048 + AST_FRIENDLY_OFFSET / 2];
  717. struct linear_state *ls = data;
  718. struct ast_frame f = {
  719. .frametype = AST_FRAME_VOICE,
  720. .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
  721. .offset = AST_FRIENDLY_OFFSET,
  722. };
  723. int res;
  724. ast_format_set(&f.subclass.format, AST_FORMAT_SLINEAR, 0);
  725. len = samples * 2;
  726. if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
  727. ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
  728. len = sizeof(buf) - AST_FRIENDLY_OFFSET;
  729. }
  730. res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
  731. if (res > 0) {
  732. f.datalen = res;
  733. f.samples = res / 2;
  734. ast_write(chan, &f);
  735. if (res == len) {
  736. return 0;
  737. }
  738. }
  739. return -1;
  740. }
  741. static void *linear_alloc(struct ast_channel *chan, void *params)
  742. {
  743. struct linear_state *ls = params;
  744. if (!params) {
  745. return NULL;
  746. }
  747. /* In this case, params is already malloc'd */
  748. if (ls->allowoverride) {
  749. ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
  750. } else {
  751. ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
  752. }
  753. ast_format_copy(&ls->origwfmt, ast_channel_writeformat(chan));
  754. if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR)) {
  755. ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
  756. ast_free(ls);
  757. ls = params = NULL;
  758. }
  759. return params;
  760. }
  761. static struct ast_generator linearstream =
  762. {
  763. .alloc = linear_alloc,
  764. .release = linear_release,
  765. .generate = linear_generator,
  766. };
  767. int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
  768. {
  769. struct linear_state *lin;
  770. char tmpf[256];
  771. int res = -1;
  772. int autoclose = 0;
  773. if (fd < 0) {
  774. if (ast_strlen_zero(filename)) {
  775. return -1;
  776. }
  777. autoclose = 1;
  778. if (filename[0] == '/') {
  779. ast_copy_string(tmpf, filename, sizeof(tmpf));
  780. } else {
  781. snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
  782. }
  783. if ((fd = open(tmpf, O_RDONLY)) < 0) {
  784. ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
  785. return -1;
  786. }
  787. }
  788. if ((lin = ast_calloc(1, sizeof(*lin)))) {
  789. lin->fd = fd;
  790. lin->allowoverride = allowoverride;
  791. lin->autoclose = autoclose;
  792. res = ast_activate_generator(chan, &linearstream, lin);
  793. }
  794. return res;
  795. }
  796. static int control_streamfile(struct ast_channel *chan,
  797. const char *file,
  798. const char *fwd,
  799. const char *rev,
  800. const char *stop,
  801. const char *suspend,
  802. const char *restart,
  803. int skipms,
  804. long *offsetms,
  805. ast_waitstream_fr_cb cb)
  806. {
  807. char *breaks = NULL;
  808. char *end = NULL;
  809. int blen = 2;
  810. int res;
  811. long pause_restart_point = 0;
  812. long offset = 0;
  813. if (!file) {
  814. return -1;
  815. }
  816. if (offsetms) {
  817. offset = *offsetms * 8; /* XXX Assumes 8kHz */
  818. }
  819. if (stop) {
  820. blen += strlen(stop);
  821. }
  822. if (suspend) {
  823. blen += strlen(suspend);
  824. }
  825. if (restart) {
  826. blen += strlen(restart);
  827. }
  828. if (blen > 2) {
  829. breaks = ast_alloca(blen + 1);
  830. breaks[0] = '\0';
  831. if (stop) {
  832. strcat(breaks, stop);
  833. }
  834. if (suspend) {
  835. strcat(breaks, suspend);
  836. }
  837. if (restart) {
  838. strcat(breaks, restart);
  839. }
  840. }
  841. if (ast_channel_state(chan) != AST_STATE_UP) {
  842. res = ast_answer(chan);
  843. }
  844. if ((end = strchr(file, ':'))) {
  845. if (!strcasecmp(end, ":end")) {
  846. *end = '\0';
  847. end++;
  848. }
  849. }
  850. for (;;) {
  851. ast_stopstream(chan);
  852. res = ast_streamfile(chan, file, ast_channel_language(chan));
  853. if (!res) {
  854. if (pause_restart_point) {
  855. ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
  856. pause_restart_point = 0;
  857. }
  858. else if (end || offset < 0) {
  859. if (offset == -8) {
  860. offset = 0;
  861. }
  862. ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
  863. ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
  864. end = NULL;
  865. offset = 0;
  866. } else if (offset) {
  867. ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
  868. ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
  869. offset = 0;
  870. }
  871. if (cb) {
  872. res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
  873. } else {
  874. res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
  875. }
  876. }
  877. if (res < 1) {
  878. break;
  879. }
  880. /* We go at next loop if we got the restart char */
  881. if (restart && strchr(restart, res)) {
  882. ast_debug(1, "we'll restart the stream here at next loop\n");
  883. pause_restart_point = 0;
  884. continue;
  885. }
  886. if (suspend && strchr(suspend, res)) {
  887. pause_restart_point = ast_tellstream(ast_channel_stream(chan));
  888. for (;;) {
  889. ast_stopstream(chan);
  890. if (!(res = ast_waitfordigit(chan, 1000))) {
  891. continue;
  892. } else if (res == -1 || strchr(suspend, res) || (stop && strchr(stop, res))) {
  893. break;
  894. }
  895. }
  896. if (res == *suspend) {
  897. res = 0;
  898. continue;
  899. }
  900. }
  901. if (res == -1) {
  902. break;
  903. }
  904. /* if we get one of our stop chars, return it to the calling function */
  905. if (stop && strchr(stop, res)) {
  906. break;
  907. }
  908. }
  909. if (pause_restart_point) {
  910. offset = pause_restart_point;
  911. } else {
  912. if (ast_channel_stream(chan)) {
  913. offset = ast_tellstream(ast_channel_stream(chan));
  914. } else {
  915. offset = -8; /* indicate end of file */
  916. }
  917. }
  918. if (offsetms) {
  919. *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
  920. }
  921. /* If we are returning a digit cast it as char */
  922. if (res > 0 || ast_channel_stream(chan)) {
  923. res = (char)res;
  924. }
  925. ast_stopstream(chan);
  926. return res;
  927. }
  928. int ast_control_streamfile_w_cb(struct ast_channel *chan,
  929. const char *file,
  930. const char *fwd,
  931. const char *rev,
  932. const char *stop,
  933. const char *suspend,
  934. const char *restart,
  935. int skipms,
  936. long *offsetms,
  937. ast_waitstream_fr_cb cb)
  938. {
  939. return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, cb);
  940. }
  941. int ast_control_streamfile(struct ast_channel *chan, const char *file,
  942. const char *fwd, const char *rev,
  943. const char *stop, const char *suspend,
  944. const char *restart, int skipms, long *offsetms)
  945. {
  946. return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL);
  947. }
  948. int ast_play_and_wait(struct ast_channel *chan, const char *fn)
  949. {
  950. int d = 0;
  951. if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
  952. return d;
  953. }
  954. d = ast_waitstream(chan, AST_DIGIT_ANY);
  955. ast_stopstream(chan);
  956. return d;
  957. }
  958. static int global_silence_threshold = 128;
  959. static int global_maxsilence = 0;
  960. /*! Optionally play a sound file or a beep, then record audio and video from the channel.
  961. * \param chan Channel to playback to/record from.
  962. * \param playfile Filename of sound to play before recording begins.
  963. * \param recordfile Filename to record to.
  964. * \param maxtime Maximum length of recording (in seconds).
  965. * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
  966. * \param duration Where to store actual length of the recorded message (in milliseconds).
  967. * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
  968. * \param beep Whether to play a beep before starting to record.
  969. * \param silencethreshold
  970. * \param maxsilence Length of silence that will end a recording (in milliseconds).
  971. * \param path Optional filesystem path to unlock.
  972. * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
  973. * \param acceptdtmf DTMF digits that will end the recording.
  974. * \param canceldtmf DTMF digits that will cancel the recording.
  975. * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
  976. *
  977. * \retval -1 failure or hangup
  978. * \retval 'S' Recording ended from silence timeout
  979. * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
  980. * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
  981. */
  982. static int __ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence, const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf, int skip_confirmation_sound)
  983. {
  984. int d = 0;
  985. char *fmts;
  986. char comment[256];
  987. int x, fmtcnt = 1, res = -1, outmsg = 0;
  988. struct ast_filestream *others[AST_MAX_FORMATS];
  989. char *sfmt[AST_MAX_FORMATS];
  990. char *stringp = NULL;
  991. time_t start, end;
  992. struct ast_dsp *sildet = NULL; /* silence detector dsp */
  993. int totalsilence = 0;
  994. int dspsilence = 0;
  995. int olddspsilence = 0;
  996. struct ast_format rfmt;
  997. struct ast_silence_generator *silgen = NULL;
  998. char prependfile[PATH_MAX];
  999. ast_format_clear(&rfmt);
  1000. if (silencethreshold < 0) {
  1001. silencethreshold = global_silence_threshold;
  1002. }
  1003. if (maxsilence < 0) {
  1004. maxsilence = global_maxsilence;
  1005. }
  1006. /* barf if no pointer passed to store duration in */
  1007. if (!duration) {
  1008. ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
  1009. return -1;
  1010. }
  1011. ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
  1012. snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
  1013. if (playfile || beep) {
  1014. if (!beep) {
  1015. d = ast_play_and_wait(chan, playfile);
  1016. }
  1017. if (d > -1) {
  1018. d = ast_stream_and_wait(chan, "beep", "");
  1019. }
  1020. if (d < 0) {
  1021. return -1;
  1022. }
  1023. }
  1024. if (prepend) {
  1025. ast_copy_string(prependfile, recordfile, sizeof(prependfile));
  1026. strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
  1027. }
  1028. fmts = ast_strdupa(fmt);
  1029. stringp = fmts;
  1030. strsep(&stringp, "|");
  1031. ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
  1032. sfmt[0] = ast_strdupa(fmts);
  1033. while ((fmt = strsep(&stringp, "|"))) {
  1034. if (fmtcnt > AST_MAX_FORMATS - 1) {
  1035. ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
  1036. break;
  1037. }
  1038. sfmt[fmtcnt++] = ast_strdupa(fmt);
  1039. }
  1040. end = start = time(NULL); /* pre-initialize end to be same as start in case we never get into loop */
  1041. for (x = 0; x < fmtcnt; x++) {
  1042. others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, AST_FILE_MODE);
  1043. ast_verb(3, "x=%d, open writing: %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
  1044. if (!others[x]) {
  1045. break;
  1046. }
  1047. }
  1048. if (path) {
  1049. ast_unlock_path(path);
  1050. }
  1051. if (maxsilence > 0) {
  1052. sildet = ast_dsp_new(); /* Create the silence detector */
  1053. if (!sildet) {
  1054. ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
  1055. return -1;
  1056. }
  1057. ast_dsp_set_threshold(sildet, silencethreshold);
  1058. ast_format_copy(&rfmt, ast_channel_readformat(chan));
  1059. res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
  1060. if (res < 0) {
  1061. ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
  1062. ast_dsp_free(sildet);
  1063. return -1;
  1064. }
  1065. }
  1066. if (!prepend) {
  1067. /* Request a video update */
  1068. ast_indicate(chan, AST_CONTROL_VIDUPDATE);
  1069. if (ast_opt_transmit_silence) {
  1070. silgen = ast_channel_start_silence_generator(chan);
  1071. }
  1072. }
  1073. if (x == fmtcnt) {
  1074. /* Loop forever, writing the packets we read to the writer(s), until
  1075. we read a digit or get a hangup */
  1076. struct ast_frame *f;
  1077. for (;;) {
  1078. if (!(res = ast_waitfor(chan, 2000))) {
  1079. ast_debug(1, "One waitfor failed, trying another\n");
  1080. /* Try one more time in case of masq */
  1081. if (!(res = ast_waitfor(chan, 2000))) {
  1082. ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
  1083. res = -1;
  1084. }
  1085. }
  1086. if (res < 0) {
  1087. f = NULL;
  1088. break;
  1089. }
  1090. if (!(f = ast_read(chan))) {
  1091. break;
  1092. }
  1093. if (f->frametype == AST_FRAME_VOICE) {
  1094. /* write each format */
  1095. for (x = 0; x < fmtcnt; x++) {
  1096. if (prepend && !others[x]) {
  1097. break;
  1098. }
  1099. res = ast_writestream(others[x], f);
  1100. }
  1101. /* Silence Detection */
  1102. if (maxsilence > 0) {
  1103. dspsilence = 0;
  1104. ast_dsp_silence(sildet, f, &dspsilence);
  1105. if (olddspsilence > dspsilence) {
  1106. totalsilence += olddspsilence;
  1107. }
  1108. olddspsilence = dspsilence;
  1109. if (dspsilence > maxsilence) {
  1110. /* Ended happily with silence */
  1111. ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
  1112. res = 'S';
  1113. outmsg = 2;
  1114. break;
  1115. }
  1116. }
  1117. /* Exit on any error */
  1118. if (res) {
  1119. ast_log(LOG_WARNING, "Error writing frame\n");
  1120. break;
  1121. }
  1122. } else if (f->frametype == AST_FRAME_VIDEO) {
  1123. /* Write only once */
  1124. ast_writestream(others[0], f);
  1125. } else if (f->frametype == AST_FRAME_DTMF) {
  1126. if (prepend) {
  1127. /* stop recording with any digit */
  1128. ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
  1129. res = 't';
  1130. outmsg = 2;
  1131. break;
  1132. }
  1133. if (strchr(acceptdtmf, f->subclass.integer)) {
  1134. ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
  1135. res = f->subclass.integer;
  1136. outmsg = 2;
  1137. break;
  1138. }
  1139. if (strchr(canceldtmf, f->subclass.integer)) {
  1140. ast_verb(3, "User cancelled message by pressing %c\n", f->subclass.integer);
  1141. res = f->subclass.integer;
  1142. outmsg = 0;
  1143. break;
  1144. }
  1145. }
  1146. if (maxtime) {
  1147. end = time(NULL);
  1148. if (maxtime < (end - start)) {
  1149. ast_verb(3, "Took too long, cutting it short...\n");
  1150. res = 't';
  1151. outmsg = 2;
  1152. break;
  1153. }
  1154. }
  1155. ast_frfree(f);
  1156. }
  1157. if (!f) {
  1158. ast_verb(3, "User hung up\n");
  1159. res = -1;
  1160. outmsg = 1;
  1161. } else {
  1162. ast_frfree(f);
  1163. }
  1164. } else {
  1165. ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
  1166. }
  1167. if (!prepend) {
  1168. if (silgen) {
  1169. ast_channel_stop_silence_generator(chan, silgen);
  1170. }
  1171. }
  1172. /*!\note
  1173. * Instead of asking how much time passed (end - start), calculate the number
  1174. * of seconds of audio which actually went into the file. This fixes a
  1175. * problem where audio is stopped up on the network and never gets to us.
  1176. *
  1177. * Note that we still want to use the number of seconds passed for the max
  1178. * message, otherwise we could get a situation where this stream is never
  1179. * closed (which would create a resource leak).
  1180. */
  1181. *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
  1182. if (sound_duration) {
  1183. *sound_duration = *duration;
  1184. }
  1185. if (!prepend) {
  1186. /* Reduce duration by a total silence amount */
  1187. if (olddspsilence <= dspsilence) {
  1188. totalsilence += dspsilence;
  1189. }
  1190. if (sound_duration) {
  1191. if (totalsilence > 0) {
  1192. *sound_duration -= (totalsilence - 200) / 1000;
  1193. }
  1194. if (*sound_duration < 0) {
  1195. *sound_duration = 0;
  1196. }
  1197. }
  1198. if (dspsilence > 0) {
  1199. *duration -= (dspsilence - 200) / 1000;
  1200. }
  1201. if (*duration < 0) {
  1202. *duration = 0;
  1203. }
  1204. for (x = 0; x < fmtcnt; x++) {
  1205. if (!others[x]) {
  1206. break;
  1207. }
  1208. /*!\note
  1209. * If we ended with silence, trim all but the first 200ms of silence
  1210. * off the recording. However, if we ended with '#', we don't want
  1211. * to trim ANY part of the recording.
  1212. */
  1213. if (res > 0 && dspsilence) {
  1214. /* rewind only the trailing silence */
  1215. ast_stream_rewind(others[x], dspsilence - 200);
  1216. }
  1217. ast_truncstream(others[x]);
  1218. ast_closestream(others[x]);
  1219. }
  1220. } else if (prepend && outmsg) {
  1221. struct ast_filestream *realfiles[AST_MAX_FORMATS];
  1222. struct ast_frame *fr;
  1223. for (x = 0; x < fmtcnt; x++) {
  1224. snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
  1225. realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
  1226. if (!others[x]) {
  1227. break;
  1228. }
  1229. if (!realfiles[x]) {
  1230. ast_closestream(others[x]);
  1231. continue;
  1232. }
  1233. /*!\note Same logic as above. */
  1234. if (dspsilence) {
  1235. ast_stream_rewind(others[x], dspsilence - 200);
  1236. }
  1237. ast_truncstream(others[x]);
  1238. /* add the original file too */
  1239. while ((fr = ast_readframe(realfiles[x]))) {
  1240. ast_writestream(others[x], fr);
  1241. ast_frfree(fr);
  1242. }
  1243. ast_closestream(others[x]);
  1244. ast_closestream(realfiles[x]);
  1245. ast_filerename(prependfile, recordfile, sfmt[x]);
  1246. ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
  1247. ast_filedelete(prependfile, sfmt[x]);
  1248. }
  1249. } else {
  1250. for (x = 0; x < fmtcnt; x++) {
  1251. if (!others[x]) {
  1252. break;
  1253. }
  1254. ast_closestream(others[x]);
  1255. }
  1256. }
  1257. if (rfmt.id && ast_set_read_format(chan, &rfmt)) {
  1258. ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(&rfmt), ast_channel_name(chan));
  1259. }
  1260. if ((outmsg == 2) && (!skip_confirmation_sound)) {
  1261. ast_stream_and_wait(chan, "auth-thankyou", "");
  1262. }
  1263. if (sildet) {
  1264. ast_dsp_free(sildet);
  1265. }
  1266. return res;
  1267. }
  1268. static const char default_acceptdtmf[] = "#";
  1269. static const char default_canceldtmf[] = "";
  1270. 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 silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf)
  1271. {
  1272. return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, default_acceptdtmf), S_OR(canceldtmf, default_canceldtmf), 0);
  1273. }
  1274. 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)
  1275. {
  1276. return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf, 0);
  1277. }
  1278. 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)
  1279. {
  1280. return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf, 1);
  1281. }
  1282. /* Channel group core functions */
  1283. int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
  1284. {
  1285. int res = 0;
  1286. char tmp[256];
  1287. char *grp = NULL, *cat = NULL;
  1288. if (!ast_strlen_zero(data)) {
  1289. ast_copy_string(tmp, data, sizeof(tmp));
  1290. grp = tmp;
  1291. if ((cat = strchr(tmp, '@'))) {
  1292. *cat++ = '\0';
  1293. }
  1294. }
  1295. if (!ast_strlen_zero(grp)) {
  1296. ast_copy_string(group, grp, group_max);
  1297. } else {
  1298. *group = '\0';
  1299. }
  1300. if (!ast_strlen_zero(cat)) {
  1301. ast_copy_string(category, cat, category_max);
  1302. }
  1303. return res;
  1304. }
  1305. int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
  1306. {
  1307. int res = 0;
  1308. char group[80] = "", category[80] = "";
  1309. struct ast_group_info *gi = NULL;
  1310. size_t len = 0;
  1311. if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
  1312. return -1;
  1313. }
  1314. /* Calculate memory we will need if this is new */
  1315. len = sizeof(*gi) + strlen(group) + 1;
  1316. if (!ast_strlen_zero(category)) {
  1317. len += strlen(category) + 1;
  1318. }
  1319. AST_RWLIST_WRLOCK(&groups);
  1320. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1321. if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
  1322. AST_RWLIST_REMOVE_CURRENT(group_list);
  1323. free(gi);
  1324. break;
  1325. }
  1326. }
  1327. AST_RWLIST_TRAVERSE_SAFE_END;
  1328. if (ast_strlen_zero(group)) {
  1329. /* Enable unsetting the group */
  1330. } else if ((gi = calloc(1, len))) {
  1331. gi->chan = chan;
  1332. gi->group = (char *) gi + sizeof(*gi);
  1333. strcpy(gi->group, group);
  1334. if (!ast_strlen_zero(category)) {
  1335. gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
  1336. strcpy(gi->category, category);
  1337. }
  1338. AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
  1339. } else {
  1340. res = -1;
  1341. }
  1342. AST_RWLIST_UNLOCK(&groups);
  1343. return res;
  1344. }
  1345. int ast_app_group_get_count(const char *group, const char *category)
  1346. {
  1347. struct ast_group_info *gi = NULL;
  1348. int count = 0;
  1349. if (ast_strlen_zero(group)) {
  1350. return 0;
  1351. }
  1352. AST_RWLIST_RDLOCK(&groups);
  1353. AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
  1354. if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
  1355. count++;
  1356. }
  1357. }
  1358. AST_RWLIST_UNLOCK(&groups);
  1359. return count;
  1360. }
  1361. int ast_app_group_match_get_count(const char *groupmatch, const char *category)
  1362. {
  1363. struct ast_group_info *gi = NULL;
  1364. regex_t regexbuf_group;
  1365. regex_t regexbuf_category;
  1366. int count = 0;
  1367. if (ast_strlen_zero(groupmatch)) {
  1368. ast_log(LOG_NOTICE, "groupmatch empty\n");
  1369. return 0;
  1370. }
  1371. /* if regex compilation fails, return zero matches */
  1372. if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
  1373. ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
  1374. return 0;
  1375. }
  1376. if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
  1377. ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
  1378. regfree(&regexbuf_group);
  1379. return 0;
  1380. }
  1381. AST_RWLIST_RDLOCK(&groups);
  1382. AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
  1383. 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)))) {
  1384. count++;
  1385. }
  1386. }
  1387. AST_RWLIST_UNLOCK(&groups);
  1388. regfree(&regexbuf_group);
  1389. if (!ast_strlen_zero(category)) {
  1390. regfree(&regexbuf_category);
  1391. }
  1392. return count;
  1393. }
  1394. int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
  1395. {
  1396. struct ast_group_info *gi = NULL;
  1397. AST_RWLIST_WRLOCK(&groups);
  1398. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1399. if (gi->chan == old) {
  1400. gi->chan = new;
  1401. } else if (gi->chan == new) {
  1402. AST_RWLIST_REMOVE_CURRENT(group_list);
  1403. ast_free(gi);
  1404. }
  1405. }
  1406. AST_RWLIST_TRAVERSE_SAFE_END;
  1407. AST_RWLIST_UNLOCK(&groups);
  1408. return 0;
  1409. }
  1410. int ast_app_group_discard(struct ast_channel *chan)
  1411. {
  1412. struct ast_group_info *gi = NULL;
  1413. AST_RWLIST_WRLOCK(&groups);
  1414. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
  1415. if (gi->chan == chan) {
  1416. AST_RWLIST_REMOVE_CURRENT(group_list);
  1417. ast_free(gi);
  1418. }
  1419. }
  1420. AST_RWLIST_TRAVERSE_SAFE_END;
  1421. AST_RWLIST_UNLOCK(&groups);
  1422. return 0;
  1423. }
  1424. int ast_app_group_list_wrlock(void)
  1425. {
  1426. return AST_RWLIST_WRLOCK(&groups);
  1427. }
  1428. int ast_app_group_list_rdlock(void)
  1429. {
  1430. return AST_RWLIST_RDLOCK(&groups);
  1431. }
  1432. struct ast_group_info *ast_app_group_list_head(void)
  1433. {
  1434. return AST_RWLIST_FIRST(&groups);
  1435. }
  1436. int ast_app_group_list_unlock(void)
  1437. {
  1438. return AST_RWLIST_UNLOCK(&groups);
  1439. }
  1440. #undef ast_app_separate_args
  1441. unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
  1442. unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
  1443. {
  1444. int argc;
  1445. char *scan, *wasdelim = NULL;
  1446. int paren = 0, quote = 0, bracket = 0;
  1447. if (!array || !arraylen) {
  1448. return 0;
  1449. }
  1450. memset(array, 0, arraylen * sizeof(*array));
  1451. if (!buf) {
  1452. return 0;
  1453. }
  1454. scan = buf;
  1455. for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
  1456. array[argc] = scan;
  1457. for (; *scan; scan++) {
  1458. if (*scan == '(') {
  1459. paren++;
  1460. } else if (*scan == ')') {
  1461. if (paren) {
  1462. paren--;
  1463. }
  1464. } else if (*scan == '[') {
  1465. bracket++;
  1466. } else if (*scan == ']') {
  1467. if (bracket) {
  1468. bracket--;
  1469. }
  1470. } else if (*scan == '"' && delim != '"') {
  1471. quote = quote ? 0 : 1;
  1472. if (remove_chars) {
  1473. /* Remove quote character from argument */
  1474. memmove(scan, scan + 1, strlen(scan));
  1475. scan--;
  1476. }
  1477. } else if (*scan == '\\') {
  1478. if (remove_chars) {
  1479. /* Literal character, don't parse */
  1480. memmove(scan, scan + 1, strlen(scan));
  1481. } else {
  1482. scan++;
  1483. }
  1484. } else if ((*scan == delim) && !paren && !quote && !bracket) {
  1485. wasdelim = scan;
  1486. *scan++ = '\0';
  1487. break;
  1488. }
  1489. }
  1490. }
  1491. /* If the last character in the original string was the delimiter, then
  1492. * there is one additional argument. */
  1493. if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
  1494. array[argc++] = scan;
  1495. }
  1496. return argc;
  1497. }
  1498. /* ABI compatible function */
  1499. unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
  1500. {
  1501. return __ast_app_separate_args(buf, delim, 1, array, arraylen);
  1502. }
  1503. static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
  1504. {
  1505. char *s;
  1506. char *fs;
  1507. int res;
  1508. int fd;
  1509. int lp = strlen(path);
  1510. time_t start;
  1511. s = ast_alloca(lp + 10);
  1512. fs = ast_alloca(lp + 20);
  1513. snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, (unsigned long)ast_random());
  1514. fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
  1515. if (fd < 0) {
  1516. ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
  1517. return AST_LOCK_PATH_NOT_FOUND;
  1518. }
  1519. close(fd);
  1520. snprintf(s, strlen(path) + 9, "%s/.lock", path);
  1521. start = time(NULL);
  1522. while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
  1523. sched_yield();
  1524. }
  1525. unlink(fs);
  1526. if (res) {
  1527. ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
  1528. return AST_LOCK_TIMEOUT;
  1529. } else {
  1530. ast_debug(1, "Locked path '%s'\n", path);
  1531. return AST_LOCK_SUCCESS;
  1532. }
  1533. }
  1534. static int ast_unlock_path_lockfile(const char *path)
  1535. {
  1536. char *s;
  1537. int res;
  1538. s = ast_alloca(strlen(path) + 10);
  1539. snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
  1540. if ((res = unlink(s))) {
  1541. ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
  1542. } else {
  1543. ast_debug(1, "Unlocked path '%s'\n", path);
  1544. }
  1545. return res;
  1546. }
  1547. struct path_lock {
  1548. AST_LIST_ENTRY(path_lock) le;
  1549. int fd;
  1550. char *path;
  1551. };
  1552. static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
  1553. static void path_lock_destroy(struct path_lock *obj)
  1554. {
  1555. if (obj->fd >= 0) {
  1556. close(obj->fd);
  1557. }
  1558. if (obj->path) {
  1559. free(obj->path);
  1560. }
  1561. free(obj);
  1562. }
  1563. static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
  1564. {
  1565. char *fs;
  1566. int res;
  1567. int fd;
  1568. time_t start;
  1569. struct path_lock *pl;
  1570. struct stat st, ost;
  1571. fs = ast_alloca(strlen(path) + 20);
  1572. snprintf(fs, strlen(path) + 19, "%s/lock", path);
  1573. if (lstat(fs, &st) == 0) {
  1574. if ((st.st_mode & S_IFMT) == S_IFLNK) {
  1575. ast_log(LOG_WARNING, "Unable to create lock file "
  1576. "'%s': it's already a symbolic link\n",
  1577. fs);
  1578. return AST_LOCK_FAILURE;
  1579. }
  1580. if (st.st_nlink > 1) {
  1581. ast_log(LOG_WARNING, "Unable to create lock file "
  1582. "'%s': %u hard links exist\n",
  1583. fs, (unsigned int) st.st_nlink);
  1584. return AST_LOCK_FAILURE;
  1585. }
  1586. }
  1587. if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
  1588. ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
  1589. fs, strerror(errno));
  1590. return AST_LOCK_PATH_NOT_FOUND;
  1591. }
  1592. if (!(pl = ast_calloc(1, sizeof(*pl)))) {
  1593. /* We don't unlink the lock file here, on the possibility that
  1594. * someone else created it - better to leave a little mess
  1595. * than create a big one by destroying someone else's lock
  1596. * and causing something to be corrupted.
  1597. */
  1598. close(fd);
  1599. return AST_LOCK_FAILURE;
  1600. }
  1601. pl->fd = fd;
  1602. pl->path = strdup(path);
  1603. time(&start);
  1604. while (
  1605. #ifdef SOLARIS
  1606. ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
  1607. #else
  1608. ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
  1609. #endif
  1610. (errno == EWOULDBLOCK) &&
  1611. (time(NULL) - start < 5))
  1612. usleep(1000);
  1613. if (res) {
  1614. ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
  1615. path, strerror(errno));
  1616. /* No unlinking of lock done, since we tried and failed to
  1617. * flock() it.
  1618. */
  1619. path_lock_destroy(pl);
  1620. return AST_LOCK_TIMEOUT;
  1621. }
  1622. /* Check for the race where the file is recreated or deleted out from
  1623. * underneath us.
  1624. */
  1625. if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
  1626. st.st_dev != ost.st_dev &&
  1627. st.st_ino != ost.st_ino) {
  1628. ast_log(LOG_WARNING, "Unable to create lock file '%s': "
  1629. "file changed underneath us\n", fs);
  1630. path_lock_destroy(pl);
  1631. return AST_LOCK_FAILURE;
  1632. }
  1633. /* Success: file created, flocked, and is the one we started with */
  1634. AST_LIST_LOCK(&path_lock_list);
  1635. AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
  1636. AST_LIST_UNLOCK(&path_lock_list);
  1637. ast_debug(1, "Locked path '%s'\n", path);
  1638. return AST_LOCK_SUCCESS;
  1639. }
  1640. static int ast_unlock_path_flock(const char *path)
  1641. {
  1642. char *s;
  1643. struct path_lock *p;
  1644. s = ast_alloca(strlen(path) + 20);
  1645. AST_LIST_LOCK(&path_lock_list);
  1646. AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
  1647. if (!strcmp(p->path, path)) {
  1648. AST_LIST_REMOVE_CURRENT(le);
  1649. break;
  1650. }
  1651. }
  1652. AST_LIST_TRAVERSE_SAFE_END;
  1653. AST_LIST_UNLOCK(&path_lock_list);
  1654. if (p) {
  1655. snprintf(s, strlen(path) + 19, "%s/lock", path);
  1656. unlink(s);
  1657. path_lock_destroy(p);
  1658. ast_debug(1, "Unlocked path '%s'\n", path);
  1659. } else {
  1660. ast_debug(1, "Failed to unlock path '%s': "
  1661. "lock not found\n", path);
  1662. }
  1663. return 0;
  1664. }
  1665. void ast_set_lock_type(enum AST_LOCK_TYPE type)
  1666. {
  1667. ast_lock_type = type;
  1668. }
  1669. enum AST_LOCK_RESULT ast_lock_path(const char *path)
  1670. {
  1671. enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
  1672. switch (ast_lock_type) {
  1673. case AST_LOCK_TYPE_LOCKFILE:
  1674. r = ast_lock_path_lockfile(path);
  1675. break;
  1676. case AST_LOCK_TYPE_FLOCK:
  1677. r = ast_lock_path_flock(path);
  1678. break;
  1679. }
  1680. return r;
  1681. }
  1682. int ast_unlock_path(const char *path)
  1683. {
  1684. int r = 0;
  1685. switch (ast_lock_type) {
  1686. case AST_LOCK_TYPE_LOCKFILE:
  1687. r = ast_unlock_path_lockfile(path);
  1688. break;
  1689. case AST_LOCK_TYPE_FLOCK:
  1690. r = ast_unlock_path_flock(path);
  1691. break;
  1692. }
  1693. return r;
  1694. }
  1695. int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
  1696. {
  1697. int silencethreshold;
  1698. int maxsilence = 0;
  1699. int res = 0;
  1700. int cmd = 0;
  1701. int max_attempts = 3;
  1702. int attempts = 0;
  1703. int recorded = 0;
  1704. int message_exists = 0;
  1705. /* Note that urgent and private are for flagging messages as such in the future */
  1706. /* barf if no pointer passed to store duration in */
  1707. if (!duration) {
  1708. ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
  1709. return -1;
  1710. }
  1711. cmd = '3'; /* Want to start by recording */
  1712. silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
  1713. while ((cmd >= 0) && (cmd != 't')) {
  1714. switch (cmd) {
  1715. case '1':
  1716. if (!message_exists) {
  1717. /* In this case, 1 is to record a message */
  1718. cmd = '3';
  1719. break;
  1720. } else {
  1721. ast_stream_and_wait(chan, "vm-msgsaved", "");
  1722. cmd = 't';
  1723. return res;
  1724. }
  1725. case '2':
  1726. /* Review */
  1727. ast_verb(3, "Reviewing the recording\n");
  1728. cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
  1729. break;
  1730. case '3':
  1731. message_exists = 0;
  1732. /* Record */
  1733. ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
  1734. recorded = 1;
  1735. if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
  1736. /* User has hung up, no options to give */
  1737. return cmd;
  1738. }
  1739. if (cmd == '0') {
  1740. break;
  1741. } else if (cmd == '*') {
  1742. break;
  1743. } else {
  1744. /* If all is well, a message exists */
  1745. message_exists = 1;
  1746. cmd = 0;
  1747. }
  1748. break;
  1749. case '4':
  1750. case '5':
  1751. case '6':
  1752. case '7':
  1753. case '8':
  1754. case '9':
  1755. case '*':
  1756. case '#':
  1757. cmd = ast_play_and_wait(chan, "vm-sorry");
  1758. break;
  1759. default:
  1760. if (message_exists) {
  1761. cmd = ast_play_and_wait(chan, "vm-review");
  1762. } else {
  1763. if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
  1764. cmd = ast_waitfordigit(chan, 600);
  1765. }
  1766. }
  1767. if (!cmd) {
  1768. cmd = ast_waitfordigit(chan, 6000);
  1769. }
  1770. if (!cmd) {
  1771. attempts++;
  1772. }
  1773. if (attempts > max_attempts) {
  1774. cmd = 't';
  1775. }
  1776. }
  1777. }
  1778. if (cmd == 't') {
  1779. cmd = 0;
  1780. }
  1781. return cmd;
  1782. }
  1783. #define RES_UPONE (1 << 16)
  1784. #define RES_EXIT (1 << 17)
  1785. #define RES_REPEAT (1 << 18)
  1786. #define RES_RESTART ((1 << 19) | RES_REPEAT)
  1787. static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
  1788. static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
  1789. {
  1790. int res;
  1791. int (*ivr_func)(struct ast_channel *, void *);
  1792. char *c;
  1793. char *n;
  1794. switch (option->action) {
  1795. case AST_ACTION_UPONE:
  1796. return RES_UPONE;
  1797. case AST_ACTION_EXIT:
  1798. return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
  1799. case AST_ACTION_REPEAT:
  1800. return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
  1801. case AST_ACTION_RESTART:
  1802. return RES_RESTART ;
  1803. case AST_ACTION_NOOP:
  1804. return 0;
  1805. case AST_ACTION_BACKGROUND:
  1806. res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
  1807. if (res < 0) {
  1808. ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
  1809. res = 0;
  1810. }
  1811. return res;
  1812. case AST_ACTION_PLAYBACK:
  1813. res = ast_stream_and_wait(chan, (char *)option->adata, "");
  1814. if (res < 0) {
  1815. ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
  1816. res = 0;
  1817. }
  1818. return res;
  1819. case AST_ACTION_MENU:
  1820. if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
  1821. /* Do not pass entry errors back up, treat as though it was an "UPONE" */
  1822. res = 0;
  1823. }
  1824. return res;
  1825. case AST_ACTION_WAITOPTION:
  1826. if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
  1827. return 't';
  1828. }
  1829. return res;
  1830. case AST_ACTION_CALLBACK:
  1831. ivr_func = option->adata;
  1832. res = ivr_func(chan, cbdata);
  1833. return res;
  1834. case AST_ACTION_TRANSFER:
  1835. res = ast_parseable_goto(chan, option->adata);
  1836. return 0;
  1837. case AST_ACTION_PLAYLIST:
  1838. case AST_ACTION_BACKLIST:
  1839. res = 0;
  1840. c = ast_strdupa(option->adata);
  1841. while ((n = strsep(&c, ";"))) {
  1842. if ((res = ast_stream_and_wait(chan, n,
  1843. (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
  1844. break;
  1845. }
  1846. }
  1847. ast_stopstream(chan);
  1848. return res;
  1849. default:
  1850. ast_log(LOG_NOTICE, "Unknown dispatch function %u, ignoring!\n", option->action);
  1851. return 0;
  1852. }
  1853. return -1;
  1854. }
  1855. static int option_exists(struct ast_ivr_menu *menu, char *option)
  1856. {
  1857. int x;
  1858. for (x = 0; menu->options[x].option; x++) {
  1859. if (!strcasecmp(menu->options[x].option, option)) {
  1860. return x;
  1861. }
  1862. }
  1863. return -1;
  1864. }
  1865. static int option_matchmore(struct ast_ivr_menu *menu, char *option)
  1866. {
  1867. int x;
  1868. for (x = 0; menu->options[x].option; x++) {
  1869. if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
  1870. (menu->options[x].option[strlen(option)])) {
  1871. return x;
  1872. }
  1873. }
  1874. return -1;
  1875. }
  1876. static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
  1877. {
  1878. int res = 0;
  1879. int ms;
  1880. while (option_matchmore(menu, exten)) {
  1881. ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
  1882. if (strlen(exten) >= maxexten - 1) {
  1883. break;
  1884. }
  1885. if ((res = ast_waitfordigit(chan, ms)) < 1) {
  1886. break;
  1887. }
  1888. exten[strlen(exten) + 1] = '\0';
  1889. exten[strlen(exten)] = res;
  1890. }
  1891. return res > 0 ? 0 : res;
  1892. }
  1893. static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
  1894. {
  1895. /* Execute an IVR menu structure */
  1896. int res = 0;
  1897. int pos = 0;
  1898. int retries = 0;
  1899. char exten[AST_MAX_EXTENSION] = "s";
  1900. if (option_exists(menu, "s") < 0) {
  1901. strcpy(exten, "g");
  1902. if (option_exists(menu, "g") < 0) {
  1903. ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
  1904. return -1;
  1905. }
  1906. }
  1907. while (!res) {
  1908. while (menu->options[pos].option) {
  1909. if (!strcasecmp(menu->options[pos].option, exten)) {
  1910. res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
  1911. ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
  1912. if (res < 0) {
  1913. break;
  1914. } else if (res & RES_UPONE) {
  1915. return 0;
  1916. } else if (res & RES_EXIT) {
  1917. return res;
  1918. } else if (res & RES_REPEAT) {
  1919. int maxretries = res & 0xffff;
  1920. if ((res & RES_RESTART) == RES_RESTART) {
  1921. retries = 0;
  1922. } else {
  1923. retries++;
  1924. }
  1925. if (!maxretries) {
  1926. maxretries = 3;
  1927. }
  1928. if ((maxretries > 0) && (retries >= maxretries)) {
  1929. ast_debug(1, "Max retries %d exceeded\n", maxretries);
  1930. return -2;
  1931. } else {
  1932. if (option_exists(menu, "g") > -1) {
  1933. strcpy(exten, "g");
  1934. } else if (option_exists(menu, "s") > -1) {
  1935. strcpy(exten, "s");
  1936. }
  1937. }
  1938. pos = 0;
  1939. continue;
  1940. } else if (res && strchr(AST_DIGIT_ANY, res)) {
  1941. ast_debug(1, "Got start of extension, %c\n", res);
  1942. exten[1] = '\0';
  1943. exten[0] = res;
  1944. if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
  1945. break;
  1946. }
  1947. if (option_exists(menu, exten) < 0) {
  1948. if (option_exists(menu, "i")) {
  1949. ast_debug(1, "Invalid extension entered, going to 'i'!\n");
  1950. strcpy(exten, "i");
  1951. pos = 0;
  1952. continue;
  1953. } else {
  1954. ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
  1955. res = -2;
  1956. break;
  1957. }
  1958. } else {
  1959. ast_debug(1, "New existing extension: %s\n", exten);
  1960. pos = 0;
  1961. continue;
  1962. }
  1963. }
  1964. }
  1965. pos++;
  1966. }
  1967. ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
  1968. pos = 0;
  1969. if (!strcasecmp(exten, "s")) {
  1970. strcpy(exten, "g");
  1971. } else {
  1972. break;
  1973. }
  1974. }
  1975. return res;
  1976. }
  1977. int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
  1978. {
  1979. int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
  1980. /* Hide internal coding */
  1981. return res > 0 ? 0 : res;
  1982. }
  1983. char *ast_read_textfile(const char *filename)
  1984. {
  1985. int fd, count = 0, res;
  1986. char *output = NULL;
  1987. struct stat filesize;
  1988. if (stat(filename, &filesize) == -1) {
  1989. ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
  1990. return NULL;
  1991. }
  1992. count = filesize.st_size + 1;
  1993. if ((fd = open(filename, O_RDONLY)) < 0) {
  1994. ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
  1995. return NULL;
  1996. }
  1997. if ((output = ast_malloc(count))) {
  1998. res = read(fd, output, count - 1);
  1999. if (res == count - 1) {
  2000. output[res] = '\0';
  2001. } else {
  2002. ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
  2003. ast_free(output);
  2004. output = NULL;
  2005. }
  2006. }
  2007. close(fd);
  2008. return output;
  2009. }
  2010. static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
  2011. {
  2012. char *s, *arg;
  2013. int curarg, res = 0;
  2014. unsigned int argloc;
  2015. struct ast_flags *flags = _flags;
  2016. struct ast_flags64 *flags64 = _flags;
  2017. if (flaglen == 32) {
  2018. ast_clear_flag(flags, AST_FLAGS_ALL);
  2019. } else {
  2020. flags64->flags = 0;
  2021. }
  2022. if (!optstr) {
  2023. return 0;
  2024. }
  2025. s = optstr;
  2026. while (*s) {
  2027. curarg = *s++ & 0x7f; /* the array (in app.h) has 128 entries */
  2028. argloc = options[curarg].arg_index;
  2029. if (*s == '(') {
  2030. int paren = 1, quote = 0;
  2031. int parsequotes = (s[1] == '"') ? 1 : 0;
  2032. /* Has argument */
  2033. arg = ++s;
  2034. for (; *s; s++) {
  2035. if (*s == '(' && !quote) {
  2036. paren++;
  2037. } else if (*s == ')' && !quote) {
  2038. /* Count parentheses, unless they're within quotes (or backslashed, below) */
  2039. paren--;
  2040. } else if (*s == '"' && parsequotes) {
  2041. /* Leave embedded quotes alone, unless they are the first character */
  2042. quote = quote ? 0 : 1;
  2043. ast_copy_string(s, s + 1, INT_MAX);
  2044. s--;
  2045. } else if (*s == '\\') {
  2046. if (!quote) {
  2047. /* If a backslash is found outside of quotes, remove it */
  2048. ast_copy_string(s, s + 1, INT_MAX);
  2049. } else if (quote && s[1] == '"') {
  2050. /* Backslash for a quote character within quotes, remove the backslash */
  2051. ast_copy_string(s, s + 1, INT_MAX);
  2052. } else {
  2053. /* Backslash within quotes, keep both characters */
  2054. s++;
  2055. }
  2056. }
  2057. if (paren == 0) {
  2058. break;
  2059. }
  2060. }
  2061. /* This will find the closing paren we found above, or none, if the string ended before we found one. */
  2062. if ((s = strchr(s, ')'))) {
  2063. if (argloc) {
  2064. args[argloc - 1] = arg;
  2065. }
  2066. *s++ = '\0';
  2067. } else {
  2068. ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
  2069. res = -1;
  2070. break;
  2071. }
  2072. } else if (argloc) {
  2073. args[argloc - 1] = "";
  2074. }
  2075. if (flaglen == 32) {
  2076. ast_set_flag(flags, options[curarg].flag);
  2077. } else {
  2078. ast_set_flag64(flags64, options[curarg].flag);
  2079. }
  2080. }
  2081. return res;
  2082. }
  2083. int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
  2084. {
  2085. return parse_options(options, flags, args, optstr, 32);
  2086. }
  2087. int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
  2088. {
  2089. return parse_options(options, flags, args, optstr, 64);
  2090. }
  2091. void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
  2092. {
  2093. unsigned int i, found = 0;
  2094. for (i = 32; i < 128 && found < len; i++) {
  2095. if (ast_test_flag64(flags, options[i].flag)) {
  2096. buf[found++] = i;
  2097. }
  2098. }
  2099. buf[found] = '\0';
  2100. }
  2101. int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
  2102. {
  2103. int i;
  2104. *consumed = 1;
  2105. *result = 0;
  2106. if (ast_strlen_zero(stream)) {
  2107. *consumed = 0;
  2108. return -1;
  2109. }
  2110. if (*stream == '\\') {
  2111. *consumed = 2;
  2112. switch (*(stream + 1)) {
  2113. case 'n':
  2114. *result = '\n';
  2115. break;
  2116. case 'r':
  2117. *result = '\r';
  2118. break;
  2119. case 't':
  2120. *result = '\t';
  2121. break;
  2122. case 'x':
  2123. /* Hexadecimal */
  2124. if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
  2125. *consumed = 3;
  2126. if (*(stream + 2) <= '9') {
  2127. *result = *(stream + 2) - '0';
  2128. } else if (*(stream + 2) <= 'F') {
  2129. *result = *(stream + 2) - 'A' + 10;
  2130. } else {
  2131. *result = *(stream + 2) - 'a' + 10;
  2132. }
  2133. } else {
  2134. ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
  2135. return -1;
  2136. }
  2137. if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
  2138. *consumed = 4;
  2139. *result <<= 4;
  2140. if (*(stream + 3) <= '9') {
  2141. *result += *(stream + 3) - '0';
  2142. } else if (*(stream + 3) <= 'F') {
  2143. *result += *(stream + 3) - 'A' + 10;
  2144. } else {
  2145. *result += *(stream + 3) - 'a' + 10;
  2146. }
  2147. }
  2148. break;
  2149. case '0':
  2150. /* Octal */
  2151. *consumed = 2;
  2152. for (i = 2; ; i++) {
  2153. if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
  2154. (*consumed)++;
  2155. ast_debug(5, "result was %d, ", *result);
  2156. *result <<= 3;
  2157. *result += *(stream + i) - '0';
  2158. ast_debug(5, "is now %d\n", *result);
  2159. } else {
  2160. break;
  2161. }
  2162. }
  2163. break;
  2164. default:
  2165. *result = *(stream + 1);
  2166. }
  2167. } else {
  2168. *result = *stream;
  2169. *consumed = 1;
  2170. }
  2171. return 0;
  2172. }
  2173. char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
  2174. {
  2175. char *cur = result;
  2176. size_t consumed;
  2177. while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
  2178. cur++;
  2179. stream += consumed;
  2180. }
  2181. *cur = '\0';
  2182. return result;
  2183. }
  2184. int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
  2185. {
  2186. char next, *buf;
  2187. size_t offset = 0;
  2188. size_t consumed;
  2189. if (strchr(stream, '\\')) {
  2190. while (!ast_get_encoded_char(stream, &next, &consumed)) {
  2191. if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
  2192. ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
  2193. }
  2194. if (offset + 2 > ast_str_size(*str)) {
  2195. break;
  2196. }
  2197. buf = ast_str_buffer(*str);
  2198. buf[offset++] = next;
  2199. stream += consumed;
  2200. }
  2201. buf = ast_str_buffer(*str);
  2202. buf[offset++] = '\0';
  2203. ast_str_update(*str);
  2204. } else {
  2205. ast_str_set(str, maxlen, "%s", stream);
  2206. }
  2207. return 0;
  2208. }
  2209. void ast_close_fds_above_n(int n)
  2210. {
  2211. closefrom(n + 1);
  2212. }
  2213. int ast_safe_fork(int stop_reaper)
  2214. {
  2215. sigset_t signal_set, old_set;
  2216. int pid;
  2217. /* Don't let the default signal handler for children reap our status */
  2218. if (stop_reaper) {
  2219. ast_replace_sigchld();
  2220. }
  2221. sigfillset(&signal_set);
  2222. pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
  2223. pid = fork();
  2224. if (pid != 0) {
  2225. /* Fork failed or parent */
  2226. pthread_sigmask(SIG_SETMASK, &old_set, NULL);
  2227. if (!stop_reaper && pid > 0) {
  2228. struct zombie *cur = ast_calloc(1, sizeof(*cur));
  2229. if (cur) {
  2230. cur->pid = pid;
  2231. AST_LIST_LOCK(&zombies);
  2232. AST_LIST_INSERT_TAIL(&zombies, cur, list);
  2233. AST_LIST_UNLOCK(&zombies);
  2234. if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
  2235. if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
  2236. ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
  2237. shaun_of_the_dead_thread = AST_PTHREADT_NULL;
  2238. }
  2239. }
  2240. }
  2241. }
  2242. return pid;
  2243. } else {
  2244. /* Child */
  2245. #ifdef HAVE_CAP
  2246. cap_t cap = cap_from_text("cap_net_admin-eip");
  2247. if (cap_set_proc(cap)) {
  2248. ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
  2249. }
  2250. cap_free(cap);
  2251. #endif
  2252. /* Before we unblock our signals, return our trapped signals back to the defaults */
  2253. signal(SIGHUP, SIG_DFL);
  2254. signal(SIGCHLD, SIG_DFL);
  2255. signal(SIGINT, SIG_DFL);
  2256. signal(SIGURG, SIG_DFL);
  2257. signal(SIGTERM, SIG_DFL);
  2258. signal(SIGPIPE, SIG_DFL);
  2259. signal(SIGXFSZ, SIG_DFL);
  2260. /* unblock important signal handlers */
  2261. if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
  2262. ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
  2263. _exit(1);
  2264. }
  2265. return pid;
  2266. }
  2267. }
  2268. void ast_safe_fork_cleanup(void)
  2269. {
  2270. ast_unreplace_sigchld();
  2271. }
  2272. int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
  2273. {
  2274. int res;
  2275. char u[10];
  2276. #ifdef HAVE_LONG_DOUBLE_WIDER
  2277. long double amount;
  2278. #define FMT "%30Lf%9s"
  2279. #else
  2280. double amount;
  2281. #define FMT "%30lf%9s"
  2282. #endif
  2283. if (!timestr) {
  2284. return -1;
  2285. }
  2286. res = sscanf(timestr, FMT, &amount, u);
  2287. if (res == 0 || res == EOF) {
  2288. #undef FMT
  2289. return -1;
  2290. } else if (res == 2) {
  2291. switch (u[0]) {
  2292. case 'h':
  2293. case 'H':
  2294. unit = TIMELEN_HOURS;
  2295. break;
  2296. case 's':
  2297. case 'S':
  2298. unit = TIMELEN_SECONDS;
  2299. break;
  2300. case 'm':
  2301. case 'M':
  2302. if (toupper(u[1]) == 'S') {
  2303. unit = TIMELEN_MILLISECONDS;
  2304. } else if (u[1] == '\0') {
  2305. unit = TIMELEN_MINUTES;
  2306. }
  2307. break;
  2308. }
  2309. }
  2310. switch (unit) {
  2311. case TIMELEN_HOURS:
  2312. amount *= 60;
  2313. /* fall-through */
  2314. case TIMELEN_MINUTES:
  2315. amount *= 60;
  2316. /* fall-through */
  2317. case TIMELEN_SECONDS:
  2318. amount *= 1000;
  2319. /* fall-through */
  2320. case TIMELEN_MILLISECONDS:
  2321. ;
  2322. }
  2323. *result = amount > INT_MAX ? INT_MAX : (int) amount;
  2324. return 0;
  2325. }