Debian Codegraph @

apps/app_voicemail.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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
19 /*!
20 * \file
21 * \author Mark Spencer <[email protected]>
22 * \brief Comedian Mail - Voicemail System
23 *
24 * unixODBC (http://www.unixodbc.org/)
25 * A source distribution of University of Washington's IMAP c-client
26 * (http://www.washington.edu/imap/)
27 *
28 * \par See also
29 * \arg \ref voicemail.conf "Config_voicemail"
30 * \note For information about voicemail IMAP storage, https://docs.asterisk.org/Configuration/Applications/Voicemail/IMAP-Voicemail-Storage/
31 * \ingroup applications
32 * \todo This module requires res_adsi to load. This needs to be optional
33 * during compilation.
34 *
35 * \todo This file is now almost impossible to work with, due to all \#ifdefs.
36 * Feels like the database code before realtime. Someone - please come up
37 * with a plan to clean this up.
38 */
39
40 /*! \li \ref app_voicemail.c uses configuration file \ref voicemail.conf
41 * \addtogroup configuration_file Configuration Files
42 */
43
44 /*!
45 * \page voicemail.conf voicemail.conf
46 * \verbinclude voicemail.conf.sample
47 */
48
49 #include "asterisk.h"
50
51 #ifdef IMAP_STORAGE
52 #include <ctype.h>
53 #include <signal.h>
54 #include <pwd.h>
55 #ifdef USE_SYSTEM_IMAP
56 #include <imap/c-client.h>
57 #include <imap/imap4r1.h>
58 #include <imap/linkage.h>
59 #elif defined (USE_SYSTEM_CCLIENT)
60 #include <c-client/c-client.h>
61 #include <c-client/imap4r1.h>
62 #include <c-client/linkage.h>
63 #else
64 #include "c-client.h"
65 #include "imap4r1.h"
66 #include "linkage.h"
67 #endif
68 #endif
69
70 #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR */
71 #include <sys/time.h>
72 #include <sys/stat.h>
73 #include <sys/mman.h>
74 #include <time.h>
75 #include <dirent.h>
76 #if defined(__FreeBSD__) || defined(__OpenBSD__)
77 #include <sys/wait.h>
78 #endif
79
80 #include "asterisk/logger.h"
81 #include "asterisk/lock.h"
82 #include "asterisk/file.h"
83 #include "asterisk/channel.h"
84 #include "asterisk/pbx.h"
85 #include "asterisk/config.h"
86 #include "asterisk/say.h"
87 #include "asterisk/module.h"
88 #include "asterisk/adsi.h"
89 #include "asterisk/app.h"
90 #include "asterisk/mwi.h"
91 #include "asterisk/manager.h"
92 #include "asterisk/dsp.h"
93 #include "asterisk/localtime.h"
94 #include "asterisk/cli.h"
95 #include "asterisk/utils.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/strings.h"
98 #include "asterisk/smdi.h"
99 #include "asterisk/astobj2.h"
100 #include "asterisk/taskprocessor.h"
101 #include "asterisk/test.h"
102 #include "asterisk/format_cache.h"
103
104 #ifdef ODBC_STORAGE
105 #include "asterisk/res_odbc.h"
106 #endif
107
108 #ifdef IMAP_STORAGE
109 #include "asterisk/threadstorage.h"
110 #endif
111
112 /*** DOCUMENTATION
113 <application name="VoiceMail" language="en_US">
114 <since>
115 <version>0.1.0</version>
116 </since>
117 <synopsis>
118 Leave a Voicemail message.
119 </synopsis>
120 <syntax>
121 <parameter name="mailboxs" argsep="&amp;" required="true">
122 <argument name="mailbox1" argsep="@" required="true">
123 <argument name="mailbox" required="true" />
124 <argument name="context" />
125 </argument>
126 <argument name="mailbox2" argsep="@" multiple="true">
127 <argument name="mailbox" required="true" />
128 <argument name="context" />
129 </argument>
130 </parameter>
131 <parameter name="options">
132 <optionlist>
133 <option name="b">
134 <para>Play the <literal>busy</literal> greeting to the calling party.</para>
135 </option>
136 <option name="d">
137 <argument name="c" />
138 <para>Accept digits for a new extension in context <replaceable>c</replaceable>,
139 if played during the greeting. Context defaults to the current context.</para>
140 </option>
141 <option name="e">
142 <para>Play greetings as early media -- only answer the channel just
143 before accepting the voice message.</para>
144 </option>
145 <option name="g">
146 <argument name="#" required="true" />
147 <para>Use the specified amount of gain when recording the voicemail
148 message. The units are whole-number decibels (dB). Only works on supported
149 technologies, which is DAHDI only.</para>
150 </option>
151 <option name="s">
152 <para>Skip the playback of instructions for leaving a message to the
153 calling party.</para>
154 </option>
155 <option name="S">
156 <para>Skip the playback of instructions for leaving a message to the
157 calling party, but only if a greeting has been recorded by the
158 mailbox user.</para>
159 </option>
160 <option name="t">
161 <argument name="x" required="false" />
162 <para>Play a custom beep tone to the caller instead of the default one.
163 If this option is used but no file is specified, the beep is suppressed.</para>
164 </option>
165 <option name="u">
166 <para>Play the <literal>unavailable</literal> greeting.</para>
167 </option>
168 <option name="U">
169 <para>Mark message as <literal>URGENT</literal>.</para>
170 </option>
171 <option name="P">
172 <para>Mark message as <literal>PRIORITY</literal>.</para>
173 </option>
174 </optionlist>
175 </parameter>
176 </syntax>
177 <description>
178 <para>This application allows the calling party to leave a message for the specified
179 list of mailboxes. When multiple mailboxes are specified, the greeting will be taken from
180 the first mailbox specified. Dialplan execution will stop if the specified mailbox does not
181 exist.</para>
182 <para>The Voicemail application will exit if any of the following DTMF digits are received:</para>
183 <enumlist>
184 <enum name="0">
185 <para>Jump to the <literal>o</literal> extension in the current dialplan context.</para>
186 </enum>
187 <enum name="*">
188 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
189 </enum>
190 </enumlist>
191 <para>This application will set the following channel variable upon completion:</para>
192 <variablelist>
193 <variable name="VMSTATUS">
194 <para>This indicates the status of the execution of the VoiceMail application.</para>
195 <value name="SUCCESS" />
196 <value name="USEREXIT" />
197 <value name="FAILED" />
198 </variable>
199 </variablelist>
200 </description>
201 <see-also>
202 <ref type="application">VoiceMailMain</ref>
203 </see-also>
204 </application>
205 <application name="VoiceMailMain" language="en_US">
206 <since>
207 <version>0.1.0</version>
208 </since>
209 <synopsis>
210 Check Voicemail messages.
211 </synopsis>
212 <syntax>
213 <parameter name="mailbox" required="true" argsep="@">
214 <argument name="mailbox" />
215 <argument name="context" />
216 </parameter>
217 <parameter name="options">
218 <optionlist>
219 <option name="p">
220 <para>Consider the <replaceable>mailbox</replaceable> parameter as a prefix to
221 the mailbox that is entered by the caller.</para>
222 </option>
223 <option name="g">
224 <argument name="#" required="true" />
225 <para>Use the specified amount of gain when recording a voicemail message.
226 The units are whole-number decibels (dB).</para>
227 </option>
228 <option name="r">
229 <para>"Read only". Prevent user from deleting any messages.</para>
230 <para>This applies only to specific executions of VoiceMailMain, NOT the mailbox itself.</para>
231 </option>
232 <option name="s">
233 <para>Skip checking the passcode for the mailbox.</para>
234 </option>
235 <option name="a">
236 <argument name="folder" required="true" />
237 <para>Skip folder prompt and go directly to <replaceable>folder</replaceable> specified.
238 Defaults to <literal>INBOX</literal> (or <literal>0</literal>).</para>
239 <enumlist>
240 <enum name="0"><para>INBOX</para></enum>
241 <enum name="1"><para>Old</para></enum>
242 <enum name="2"><para>Work</para></enum>
243 <enum name="3"><para>Family</para></enum>
244 <enum name="4"><para>Friends</para></enum>
245 <enum name="5"><para>Cust1</para></enum>
246 <enum name="6"><para>Cust2</para></enum>
247 <enum name="7"><para>Cust3</para></enum>
248 <enum name="8"><para>Cust4</para></enum>
249 <enum name="9"><para>Cust5</para></enum>
250 </enumlist>
251 </option>
252 </optionlist>
253 </parameter>
254 </syntax>
255 <description>
256 <para>This application allows the calling party to check voicemail messages. A specific
257 <replaceable>mailbox</replaceable>, and optional corresponding <replaceable>context</replaceable>,
258 may be specified. If a <replaceable>mailbox</replaceable> is not provided, the calling party will
259 be prompted to enter one. If a <replaceable>context</replaceable> is not specified, the
260 <literal>default</literal> context will be used.</para>
261 <para>The VoiceMailMain application will exit if the following DTMF digit is entered as Mailbox
262 or Password, and the extension exists:</para>
263 <enumlist>
264 <enum name="*">
265 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
266 </enum>
267 </enumlist>
268 </description>
269 <see-also>
270 <ref type="application">VoiceMail</ref>
271 </see-also>
272 </application>
273 <application name="VMAuthenticate" language="en_US">
274 <since>
275 <version>1.2.0</version>
276 </since>
277 <synopsis>
278 Authenticate with Voicemail passwords.
279 </synopsis>
280 <syntax>
281 <parameter name="mailbox" required="true" argsep="@">
282 <argument name="mailbox" />
283 <argument name="context" />
284 </parameter>
285 <parameter name="options">
286 <optionlist>
287 <option name="s">
288 <para>Skip playing the initial prompts.</para>
289 </option>
290 </optionlist>
291 </parameter>
292 </syntax>
293 <description>
294 <para>This application behaves the same way as the Authenticate application, but the passwords
295 are taken from <filename>voicemail.conf</filename>. If the <replaceable>mailbox</replaceable> is
296 specified, only that mailbox's password will be considered valid. If the <replaceable>mailbox</replaceable>
297 is not specified, the channel variable <variable>AUTH_MAILBOX</variable> will be set with the authenticated
298 mailbox.</para>
299 <para>The VMAuthenticate application will exit if the following DTMF digit is entered as Mailbox
300 or Password, and the extension exists:</para>
301 <enumlist>
302 <enum name="*">
303 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
304 </enum>
305 </enumlist>
306 </description>
307 </application>
308 <application name="VoiceMailPlayMsg" language="en_US">
309 <since>
310 <version>11.0.0</version>
311 </since>
312 <synopsis>
313 Play a single voice mail msg from a mailbox by msg id.
314 </synopsis>
315 <syntax>
316 <parameter name="mailbox" required="true" argsep="@">
317 <argument name="mailbox" />
318 <argument name="context" />
319 </parameter>
320 <parameter name="msg_id" required="true">
321 <para>The msg id of the msg to play back. </para>
322 </parameter>
323 </syntax>
324 <description>
325 <para>This application sets the following channel variable upon completion:</para>
326 <variablelist>
327 <variable name="VOICEMAIL_PLAYBACKSTATUS">
328 <para>The status of the playback attempt as a text string.</para>
329 <value name="SUCCESS"/>
330 <value name="FAILED"/>
331 </variable>
332 </variablelist>
333 </description>
334 </application>
335 <application name="VMSayName" language="en_US">
336 <since>
337 <version>1.8.0</version>
338 </since>
339 <synopsis>
340 Play the name of a voicemail user
341 </synopsis>
342 <syntax>
343 <parameter name="mailbox" required="true" argsep="@">
344 <argument name="mailbox" />
345 <argument name="context" />
346 </parameter>
347 </syntax>
348 <description>
349 <para>This application will say the recorded name of the voicemail user specified as the
350 argument to this application. If no context is provided, <literal>default</literal> is assumed.</para>
351 <para>Similar to the Background() application, playback of the recorded
352 name can be interrupted by entering an extension, which will be searched
353 for in the current context.</para>
354 </description>
355 </application>
356 <function name="VM_INFO" language="en_US">
357 <since>
358 <version>11.0.0</version>
359 </since>
360 <synopsis>
361 Returns the selected attribute from a mailbox.
362 </synopsis>
363 <syntax argsep=",">
364 <parameter name="mailbox" argsep="@" required="true">
365 <argument name="mailbox" required="true" />
366 <argument name="context" />
367 </parameter>
368 <parameter name="attribute" required="true">
369 <optionlist>
370 <option name="count">
371 <para>Count of messages in specified <replaceable>folder</replaceable>.
372 If <replaceable>folder</replaceable> is not specified, defaults to <literal>INBOX</literal>.</para>
373 </option>
374 <option name="email">
375 <para>E-mail address associated with the mailbox.</para>
376 </option>
377 <option name="exists">
378 <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.</para>
379 </option>
380 <option name="fullname">
381 <para>Full name associated with the mailbox.</para>
382 </option>
383 <option name="language">
384 <para>Mailbox language if overridden, otherwise the language of the channel.</para>
385 </option>
386 <option name="locale">
387 <para>Mailbox locale if overridden, otherwise global locale.</para>
388 </option>
389 <option name="pager">
390 <para>Pager e-mail address associated with the mailbox.</para>
391 </option>
392 <option name="password">
393 <para>Mailbox access password.</para>
394 </option>
395 <option name="tz">
396 <para>Mailbox timezone if overridden, otherwise global timezone</para>
397 </option>
398 </optionlist>
399 </parameter>
400 <parameter name="folder" required="false">
401 <para>If not specified, <literal>INBOX</literal> is assumed.</para>
402 </parameter>
403 </syntax>
404 <description>
405 <para>Returns the selected attribute from the specified <replaceable>mailbox</replaceable>.
406 If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
407 context. Where the <replaceable>folder</replaceable> can be specified, common folders
408 include <literal>INBOX</literal>, <literal>Old</literal>, <literal>Work</literal>,
409 <literal>Family</literal> and <literal>Friends</literal>.</para>
410 </description>
411 </function>
412 <manager name="VoicemailUsersList" language="en_US">
413 <since>
414 <version>1.6.0</version>
415 </since>
416 <synopsis>
417 List All Voicemail User Information.
418 </synopsis>
419 <syntax>
420 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
421 </syntax>
422 <description>
423 </description>
424 </manager>
425 <manager name="VoicemailUserStatus" language="en_US">
426 <since>
427 <version>16.0.0</version>
428 </since>
429 <synopsis>
430 Show the status of given voicemail user's info.
431 </synopsis>
432 <syntax>
433 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
434 <parameter name="Context" required="true">
435 <para>The context you want to check.</para>
436 </parameter>
437 <parameter name="Mailbox" required="true">
438 <para>The mailbox you want to check.</para>
439 </parameter>
440 </syntax>
441 <description>
442 <para>Retrieves the status of the given voicemail user.</para>
443 </description>
444 </manager>
445 <manager name="VoicemailRefresh" language="en_US">
446 <since>
447 <version>12.0.0</version>
448 </since>
449 <synopsis>
450 Tell Asterisk to poll mailboxes for a change
451 </synopsis>
452 <syntax>
453 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
454 <parameter name="Context" />
455 <parameter name="Mailbox" />
456 </syntax>
457 <description>
458 <para>Normally, MWI indicators are only sent when Asterisk itself
459 changes a mailbox. With external programs that modify the content
460 of a mailbox from outside the application, an option exists called
461 <literal>pollmailboxes</literal> that will cause voicemail to
462 continually scan all mailboxes on a system for changes. This can
463 cause a large amount of load on a system. This command allows
464 external applications to signal when a particular mailbox has
465 changed, thus permitting external applications to modify mailboxes
466 and MWI to work without introducing considerable CPU load.</para>
467 <para>If <replaceable>Context</replaceable> is not specified, all
468 mailboxes on the system will be polled for changes. If
469 <replaceable>Context</replaceable> is specified, but
470 <replaceable>Mailbox</replaceable> is omitted, then all mailboxes
471 within <replaceable>Context</replaceable> will be polled.
472 Otherwise, only a single mailbox will be polled for changes.</para>
473 </description>
474 </manager>
475 <manager name="VoicemailBoxSummary" language="en_US">
476 <since>
477 <version>20.5.0</version>
478 <version>18.20.0</version>
479 </since>
480 <synopsis>
481 Show the mailbox contents of given voicemail user.
482 </synopsis>
483 <syntax>
484 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
485 <parameter name="Context" required="true">
486 <para>The context you want to check.</para>
487 </parameter>
488 <parameter name="Mailbox" required="true">
489 <para>The mailbox you want to check.</para>
490 </parameter>
491 </syntax>
492 <description>
493 <para>Retrieves the contents of the given voicemail user's mailbox.</para>
494 </description>
495 </manager>
496 <manager name="VoicemailMove" language="en_US">
497 <since>
498 <version>20.5.0</version>
499 <version>18.20.0</version>
500 </since>
501 <synopsis>
502 Move Voicemail between mailbox folders of given user.
503 </synopsis>
504 <syntax>
505 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
506 <parameter name="Context" required="true">
507 <para>The context of the Voicemail you want to move.</para>
508 </parameter>
509 <parameter name="Mailbox" required="true">
510 <para>The mailbox of the Voicemail you want to move.</para>
511 </parameter>
512 <parameter name="Folder" required="true">
513 <para>The Folder containing the Voicemail you want to move.</para>
514 </parameter>
515 <parameter name="ID" required="true">
516 <para>The ID of the Voicemail you want to move.</para>
517 </parameter>
518 <parameter name="ToFolder" required="true">
519 <para>The Folder you want to move the Voicemail to.</para>
520 </parameter>
521 </syntax>
522 <description>
523 <para>Move a given Voicemail between Folders within a user's Mailbox.</para>
524 </description>
525 </manager>
526 <manager name="VoicemailRemove" language="en_US">
527 <since>
528 <version>20.5.0</version>
529 <version>18.20.0</version>
530 </since>
531 <synopsis>
532 Remove Voicemail from mailbox folder.
533 </synopsis>
534 <syntax>
535 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
536 <parameter name="Context" required="true">
537 <para>The context of the Voicemail you want to remove.</para>
538 </parameter>
539 <parameter name="Mailbox" required="true">
540 <para>The mailbox of the Voicemail you want to remove.</para>
541 </parameter>
542 <parameter name="Folder" required="true">
543 <para>The Folder containing the Voicemail you want to remove.</para>
544 </parameter>
545 <parameter name="ID" required="true">
546 <para>The ID of the Voicemail you want to remove.</para>
547 </parameter>
548 </syntax>
549 <description>
550 <para>Remove a given Voicemail from a user's Mailbox Folder.</para>
551 </description>
552 </manager>
553 <manager name="VoicemailForward" language="en_US">
554 <since>
555 <version>20.5.0</version>
556 <version>18.20.0</version>
557 </since>
558 <synopsis>
559 Forward Voicemail from one mailbox folder to another between given users.
560 </synopsis>
561 <syntax>
562 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
563 <parameter name="Context" required="true">
564 <para>The context of the Voicemail you want to move.</para>
565 </parameter>
566 <parameter name="Mailbox" required="true">
567 <para>The mailbox of the Voicemail you want to move.</para>
568 </parameter>
569 <parameter name="Folder" required="true">
570 <para>The Folder containing the Voicemail you want to move.</para>
571 </parameter>
572 <parameter name="ID" required="true">
573 <para>The ID of the Voicemail you want to move.</para>
574 </parameter>
575 <parameter name="ToContext" required="true">
576 <para>The context you want to move the Voicemail to.</para>
577 </parameter>
578 <parameter name="ToMailbox" required="true">
579 <para>The mailbox you want to move the Voicemail to.</para>
580 </parameter>
581 <parameter name="ToFolder" required="true">
582 <para>The Folder you want to move the Voicemail to.</para>
583 </parameter>
584 </syntax>
585 <description>
586 <para>Forward a given Voicemail from a user's Mailbox Folder to
587 another user's Mailbox Folder. Can be used to copy between
588 Folders within a mailbox by specifying the to context and user
589 as the same as the from.</para>
590 </description>
591 </manager>
592 <managerEvent language="en_US" name="VoicemailPasswordChange">
593 <managerEventInstance class="EVENT_FLAG_USER">
594 <since>
595 <version>18.21.0</version>
596 <version>20.6.0</version>
597 <version>21.1.0</version>
598 </since>
599 <synopsis>Raised in response to a mailbox password change.</synopsis>
600 <syntax>
601 <parameter name="Context">
602 <para>Mailbox context.</para>
603 </parameter>
604 <parameter name="Mailbox">
605 <para>Mailbox name.</para>
606 </parameter>
607 <parameter name="NewPassword">
608 <para>New password for mailbox.</para>
609 </parameter>
610 </syntax>
611 </managerEventInstance>
612 </managerEvent>
613 ***/
614
615 #ifdef IMAP_STORAGE
616 static char imapserver[48] = "localhost";
617 static char imapport[8] = "143";
618 static char imapflags[128];
619 static char imapfolder[64] = "INBOX";
620 static char imapparentfolder[64];
621 static char greetingfolder[64] = "INBOX";
622 static char authuser[32];
623 static char authpassword[42];
624 static int imapversion = 1;
625
626 static int expungeonhangup = 1;
627 static int imapgreetings;
628 static int imap_poll_logout;
629 static char delimiter;
630
631 /* mail_open cannot be protected on a stream basis */
632 ast_mutex_t mail_open_lock;
633
634 struct vm_state;
635 struct ast_vm_user;
636
637 AST_THREADSTORAGE(ts_vmstate);
638
639 /* Forward declarations for IMAP */
640 static int init_mailstream(struct vm_state *vms, int box);
641 static void write_file(char *filename, char *buffer, unsigned long len);
642 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
643 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu);
644 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
645 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive);
646 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
647 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
648 static void vmstate_insert(struct vm_state *vms);
649 static void vmstate_delete(struct vm_state *vms);
650 static void set_update(MAILSTREAM * stream);
651 static void init_vm_state(struct vm_state *vms);
652 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
653 static void get_mailbox_delimiter(struct vm_state *vms, MAILSTREAM *stream);
654 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
655 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
656 static int imap_store_file(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms, const char *flag, const char *msg_id);
657 static void vm_imap_update_msg_id(char *dir, int msgnum, const char *msg_id, struct ast_vm_user *vmu, struct ast_config *msg_cfg, int folder);
658 static void update_messages_by_imapuser(const char *user, unsigned long number);
659 static int vm_delete(char *file);
660
661 static int imap_remove_file (char *dir, int msgnum);
662 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
663 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
664 static void check_quota(struct vm_state *vms, char *mailbox);
665 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
666 static void imap_logout(const char *mailbox_id);
667
668 struct vmstate {
669 struct vm_state *vms;
670 AST_LIST_ENTRY(vmstate) list;
671 };
672
673 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
674
675 #endif
676
677 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
678
679 #define COMMAND_TIMEOUT 5000
680 /* Don't modify these here; set your umask at runtime instead */
681 #define VOICEMAIL_DIR_MODE 0777
682 #define VOICEMAIL_FILE_MODE 0666
683 #define CHUNKSIZE 65536
684
685 #define VOICEMAIL_CONFIG "voicemail.conf"
686 #define ASTERISK_USERNAME "asterisk"
687
688 /* Define fast-forward, pause, restart, and reverse keys
689 * while listening to a voicemail message - these are
690 * strings, not characters */
691 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
692 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
693 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
694 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
695 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
696 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
697
698 /* Default mail command to mail voicemail. Change it with the
699 * mailcmd= command in voicemail.conf */
700 #define SENDMAIL "/usr/sbin/sendmail -t"
701 #define INTRO "vm-intro"
702
703 #define MAX_MAIL_BODY_CONTENT_SIZE 134217728L // 128 Mbyte
704
705 #define MAXMSG 100
706 #define MAXMSGLIMIT 9999
707
708 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
709
710 #ifdef IMAP_STORAGE
711 #define ENDL "\r\n"
712 #else
713 #define ENDL "\n"
714 #endif
715
716 #define MAX_DATETIME_FORMAT 512
717 #define MAX_NUM_CID_CONTEXTS 10
718
719 #define VM_REVIEW (1 << 0) /*!< After recording, permit the caller to review the recording before saving */
720 #define VM_OPERATOR (1 << 1) /*!< Allow 0 to be pressed to go to 'o' extension */
721 #define VM_SAYCID (1 << 2) /*!< Repeat the CallerID info during envelope playback */
722 #define VM_SVMAIL (1 << 3) /*!< Allow the user to compose a new VM from within VoicemailMain */
723 #define VM_ENVELOPE (1 << 4) /*!< Play the envelope information (who-from, time received, etc.) */
724 #define VM_SAYDURATION (1 << 5) /*!< Play the length of the message during envelope playback */
725 #define VM_SKIPAFTERCMD (1 << 6) /*!< After deletion, assume caller wants to go to the next message */
726 #define VM_FORCENAME (1 << 7) /*!< Have new users record their name */
727 #define VM_FORCEGREET (1 << 8) /*!< Have new users record their greetings */
728 #define VM_PBXSKIP (1 << 9) /*!< Skip the [PBX] preamble in the Subject line of emails */
729 #define VM_DIRECTFORWARD (1 << 10) /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
730 #define VM_ATTACH (1 << 11) /*!< Attach message to voicemail notifications? */
731 #define VM_DELETE (1 << 12) /*!< Delete message after sending notification */
732 #define VM_ALLOCED (1 << 13) /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
733 #define VM_SEARCH (1 << 14) /*!< Search all contexts for a matching mailbox */
734 #define VM_TEMPGREETWARN (1 << 15) /*!< Remind user tempgreeting is set */
735 #define VM_MOVEHEARD (1 << 16) /*!< Move a "heard" message to Old after listening to it */
736 #define VM_MESSAGEWRAP (1 << 17) /*!< Wrap around from the last message to the first, and vice-versa */
737 #define VM_FWDURGAUTO (1 << 18) /*!< Autoset of Urgent flag on forwarded Urgent messages set globally */
738 #define VM_EMAIL_EXT_RECS (1 << 19) /*!< Send voicemail emails when an external recording is added to a mailbox */
739 #define VM_MARK_URGENT (1 << 20) /*!< After recording, permit the caller to mark the message as urgent */
740 #define VM_ODBC_AUDIO_ON_DISK (1 << 21) /*!< When using ODBC, leave the message and greeting recordings on disk instead of moving them into the table */
741
742 #define ERROR_LOCK_PATH -100
743 #define ERROR_MAX_MSGS -101
744 #define OPERATOR_EXIT 300
745
746 #define MSGFILE_LEN (7) /*!< Length of the message file name: msgXXXX */
747
748 enum vm_box {
749 NEW_FOLDER = 0,
750 OLD_FOLDER = 1,
751 WORK_FOLDER = 2,
752 FAMILY_FOLDER = 3,
753 FRIENDS_FOLDER = 4,
754 GREETINGS_FOLDER = -1
755 };
756
757 enum vm_option_flags {
758 OPT_SILENT = (1 << 0),
759 OPT_BUSY_GREETING = (1 << 1),
760 OPT_UNAVAIL_GREETING = (1 << 2),
761 OPT_RECORDGAIN = (1 << 3),
762 OPT_PREPEND_MAILBOX = (1 << 4),
763 OPT_AUTOPLAY = (1 << 6),
764 OPT_DTMFEXIT = (1 << 7),
765 OPT_MESSAGE_Urgent = (1 << 8),
766 OPT_MESSAGE_PRIORITY = (1 << 9),
767 OPT_EARLYM_GREETING = (1 << 10),
768 OPT_BEEP = (1 << 11),
769 OPT_SILENT_IF_GREET = (1 << 12),
770 OPT_READONLY = (1 << 13),
771 };
772
773 enum vm_option_args {
774 OPT_ARG_RECORDGAIN = 0,
775 OPT_ARG_PLAYFOLDER = 1,
776 OPT_ARG_DTMFEXIT = 2,
777 OPT_ARG_BEEP_TONE = 3,
778 /* This *must* be the last value in this enum! */
779 OPT_ARG_ARRAY_SIZE = 4,
780 };
781
782 enum vm_passwordlocation {
783 OPT_PWLOC_VOICEMAILCONF = 0,
784 OPT_PWLOC_SPOOLDIR = 1,
785 OPT_PWLOC_USERSCONF = 2,
786 };
787
788 AST_APP_OPTIONS(vm_app_options, {
789 AST_APP_OPTION('s', OPT_SILENT),
790 AST_APP_OPTION('S', OPT_SILENT_IF_GREET),
791 AST_APP_OPTION('b', OPT_BUSY_GREETING),
792 AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
793 AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
794 AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
795 AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
796 AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
797 AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
798 AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY),
799 AST_APP_OPTION('e', OPT_EARLYM_GREETING),
800 AST_APP_OPTION_ARG('t', OPT_BEEP, OPT_ARG_BEEP_TONE),
801 AST_APP_OPTION('r', OPT_READONLY),
802 });
803
804 static const char * const mailbox_folders[] = {
805 #ifdef IMAP_STORAGE
806 imapfolder,
807 #else
808 "INBOX",
809 #endif
810 "Old",
811 "Work",
812 "Family",
813 "Friends",
814 "Cust1",
815 "Cust2",
816 "Cust3",
817 "Cust4",
818 "Cust5",
819 "Deleted",
820 "Urgent",
821 };
822
823 /*!
824 * \brief Reload voicemail.conf
825 * \param reload Whether this is a reload as opposed to module load
826 * \param force Forcefully reload the config, even it has not changed
827 * \retval 0 on success, nonzero on failure
828 */
829 static int load_config_force(int reload, int force);
830
831 /*! \brief Forcibly reload voicemail.conf, even if it has not changed.
832 * This is necessary after running unit tests. */
833 #define force_reload_config() load_config_force(1, 1)
834
835 static int load_config(int reload);
836 #ifdef TEST_FRAMEWORK
837 static int load_config_from_memory(int reload, struct ast_config *cfg, struct ast_config *ucfg);
838 #endif
839 static int actual_load_config(int reload, struct ast_config *cfg, struct ast_config *ucfg);
840
841 /*! \page vmlang Voicemail Language Syntaxes Supported
842
843 \par Syntaxes supported, not really language codes.
844 \arg \b en - English
845 \arg \b de - German
846 \arg \b es - Spanish
847 \arg \b fr - French
848 \arg \b it - Italian
849 \arg \b nl - Dutch
850 \arg \b pt - Portuguese
851 \arg \b pt_BR - Portuguese (Brazil)
852 \arg \b gr - Greek
853 \arg \b no - Norwegian
854 \arg \b se - Swedish
855 \arg \b tw - Chinese (Taiwan)
856 \arg \b ua - Ukrainian
857
858 German requires the following additional soundfile:
859 \arg \b 1F einE (feminine)
860
861 Spanish requires the following additional soundfile:
862 \arg \b 1M un (masculine)
863
864 Dutch, Portuguese & Spanish require the following additional soundfiles:
865 \arg \b vm-INBOXs singular of 'new'
866 \arg \b vm-Olds singular of 'old/heard/read'
867
868 NB these are plural:
869 \arg \b vm-INBOX nieuwe (nl)
870 \arg \b vm-Old oude (nl)
871
872 Polish uses:
873 \arg \b vm-new-a 'new', feminine singular accusative
874 \arg \b vm-new-e 'new', feminine plural accusative
875 \arg \b vm-new-ych 'new', feminine plural genitive
876 \arg \b vm-old-a 'old', feminine singular accusative
877 \arg \b vm-old-e 'old', feminine plural accusative
878 \arg \b vm-old-ych 'old', feminine plural genitive
879 \arg \b digits/1-a 'one', not always same as 'digits/1'
880 \arg \b digits/2-ie 'two', not always same as 'digits/2'
881
882 Swedish uses:
883 \arg \b vm-nytt singular of 'new'
884 \arg \b vm-nya plural of 'new'
885 \arg \b vm-gammalt singular of 'old'
886 \arg \b vm-gamla plural of 'old'
887 \arg \b digits/ett 'one', not always same as 'digits/1'
888
889 Norwegian uses:
890 \arg \b vm-ny singular of 'new'
891 \arg \b vm-nye plural of 'new'
892 \arg \b vm-gammel singular of 'old'
893 \arg \b vm-gamle plural of 'old'
894
895 Dutch also uses:
896 \arg \b nl-om 'at'?
897
898 Spanish also uses:
899 \arg \b vm-youhaveno
900
901 Italian requires the following additional soundfile:
902
903 For vm_intro_it:
904 \arg \b vm-nuovo new
905 \arg \b vm-nuovi new plural
906 \arg \b vm-vecchio old
907 \arg \b vm-vecchi old plural
908
909 Japanese requires the following additional soundfile:
910 \arg \b jp-arimasu there is
911 \arg \b jp-arimasen there is not
912 \arg \b jp-oshitekudasai please press
913 \arg \b jp-ni article ni
914 \arg \b jp-ga article ga
915 \arg \b jp-wa article wa
916 \arg \b jp-wo article wo
917
918 Chinese (Taiwan) requires the following additional soundfile:
919 \arg \b vm-tong A class-word for call (tong1)
920 \arg \b vm-ri A class-word for day (ri4)
921 \arg \b vm-you You (ni3)
922 \arg \b vm-haveno Have no (mei2 you3)
923 \arg \b vm-have Have (you3)
924 \arg \b vm-listen To listen (yao4 ting1)
925
926
927 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
928 spelled among others when you have to change folder. For the above reasons, vm-INBOX
929 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
930
931 */
932
933 #define MAX_VM_MBOX_ID_LEN (AST_MAX_EXTENSION)
934 #define MAX_VM_CONTEXT_LEN (AST_MAX_CONTEXT)
935 /* MAX_VM_MAILBOX_LEN allows enough room for the '@' and NULL terminator */
936 #define MAX_VM_MAILBOX_LEN (MAX_VM_MBOX_ID_LEN + MAX_VM_CONTEXT_LEN)
937
938 /*! Structure for linked list of users
939 * Use ast_vm_user_destroy() to free one of these structures. */
940 struct ast_vm_user {
941 char context[MAX_VM_CONTEXT_LEN];/*!< Voicemail context */
942 char mailbox[MAX_VM_MBOX_ID_LEN];/*!< Mailbox id, unique within vm context */
943 char password[80]; /*!< Secret pin code, numbers only */
944 char fullname[80]; /*!< Full name, for directory app */
945 char *email; /*!< E-mail address */
946 char *emailsubject; /*!< E-mail subject */
947 char *emailbody; /*!< E-mail body */
948 char pager[80]; /*!< E-mail address to pager (no attachment) */
949 char serveremail[80]; /*!< From: Mail address */
950 char fromstring[100]; /*!< From: Username */
951 char language[MAX_LANGUAGE]; /*!< Config: Language setting */
952 char zonetag[80]; /*!< Time zone */
953 char locale[20]; /*!< The locale (for presentation of date/time) */
954 char callback[80];
955 char dialout[80];
956 char uniqueid[80]; /*!< Unique integer identifier */
957 char exit[80];
958 char attachfmt[20]; /*!< Attachment format */
959 unsigned int flags; /*!< VM_ flags */
960 int saydurationm;
961 int minsecs; /*!< Minimum number of seconds per message for this mailbox */
962 int maxmsg; /*!< Maximum number of msgs per folder for this mailbox */
963 int maxdeletedmsg; /*!< Maximum number of deleted msgs saved for this mailbox */
964 int maxsecs; /*!< Maximum number of seconds per message for this mailbox */
965 int passwordlocation; /*!< Storage location of the password */
966 #ifdef IMAP_STORAGE
967 char imapserver[48]; /*!< IMAP server address */
968 char imapport[8]; /*!< IMAP server port */
969 char imapflags[128]; /*!< IMAP optional flags */
970 char imapuser[80]; /*!< IMAP server login */
971 char imappassword[80]; /*!< IMAP server password if authpassword not defined */
972 char imapfolder[64]; /*!< IMAP voicemail folder */
973 char imapvmshareid[80]; /*!< Shared mailbox ID to use rather than the dialed one */
974 int imapversion; /*!< If configuration changes, use the new values */
975 #endif
976 double volgain; /*!< Volume gain for voicemails sent via email */
977 AST_LIST_ENTRY(ast_vm_user) list;
978 };
979
980 /*! Voicemail time zones */
981 struct vm_zone {
982 AST_LIST_ENTRY(vm_zone) list;
983 char name[80];
984 char timezone[80];
985 char msg_format[512];
986 };
987
988 #define VMSTATE_MAX_MSG_ARRAY 256
989
990 /*! Voicemail mailbox state */
991 struct vm_state {
992 char curbox[80];
993 char username[80];
994 char context[80];
995 char curdir[PATH_MAX];
996 char vmbox[PATH_MAX];
997 char fn[PATH_MAX];
998 char intro[PATH_MAX];
999 int *deleted;
1000 int *heard;
1001 int dh_arraysize; /* used for deleted / heard allocation */
1002 int curmsg;
1003 int lastmsg;
1004 int newmessages;
1005 int oldmessages;
1006 int urgentmessages;
1007 int starting;
1008 int repeats;
1009 #ifdef IMAP_STORAGE
1010 ast_mutex_t lock;
1011 int updated; /*!< decremented on each mail check until 1 -allows delay */
1012 long *msgArray;
1013 unsigned msg_array_max;
1014 MAILSTREAM *mailstream;
1015 int vmArrayIndex;
1016 char imapuser[80]; /*!< IMAP server login */
1017 char imapfolder[64]; /*!< IMAP voicemail folder */
1018 char imapserver[48]; /*!< IMAP server address */
1019 char imapport[8]; /*!< IMAP server port */
1020 char imapflags[128]; /*!< IMAP optional flags */
1021 int imapversion;
1022 int interactive;
1023 char introfn[PATH_MAX]; /*!< Name of prepended file */
1024 unsigned int quota_limit;
1025 unsigned int quota_usage;
1026 struct vm_state *persist_vms;
1027 #endif
1028 };
1029
1030 #ifdef ODBC_STORAGE
1031 static char odbc_database[80] = "asterisk";
1032 static char odbc_table[80] = "voicemessages";
1033 size_t odbc_table_len = sizeof(odbc_table);
1034 #define COUNT(a, b) odbc_count_messages(a,b)
1035 #define LAST_MSG_INDEX(a) odbc_last_message_index(a)
1036 #define RETRIEVE(a,b,c,d) odbc_retrieve_message(a,b)
1037 #define DISPOSE(a,b) odbc_remove_files(a,b)
1038 #define STORE(a,b,c,d,e,f,g,h,i,j,k) odbc_store_message(a,b,c,d)
1039 #define EXISTS(a,b,c,d) (odbc_message_exists(a,b))
1040 #define RENAME(a,b,c,d,e,f,g,h) (odbc_rename_message(a,b,c,d,e,f))
1041 #define COPY(a,b,c,d,e,f,g,h) (odbc_copy_message(a,b,c,d,e,f))
1042 #define DELETE(a,b,c,d) (odbc_delete_message(a,b))
1043 #define UPDATE_MSG_ID(a, b, c, d, e, f) (odbc_update_msg_id((a), (b), (c)))
1044 #else
1045 #ifdef IMAP_STORAGE
1046 #define DISPOSE(a,b) (imap_remove_file(a,b))
1047 #define STORE(a,b,c,d,e,f,g,h,i,j,k) (imap_store_file(a,b,c,d,e,f,g,h,i,j,k))
1048 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
1049 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
1050 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
1051 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
1052 #define DELETE(a,b,c,d) (vm_imap_delete(a,b,d))
1053 #define UPDATE_MSG_ID(a, b, c, d, e, f) (vm_imap_update_msg_id((a), (b), (c), (d), (e), (f)))
1054 #else
1055 #define COUNT(a, b) count_messages(a,b)
1056 #define LAST_MSG_INDEX(a) last_message_index(a)
1057 #define RETRIEVE(a,b,c,d)
1058 #define DISPOSE(a,b)
1059 #define STORE(a,b,c,d,e,f,g,h,i,j,k)
1060 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
1061 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
1062 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
1063 #define DELETE(a,b,c,d) (vm_delete(c))
1064 #define UPDATE_MSG_ID(a, b, c, d, e, f)
1065 #endif
1066 #endif
1067
1068 static char VM_SPOOL_DIR[PATH_MAX];
1069
1070 static char ext_pass_cmd[128];
1071 static char ext_pass_check_cmd[128];
1072
1073 static int my_umask;
1074
1075 #define PWDCHANGE_INTERNAL (1 << 1)
1076 #define PWDCHANGE_EXTERNAL (1 << 2)
1077 static int pwdchange = PWDCHANGE_INTERNAL;
1078
1079 #ifdef ODBC_STORAGE
1080 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
1081 #else
1082 # ifdef IMAP_STORAGE
1083 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
1084 # else
1085 # define tdesc "Comedian Mail (Voicemail System)"
1086 # endif
1087 #endif
1088
1089 static char userscontext[AST_MAX_EXTENSION] = "default";
1090
1091 static char *addesc = "Comedian Mail";
1092
1093 /* Leave a message */
1094 static char *voicemail_app = "VoiceMail";
1095
1096 /* Check mail, control, etc */
1097 static char *voicemailmain_app = "VoiceMailMain";
1098
1099 static char *vmauthenticate_app = "VMAuthenticate";
1100
1101 static char *playmsg_app = "VoiceMailPlayMsg";
1102
1103 static char *sayname_app = "VMSayName";
1104
1105 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
1106 static AST_LIST_HEAD_STATIC(zones, vm_zone);
1107 static char zonetag[80];
1108 static char locale[20];
1109 static int maxsilence;
1110 static int maxmsg = MAXMSG;
1111 static int maxdeletedmsg;
1112 static int silencethreshold = 128;
1113 static char serveremail[80] = ASTERISK_USERNAME;
1114 static char mailcmd[160] = SENDMAIL; /* Configurable mail cmd */
1115 static char externnotify[160];
1116 static struct ast_smdi_interface *smdi_iface = NULL;
1117 static char vmfmts[80] = "wav";
1118 static double volgain;
1119 static int vmminsecs;
1120 static int vmmaxsecs;
1121 static int maxgreet;
1122 static int skipms = 3000;
1123 static int maxlogins = 3;
1124 static int minpassword = MINPASSWORD;
1125 static int passwordlocation;
1126 static char aliasescontext[MAX_VM_CONTEXT_LEN];
1127
1128 /*! Poll mailboxes for changes since there is something external to
1129 * app_voicemail that may change them. */
1130 static unsigned int poll_mailboxes;
1131
1132 /*! By default, poll every 30 seconds */
1133 #define DEFAULT_POLL_FREQ 30
1134 /*! Polling frequency */
1135 static unsigned int poll_freq = DEFAULT_POLL_FREQ;
1136
1137 AST_MUTEX_DEFINE_STATIC(poll_lock);
1138 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
1139 static pthread_t poll_thread = AST_PTHREADT_NULL;
1140 static unsigned char poll_thread_run;
1141
1142 static struct ast_taskprocessor *mwi_subscription_tps;
1143
1144 struct alias_mailbox_mapping {
1145 char *alias;
1146 char *mailbox;
1147 char buf[0];
1148 };
1149
1150 struct mailbox_alias_mapping {
1151 char *alias;
1152 char *mailbox;
1153 char buf[0];
1154 };
1155
1156 #define MAPPING_BUCKETS 511
1157 static struct ao2_container *alias_mailbox_mappings;
1158 AO2_STRING_FIELD_HASH_FN(alias_mailbox_mapping, alias);
1159 AO2_STRING_FIELD_CMP_FN(alias_mailbox_mapping, alias);
1160
1161 static struct ao2_container *mailbox_alias_mappings;
1162 AO2_STRING_FIELD_HASH_FN(mailbox_alias_mapping, mailbox);
1163 AO2_STRING_FIELD_CMP_FN(mailbox_alias_mapping, mailbox);
1164
1165 /* custom audio control prompts for voicemail playback */
1166 static char listen_control_forward_key[12];
1167 static char listen_control_reverse_key[12];
1168 static char listen_control_pause_key[12];
1169 static char listen_control_restart_key[12];
1170 static char listen_control_stop_key[12];
1171
1172 /* custom password sounds */
1173 static char vm_login[80] = "vm-login";
1174 static char vm_newuser[80] = "vm-newuser";
1175 static char vm_password[80] = "vm-password";
1176 static char vm_newpassword[80] = "vm-newpassword";
1177 static char vm_passchanged[80] = "vm-passchanged";
1178 static char vm_reenterpassword[80] = "vm-reenterpassword";
1179 static char vm_mismatch[80] = "vm-mismatch";
1180 static char vm_invalid_password[80] = "vm-invalid-password";
1181 static char vm_pls_try_again[80] = "vm-pls-try-again";
1182
1183 /*
1184 * XXX If we have the time, motivation, etc. to fix up this prompt, one of the following would be appropriate:
1185 * 1. create a sound along the lines of "Please try again. When done, press the pound key" which could be spliced
1186 * from existing sound clips. This would require some programming changes in the area of vm_forward options and also
1187 * app.c's __ast_play_and_record function
1188 * 2. create a sound prompt saying "Please try again. When done recording, press any key to stop and send the prepended
1189 * message." At the time of this comment, I think this would require new voice work to be commissioned.
1190 * 3. Something way different like providing instructions before a time out or a post-recording menu. This would require
1191 * more effort than either of the other two.
1192 */
1193 static char vm_prepend_timeout[80] = "vm-then-pound";
1194
1195 static struct ast_flags globalflags = {0};
1196
1197 static int saydurationminfo = 2;
1198
1199 static char dialcontext[AST_MAX_CONTEXT] = "";
1200 static char callcontext[AST_MAX_CONTEXT] = "";
1201 static char exitcontext[AST_MAX_CONTEXT] = "";
1202
1203 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
1204
1205
1206 static char *emailbody;
1207 static char *emailsubject;
1208 static char *pagerbody;
1209 static char *pagersubject;
1210 static char fromstring[100];
1211 static char pagerfromstring[100];
1212 static char charset[32] = "ISO-8859-1";
1213
1214 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
1215 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
1216 static int adsiver = 1;
1217 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
1218 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
1219
1220 /* Forward declarations - generic */
1221 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
1222 static int close_mailbox(struct vm_state *vms, struct ast_vm_user *vmu);
1223 static int advanced_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int msg, int option, signed char record_gain);
1224 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
1225 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
1226 char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, int *sound_duration, const char *unlockdir,
1227 signed char record_gain, struct vm_state *vms, char *flag, const char *msg_id, int forwardintro);
1228 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
1229 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
1230 static int notify_new_message(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int msgnum, long duration, char *fmt, char *cidnum, char *cidname, const char *flag);
1231 static void make_email_file(FILE *p, char *srcemail, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, const char *fromfolder, char *cidnum, char *cidname, char *attach, char *attach2, char *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category, int imap, const char *flag, const char *msg_id);
1232 static void apply_options(struct ast_vm_user *vmu, const char *options);
1233 static int add_email_attachment(FILE *p, struct ast_vm_user *vmu, char *format, char *attach, char *greeting_attachment, char *mailbox, char *bound, char *filename, int last, int msgnum);
1234 static int is_valid_dtmf(const char *key);
1235 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
1236 static int write_password_to_file(const char *secretfn, const char *password);
1237 static const char *substitute_escapes(const char *value);
1238 static int message_range_and_existence_check(struct vm_state *vms, const char *msg_ids [], size_t num_msgs, int *msg_nums, struct ast_vm_user *vmu);
1239 static void notify_new_state(struct ast_vm_user *vmu);
1240 static int append_vmu_info_astman(struct mansession *s, struct ast_vm_user *vmu, const char* event_name, const char* actionid);
1241 static int append_vmbox_info_astman(struct mansession *s, const struct message *m, struct ast_vm_user *vmu, const char* event_name, const char* actionid);
1242
1243
1244 /*!
1245 * Place a message in the indicated folder
1246 *
1247 * \param vmu Voicemail user
1248 * \param vms Current voicemail state for the user
1249 * \param msg The message number to save
1250 * \param box The folder into which the message should be saved
1251 * \param[out] newmsg The new message number of the saved message
1252 * \param move Tells whether to copy or to move the message
1253 *
1254 * \note the "move" parameter is only honored for IMAP voicemail presently
1255 * \retval 0 Success
1256 * \retval other Failure
1257 */
1258 static int save_to_folder(struct ast_vm_user *vmu, struct vm_state *vms, int msg, int box, int *newmsg, int move);
1259
1260 static struct ast_vm_mailbox_snapshot *vm_mailbox_snapshot_create(const char *mailbox, const char *context, const char *folder, int descending, enum ast_vm_snapshot_sort_val sort_val, int combine_INBOX_and_OLD);
1261 static struct ast_vm_mailbox_snapshot *vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot);
1262
1263 static int vm_msg_forward(const char *from_mailbox, const char *from_context, const char *from_folder, const char *to_mailbox, const char *to_context, const char *to_folder, size_t num_msgs, const char *msg_ids[], int delete_old);
1264 static int vm_msg_move(const char *mailbox, const char *context, size_t num_msgs, const char *oldfolder, const char *old_msg_ids[], const char *newfolder);
1265 static int vm_msg_remove(const char *mailbox, const char *context, size_t num_msgs, const char *folder, const char *msgs[]);
1266 static int vm_msg_play(struct ast_channel *chan, const char *mailbox, const char *context, const char *folder, const char *msg_num, ast_vm_msg_play_cb cb);
1267
1268 #ifdef TEST_FRAMEWORK
1269 static int vm_test_destroy_user(const char *context, const char *mailbox);
1270 static int vm_test_create_user(const char *context, const char *mailbox);
1271 #endif
1272
1273 /*!
1274 * \internal
1275 * \brief Parse the given mailbox_id into mailbox and context.
1276 * \since 12.0.0
1277 *
1278 * \param mailbox_id The mailbox\@context string to separate.
1279 * \param mailbox Where the mailbox part will start.
1280 * \param context Where the context part will start. ("default" if not present)
1281 *
1282 * \retval 0 on success.
1283 * \retval -1 on error.
1284 */
1285 static int separate_mailbox(char *mailbox_id, char **mailbox, char **context)
1286 {
1287 if (ast_strlen_zero(mailbox_id) || !mailbox || !context) {
1288 return -1;
1289 }
1290 *context = mailbox_id;
1291 *mailbox = strsep(context, "@");
1292 if (ast_strlen_zero(*mailbox)) {
1293 return -1;
1294 }
1295 if (ast_strlen_zero(*context)) {
1296 *context = "default";
1297 }
1298 return 0;
1299 }
1300
1301 struct ao2_container *inprocess_container;
1302
1303 struct inprocess {
1304 int count;
1305 char *context;
1306 char mailbox[0];
1307 };
1308
1309 static int inprocess_hash_fn(const void *obj, const int flags)
1310 {
1311 const struct inprocess *i = obj;
1312 return atoi(i->mailbox);
1313 }
1314
1315 static int inprocess_cmp_fn(void *obj, void *arg, int flags)
1316 {
1317 struct inprocess *i = obj, *j = arg;
1318 if (strcmp(i->mailbox, j->mailbox)) {
1319 return 0;
1320 }
1321 return !strcmp(i->context, j->context) ? CMP_MATCH : 0;
1322 }
1323
1324 static int inprocess_count(const char *context, const char *mailbox, int delta)
1325 {
1326 int context_len = strlen(context) + 1;
1327 int mailbox_len = strlen(mailbox) + 1;
1328 struct inprocess *i, *arg = ast_alloca(sizeof(*arg) + context_len + mailbox_len);
1329 arg->context = arg->mailbox + mailbox_len;
1330 ast_copy_string(arg->mailbox, mailbox, mailbox_len); /* SAFE */
1331 ast_copy_string(arg->context, context, context_len); /* SAFE */
1332 ao2_lock(inprocess_container);
1333 if ((i = ao2_find(inprocess_container, arg, 0))) {
1334 int ret = ast_atomic_fetchadd_int(&i->count, delta);
1335 ao2_unlock(inprocess_container);
1336 ao2_ref(i, -1);
1337 return ret;
1338 }
1339 if (delta < 0) {
1340 ast_log(LOG_WARNING, "BUG: ref count decrement on non-existing object???\n");
1341 }
1342 if (!(i = ao2_alloc(sizeof(*i) + context_len + mailbox_len, NULL))) {
1343 ao2_unlock(inprocess_container);
1344 return 0;
1345 }
1346 i->context = i->mailbox + mailbox_len;
1347 ast_copy_string(i->mailbox, mailbox, mailbox_len); /* SAFE */
1348 ast_copy_string(i->context, context, context_len); /* SAFE */
1349 i->count = delta;
1350 ao2_link(inprocess_container, i);
1351 ao2_unlock(inprocess_container);
1352 ao2_ref(i, -1);
1353 return 0;
1354 }
1355
1356 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
1357 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
1358 #endif
1359
1360 /*!
1361 * \brief Strips control and non 7-bit clean characters from input string.
1362 *
1363 * \note To map control and none 7-bit characters to a 7-bit clean characters
1364 * please use ast_str_encode_mine().
1365 */
1366 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
1367 {
1368 char *bufptr = buf;
1369 for (; *input; input++) {
1370 if (*input < 32) {
1371 continue;
1372 }
1373 *bufptr++ = *input;
1374 if (bufptr == buf + buflen - 1) {
1375 break;
1376 }
1377 }
1378 *bufptr = '\0';
1379 return buf;
1380 }
1381
1382 /*
1383 * These macros are currently only used by the ODBC code but
1384 * should be used anyplace we're allocating a PATH_MAX
1385 * sized buffer for something which will be much smaller
1386 * in practice.
1387 */
1388 #ifdef ODBC_STORAGE
1389 /*!
1390 * \internal
1391 * \brief Get the length needed for a message path base.
1392 *
1393 * \param dir The absolute path to a directory
1394 *
1395 * \note The directory provided should include all components
1396 * down to the folder level. For example:
1397 * /var/spool/asterisk/voicemail/default/1234/INBOX
1398 *
1399 * \returns Number of bytes needed for the message path base.
1400 */
1401 static size_t get_msg_path_len(const char *dir)
1402 {
1403 if (ast_strlen_zero(dir)) {
1404 return 0;
1405 }
1406 /* dir + '/' + MSGFILE_LEN + '\0' */
1407 return strlen(dir) + 1 + MSGFILE_LEN + 1;
1408 }
1409
1410 /*
1411 * The longest sound file extension we currently
1412 * have is "siren14" which is 7 characters long
1413 * but we'll make this 12 to be extra safe.
1414 */
1415 #define MAX_SOUND_EXTEN_LEN 12
1416 /*!
1417 * \internal
1418 * \brief Get the length needed for a message sound or metadata file path.
1419 *
1420 * \param dir The absolute path to a directory
1421 *
1422 * \note The directory provided should include all components
1423 * down to the folder level. For example:
1424 * /var/spool/asterisk/voicemail/default/1234/INBOX
1425 *
1426 * \returns Number of bytes needed for the message sound or metadata file path.
1427 */
1428 static size_t get_msg_path_ext_len(const char *dir)
1429 {
1430 if (ast_strlen_zero(dir)) {
1431 return 0;
1432 }
1433 /* dir + '/' + MSGFILE_LEN + extlen(including '.') + '\0' */
1434 return strlen(dir) + 1 + MSGFILE_LEN + MAX_SOUND_EXTEN_LEN + 1;
1435 }
1436
1437 /*!
1438 * \internal
1439 * \brief Allocate a buffer on the stack containing a message file path base.
1440 *
1441 * \param dir The absolute path to a directory
1442 * \param msgnum The message number or -1 for a prompt file
1443 *
1444 * \note The returned buffer will automatically be freed when it
1445 * goes out of scope.
1446 *
1447 * If passed (/var/spool/asterisk/voicemail/default/1234/INBOX, 0)
1448 * the returned path would be:
1449 * /var/spool/asterisk/voicemail/default/1234/INBOX/msg0000
1450 *
1451 * If passed (/var/spool/asterisk/voicemail/default/1234/unavail, -1)
1452 * the returned path would be:
1453 * /var/spool/asterisk/voicemail/default/1234/unavail
1454 * (no change)
1455 *
1456 * \returns A pointer to the buffer containing the path.
1457 */
1458 #define MAKE_FILE_PTRA(dir, msgnum) \
1459 ({ \
1460 size_t __len = get_msg_path_len(dir); \
1461 char *__var; \
1462 if (msgnum < 0) { \
1463 __var = ast_strdupa(dir); \
1464 } else { \
1465 __var = ast_alloca(__len); \
1466 snprintf(__var, __len, "%s/msg%04d", dir, msgnum); \
1467 } \
1468 __var; \
1469 })
1470
1471 /*!
1472 * \internal
1473 * \brief Allocate a buffer on the stack for a message sound or metadata file path.
1474 *
1475 * \param dir The absolute path to a directory
1476 * \param msgnum The message number or -1 for a prompt file
1477 *
1478 * \note The returned buffer will automatically be freed when it
1479 * goes out of scope.
1480 *
1481 * If passed (/var/spool/asterisk/voicemail/default/1234/INBOX, 0, "txt")
1482 * the returned path would be:
1483 * /var/spool/asterisk/voicemail/default/1234/INBOX/msg0000.txt
1484 *
1485 * If passed (/var/spool/asterisk/voicemail/default/1234/unavail, -1, "WAV")
1486 * the returned path would be:
1487 * /var/spool/asterisk/voicemail/default/1234/unavail.WAV
1488 *
1489 * The buffer returned has enough space that you can safely re-use it
1490 * for other sound file extensions. For instance:
1491 *
1492 * char *fn = MAKE_FILE_PTRA(dir, msgnum);
1493 * char *full_fn = MAKE_FILE_EXT_PTRA(dir, msgnum, "txt");
1494 * char *fmt = "g722";
1495 * ...do domething with full_fn then re-use it...
1496 * sprintf(full_fn, "%s.%s", fn, fmt); * Safe since the same dir and msgnum were used *
1497 *
1498 * \returns A pointer to the allocated buffer
1499 */
1500 #define MAKE_FILE_EXT_PTRA(dir, msgnum, ext) \
1501 ({ \
1502 size_t __len = get_msg_path_ext_len(dir); \
1503 char *__var = ast_alloca(__len); \
1504 if (msgnum < 0) { \
1505 snprintf(__var, __len, "%s.%s", dir, ext); \
1506 } else { \
1507 snprintf(__var, __len, "%s/msg%04d.%s", dir, msgnum, ext); \
1508 } \
1509 __var; \
1510 })
1511 #endif
1512
1513 /*!
1514 * \brief Sets default voicemail system options to a voicemail user.
1515 *
1516 * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
1517 * - all the globalflags
1518 * - the saydurationminfo
1519 * - the callcontext
1520 * - the dialcontext
1521 * - the exitcontext
1522 * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
1523 * - volume gain.
1524 * - emailsubject, emailbody set to NULL
1525 */
1526 static void populate_defaults(struct ast_vm_user *vmu)
1527 {
1528 ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);
1529 vmu->passwordlocation = passwordlocation;
1530 if (saydurationminfo) {
1531 vmu->saydurationm = saydurationminfo;
1532 }
1533 ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
1534 ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
1535 ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
1536 ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
1537 ast_copy_string(vmu->locale, locale, sizeof(vmu->locale));
1538 if (vmminsecs) {
1539 vmu->minsecs = vmminsecs;
1540 }
1541 if (vmmaxsecs) {
1542 vmu->maxsecs = vmmaxsecs;
1543 }
1544 if (maxmsg) {
1545 vmu->maxmsg = maxmsg;
1546 }
1547 if (maxdeletedmsg) {
1548 vmu->maxdeletedmsg = maxdeletedmsg;
1549 }
1550 vmu->volgain = volgain;
1551 ast_free(vmu->email);
1552 vmu->email = NULL;
1553 ast_free(vmu->emailsubject);
1554 vmu->emailsubject = NULL;
1555 ast_free(vmu->emailbody);
1556 vmu->emailbody = NULL;
1557 #ifdef IMAP_STORAGE
1558 ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
1559 ast_copy_string(vmu->imapserver, imapserver, sizeof(vmu->imapserver));
1560 ast_copy_string(vmu->imapport, imapport, sizeof(vmu->imapport));
1561 ast_copy_string(vmu->imapflags, imapflags, sizeof(vmu->imapflags));
1562 #endif
1563 }
1564
1565 /*!
1566 * \brief Sets a specific property value.
1567 * \param vmu The voicemail user object to work with.
1568 * \param var The name of the property to be set.
1569 * \param value The value to be set to the property.
1570 *
1571 * The property name must be one of the understood properties. See the source for details.
1572 */
1573 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
1574 {
1575 int x;
1576 if (!strcasecmp(var, "attach")) {
1577 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
1578 } else if (!strcasecmp(var, "attachfmt")) {
1579 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
1580 } else if (!strcasecmp(var, "attachextrecs")) {
1581 ast_set2_flag(vmu, ast_true(value), VM_EMAIL_EXT_RECS);
1582 } else if (!strcasecmp(var, "serveremail")) {
1583 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
1584 } else if (!strcasecmp(var, "fromstring")) {
1585 ast_copy_string(vmu->fromstring, value, sizeof(vmu->fromstring));
1586 } else if (!strcasecmp(var, "emailbody")) {
1587 ast_free(vmu->emailbody);
1588 vmu->emailbody = ast_strdup(substitute_escapes(value));
1589 } else if (!strcasecmp(var, "emailsubject")) {
1590 ast_free(vmu->emailsubject);
1591 vmu->emailsubject = ast_strdup(substitute_escapes(value));
1592 } else if (!strcasecmp(var, "language")) {
1593 ast_copy_string(vmu->language, value, sizeof(vmu->language));
1594 } else if (!strcasecmp(var, "tz")) {
1595 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
1596 } else if (!strcasecmp(var, "locale")) {
1597 ast_copy_string(vmu->locale, value, sizeof(vmu->locale));
1598 #ifdef IMAP_STORAGE
1599 } else if (!strcasecmp(var, "imapuser")) {
1600 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
1601 vmu->imapversion = imapversion;
1602 } else if (!strcasecmp(var, "imapserver")) {
1603 ast_copy_string(vmu->imapserver, value, sizeof(vmu->imapserver));
1604 vmu->imapversion = imapversion;
1605 } else if (!strcasecmp(var, "imapport")) {
1606 ast_copy_string(vmu->imapport, value, sizeof(vmu->imapport));
1607 vmu->imapversion = imapversion;
1608 } else if (!strcasecmp(var, "imapflags")) {
1609 ast_copy_string(vmu->imapflags, value, sizeof(vmu->imapflags));
1610 vmu->imapversion = imapversion;
1611 } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
1612 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
1613 vmu->imapversion = imapversion;
1614 } else if (!strcasecmp(var, "imapfolder")) {
1615 ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
1616 vmu->imapversion = imapversion;
1617 } else if (!strcasecmp(var, "imapvmshareid")) {
1618 ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
1619 vmu->imapversion = imapversion;
1620 #endif
1621 } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
1622 ast_set2_flag(vmu, ast_true(value), VM_DELETE);
1623 } else if (!strcasecmp(var, "saycid")){
1624 ast_set2_flag(vmu, ast_true(value), VM_SAYCID);
1625 } else if (!strcasecmp(var, "sendvoicemail")){
1626 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);
1627 } else if (!strcasecmp(var, "review")){
1628 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
1629 } else if (!strcasecmp(var, "leaveurgent")){
1630 ast_set2_flag(vmu, ast_true(value), VM_MARK_URGENT);
1631 } else if (!strcasecmp(var, "tempgreetwarn")){
1632 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);
1633 } else if (!strcasecmp(var, "messagewrap")){
1634 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);
1635 } else if (!strcasecmp(var, "operator")) {
1636 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);
1637 } else if (!strcasecmp(var, "envelope")){
1638 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);
1639 } else if (!strcasecmp(var, "moveheard")){
1640 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
1641 } else if (!strcasecmp(var, "sayduration")){
1642 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);
1643 } else if (!strcasecmp(var, "saydurationm")){
1644 if (sscanf(value, "%30d", &x) == 1) {
1645 vmu->saydurationm = x;
1646 } else {
1647 ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
1648 }
1649 } else if (!strcasecmp(var, "forcename")){
1650 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);
1651 } else if (!strcasecmp(var, "forcegreetings")){
1652 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);
1653 } else if (!strcasecmp(var, "callback")) {
1654 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
1655 } else if (!strcasecmp(var, "dialout")) {
1656 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
1657 } else if (!strcasecmp(var, "exitcontext")) {
1658 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
1659 } else if (!strcasecmp(var, "minsecs")) {
1660 if (sscanf(value, "%30d", &x) == 1 && x >= 0) {
1661 vmu->minsecs = x;
1662 } else {
1663 ast_log(LOG_WARNING, "Invalid min message length of %s. Using global value %d\n", value, vmminsecs);
1664 vmu->minsecs = vmminsecs;
1665 }
1666 } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
1667 vmu->maxsecs = atoi(value);
1668 if (vmu->maxsecs <= 0) {
1669 ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
1670 vmu->maxsecs = vmmaxsecs;
1671 } else {
1672 vmu->maxsecs = atoi(value);
1673 }
1674 if (!strcasecmp(var, "maxmessage"))
1675 ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'. Please make that change in your voicemail config.\n");
1676 } else if (!strcasecmp(var, "maxmsg")) {
1677 vmu->maxmsg = atoi(value);
1678 /* Accept maxmsg=0 (Greetings only voicemail) */
1679 if (vmu->maxmsg < 0) {
1680 ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
1681 vmu->maxmsg = MAXMSG;
1682 } else if (vmu->maxmsg > MAXMSGLIMIT) {
1683 ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
1684 vmu->maxmsg = MAXMSGLIMIT;
1685 }
1686 } else if (!strcasecmp(var, "nextaftercmd")) {
1687 ast_set2_flag(vmu, ast_true(value), VM_SKIPAFTERCMD);
1688 } else if (!strcasecmp(var, "backupdeleted")) {
1689 if (sscanf(value, "%30d", &x) == 1)
1690 vmu->maxdeletedmsg = x;
1691 else if (ast_true(value))
1692 vmu->maxdeletedmsg = MAXMSG;
1693 else
1694 vmu->maxdeletedmsg = 0;
1695
1696 if (vmu->maxdeletedmsg < 0) {
1697 ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
1698 vmu->maxdeletedmsg = MAXMSG;
1699 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
1700 ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
1701 vmu->maxdeletedmsg = MAXMSGLIMIT;
1702 }
1703 } else if (!strcasecmp(var, "volgain")) {
1704 sscanf(value, "%30lf", &vmu->volgain);
1705 } else if (!strcasecmp(var, "passwordlocation")) {
1706 if (!strcasecmp(value, "spooldir")) {
1707 vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
1708 } else {
1709 vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
1710 }
1711 } else if (!strcasecmp(var, "options")) {
1712 apply_options(vmu, value);
1713 }
1714 }
1715
1716 static char *vm_check_password_shell(char *command, char *buf, size_t len)
1717 {
1718 int fds[2], pid = 0;
1719
1720 memset(buf, 0, len);
1721
1722 if (pipe(fds)) {
1723 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
1724 } else {
1725 /* good to go*/
1726 pid = ast_safe_fork(0);
1727
1728 if (pid < 0) {
1729 /* ok maybe not */
1730 close(fds[0]);
1731 close(fds[1]);
1732 snprintf(buf, len, "FAILURE: Fork failed");
1733 } else if (pid) {
1734 /* parent */
1735 close(fds[1]);
1736 if (read(fds[0], buf, len) < 0) {
1737 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
1738 }
1739 close(fds[0]);
1740 } else {
1741 /* child */
1742 AST_DECLARE_APP_ARGS(arg,
1743 AST_APP_ARG(v)[20];
1744 );
1745 char *mycmd = ast_strdupa(command);
1746
1747 close(fds[0]);
1748 dup2(fds[1], STDOUT_FILENO);
1749 close(fds[1]);
1750 ast_close_fds_above_n(STDOUT_FILENO);
1751
1752 AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
1753
1754 execv(arg.v[0], arg.v);
1755 printf("FAILURE: %s", strerror(errno));
1756 _exit(0);
1757 }
1758 }
1759 return buf;
1760 }
1761
1762 /*!
1763 * \brief Check that password meets minimum required length
1764 * \param vmu The voicemail user to change the password for.
1765 * \param password The password string to check
1766 *
1767 * \return zero on ok, 1 on not ok.
1768 */
1769 static int check_password(struct ast_vm_user *vmu, char *password)
1770 {
1771 /* check minimum length */
1772 if (strlen(password) < minpassword)
1773 return 1;
1774 /* check that password does not contain '*' character */
1775 if (!ast_strlen_zero(password) && password[0] == '*')
1776 return 1;
1777 if (!ast_strlen_zero(ext_pass_check_cmd)) {
1778 char cmd[255], buf[255];
1779
1780 ast_debug(1, "Verify password policies for %s\n", password);
1781
1782 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
1783 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
1784 ast_debug(5, "Result: %s\n", buf);
1785 if (!strncasecmp(buf, "VALID", 5)) {
1786 ast_debug(3, "Passed password check: '%s'\n", buf);
1787 return 0;
1788 } else if (!strncasecmp(buf, "FAILURE", 7)) {
1789 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
1790 return 0;
1791 } else {
1792 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
1793 return 1;
1794 }
1795 }
1796 }
1797 return 0;
1798 }
1799
1800 /*!
1801 * \brief Performs a change of the voicemail password in the realtime engine.
1802 * \param vmu The voicemail user to change the password for.
1803 * \param password The new value to be set to the password for this user.
1804 *
1805 * This only works if there is a realtime engine configured.
1806 * This is called from the (top level) vm_change_password.
1807 *
1808 * \return zero on success, -1 on error.
1809 */
1810 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
1811 {
1812 int res = -1;
1813 if (!strcmp(vmu->password, password)) {
1814 /* No change (but an update would return 0 rows updated, so we opt out here) */
1815 return 0;
1816 }
1817
1818 if (strlen(password) > 10) {
1819 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
1820 }
1821 if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
1822 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: realtime engine updated with new password\r\nPasswordSource: realtime");
1823 ast_copy_string(vmu->password, password, sizeof(vmu->password));
1824 res = 0;
1825 }
1826 return res;
1827 }
1828
1829 /*!
1830 * \brief Destructively Parse options and apply.
1831 */
1832 static void apply_options(struct ast_vm_user *vmu, const char *options)
1833 {
1834 char *stringp;
1835 char *s;
1836 char *var, *value;
1837 stringp = ast_strdupa(options);
1838 while ((s = strsep(&stringp, "|"))) {
1839 value = s;
1840 if ((var = strsep(&value, "=")) && value) {
1841 apply_option(vmu, var, value);
1842 }
1843 }
1844 }
1845
1846 /*!
1847 * \brief Loads the options specific to a voicemail user.
1848 *
1849 * This is called when a vm_user structure is being set up, such as from load_options.
1850 */
1851 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
1852 {
1853 for (; var; var = var->next) {
1854 if (!strcasecmp(var->name, "vmsecret")) {
1855 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1856 } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
1857 if (ast_strlen_zero(retval->password)) {
1858 if (!ast_strlen_zero(var->value) && var->value[0] == '*') {
1859 ast_log(LOG_WARNING, "Invalid password detected for mailbox %s. The password"
1860 "\n\tmust be reset in voicemail.conf.\n", retval->mailbox);
1861 } else {
1862 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1863 }
1864 }
1865 } else if (!strcasecmp(var->name, "uniqueid")) {
1866 ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
1867 } else if (!strcasecmp(var->name, "pager")) {
1868 ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
1869 } else if (!strcasecmp(var->name, "email")) {
1870 ast_free(retval->email);
1871 retval->email = ast_strdup(var->value);
1872 } else if (!strcasecmp(var->name, "fullname")) {
1873 ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
1874 } else if (!strcasecmp(var->name, "context")) {
1875 ast_copy_string(retval->context, var->value, sizeof(retval->context));
1876 } else if (!strcasecmp(var->name, "emailsubject")) {
1877 ast_free(retval->emailsubject);
1878 retval->emailsubject = ast_strdup(substitute_escapes(var->value));
1879 } else if (!strcasecmp(var->name, "emailbody")) {
1880 ast_free(retval->emailbody);
1881 retval->emailbody = ast_strdup(substitute_escapes(var->value));
1882 #ifdef IMAP_STORAGE
1883 } else if (!strcasecmp(var->name, "imapuser")) {
1884 ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
1885 retval->imapversion = imapversion;
1886 } else if (!strcasecmp(var->name, "imapserver")) {
1887 ast_copy_string(retval->imapserver, var->value, sizeof(retval->imapserver));
1888 retval->imapversion = imapversion;
1889 } else if (!strcasecmp(var->name, "imapport")) {
1890 ast_copy_string(retval->imapport, var->value, sizeof(retval->imapport));
1891 retval->imapversion = imapversion;
1892 } else if (!strcasecmp(var->name, "imapflags")) {
1893 ast_copy_string(retval->imapflags, var->value, sizeof(retval->imapflags));
1894 retval->imapversion = imapversion;
1895 } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
1896 ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
1897 retval->imapversion = imapversion;
1898 } else if (!strcasecmp(var->name, "imapfolder")) {
1899 ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
1900 retval->imapversion = imapversion;
1901 } else if (!strcasecmp(var->name, "imapvmshareid")) {
1902 ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
1903 retval->imapversion = imapversion;
1904 #endif
1905 } else
1906 apply_option(retval, var->name, var->value);
1907 }
1908 }
1909
1910 /*!
1911 * \brief Determines if a DTMF key entered is valid.
1912 * \param key The character to be compared. expects a single character. Though is capable of handling a string, this is internally copies using ast_strdupa.
1913 *
1914 * Tests the character entered against the set of valid DTMF characters.
1915 * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1916 */
1917 static int is_valid_dtmf(const char *key)
1918 {
1919 int i;
1920 char *local_key = ast_strdupa(key);
1921
1922 for (i = 0; i < strlen(key); ++i) {
1923 if (!strchr(VALID_DTMF, *local_key)) {
1924 ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1925 return 0;
1926 }
1927 local_key++;
1928 }
1929 return 1;
1930 }
1931
1932 /*!
1933 * \brief Finds a voicemail user from the realtime engine.
1934 * \param ivm
1935 * \param context
1936 * \param mailbox
1937 *
1938 * This is called as a fall through case when the normal find_user() was not able to find a user. That is, the default it so look in the usual voicemail users file first.
1939 *
1940 * \return The ast_vm_user structure for the user that was found.
1941 */
1942 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1943 {
1944 struct ast_variable *var;
1945 struct ast_vm_user *retval;
1946
1947 if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1948 if (ivm) {
1949 memset(retval, 0, sizeof(*retval));
1950 }
1951 populate_defaults(retval);
1952 if (!ivm) {
1953 ast_set_flag(retval, VM_ALLOCED);
1954 }
1955 if (mailbox) {
1956 ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1957 }
1958 if (!context && ast_test_flag((&globalflags), VM_SEARCH)) {
1959 var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1960 } else {
1961 var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1962 }
1963 if (var) {
1964 apply_options_full(retval, var);
1965 ast_variables_destroy(var);
1966 } else {
1967 if (!ivm)
1968 ast_free(retval);
1969 retval = NULL;
1970 }
1971 }
1972 return retval;
1973 }
1974
1975 /*!
1976 * \brief Finds a voicemail user from the users file or the realtime engine.
1977 * \param ivm
1978 * \param context
1979 * \param mailbox
1980 *
1981 * \return The ast_vm_user structure for the user that was found.
1982 */
1983 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1984 {
1985 /* This function could be made to generate one from a database, too */
1986 struct ast_vm_user *vmu = NULL, *cur;
1987 AST_LIST_LOCK(&users);
1988
1989 if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1990 context = "default";
1991
1992 AST_LIST_TRAVERSE(&users, cur, list) {
1993 #ifdef IMAP_STORAGE
1994 if (cur->imapversion != imapversion) {
1995 continue;
1996 }
1997 #endif
1998 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1999 break;
2000 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
2001 break;
2002 }
2003 if (cur) {
2004 /* Make a copy, so that on a reload, we have no race */
2005 if ((vmu = (ivm ? ivm : ast_calloc(1, sizeof(*vmu))))) {
2006 ast_free(vmu->email);
2007 ast_free(vmu->emailbody);
2008 ast_free(vmu->emailsubject);
2009 *vmu = *cur;
2010 vmu->email = ast_strdup(cur->email);
2011 vmu->emailbody = ast_strdup(cur->emailbody);
2012 vmu->emailsubject = ast_strdup(cur->emailsubject);
2013 ast_set2_flag(vmu, !ivm, VM_ALLOCED);
2014 AST_LIST_NEXT(vmu, list) = NULL;
2015 }
2016 }
2017 AST_LIST_UNLOCK(&users);
2018 if (!vmu) {
2019 vmu = find_user_realtime(ivm, context, mailbox);
2020 }
2021 if (!vmu && !ast_strlen_zero(aliasescontext)) {
2022 struct alias_mailbox_mapping *mapping;
2023 char *search_string = ast_alloca(MAX_VM_MAILBOX_LEN);
2024
2025 snprintf(search_string, MAX_VM_MAILBOX_LEN, "%s%s%s",
2026 mailbox,
2027 ast_strlen_zero(context) ? "" : "@",
2028 S_OR(context, ""));
2029
2030 mapping = ao2_find(alias_mailbox_mappings, search_string, OBJ_SEARCH_KEY);
2031 if (mapping) {
2032 char *search_mailbox = NULL;
2033 char *search_context = NULL;
2034
2035 separate_mailbox(ast_strdupa(mapping->mailbox), &search_mailbox, &search_context);
2036 ao2_ref(mapping, -1);
2037 vmu = find_user(ivm, search_mailbox, search_context);
2038 }
2039 }
2040
2041 return vmu;
2042 }
2043
2044 /*!
2045 * \brief Resets a user password to a specified password.
2046 * \param context
2047 * \param mailbox
2048 * \param newpass
2049 *
2050 * This does the actual change password work, called by the vm_change_password() function.
2051 *
2052 * \return zero on success, -1 on error.
2053 */
2054 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
2055 {
2056 /* This function could be made to generate one from a database, too */
2057 struct ast_vm_user *cur;
2058 int res = -1;
2059 AST_LIST_LOCK(&users);
2060 AST_LIST_TRAVERSE(&users, cur, list) {
2061 if ((!context || !strcasecmp(context, cur->context)) &&
2062 (!strcasecmp(mailbox, cur->mailbox)))
2063 break;
2064 }
2065 if (cur) {
2066 ast_copy_string(cur->password, newpass, sizeof(cur->password));
2067 res = 0;
2068 }
2069 AST_LIST_UNLOCK(&users);
2070 if (!res) {
2071 struct ast_json *json_object;
2072
2073 json_object = ast_json_pack("{s: s, s: s, s: s}",
2074 "Context", S_OR(context, "default"),
2075 "Mailbox", mailbox,
2076 "NewPassword", newpass);
2077 ast_manager_publish_event("VoicemailPasswordChange", EVENT_FLAG_SYSTEM | EVENT_FLAG_USER, json_object);
2078 ast_json_unref(json_object);
2079 }
2080 return res;
2081 }
2082
2083 /*!
2084 * \brief Check if configuration file is valid
2085 */
2086 static inline int valid_config(const struct ast_config *cfg)
2087 {
2088 return cfg && cfg != CONFIG_STATUS_FILEINVALID;
2089 }
2090
2091 /*!
2092 * \brief The handler for the change password option.
2093 * \param vmu The voicemail user to work with.
2094 * \param newpassword The new password (that has been gathered from the appropriate prompting).
2095 * This is called when a new user logs in for the first time and the option to force them to change their password is set.
2096 * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
2097 */
2098 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
2099 {
2100 struct ast_config *cfg = NULL;
2101 struct ast_variable *var = NULL;
2102 struct ast_category *cat = NULL;
2103 char *category = NULL;
2104 const char *tmp = NULL;
2105 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
2106 char secretfn[PATH_MAX] = "";
2107 int found = 0;
2108
2109 if (!change_password_realtime(vmu, newpassword))
2110 return;
2111
2112 /* check if we should store the secret in the spool directory next to the messages */
2113 switch (vmu->passwordlocation) {
2114 case OPT_PWLOC_SPOOLDIR:
2115 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
2116 if (write_password_to_file(secretfn, newpassword) == 0) {
2117 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: secret.conf updated with new password\r\nPasswordSource: secret.conf");
2118 ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
2119 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
2120 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
2121 break;
2122 } else {
2123 ast_log(LOG_WARNING, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
2124 }
2125 /* Fall-through */
2126 case OPT_PWLOC_VOICEMAILCONF:
2127 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && valid_config(cfg)) {
2128 while ((category = ast_category_browse(cfg, category))) {
2129 if (!strcasecmp(category, vmu->context)) {
2130 const char *value = NULL;
2131 char *new = NULL;
2132 if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
2133 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
2134 break;
2135 }
2136 value = strstr(tmp, ",");
2137 if (!value) {
2138 new = ast_malloc(strlen(newpassword) + 1);
2139 sprintf(new, "%s", newpassword);
2140 } else {
2141 new = ast_malloc((strlen(value) + strlen(newpassword) + 1));
2142 sprintf(new, "%s%s", newpassword, value);
2143 }
2144 if (!(cat = ast_category_get(cfg, category, NULL))) {
2145 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
2146 ast_free(new);
2147 break;
2148 }
2149 ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
2150 found = 1;
2151 ast_free(new);
2152 }
2153 }
2154 /* save the results */
2155 if (found) {
2156 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: voicemail.conf updated with new password\r\nPasswordSource: voicemail.conf");
2157 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
2158 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
2159 ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "app_voicemail");
2160 ast_config_destroy(cfg);
2161 break;
2162 }
2163
2164 ast_config_destroy(cfg);
2165 }
2166 /* Fall-through */
2167 case OPT_PWLOC_USERSCONF:
2168 /* check users.conf and update the password stored for the mailbox */
2169 /* if no vmsecret entry exists create one. */
2170 if ((cfg = ast_config_load("users.conf", config_flags)) && valid_config(cfg)) {
2171 ast_debug(4, "we are looking for %s\n", vmu->mailbox);
2172 for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
2173 ast_debug(4, "users.conf: %s\n", category);
2174 if (!strcasecmp(category, vmu->mailbox)) {
2175 char new[strlen(newpassword) + 1];
2176 if (!ast_variable_retrieve(cfg, category, "vmsecret")) {
2177 ast_debug(3, "looks like we need to make vmsecret!\n");
2178 var = ast_variable_new("vmsecret", newpassword, "");
2179 } else {
2180 var = NULL;
2181 }
2182
2183 sprintf(new, "%s", newpassword);
2184 if (!(cat = ast_category_get(cfg, category, NULL))) {
2185 ast_debug(4, "failed to get category!\n");
2186 ast_free(var);
2187 break;
2188 }
2189 if (!var) {
2190 ast_variable_update(cat, "vmsecret", new, NULL, 0);
2191 } else {
2192 ast_variable_append(cat, var);
2193 }
2194 found = 1;
2195 break;
2196 }
2197 }
2198 /* save the results and clean things up */
2199 if (found) {
2200 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: users.conf updated with new password\r\nPasswordSource: users.conf");
2201 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
2202 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
2203 ast_config_text_file_save("users.conf", cfg, "app_voicemail");
2204 }
2205
2206 ast_config_destroy(cfg);
2207 }
2208 }
2209 }
2210
2211 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
2212 {
2213 char buf[255];
2214 snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
2215 ast_debug(1, "External password: %s\n",buf);
2216 if (!ast_safe_system(buf)) {
2217 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: external script updated with new password\r\nPasswordSource: external");
2218 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
2219 /* Reset the password in memory, too */
2220 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
2221 }
2222 }
2223
2224 /*!
2225 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
2226 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
2227 * \param len The length of the path string that was written out.
2228 * \param context
2229 * \param ext
2230 * \param folder
2231 *
2232 * The path is constructed as
2233 * VM_SPOOL_DIRcontext/ext/folder
2234 *
2235 * \return zero on success, -1 on error.
2236 */
2237 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
2238 {
2239 return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
2240 }
2241
2242 /*!
2243 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
2244 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
2245 * \param len The length of the path string that was written out.
2246 * \param dir
2247 * \param num
2248 *
2249 * The path is constructed as
2250 * VM_SPOOL_DIRcontext/ext/folder
2251 *
2252 * \return zero on success, -1 on error.
2253 */
2254 static int make_file(char *dest, const int len, const char *dir, const int num)
2255 {
2256 return snprintf(dest, len, "%s/msg%04d", dir, num);
2257 }
2258
2259 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
2260 * \param dest String. base directory.
2261 * \param len Length of dest.
2262 * \param context String. Ignored if is null or empty string.
2263 * \param ext String. Ignored if is null or empty string.
2264 * \param folder String. Ignored if is null or empty string.
2265 * \return -1 on failure, 0 on success.
2266 */
2267 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
2268 {
2269 mode_t mode = VOICEMAIL_DIR_MODE;
2270 int res;
2271
2272 make_dir(dest, len, context, ext, folder);
2273 if ((res = ast_mkdir(dest, mode))) {
2274 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
2275 return -1;
2276 }
2277 return 0;
2278 }
2279
2280 static const char *mbox(struct ast_vm_user *vmu, int id)
2281 {
2282 #ifdef IMAP_STORAGE
2283 if (vmu && id == 0) {
2284 return vmu->imapfolder;
2285 }
2286 #endif
2287 return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
2288 }
2289
2290 static const char *vm_index_to_foldername(int id)
2291 {
2292 return mbox(NULL, id);
2293 }
2294
2295
2296 static int get_folder_by_name(const char *name)
2297 {
2298 size_t i;
2299
2300 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
2301 if (strcasecmp(name, mailbox_folders[i]) == 0) {
2302 return i;
2303 }
2304 }
2305
2306 return -1;
2307 }
2308
2309 static void free_user(struct ast_vm_user *vmu)
2310 {
2311 if (!vmu) {
2312 return;
2313 }
2314
2315 ast_free(vmu->email);
2316 vmu->email = NULL;
2317 ast_free(vmu->emailbody);
2318 vmu->emailbody = NULL;
2319 ast_free(vmu->emailsubject);
2320 vmu->emailsubject = NULL;
2321
2322 if (ast_test_flag(vmu, VM_ALLOCED)) {
2323 ast_free(vmu);
2324 }
2325 }
2326
2327 static void free_user_final(struct ast_vm_user *vmu)
2328 {
2329 if (!vmu) {
2330 return;
2331 }
2332
2333 if (!ast_strlen_zero(vmu->mailbox)) {
2334 ast_delete_mwi_state_full(vmu->mailbox, vmu->context, NULL);
2335 }
2336
2337 free_user(vmu);
2338 }
2339
2340 static int vm_allocate_dh(struct vm_state *vms, struct ast_vm_user *vmu, int count_msg) {
2341
2342 int arraysize = (vmu->maxmsg > count_msg ? vmu->maxmsg : count_msg);
2343
2344 /* remove old allocation */
2345 if (vms->deleted) {
2346 ast_free(vms->deleted);
2347 vms->deleted = NULL;
2348 }
2349 if (vms->heard) {
2350 ast_free(vms->heard);
2351 vms->heard = NULL;
2352 }
2353 vms->dh_arraysize = 0;
2354
2355 if (arraysize > 0) {
2356 if (!(vms->deleted = ast_calloc(arraysize, sizeof(int)))) {
2357 return -1;
2358 }
2359 if (!(vms->heard = ast_calloc(arraysize, sizeof(int)))) {
2360 ast_free(vms->deleted);
2361 vms->deleted = NULL;
2362 return -1;
2363 }
2364 vms->dh_arraysize = arraysize;
2365 }
2366
2367 return 0;
2368 }
2369
2370 /* All IMAP-specific functions should go in this block. This
2371 * keeps them from being spread out all over the code */
2372 #ifdef IMAP_STORAGE
2373 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
2374 {
2375 char arg[10];
2376 struct vm_state *vms;
2377 unsigned long messageNum;
2378
2379 /* If greetings aren't stored in IMAP, just delete the file */
2380 if (msgnum < 0 && !imapgreetings) {
2381 ast_filedelete(file, NULL);
2382 return;
2383 }
2384
2385 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2386 ast_log(LOG_WARNING, "Couldn't find a vm_state for mailbox %s. Unable to set \\DELETED flag for message %d\n", vmu->mailbox, msgnum);
2387 return;
2388 }
2389
2390 if (msgnum < 0) {
2391 imap_delete_old_greeting(file, vms);
2392 return;
2393 }
2394
2395 /* find real message number based on msgnum */
2396 /* this may be an index into vms->msgArray based on the msgnum. */
2397 messageNum = vms->msgArray[msgnum];
2398 if (messageNum == 0) {
2399 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
2400 return;
2401 }
2402 ast_debug(3, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
2403 /* delete message */
2404 snprintf (arg, sizeof(arg), "%lu", messageNum);
2405 ast_mutex_lock(&vms->lock);
2406 mail_setflag (vms->mailstream, arg, "\\DELETED");
2407 mail_expunge(vms->mailstream);
2408 ast_mutex_unlock(&vms->lock);
2409 }
2410
2411 static void vm_imap_update_msg_id(char *dir, int msgnum, const char *msg_id, struct ast_vm_user *vmu, struct ast_config *msg_cfg, int folder)
2412 {
2413 struct ast_channel *chan;
2414 char *cid;
2415 char *cid_name;
2416 char *cid_num;
2417 struct vm_state *vms;
2418 const char *duration_str;
2419 int duration = 0;
2420
2421 /*
2422 * First, get things initially set up. If any of this fails, then
2423 * back out before doing anything substantial
2424 */
2425 vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0);
2426 if (!vms) {
2427 return;
2428 }
2429
2430 if (open_mailbox(vms, vmu, folder)) {
2431 return;
2432 }
2433
2434 chan = ast_dummy_channel_alloc();
2435 if (!chan) {
2436 close_mailbox(vms, vmu);
2437 return;
2438 }
2439
2440 /*
2441 * We need to make sure the new message we save has the same
2442 * callerid, flag, and duration as the original message
2443 */
2444 cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
2445
2446 if (!ast_strlen_zero(cid)) {
2447 ast_callerid_parse(cid, &cid_name, &cid_num);
2448 ast_party_caller_init(ast_channel_caller(chan));
2449 if (!ast_strlen_zero(cid_name)) {
2450 ast_channel_caller(chan)->id.name.valid = 1;
2451 ast_channel_caller(chan)->id.name.str = ast_strdup(cid_name);
2452 }
2453 if (!ast_strlen_zero(cid_num)) {
2454 ast_channel_caller(chan)->id.number.valid = 1;
2455 ast_channel_caller(chan)->id.number.str = ast_strdup(cid_num);
2456 }
2457 }
2458
2459 duration_str = ast_variable_retrieve(msg_cfg, "message", "duration");
2460
2461 if (!ast_strlen_zero(duration_str)) {
2462 sscanf(duration_str, "%30d", &duration);
2463 }
2464
2465 /*
2466 * IMAP messages cannot be altered once delivered. So we have to delete the
2467 * current message and then re-add it with the updated message ID.
2468 *
2469 * Furthermore, there currently is no atomic way to create a new message and to
2470 * store it in an arbitrary folder. So we have to save it to the INBOX and then
2471 * move to the appropriate folder.
2472 */
2473 if (!imap_store_file(dir, vmu->mailbox, vmu->context, msgnum, chan, vmu, vmfmts,
2474 duration, vms, ast_variable_retrieve(msg_cfg, "message", "flag"), msg_id)) {
2475 if (folder != NEW_FOLDER) {
2476 save_to_folder(vmu, vms, msgnum, folder, NULL, 1);
2477 }
2478 vm_imap_delete(dir, msgnum, vmu);
2479 }
2480 close_mailbox(vms, vmu);
2481 ast_channel_unref(chan);
2482 }
2483
2484 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
2485 {
2486 struct vm_state *vms_p;
2487 char *file, *filename;
2488 char dest[PATH_MAX];
2489 int i;
2490 BODY *body;
2491 int ret = 0;
2492 int curr_mbox;
2493
2494 /* This function is only used for retrieval of IMAP greetings
2495 * regular messages are not retrieved this way, nor are greetings
2496 * if they are stored locally*/
2497 if (msgnum > -1 || !imapgreetings) {
2498 return 0;
2499 } else {
2500 file = strrchr(ast_strdupa(dir), '/');
2501 if (file)
2502 *file++ = '\0';
2503 else {
2504 ast_debug(1, "Failed to procure file name from directory passed.\n");
2505 return -1;
2506 }
2507 }
2508
2509 /* check if someone is accessing this box right now... */
2510 if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) &&
2511 !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2512 /* Unlike when retrieving a message, it is reasonable not to be able to find a
2513 * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
2514 * that's all we need to do.
2515 */
2516 if (!(vms_p = create_vm_state_from_user(vmu))) {
2517 ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
2518 return -1;
2519 }
2520 }
2521
2522 /* Greetings will never have a prepended message */
2523 *vms_p->introfn = '\0';
2524
2525 ast_mutex_lock(&vms_p->lock);
2526
2527 /* get the current mailbox so that we can point the mailstream back to it later */
2528 curr_mbox = get_folder_by_name(vms_p->curbox);
2529
2530 if (init_mailstream(vms_p, GREETINGS_FOLDER) || !vms_p->mailstream) {
2531 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
2532 ast_mutex_unlock(&vms_p->lock);
2533 return -1;
2534 }
2535
2536 /*XXX Yuck, this could probably be done a lot better */
2537 for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
2538 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
2539 /* We have the body, now we extract the file name of the first attachment. */
2540 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
2541 char *attachment = body->nested.part->next->body.parameter->value;
2542 char copy[strlen(attachment) + 1];
2543
2544 strcpy(copy, attachment); /* safe */
2545 attachment = copy;
2546
2547 filename = strsep(&attachment, ".");
2548 if (!strcmp(filename, file)) {
2549 ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
2550 vms_p->msgArray[vms_p->curmsg] = i + 1;
2551 create_dirpath(dest, sizeof(dest), vmu->context, vms_p->username, "");
2552 save_body(body, vms_p, "2", attachment, 0);
2553 ret = 0;
2554 break;
2555 }
2556 } else {
2557 ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
2558 ret = -1;
2559 break;
2560 }
2561 }
2562
2563 if (curr_mbox != -1) {
2564 /* restore previous mbox stream */
2565 if (init_mailstream(vms_p, curr_mbox) || !vms_p->mailstream) {
2566 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
2567 ret = -1;
2568 }
2569 }
2570 ast_mutex_unlock(&vms_p->lock);
2571 return ret;
2572 }
2573
2574 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
2575 {
2576 BODY *body;
2577 char *header_content;
2578 char *attachedfilefmt;
2579 char buf[80];
2580 struct vm_state *vms;
2581 char text_file[PATH_MAX];
2582 FILE *text_file_ptr;
2583 int res = 0;
2584 struct ast_vm_user *vmu;
2585 int curr_mbox;
2586
2587 if (!(vmu = find_user(NULL, context, mailbox))) {
2588 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
2589 return -1;
2590 }
2591
2592 if (msgnum < 0) {
2593 if (imapgreetings) {
2594 res = imap_retrieve_greeting(dir, msgnum, vmu);
2595 goto exit;
2596 } else {
2597 res = 0;
2598 goto exit;
2599 }
2600 }
2601
2602 /* Before anything can happen, we need a vm_state so that we can
2603 * actually access the imap server through the vms->mailstream
2604 */
2605 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2606 /* This should not happen. If it does, then I guess we'd
2607 * need to create the vm_state, extract which mailbox to
2608 * open, and then set up the msgArray so that the correct
2609 * IMAP message could be accessed. If I have seen correctly
2610 * though, the vms should be obtainable from the vmstates list
2611 * and should have its msgArray properly set up.
2612 */
2613 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
2614 res = -1;
2615 goto exit;
2616 }
2617
2618 /* Ensure we have the correct mailbox open and have a valid mailstream for it */
2619 curr_mbox = get_folder_by_name(vms->curbox);
2620 if (curr_mbox < 0) {
2621 ast_debug(3, "Mailbox folder curbox not set, defaulting to Inbox\n");
2622 curr_mbox = 0;
2623 }
2624 init_mailstream(vms, curr_mbox);
2625 if (!vms->mailstream) {
2626 ast_log(AST_LOG_ERROR, "IMAP mailstream for %s is NULL\n", vmu->mailbox);
2627 res = -1;
2628 goto exit;
2629 }
2630
2631 make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
2632 snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
2633
2634 /* Don't try to retrieve a message from IMAP if it already is on the file system */
2635 if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
2636 res = 0;
2637 goto exit;
2638 }
2639
2640 ast_debug(3, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
2641 if (vms->msgArray[msgnum] == 0) {
2642 ast_log(LOG_WARNING, "Trying to access unknown message\n");
2643 res = -1;
2644 goto exit;
2645 }
2646
2647 /* This will only work for new messages... */
2648 ast_mutex_lock(&vms->lock);
2649 header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
2650 ast_mutex_unlock(&vms->lock);
2651 /* empty string means no valid header */
2652 if (ast_strlen_zero(header_content)) {
2653 ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
2654 res = -1;
2655 goto exit;
2656 }
2657
2658 ast_mutex_lock(&vms->lock);
2659 mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
2660 ast_mutex_unlock(&vms->lock);
2661
2662 /* We have the body, now we extract the file name of the first attachment. */
2663 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
2664 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
2665 } else {
2666 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
2667 res = -1;
2668 goto exit;
2669 }
2670
2671 /* Find the format of the attached file */
2672
2673 strsep(&attachedfilefmt, ".");
2674 if (!attachedfilefmt) {
2675 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
2676 res = -1;
2677 goto exit;
2678 }
2679
2680 save_body(body, vms, "2", attachedfilefmt, 0);
2681 if (save_body(body, vms, "3", attachedfilefmt, 1)) {
2682 *vms->introfn = '\0';
2683 }
2684
2685 /* Get info from headers!! */
2686 snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
2687
2688 if (!(text_file_ptr = fopen(text_file, "w"))) {
2689 ast_log(LOG_ERROR, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
2690 goto exit;
2691 }
2692
2693 fprintf(text_file_ptr, "%s\n", "[message]");
2694
2695 if (get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf))) {
2696 fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
2697 }
2698 if (get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf))) {
2699 fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
2700 }
2701 if (get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf))) {
2702 fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
2703 }
2704 if (get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf))) {
2705 fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
2706 }
2707 if (get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf))) {
2708 fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
2709 }
2710 if (get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf))) {
2711 fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
2712 }
2713 if (get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf))) {
2714 fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
2715 }
2716 if (get_header_by_tag(header_content, "X-Asterisk-VM-Message-ID:", buf, sizeof(buf))) {
2717 fprintf(text_file_ptr, "msg_id=%s\n", S_OR(buf, ""));
2718 }
2719 fclose(text_file_ptr);
2720
2721 exit:
2722 free_user(vmu);
2723 return res;
2724 }
2725
2726 static int folder_int(const char *folder)
2727 {
2728 /*assume a NULL folder means INBOX*/
2729 if (!folder) {
2730 return 0;
2731 }
2732 if (!strcasecmp(folder, imapfolder)) {
2733 return 0;
2734 } else if (!strcasecmp(folder, "Old")) {
2735 return 1;
2736 } else if (!strcasecmp(folder, "Work")) {
2737 return 2;
2738 } else if (!strcasecmp(folder, "Family")) {
2739 return 3;
2740 } else if (!strcasecmp(folder, "Friends")) {
2741 return 4;
2742 } else if (!strcasecmp(folder, "Cust1")) {
2743 return 5;
2744 } else if (!strcasecmp(folder, "Cust2")) {
2745 return 6;
2746 } else if (!strcasecmp(folder, "Cust3")) {
2747 return 7;
2748 } else if (!strcasecmp(folder, "Cust4")) {
2749 return 8;
2750 } else if (!strcasecmp(folder, "Cust5")) {
2751 return 9;
2752 } else if (!strcasecmp(folder, "Urgent")) {
2753 return 11;
2754 } else { /*assume they meant INBOX if folder is not found otherwise*/
2755 return 0;
2756 }
2757 }
2758
2759 static int __messagecount(const char *context, const char *mailbox, const char *folder)
2760 {
2761 SEARCHPGM *pgm;
2762 SEARCHHEADER *hdr;
2763
2764 struct ast_vm_user *vmu, vmus;
2765 struct vm_state *vms_p;
2766 int ret = 0;
2767 int fold = folder_int(folder);
2768 int urgent = 0;
2769
2770 /* If URGENT, then look at INBOX */
2771 if (fold == 11) {
2772 fold = NEW_FOLDER;
2773 urgent = 1;
2774 }
2775
2776 if (ast_strlen_zero(mailbox))
2777 return 0;
2778
2779 /* We have to get the user before we can open the stream! */
2780 memset(&vmus, 0, sizeof(vmus));
2781 vmu = find_user(&vmus, context, mailbox);
2782 if (!vmu) {
2783 ast_log(AST_LOG_WARNING, "Couldn't find mailbox %s in context %s\n", mailbox, context);
2784 free_user(vmu);
2785 return -1;
2786 } else {
2787 /* No IMAP account available */
2788 if (vmu->imapuser[0] == '\0') {
2789 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2790 free_user(vmu);
2791 return -1;
2792 }
2793 }
2794
2795 /* No IMAP account available */
2796 if (vmu->imapuser[0] == '\0') {
2797 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2798 free_user(vmu);
2799 return -1;
2800 }
2801
2802 /* check if someone is accessing this box right now... */
2803 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
2804 if (!vms_p) {
2805 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
2806 }
2807 if (vms_p) {
2808 ast_debug(3, "Returning before search - user is logged in\n");
2809 if (fold == 0) { /* INBOX */
2810 free_user(vmu);
2811 return urgent ? vms_p->urgentmessages : vms_p->newmessages;
2812 }
2813 if (fold == 1) { /* Old messages */
2814 free_user(vmu);
2815 return vms_p->oldmessages;
2816 }
2817 }
2818
2819 /* add one if not there... */
2820 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
2821 if (!vms_p) {
2822 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
2823 }
2824
2825 if (!vms_p) {
2826 vms_p = create_vm_state_from_user(vmu);
2827 }
2828 ret = init_mailstream(vms_p, fold);
2829 if (!vms_p->mailstream) {
2830 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
2831 free_user(vmu);
2832 return -1;
2833 }
2834 if (ret == 0) {
2835 ast_mutex_lock(&vms_p->lock);
2836 pgm = mail_newsearchpgm ();
2837 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
2838 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
2839 pgm->header = hdr;
2840 if (fold != OLD_FOLDER) {
2841 pgm->unseen = 1;
2842 pgm->seen = 0;
2843 }
2844 /* In the special case where fold is 1 (old messages) we have to do things a bit
2845 * differently. Old messages are stored in the INBOX but are marked as "seen"
2846 */
2847 else {
2848 pgm->unseen = 0;
2849 pgm->seen = 1;
2850 }
2851 /* look for urgent messages */
2852 if (fold == NEW_FOLDER) {
2853 if (urgent) {
2854 pgm->flagged = 1;
2855 pgm->unflagged = 0;
2856 } else {
2857 pgm->flagged = 0;
2858 pgm->unflagged = 1;
2859 }
2860 }
2861 pgm->undeleted = 1;
2862 pgm->deleted = 0;
2863
2864 vms_p->vmArrayIndex = 0;
2865 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
2866 if (fold == 0 && urgent == 0)
2867 vms_p->newmessages = vms_p->vmArrayIndex;
2868 if (fold == 1)
2869 vms_p->oldmessages = vms_p->vmArrayIndex;
2870 if (fold == 0 && urgent == 1)
2871 vms_p->urgentmessages = vms_p->vmArrayIndex;
2872 /*Freeing the searchpgm also frees the searchhdr*/
2873 mail_free_searchpgm(&pgm);
2874 ast_mutex_unlock(&vms_p->lock);
2875 free_user(vmu);
2876 vms_p->updated = 0;
2877 return vms_p->vmArrayIndex;
2878 } else {
2879 ast_mutex_lock(&vms_p->lock);
2880 mail_ping(vms_p->mailstream);
2881 ast_mutex_unlock(&vms_p->lock);
2882 }
2883 free_user(vmu);
2884 return 0;
2885 }
2886
2887 static int imap_check_limits(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu, int msgnum)
2888 {
2889 /* Check if mailbox is full */
2890 check_quota(vms, vmu->imapfolder);
2891 if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
2892 ast_debug(1, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
2893 if (chan) {
2894 ast_play_and_wait(chan, "vm-mailboxfull");
2895 }
2896 return -1;
2897 }
2898
2899 /* Check if we have exceeded maxmsg */
2900 ast_debug(3, "Checking message number quota: mailbox has %d messages, maximum is set to %d, current messages %d\n", msgnum, vmu->maxmsg, inprocess_count(vmu->mailbox, vmu->context, 0));
2901 if (msgnum >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
2902 ast_log(LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u >= %u)\n", msgnum, vmu->maxmsg);
2903 if (chan) {
2904 ast_play_and_wait(chan, "vm-mailboxfull");
2905 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
2906 }
2907 return -1;
2908 }
2909
2910 return 0;
2911 }
2912
2913 /*!
2914 * \brief Gets the number of messages that exist in a mailbox folder.
2915 * \param mailbox_id
2916 * \param folder
2917 *
2918 * This method is used when IMAP backend is used.
2919 * \return The number of messages in this mailbox folder (zero or more).
2920 */
2921 static int messagecount(const char *mailbox_id, const char *folder)
2922 {
2923 char *context;
2924 char *mailbox;
2925 int count;
2926
2927 if (ast_strlen_zero(mailbox_id)
2928 || separate_mailbox(ast_strdupa(mailbox_id), &mailbox, &context)) {
2929 return 0;
2930 }
2931
2932 if (ast_strlen_zero(folder) || !strcmp(folder, "INBOX")) {
2933 count = __messagecount(context, mailbox, "INBOX") + __messagecount(context, mailbox, "Urgent");
2934 } else {
2935 count = __messagecount(context, mailbox, folder);
2936 }
2937 return count < 0 ? 0 : count;
2938 }
2939
2940 static int imap_store_file(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms, const char *flag, const char *msg_id)
2941 {
2942 char *myserveremail = serveremail;
2943 char fn[PATH_MAX];
2944 char introfn[PATH_MAX];
2945 char mailbox[256];
2946 char *stringp;
2947 FILE *p = NULL;
2948 char tmp[80] = "/tmp/astmail-XXXXXX";
2949 long len;
2950 void *buf;
2951 int tempcopy = 0;
2952 STRING str;
2953 int ret; /* for better error checking */
2954 char *imap_flags = NIL;
2955 int msgcount;
2956 int box = NEW_FOLDER;
2957
2958 snprintf(mailbox, sizeof(mailbox), "%s@%s", vmu->mailbox, vmu->context);
2959 msgcount = messagecount(mailbox, "INBOX") + messagecount(mailbox, "Old");
2960
2961 /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
2962 if (msgnum < 0) {
2963 if(!imapgreetings) {
2964 return 0;
2965 } else {
2966 box = GREETINGS_FOLDER;
2967 }
2968 }
2969
2970 if (imap_check_limits(chan, vms, vmu, msgcount)) {
2971 return -1;
2972 }
2973
2974 /* Set urgent flag for IMAP message */
2975 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
2976 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
2977 imap_flags = "\\FLAGGED";
2978 }
2979
2980 /* Attach only the first format */
2981 fmt = ast_strdupa(fmt);
2982 stringp = fmt;
2983 strsep(&stringp, "|");
2984
2985 if (!ast_strlen_zero(vmu->serveremail))
2986 myserveremail = vmu->serveremail;
2987
2988 if (msgnum > -1)
2989 make_file(fn, sizeof(fn), dir, msgnum);
2990 else
2991 ast_copy_string (fn, dir, sizeof(fn));
2992
2993 snprintf(introfn, sizeof(introfn), "%sintro", fn);
2994 if (ast_fileexists(introfn, NULL, NULL) <= 0) {
2995 *introfn = '\0';
2996 }
2997
2998 if (ast_strlen_zero(vmu->email)) {
2999 /* We need the vmu->email to be set when we call make_email_file, but
3000 * if we keep it set, a duplicate e-mail will be created. So at the end
3001 * of this function, we will revert back to an empty string if tempcopy
3002 * is 1.
3003 */
3004 vmu->email = ast_strdup(vmu->imapuser);
3005 tempcopy = 1;
3006 }
3007
3008 if (!strcmp(fmt, "wav49"))
3009 fmt = "WAV";
3010 ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
3011
3012 /* Make a temporary file instead of piping directly to sendmail, in case the mail
3013 command hangs. */
3014 if (!(p = ast_file_mkftemp(tmp, VOICEMAIL_FILE_MODE & ~my_umask))) {
3015 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
3016 if (tempcopy) {
3017 ast_free(vmu->email);
3018 vmu->email = NULL;
3019 }
3020 return -1;
3021 }
3022
3023 if (msgnum < 0 && imapgreetings) {
3024 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
3025 ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
3026 return -1;
3027 }
3028 imap_delete_old_greeting(fn, vms);
3029 }
3030
3031 make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, "INBOX",
3032 chan ? S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL) : NULL,
3033 chan ? S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL) : NULL,
3034 fn, introfn, fmt, duration, 1, chan, NULL, 1, flag, msg_id);
3035 /* read mail file to memory */
3036 len = ftell(p);
3037 rewind(p);
3038 if (!(buf = ast_malloc(len + 1))) {
3039 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
3040 fclose(p);
3041 if (tempcopy)
3042 *(vmu->email) = '\0';
3043 return -1;
3044 }
3045 if (fread(buf, 1, len, p) != len) {
3046 if (ferror(p)) {
3047 ast_log(LOG_ERROR, "Error while reading mail file: %s\n", tmp);
3048 return -1;
3049 }
3050 }
3051 ((char *) buf)[len] = '\0';
3052 INIT(&str, mail_string, buf, len);
3053 ret = init_mailstream(vms, box);
3054 if (ret == 0) {
3055 imap_mailbox_name(mailbox, sizeof(mailbox), vms, box, 1);
3056 ast_mutex_lock(&vms->lock);
3057 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
3058 ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
3059 ast_mutex_unlock(&vms->lock);
3060 fclose(p);
3061 unlink(tmp);
3062 ast_free(buf);
3063 } else {
3064 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
3065 fclose(p);
3066 unlink(tmp);
3067 ast_free(buf);
3068 return -1;
3069 }
3070 ast_debug(3, "%s stored\n", fn);
3071
3072 if (tempcopy)
3073 *(vmu->email) = '\0';
3074 inprocess_count(vmu->mailbox, vmu->context, -1);
3075 return 0;
3076
3077 }
3078
3079 /*!
3080 * \brief Gets the number of messages that exist in the inbox folder.
3081 * \param mailbox_context
3082 * \param newmsgs The variable that is updated with the count of new messages within this inbox.
3083 * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
3084 * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
3085 *
3086 * This method is used when IMAP backend is used.
3087 * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
3088 *
3089 * \return zero on success, -1 on error.
3090 */
3091
3092 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
3093 {
3094 char tmp[PATH_MAX] = "";
3095 char *mailboxnc;
3096 char *context;
3097 char *mb;
3098 char *cur;
3099 int count = 0;
3100 if (newmsgs)
3101 *newmsgs = 0;
3102 if (oldmsgs)
3103 *oldmsgs = 0;
3104 if (urgentmsgs)
3105 *urgentmsgs = 0;
3106
3107 ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
3108 /* If no mailbox, return immediately */
3109 if (ast_strlen_zero(mailbox_context))
3110 return 0;
3111
3112 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
3113 context = strchr(tmp, '@');
3114 if (strchr(mailbox_context, ',')) {
3115 int tmpnew, tmpold, tmpurgent;
3116 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
3117 mb = tmp;
3118 while ((cur = strsep(&mb, ", "))) {
3119 if (!ast_strlen_zero(cur)) {
3120 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
3121 return -1;
3122 else {
3123 if (newmsgs)
3124 *newmsgs += tmpnew;
3125 if (oldmsgs)
3126 *oldmsgs += tmpold;
3127 if (urgentmsgs)
3128 *urgentmsgs += tmpurgent;
3129 }
3130 }
3131 }
3132 return 0;
3133 }
3134 if (context) {
3135 *context = '\0';
3136 mailboxnc = tmp;
3137 context++;
3138 } else {
3139 context = "default";
3140 mailboxnc = (char *) mailbox_context;
3141 }
3142
3143 if (newmsgs) {
3144 struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
3145 if (!vmu) {
3146 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
3147 return -1;
3148 }
3149 if ((count = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
3150 free_user(vmu);
3151 return -1;
3152 }
3153 *newmsgs = count;
3154 free_user(vmu);
3155 }
3156 if (oldmsgs) {
3157 if ((count = __messagecount(context, mailboxnc, "Old")) < 0) {
3158 return -1;
3159 }
3160 *oldmsgs = count;
3161 }
3162 if (urgentmsgs) {
3163 if ((count = __messagecount(context, mailboxnc, "Urgent")) < 0) {
3164 return -1;
3165 }
3166 *urgentmsgs = count;
3167 }
3168 return 0;
3169 }
3170
3171 /*!
3172 * \brief Determines if the given folder has messages.
3173 * \param mailbox The \@ delimited string for user\@context. If no context is found, uses 'default' for the context.
3174 * \param folder the folder to look in
3175 *
3176 * This function is used when the mailbox is stored in an IMAP back end.
3177 * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
3178 * \return 1 if the folder has one or more messages. zero otherwise.
3179 */
3180
3181 static int has_voicemail(const char *mailbox, const char *folder)
3182 {
3183 char tmp[256], *tmp2, *box, *context;
3184 ast_copy_string(tmp, mailbox, sizeof(tmp));
3185 tmp2 = tmp;
3186 if (strchr(tmp2, ',') || strchr(tmp2, '&')) {
3187 while ((box = strsep(&tmp2, ",&"))) {
3188 if (!ast_strlen_zero(box)) {
3189 if (has_voicemail(box, folder)) {
3190 return 1;
3191 }
3192 }
3193 }
3194 }
3195 if ((context = strchr(tmp, '@'))) {
3196 *context++ = '\0';
3197 } else {
3198 context = "default";
3199 }
3200 return __messagecount(context, tmp, folder) > 0 ? 1 : 0;
3201 }
3202
3203 /*!
3204 * \brief Copies a message from one mailbox to another.
3205 * \param chan
3206 * \param vmu
3207 * \param imbox
3208 * \param msgnum
3209 * \param duration
3210 * \param recip
3211 * \param fmt
3212 * \param dir
3213 * \param flag, dest_folder
3214 *
3215 * This works with IMAP storage based mailboxes.
3216 *
3217 * \return zero on success, -1 on error.
3218 */
3219 static int copy_message(struct ast_channel *chan, struct ast_vm_user *vmu, int imbox, int msgnum, long duration, struct ast_vm_user *recip, char *fmt, char *dir, char *flag, const char *dest_folder)
3220 {
3221 struct vm_state *sendvms = NULL;
3222 char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
3223 if (msgnum >= recip->maxmsg) {
3224 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
3225 return -1;
3226 }
3227 if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
3228 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
3229 return -1;
3230 }
3231 if (!get_vm_state_by_imapuser(recip->imapuser, 0)) {
3232 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
3233 return -1;
3234 }
3235 snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
3236 ast_mutex_lock(&sendvms->lock);
3237 if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
3238 ast_mutex_unlock(&sendvms->lock);
3239 return 0;
3240 }
3241 ast_mutex_unlock(&sendvms->lock);
3242 ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
3243 return -1;
3244 }
3245
3246 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
3247 {
3248 char tmp[256], *t = tmp;
3249 size_t left = sizeof(tmp);
3250
3251 if (box == OLD_FOLDER) {
3252 ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
3253 } else {
3254 ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
3255 }
3256
3257 if (box == NEW_FOLDER) {
3258 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
3259 } else {
3260 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
3261 }
3262
3263 /* Build up server information */
3264 ast_build_string(&t, &left, "{%s:%s/imap", S_OR(vms->imapserver, imapserver), S_OR(vms->imapport, imapport));
3265
3266 /* Add authentication user if present */
3267 if (!ast_strlen_zero(authuser))
3268 ast_build_string(&t, &left, "/authuser=%s", authuser);
3269
3270 /* Add flags if present */
3271 if (!ast_strlen_zero(imapflags) || !(ast_strlen_zero(vms->imapflags))) {
3272 ast_build_string(&t, &left, "/%s", S_OR(vms->imapflags, imapflags));
3273 }
3274
3275 /* End with username */
3276 #if 1
3277 ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
3278 #else
3279 ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
3280 #endif
3281 if (box == NEW_FOLDER || box == OLD_FOLDER)
3282 snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
3283 else if (box == GREETINGS_FOLDER)
3284 snprintf(spec, len, "%s%s", tmp, greetingfolder);
3285 else { /* Other folders such as Friends, Family, etc... */
3286 if (!ast_strlen_zero(imapparentfolder)) {
3287 /* imapparentfolder would typically be set to INBOX */
3288 snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
3289 } else {
3290 snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
3291 }
3292 }
3293 }
3294
3295 static int init_mailstream(struct vm_state *vms, int box)
3296 {
3297 MAILSTREAM *stream = NIL;
3298 long debug;
3299 char tmp[256];
3300
3301 if (!vms) {
3302 ast_log(LOG_ERROR, "vm_state is NULL!\n");
3303 return -1;
3304 }
3305 ast_debug(3, "vm_state user is:%s\n", vms->imapuser);
3306 if (vms->mailstream == NIL || !vms->mailstream) {
3307 ast_debug(1, "mailstream not set.\n");
3308 } else {
3309 stream = vms->mailstream;
3310 }
3311 /* debug = T; user wants protocol telemetry? */
3312 debug = NIL; /* NO protocol telemetry? */
3313
3314 if (delimiter == '\0') { /* did not probe the server yet */
3315 char *cp;
3316 #ifdef USE_SYSTEM_IMAP
3317 #include <imap/linkage.c>
3318 #elif defined(USE_SYSTEM_CCLIENT)
3319 #include <c-client/linkage.c>
3320 #else
3321 #include "linkage.c"
3322 #endif
3323 /* Connect to INBOX first to get folders delimiter */
3324 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
3325 ast_mutex_lock(&vms->lock);
3326 ast_mutex_lock(&mail_open_lock);
3327 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
3328 ast_mutex_unlock(&mail_open_lock);
3329 ast_mutex_unlock(&vms->lock);
3330 if (stream == NIL) {
3331 ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
3332 return -1;
3333 }
3334 get_mailbox_delimiter(vms, stream);
3335 /* update delimiter in imapfolder */
3336 for (cp = vms->imapfolder; *cp; cp++)
3337 if (*cp == '/')
3338 *cp = delimiter;
3339 }
3340 /* Now connect to the target folder */
3341 imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
3342 ast_debug(3, "Before mail_open, server: %s, box:%d\n", tmp, box);
3343 ast_mutex_lock(&vms->lock);
3344 ast_mutex_lock(&mail_open_lock);
3345 vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
3346 /* Create the folder if it doesn't exist */
3347 if (vms->mailstream && !mail_status(vms->mailstream, tmp, SA_UIDNEXT)) {
3348 mail_create(vms->mailstream, tmp);
3349 }
3350 ast_mutex_unlock(&mail_open_lock);
3351 ast_mutex_unlock(&vms->lock);
3352 if (vms->mailstream == NIL) {
3353 return -1;
3354 } else {
3355 return 0;
3356 }
3357 }
3358
3359 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
3360 {
3361 SEARCHPGM *pgm;
3362 SEARCHHEADER *hdr;
3363 int urgent = 0;
3364
3365 /* If Urgent, then look at INBOX */
3366 if (box == 11) {
3367 box = NEW_FOLDER;
3368 urgent = 1;
3369 }
3370
3371 ast_copy_string(vms->imapuser, vmu->imapuser, sizeof(vms->imapuser));
3372 ast_copy_string(vms->imapfolder, vmu->imapfolder, sizeof(vms->imapfolder));
3373 ast_copy_string(vms->imapserver, vmu->imapserver, sizeof(vms->imapserver));
3374 ast_copy_string(vms->imapport, vmu->imapport, sizeof(vms->imapport));
3375 ast_copy_string(vms->imapflags, vmu->imapflags, sizeof(vms->imapflags));
3376 vms->imapversion = vmu->imapversion;
3377 ast_debug(3, "Before init_mailstream, user is %s\n", vmu->imapuser);
3378
3379 if (init_mailstream(vms, box) || !vms->mailstream) {
3380 ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
3381 return -1;
3382 }
3383
3384 create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
3385
3386 /* Check Quota */
3387 if (box == 0) {
3388 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(vmu, box));
3389 check_quota(vms, (char *) mbox(vmu, box));
3390 }
3391
3392 ast_mutex_lock(&vms->lock);
3393 pgm = mail_newsearchpgm();
3394
3395 /* Check IMAP folder for Asterisk messages only... */
3396 hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : vmu->mailbox));
3397 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", vmu->context);
3398 pgm->header = hdr;
3399 pgm->deleted = 0;
3400 pgm->undeleted = 1;
3401
3402 /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
3403 if (box == NEW_FOLDER && urgent == 1) {
3404 pgm->unseen = 1;
3405 pgm->seen = 0;
3406 pgm->flagged = 1;
3407 pgm->unflagged = 0;
3408 } else if (box == NEW_FOLDER && urgent == 0) {
3409 pgm->unseen = 1;
3410 pgm->seen = 0;
3411 pgm->flagged = 0;
3412 pgm->unflagged = 1;
3413 } else if (box == OLD_FOLDER) {
3414 pgm->seen = 1;
3415 pgm->unseen = 0;
3416 }
3417
3418 ast_debug(3, "Before mail_search_full, user is %s\n", vmu->imapuser);
3419
3420 vms->vmArrayIndex = 0;
3421 mail_search_full (vms->mailstream, NULL, pgm, NIL);
3422 vms->lastmsg = vms->vmArrayIndex - 1;
3423 mail_free_searchpgm(&pgm);
3424 /* Since IMAP storage actually stores both old and new messages in the same IMAP folder,
3425 * ensure to allocate enough space to account for all of them. Warn if old messages
3426 * have not been checked first as that is required.
3427 */
3428 if (box == 0 && !vms->dh_arraysize) {
3429 ast_log(LOG_WARNING, "The code expects the old messages to be checked first, fix the code.\n");
3430 }
3431 if (vm_allocate_dh(vms, vmu, box == 0 ? vms->vmArrayIndex + vms->oldmessages : vms->lastmsg)) {
3432 ast_mutex_unlock(&vms->lock);
3433 return -1;
3434 }
3435
3436 ast_mutex_unlock(&vms->lock);
3437 return 0;
3438 }
3439
3440 static void write_file(char *filename, char *buffer, unsigned long len)
3441 {
3442 FILE *output;
3443
3444 if (!filename || !buffer) {
3445 return;
3446 }
3447
3448 if (!(output = fopen(filename, "w"))) {
3449 ast_log(LOG_ERROR, "Unable to open/create file %s: %s\n", filename, strerror(errno));
3450 return;
3451 }
3452
3453 if (fwrite(buffer, len, 1, output) != 1) {
3454 if (ferror(output)) {
3455 ast_log(LOG_ERROR, "Short write while writing e-mail body: %s.\n", strerror(errno));
3456 }
3457 }
3458 fclose (output);
3459 }
3460
3461 static void update_messages_by_imapuser(const char *user, unsigned long number)
3462 {
3463 struct vm_state *vms = get_vm_state_by_imapuser(user, 1);
3464
3465 if (!vms && !(vms = get_vm_state_by_imapuser(user, 0))) {
3466 return;
3467 }
3468
3469 ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vms->vmArrayIndex, vms->interactive);
3470
3471 /* Ensure we have room for the next message. */
3472 if (vms->vmArrayIndex >= vms->msg_array_max) {
3473 long *new_mem = ast_realloc(vms->msgArray, 2 * vms->msg_array_max * sizeof(long));
3474 if (!new_mem) {
3475 return;
3476 }
3477 vms->msgArray = new_mem;
3478 vms->msg_array_max *= 2;
3479 }
3480
3481 vms->msgArray[vms->vmArrayIndex++] = number;
3482 }
3483
3484 void mm_searched(MAILSTREAM *stream, unsigned long number)
3485 {
3486 char *mailbox = stream->mailbox, buf[1024] = "", *user;
3487
3488 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
3489 return;
3490
3491 update_messages_by_imapuser(user, number);
3492 }
3493
3494 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
3495 {
3496 struct ast_variable *var;
3497 struct ast_vm_user *vmu;
3498
3499 vmu = ast_calloc(1, sizeof *vmu);
3500 if (!vmu)
3501 return NULL;
3502
3503 populate_defaults(vmu);
3504 ast_set_flag(vmu, VM_ALLOCED);
3505
3506 var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
3507 if (var) {
3508 apply_options_full(vmu, var);
3509 ast_variables_destroy(var);
3510 return vmu;
3511 } else {
3512 ast_free(vmu);
3513 return NULL;
3514 }
3515 }
3516
3517 /* Interfaces to C-client */
3518
3519 void mm_exists(MAILSTREAM * stream, unsigned long number)
3520 {
3521 /* mail_ping will callback here if new mail! */
3522 ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
3523 if (number == 0) return;
3524 set_update(stream);
3525 }
3526
3527
3528 void mm_expunged(MAILSTREAM * stream, unsigned long number)
3529 {
3530 /* mail_ping will callback here if expunged mail! */
3531 ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
3532 if (number == 0) return;
3533 set_update(stream);
3534 }
3535
3536
3537 void mm_flags(MAILSTREAM * stream, unsigned long number)
3538 {
3539 /* mail_ping will callback here if read mail! */
3540 ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
3541 if (number == 0) return;
3542 set_update(stream);
3543 }
3544
3545
3546 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
3547 {
3548 ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
3549 mm_log (string, errflg);
3550 }
3551
3552
3553 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
3554 {
3555 if (delimiter == '\0') {
3556 delimiter = delim;
3557 }
3558
3559 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
3560 if (attributes & LATT_NOINFERIORS)
3561 ast_debug(5, "no inferiors\n");
3562 if (attributes & LATT_NOSELECT)
3563 ast_debug(5, "no select\n");
3564 if (attributes & LATT_MARKED)
3565 ast_debug(5, "marked\n");
3566 if (attributes & LATT_UNMARKED)
3567 ast_debug(5, "unmarked\n");
3568 }
3569
3570
3571 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
3572 {
3573 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
3574 if (attributes & LATT_NOINFERIORS)
3575 ast_debug(5, "no inferiors\n");
3576 if (attributes & LATT_NOSELECT)
3577 ast_debug(5, "no select\n");
3578 if (attributes & LATT_MARKED)
3579 ast_debug(5, "marked\n");
3580 if (attributes & LATT_UNMARKED)
3581 ast_debug(5, "unmarked\n");
3582 }
3583
3584
3585 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
3586 {
3587 struct ast_str *str;
3588
3589 if (!DEBUG_ATLEAST(5) || !(str = ast_str_create(256))) {
3590 return;
3591 }
3592
3593 ast_str_append(&str, 0, " Mailbox %s", mailbox);
3594 if (status->flags & SA_MESSAGES) {
3595 ast_str_append(&str, 0, ", %lu messages", status->messages);
3596 }
3597 if (status->flags & SA_RECENT) {
3598 ast_str_append(&str, 0, ", %lu recent", status->recent);
3599 }
3600 if (status->flags & SA_UNSEEN) {
3601 ast_str_append(&str, 0, ", %lu unseen", status->unseen);
3602 }
3603 if (status->flags & SA_UIDVALIDITY) {
3604 ast_str_append(&str, 0, ", %lu UID validity", status->uidvalidity);
3605 }
3606 if (status->flags & SA_UIDNEXT) {
3607 ast_str_append(&str, 0, ", %lu next UID", status->uidnext);
3608 }
3609 ast_log(LOG_DEBUG, "%s\n", ast_str_buffer(str));
3610
3611 ast_free(str);
3612 }
3613
3614
3615 void mm_log(char *string, long errflg)
3616 {
3617 switch ((short) errflg) {
3618 case NIL:
3619 ast_debug(1, "IMAP Info: %s\n", string);
3620 break;
3621 case PARSE:
3622 case WARN:
3623 ast_log(AST_LOG_WARNING, "IMAP Warning: %s\n", string);
3624 break;
3625 case ERROR:
3626 ast_log(AST_LOG_ERROR, "IMAP Error: %s\n", string);
3627 break;
3628 }
3629 }
3630
3631
3632 void mm_dlog(char *string)
3633 {
3634 ast_log(AST_LOG_NOTICE, "%s\n", string);
3635 }
3636
3637
3638 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
3639 {
3640 struct ast_vm_user *vmu;
3641
3642 ast_debug(4, "Entering callback mm_login\n");
3643
3644 ast_copy_string(user, mb->user, MAILTMPLEN);
3645
3646 /* We should only do this when necessary */
3647 if (!ast_strlen_zero(authpassword)) {
3648 ast_copy_string(pwd, authpassword, MAILTMPLEN);
3649 } else {
3650 AST_LIST_TRAVERSE(&users, vmu, list) {
3651 if (!strcasecmp(mb->user, vmu->imapuser)) {
3652 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
3653 break;
3654 }
3655 }
3656 if (!vmu) {
3657 if ((vmu = find_user_realtime_imapuser(mb->user))) {
3658 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
3659 free_user(vmu);
3660 }
3661 }
3662 }
3663 }
3664
3665
3666 void mm_critical(MAILSTREAM * stream)
3667 {
3668 }
3669
3670
3671 void mm_nocritical(MAILSTREAM * stream)
3672 {
3673 }
3674
3675
3676 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
3677 {
3678 kill (getpid (), SIGSTOP);
3679 return NIL;
3680 }
3681
3682
3683 void mm_fatal(char *string)
3684 {
3685 ast_log(AST_LOG_ERROR, "IMAP access FATAL error: %s\n", string);
3686 }
3687
3688 /* C-client callback to handle quota */
3689 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
3690 {
3691 struct vm_state *vms;
3692 char *mailbox = stream->mailbox, *user;
3693 char buf[1024] = "";
3694 unsigned long usage = 0, limit = 0;
3695
3696 while (pquota) {
3697 usage = pquota->usage;
3698 limit = pquota->limit;
3699 pquota = pquota->next;
3700 }
3701
3702 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || (!(vms = get_vm_state_by_imapuser(user, 2)) && !(vms = get_vm_state_by_imapuser(user, 0)))) {
3703 ast_log(AST_LOG_ERROR, "No state found.\n");
3704 return;
3705 }
3706
3707 ast_debug(3, "User %s usage is %lu, limit is %lu\n", user, usage, limit);
3708
3709 vms->quota_usage = usage;
3710 vms->quota_limit = limit;
3711 }
3712
3713 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len)
3714 {
3715 char *start, *eol_pnt;
3716 int taglen;
3717
3718 if (ast_strlen_zero(header) || ast_strlen_zero(tag))
3719 return NULL;
3720
3721 taglen = strlen(tag) + 1;
3722 if (taglen < 1)
3723 return NULL;
3724
3725 if (!(start = strcasestr(header, tag)))
3726 return NULL;
3727
3728 /* Since we can be called multiple times we should clear our buffer */
3729 memset(buf, 0, len);
3730
3731 ast_copy_string(buf, start+taglen, len);
3732 if ((eol_pnt = strchr(buf,'\r')) || (eol_pnt = strchr(buf,'\n')))
3733 *eol_pnt = '\0';
3734 return buf;
3735 }
3736
3737 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len)
3738 {
3739 char *start, *eol_pnt, *quote;
3740
3741 if (ast_strlen_zero(mailbox))
3742 return NULL;
3743
3744 if (!(start = strstr(mailbox, "/user=")))
3745 return NULL;
3746
3747 ast_copy_string(buf, start+6, len);
3748
3749 if (!(quote = strchr(buf, '"'))) {
3750 if ((eol_pnt = strchr(buf, '/')) || (eol_pnt = strchr(buf, '}'))) {
3751 *eol_pnt = '\0';
3752 }
3753 return buf;
3754 } else {
3755 if ((eol_pnt = strchr(quote + 1, '"'))) {
3756 *eol_pnt = '\0';
3757 }
3758 return quote + 1;
3759 }
3760 }
3761
3762 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
3763 {
3764 struct vm_state *vms_p;
3765
3766 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
3767 if ((vms_p = pthread_getspecific(ts_vmstate.key)) && !strcmp(vms_p->imapuser, vmu->imapuser) && !strcmp(vms_p->username, vmu->mailbox)) {
3768 return vms_p;
3769 }
3770 ast_debug(5, "Adding new vmstate for %s\n", vmu->imapuser);
3771 /* XXX: Is this correctly freed always? */
3772 if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
3773 return NULL;
3774 ast_copy_string(vms_p->imapuser, vmu->imapuser, sizeof(vms_p->imapuser));
3775 ast_copy_string(vms_p->imapfolder, vmu->imapfolder, sizeof(vms_p->imapfolder));
3776 ast_copy_string(vms_p->imapserver, vmu->imapserver, sizeof(vms_p->imapserver));
3777 ast_copy_string(vms_p->imapport, vmu->imapport, sizeof(vms_p->imapport));
3778 ast_copy_string(vms_p->imapflags, vmu->imapflags, sizeof(vms_p->imapflags));
3779 ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
3780 ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
3781 vms_p->mailstream = NIL; /* save for access from interactive entry point */
3782 vms_p->imapversion = vmu->imapversion;
3783 ast_debug(5, "Copied %s to %s\n", vmu->imapuser, vms_p->imapuser);
3784 vms_p->updated = 1;
3785 /* set mailbox to INBOX! */
3786 ast_copy_string(vms_p->curbox, mbox(vmu, 0), sizeof(vms_p->curbox));
3787 init_vm_state(vms_p);
3788 vmstate_insert(vms_p);
3789 return vms_p;
3790 }
3791
3792 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive)
3793 {
3794 struct vmstate *vlist = NULL;
3795
3796 if (interactive) {
3797 struct vm_state *vms;
3798 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
3799 if ((vms = pthread_getspecific(ts_vmstate.key)) && !strcmp(vms->imapuser, user)) {
3800 return vms;
3801 }
3802 }
3803
3804 AST_LIST_LOCK(&vmstates);
3805 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
3806 if (!vlist->vms) {
3807 ast_debug(3, "error: vms is NULL for %s\n", user);
3808 continue;
3809 }
3810 if (vlist->vms->imapversion != imapversion) {
3811 continue;
3812 }
3813
3814 if (!strcmp(vlist->vms->imapuser, user) && (interactive == 2 || vlist->vms->interactive == interactive)) {
3815 AST_LIST_UNLOCK(&vmstates);
3816 return vlist->vms;
3817 }
3818 }
3819 AST_LIST_UNLOCK(&vmstates);
3820
3821 ast_debug(3, "%s not found in vmstates\n", user);
3822
3823 return NULL;
3824 }
3825
3826 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
3827 {
3828
3829 struct vmstate *vlist = NULL;
3830 const char *local_context = S_OR(context, "default");
3831
3832 if (interactive) {
3833 struct vm_state *vms;
3834 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
3835 if ((vms = pthread_getspecific(ts_vmstate.key)) &&
3836 !strcmp(vms->username,mailbox) && !strcmp(vms->context, local_context)) {
3837 return vms;
3838 }
3839 }
3840
3841 AST_LIST_LOCK(&vmstates);
3842 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
3843 if (!vlist->vms) {
3844 ast_debug(3, "error: vms is NULL for %s\n", mailbox);
3845 continue;
3846 }
3847 if (vlist->vms->imapversion != imapversion) {
3848 continue;
3849 }
3850
3851 ast_debug(3, "comparing mailbox %s@%s (i=%d) to vmstate mailbox %s@%s (i=%d)\n", mailbox, local_context, interactive, vlist->vms->username, vlist->vms->context, vlist->vms->interactive);
3852
3853 if (!strcmp(vlist->vms->username, mailbox) && !strcmp(vlist->vms->context, local_context) && vlist->vms->interactive == interactive) {
3854 ast_debug(3, "Found it!\n");
3855 AST_LIST_UNLOCK(&vmstates);
3856 return vlist->vms;
3857 }
3858 }
3859 AST_LIST_UNLOCK(&vmstates);
3860
3861 ast_debug(3, "%s not found in vmstates\n", mailbox);
3862
3863 return NULL;
3864 }
3865
3866 static void vmstate_insert(struct vm_state *vms)
3867 {
3868 struct vmstate *v;
3869 struct vm_state *altvms;
3870
3871 /* If interactive, it probably already exists, and we should
3872 use the one we already have since it is more up to date.
3873 We can compare the username to find the duplicate */
3874 if (vms->interactive == 1) {
3875 altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
3876 if (altvms) {
3877 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
3878 vms->newmessages = altvms->newmessages;
3879 vms->oldmessages = altvms->oldmessages;
3880 vms->vmArrayIndex = altvms->vmArrayIndex;
3881 /* XXX: no msgArray copying? */
3882 vms->lastmsg = altvms->lastmsg;
3883 vms->curmsg = altvms->curmsg;
3884 /* get a pointer to the persistent store */
3885 vms->persist_vms = altvms;
3886 /* Reuse the mailstream? */
3887 #ifdef REALLY_FAST_EVEN_IF_IT_MEANS_RESOURCE_LEAKS
3888 vms->mailstream = altvms->mailstream;
3889 #else
3890 vms->mailstream = NIL;
3891 #endif
3892 }
3893 return;
3894 }
3895
3896 if (!(v = ast_calloc(1, sizeof(*v))))
3897 return;
3898
3899 v->vms = vms;
3900
3901 ast_debug(3, "Inserting vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3902
3903 AST_LIST_LOCK(&vmstates);
3904 AST_LIST_INSERT_TAIL(&vmstates, v, list);
3905 AST_LIST_UNLOCK(&vmstates);
3906 }
3907
3908 static void vmstate_delete(struct vm_state *vms)
3909 {
3910 struct vmstate *vc = NULL;
3911 struct vm_state *altvms = NULL;
3912
3913 /* If interactive, we should copy pertinent info
3914 back to the persistent state (to make update immediate) */
3915 if (vms->interactive == 1 && (altvms = vms->persist_vms)) {
3916 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
3917 altvms->newmessages = vms->newmessages;
3918 altvms->oldmessages = vms->oldmessages;
3919 altvms->updated = 1;
3920 vms->mailstream = mail_close(vms->mailstream);
3921
3922 /* Interactive states are not stored within the persistent list */
3923 return;
3924 }
3925
3926 ast_debug(3, "Removing vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3927
3928 AST_LIST_LOCK(&vmstates);
3929 AST_LIST_TRAVERSE_SAFE_BEGIN(&vmstates, vc, list) {
3930 if (vc->vms == vms) {
3931 AST_LIST_REMOVE_CURRENT(list);
3932 break;
3933 }
3934 }
3935 AST_LIST_TRAVERSE_SAFE_END
3936 AST_LIST_UNLOCK(&vmstates);
3937
3938 if (vc) {
3939 ast_mutex_destroy(&vc->vms->lock);
3940 ast_free(vc->vms->msgArray);
3941 vc->vms->msgArray = NULL;
3942 vc->vms->msg_array_max = 0;
3943 /* XXX: is no one supposed to free vms itself? */
3944 ast_free(vc);
3945 } else {
3946 ast_log(AST_LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3947 }
3948 }
3949
3950 static void set_update(MAILSTREAM * stream)
3951 {
3952 struct vm_state *vms;
3953 char *mailbox = stream->mailbox, *user;
3954 char buf[1024] = "";
3955
3956 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || !(vms = get_vm_state_by_imapuser(user, 0))) {
3957 if (user && DEBUG_ATLEAST(3))
3958 ast_log(AST_LOG_WARNING, "User %s mailbox not found for update.\n", user);
3959 return;
3960 }
3961
3962 ast_debug(3, "User %s mailbox set for update.\n", user);
3963
3964 vms->updated = 1; /* Set updated flag since mailbox changed */
3965 }
3966
3967 static void init_vm_state(struct vm_state *vms)
3968 {
3969 vms->msg_array_max = VMSTATE_MAX_MSG_ARRAY;
3970 vms->msgArray = ast_calloc(vms->msg_array_max, sizeof(long));
3971 if (!vms->msgArray) {
3972 /* Out of mem? This can't be good. */
3973 vms->msg_array_max = 0;
3974 }
3975 vms->vmArrayIndex = 0;
3976 ast_mutex_init(&vms->lock);
3977 }
3978
3979 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro)
3980 {
3981 char *body_content;
3982 char *body_decoded;
3983 char *fn = is_intro ? vms->introfn : vms->fn;
3984 unsigned long len = 0;
3985 unsigned long newlen = 0;
3986 char filename[256];
3987
3988 if (!body || body == NIL)
3989 return -1;
3990
3991 ast_mutex_lock(&vms->lock);
3992 body_content = mail_fetchbody(vms->mailstream, vms->msgArray[vms->curmsg], section, &len);
3993 ast_mutex_unlock(&vms->lock);
3994 if (len > MAX_MAIL_BODY_CONTENT_SIZE) {
3995 ast_log(AST_LOG_ERROR,
3996 "Msgno %ld, section %s. The body's content size %ld is huge (max %ld). User:%s, mailbox %s\n",
3997 vms->msgArray[vms->curmsg], section, len, MAX_MAIL_BODY_CONTENT_SIZE, vms->imapuser, vms->username);
3998 return -1;
3999 }
4000 if (body_content != NIL && len) {
4001 snprintf(filename, sizeof(filename), "%s.%s", fn, format);
4002 /* ast_debug(1, body_content); */
4003 body_decoded = rfc822_base64((unsigned char *) body_content, len, &newlen);
4004 /* If the body of the file is empty, return an error */
4005 if (!newlen || !body_decoded) {
4006 return -1;
4007 }
4008 write_file(filename, (char *) body_decoded, newlen);
4009 } else {
4010 ast_debug(5, "Body of message is NULL.\n");
4011 return -1;
4012 }
4013 return 0;
4014 }
4015
4016 /*!
4017 * \brief Get delimiter via mm_list callback
4018 * \param vms The voicemail state object
4019 * \param stream
4020 *
4021 * Determines the delimiter character that is used by the underlying IMAP based mail store.
4022 */
4023 /* MUTEX should already be held */
4024 static void get_mailbox_delimiter(struct vm_state *vms, MAILSTREAM *stream) {
4025 char tmp[50];
4026 snprintf(tmp, sizeof(tmp), "{%s}", S_OR(vms->imapserver, imapserver));
4027 mail_list(stream, tmp, "*");
4028 }
4029
4030 /*!
4031 * \brief Check Quota for user
4032 * \param vms a pointer to a vm_state struct, will use the mailstream property of this.
4033 * \param mailbox the mailbox to check the quota for.
4034 *
4035 * Calls imap_getquotaroot, which will populate its results into the vm_state vms input structure.
4036 */
4037 static void check_quota(struct vm_state *vms, char *mailbox) {
4038 ast_mutex_lock(&vms->lock);
4039 mail_parameters(NULL, SET_QUOTA, (void *) mm_parsequota);
4040 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mailbox);
4041 if (vms && vms->mailstream != NULL) {
4042 imap_getquotaroot(vms->mailstream, mailbox);
4043 } else {
4044 ast_log(AST_LOG_WARNING, "Mailstream not available for mailbox: %s\n", mailbox);
4045 }
4046 ast_mutex_unlock(&vms->lock);
4047 }
4048
4049 #endif /* IMAP_STORAGE */
4050
4051 /*! \brief Lock file path
4052 * only return failure if ast_lock_path returns 'timeout',
4053 * not if the path does not exist or any other reason
4054 */
4055 static int vm_lock_path(const char *path)
4056 {
4057 switch (ast_lock_path(path)) {
4058 case AST_LOCK_TIMEOUT:
4059 return -1;
4060 default:
4061 return 0;
4062 }
4063 }
4064
4065 #define MSG_ID_LEN 256
4066
4067 /* Used to attach a unique identifier to an msg_id */
4068 static int msg_id_incrementor;
4069
4070 /*!
4071 * \brief Sets the destination string to a uniquely identifying msg_id string
4072 * \param dst pointer to a character buffer that should contain MSG_ID_LEN characters.
4073 */
4074 static void generate_msg_id(char *dst);
4075
4076 #ifdef ODBC_STORAGE
4077
4078 /*!
4079 * \internal
4080 * \brief Create a buffer containing the SQL statement with the table name inserted.
4081 *
4082 * \param __sql_fmt The SQL statement with a single '%s' where the table name should be inserted.
4083 *
4084 * \note The buffer is allocated on the stack and should not be freed.
4085 *
4086 * \return A pointer to a buffer containing the SQL statement with the table name inserted.
4087 */
4088 #define MAKE_SQL_PTRA(__sql_fmt) \
4089 ({ \
4090 /* The NULL terminator is included in odbc_table_len. */ \
4091 char *__sql = ast_alloca(strlen(__sql_fmt) + odbc_table_len); \
4092 sprintf(__sql, __sql_fmt, odbc_table); /* Safe */ \
4093 __sql; \
4094 })
4095
4096 /*!
4097 * \internal
4098 * \brief Create a buffer containing the SQL statement with the table name inserted twice.
4099 *
4100 * \param __sql_fmt The SQL statement with two '%s' where the table name should be inserted.
4101 *
4102 * \note The buffer is allocated on the stack and should not be freed.
4103 *
4104 * \return A pointer to a buffer containing the SQL statement with the table name inserted.
4105 */
4106 #define MAKE_SQL_PTRA2(__sql_fmt) \
4107 ({ \
4108 /* The NULL terminator is included in odbc_table_len. */ \
4109 char *__sql = ast_alloca(strlen(__sql_fmt) + (odbc_table_len * 2)); \
4110 sprintf(__sql, __sql_fmt, odbc_table, odbc_table); /* Safe */ \
4111 __sql; \
4112 })
4113
4114 struct generic_prepare_struct {
4115 char *sql;
4116 int argc;
4117 char **argv;
4118 };
4119
4120 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
4121 {
4122 struct generic_prepare_struct *gps = data;
4123 int res, i;
4124 SQLHSTMT stmt;
4125
4126 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
4127 if (!SQL_SUCCEEDED(res)) {
4128 ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
4129 return NULL;
4130 }
4131 res = ast_odbc_prepare(obj, stmt, gps->sql);
4132 if (!SQL_SUCCEEDED(res)) {
4133 ast_log(AST_LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
4134 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4135 return NULL;
4136 }
4137 for (i = 0; i < gps->argc; i++)
4138 SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
4139
4140 return stmt;
4141 }
4142
4143 static void odbc_update_msg_id(char *dir, int msg_num, char *msg_id)
4144 {
4145 SQLHSTMT stmt;
4146 char *sql = MAKE_SQL_PTRA("UPDATE %s SET msg_id=? WHERE dir=? AND msgnum=?");
4147 struct odbc_obj *obj;
4148 char msg_num_str[20];
4149 char *argv[] = { msg_id, dir, msg_num_str };
4150 struct generic_prepare_struct gps = { .sql = sql, .argc = 3, .argv = argv };
4151 SCOPE_ENTER(3, "dir: %s msg_num: %d msg_id: %s\n", dir, msg_num, msg_id);
4152
4153 obj = ast_odbc_request_obj(odbc_database, 0);
4154 if (!obj) {
4155 SCOPE_EXIT_LOG_RTN(LOG_WARNING, "Unable to update message ID for message %d in %s\n", msg_num, dir);
4156 }
4157
4158 snprintf(msg_num_str, sizeof(msg_num_str), "%d", msg_num);
4159 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4160 if (!stmt) {
4161 ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4162 } else {
4163 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4164 }
4165 ast_odbc_release_obj(obj);
4166 SCOPE_EXIT_RTN();
4167 }
4168
4169 #define AUDIO_ON_DISK_MAGIC "AUDMAGIC"
4170 #define AUDIO_ON_DISK_MAGIC_LEN 8
4171
4172 static void odbc_update_set_audmagic(char *dir, int msg_num)
4173 {
4174 SQLHSTMT stmt;
4175 char *sql = MAKE_SQL_PTRA("UPDATE %s SET recording=? WHERE dir=? AND msgnum=?");
4176 struct odbc_obj *obj;
4177 SQLLEN datalen = AUDIO_ON_DISK_MAGIC_LEN;
4178 SQLLEN indlen = datalen;
4179 int res;
4180 char msg_num_str[20];
4181 SCOPE_ENTER(3, "dir: %s msg_num: %d\n", dir, msg_num);
4182
4183 obj = ast_odbc_request_obj(odbc_database, 0);
4184 if (!obj) {
4185 SCOPE_EXIT_LOG_RTN(LOG_WARNING, "Unable to request obj for message %d in %s\n", msg_num, dir);
4186 }
4187
4188 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
4189 if (!SQL_SUCCEEDED(res)) {
4190 ast_odbc_release_obj(obj);
4191 SCOPE_EXIT_LOG_RTN(LOG_WARNING, "Unable to allocate stmt for message %d in %s\n", msg_num, dir);
4192 }
4193
4194 snprintf(msg_num_str, sizeof(msg_num_str), "%d", msg_num);
4195
4196 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY,
4197 datalen, 0, (void *) AUDIO_ON_DISK_MAGIC,
4198 datalen, &indlen);
4199
4200 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,
4201 strlen(dir), 0, (void *) dir, 0, NULL);
4202
4203 SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,
4204 strlen(msg_num_str), 0, (void *) msg_num_str, 0, NULL);
4205
4206 res = ast_odbc_execute_sql(obj, stmt, sql);
4207 if (!SQL_SUCCEEDED(res)) {
4208 ast_log(LOG_WARNING, "Unable to execute stmt for message %d in %s\n", msg_num, dir);
4209 ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
4210 }
4211 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4212 stmt = NULL;
4213
4214 ast_odbc_release_obj(obj);
4215 SCOPE_EXIT_RTN("Done\n");
4216 }
4217
4218 static int odbc_store_message(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum);
4219
4220 /*!
4221 * \brief Retrieves a file from an ODBC data store.
4222 * \param dir the path to the file to be retrieved.
4223 * \param msgnum the message number, such as within a mailbox folder.
4224 *
4225 * This method is used by the RETRIEVE macro when mailboxes are stored in an ODBC back end.
4226 * The purpose is to get the message from the database store to the local file system, so that the message may be played, or the information file may be read.
4227 *
4228 * The file is looked up by invoking a SQL on the odbc_table (default 'voicemessages') using the dir and msgnum input parameters.
4229 * The output is the message information file with the name msgnum and the extension .txt
4230 * and the message file with the extension of its format, in the directory with base file name of the msgnum.
4231 *
4232 * \return 0 on success, -1 on error.
4233 */
4234 static int odbc_retrieve_message(char *dir, int msgnum)
4235 {
4236 int x = 0;
4237 int res;
4238 int fd = -1;
4239 size_t fdlen = 0;
4240 void *fdm = MAP_FAILED;
4241 SQLSMALLINT colcount = 0;
4242 SQLHSTMT stmt;
4243 char *sql = MAKE_SQL_PTRA("SELECT * FROM %s WHERE dir=? AND msgnum=?");
4244 char fmt[80] = "";
4245 char *c;
4246 char coltitle[256];
4247 SQLSMALLINT collen;
4248 SQLSMALLINT datatype;
4249 SQLSMALLINT decimaldigits;
4250 SQLSMALLINT nullable;
4251 SQLULEN colsize;
4252 SQLLEN colsize2;
4253 FILE *f = NULL;
4254 char rowdata[80];
4255 char *fn = MAKE_FILE_PTRA(dir, msgnum);
4256 char *full_fn = MAKE_FILE_EXT_PTRA(dir, msgnum, "txt");
4257 char msgnums[80];
4258 char *mailboxuser = NULL;
4259 char *mailboxcontext = NULL;
4260 char msg_id[MSG_ID_LEN] = "";
4261 char *argv[] = { dir, msgnums };
4262 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
4263 struct odbc_obj *obj;
4264 int storage_conversion_to_disk = 0;
4265 int storage_conversion_to_odbc = 0;
4266 SCOPE_ENTER(3, "dir: %s msgnum: %d msgtype: %s\n", dir, msgnum, msgnum < 0 ? "Greeting" : "Message");
4267
4268 obj = ast_odbc_request_obj(odbc_database, 0);
4269 if (!obj) {
4270 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4271 }
4272
4273 ast_copy_string(fmt, vmfmts, sizeof(fmt));
4274 c = strchr(fmt, '|');
4275 if (c)
4276 *c = '\0';
4277 if (!strcasecmp(fmt, "wav49"))
4278 strcpy(fmt, "WAV");
4279
4280 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
4281
4282 ast_trace(-1, "Opening '%s' for writing\n", full_fn);
4283 if (!(f = fopen(full_fn, "w+"))) {
4284 ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
4285 goto bail;
4286 }
4287
4288 sprintf(full_fn, "%s.%s", fn, fmt); /* Safe. We're just replacing the file exten. */
4289
4290 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4291 if (!stmt) {
4292 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4293 goto bail;
4294 }
4295
4296 res = SQLFetch(stmt);
4297 if (!SQL_SUCCEEDED(res)) {
4298 if (res != SQL_NO_DATA) {
4299 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
4300 }
4301 goto bail_with_handle;
4302 }
4303
4304 res = SQLNumResultCols(stmt, &colcount);
4305 if (!SQL_SUCCEEDED(res)) {
4306 ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
4307 goto bail_with_handle;
4308 }
4309
4310 fprintf(f, "[message]\n");
4311 for (x = 0; x < colcount; x++) {
4312 rowdata[0] = '\0';
4313 colsize = 0;
4314 collen = sizeof(coltitle);
4315 res = SQLDescribeCol(stmt, x + 1, (unsigned char *) coltitle, sizeof(coltitle), &collen,
4316 &datatype, &colsize, &decimaldigits, &nullable);
4317 if (!SQL_SUCCEEDED(res)) {
4318 ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
4319 goto bail_with_handle;
4320 }
4321
4322 if (!strcasecmp(coltitle, "recording")) {
4323 off_t offset;
4324 char tmp[1] = "";
4325
4326 res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
4327 fdlen = colsize2;
4328 ast_trace(-1, "Audio size: %ld\n", colsize2);
4329 if (colsize2 == AUDIO_ON_DISK_MAGIC_LEN) {
4330 res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, AUDIO_ON_DISK_MAGIC_LEN, NULL);
4331 if (memcmp(rowdata, AUDIO_ON_DISK_MAGIC, AUDIO_ON_DISK_MAGIC_LEN) != 0) {
4332 ast_log(AST_LOG_WARNING, "Invalid audio magic number '0x%02X%02X%02X%02X%02X%02X%02X%02X' for '%s'\n",
4333 rowdata[0], rowdata[1], rowdata[2], rowdata[3], rowdata[4], rowdata[5], rowdata[6],
4334 rowdata[7], full_fn);
4335 goto bail_with_handle;
4336 }
4337 ast_trace(-1, "Audio is stored on disk. No need to write '%s'\n", full_fn);
4338 if (!ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
4339 storage_conversion_to_odbc = 1;
4340 }
4341
4342 continue;
4343 }
4344
4345 ast_trace(-1, "Opening '%s' for writing\n", full_fn);
4346 fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
4347 if (fd < 0) {
4348 ast_log(AST_LOG_WARNING, "Failed to open '%s' for writing: %s\n", full_fn, strerror(errno));
4349 goto bail_with_handle;
4350 }
4351 if (ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
4352 storage_conversion_to_disk = 1;
4353 }
4354
4355 lseek(fd, fdlen - 1, SEEK_SET);
4356 if (write(fd, tmp, 1) != 1) {
4357 close(fd);
4358 fd = -1;
4359 continue;
4360 }
4361 /* Read out in small chunks */
4362 for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
4363 if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
4364 ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
4365 goto bail_with_handle;
4366 }
4367 res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
4368 munmap(fdm, CHUNKSIZE);
4369 if (!SQL_SUCCEEDED(res)) {
4370 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
4371 unlink(full_fn);
4372 goto bail_with_handle;
4373 }
4374 }
4375 if (truncate(full_fn, fdlen) < 0) {
4376 ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
4377 }
4378 ast_trace(-1, "Wrote %d bytes to '%s'\n", (int)fdlen, full_fn);
4379 } else {
4380 res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
4381 if (res == SQL_NULL_DATA && !strcasecmp(coltitle, "msg_id")) {
4382 /*
4383 * Generate msg_id if there wasn't one, but don't store it until we're
4384 * done with this connection.
4385 */
4386 generate_msg_id(msg_id);
4387 ast_trace(-1, "msg_id was NULL. Generating new one: %s\n", msg_id);
4388 snprintf(rowdata, sizeof(rowdata), "%s", msg_id);
4389 } else if (!strcasecmp(coltitle, "mailboxuser")) {
4390 mailboxuser = ast_strdupa(rowdata);
4391 } else if (!strcasecmp(coltitle, "mailboxcontext")) {
4392 mailboxcontext = ast_strdupa(rowdata);
4393 } else if (res == SQL_NULL_DATA && !strcasecmp(coltitle, "category")) {
4394 /* Ignore null column value for category */
4395 ast_trace(-1, "Ignoring null category column in ODBC voicemail retrieve_file.\n");
4396 continue;
4397 } else if (!SQL_SUCCEEDED(res)) {
4398 ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
4399 goto bail_with_handle;
4400 }
4401 if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir")) {
4402 fprintf(f, "%s=%s\n", coltitle, rowdata);
4403 }
4404 }
4405 }
4406
4407 bail_with_handle:
4408 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4409
4410 bail:
4411 if (f)
4412 fclose(f);
4413 if (fd > -1)
4414 close(fd);
4415
4416 ast_odbc_release_obj(obj);
4417
4418 /* If res_odbc is configured to only allow a single database connection, we
4419 will deadlock if we try to do this before releasing the connection we
4420 were just using. */
4421 if (!ast_strlen_zero(msg_id)) {
4422 odbc_update_msg_id(dir, msgnum, msg_id);
4423 }
4424
4425 if (SQL_SUCCEEDED(res)) {
4426 if (storage_conversion_to_disk) {
4427 /*
4428 * If we're currently storing audio on disk but there was pre-existing
4429 * audio in the database, we need to update the database to set the
4430 * 'recording' column to AUDIO_ON_DISK_MAGIC.
4431 */
4432 SCOPE_CALL(-1, odbc_update_set_audmagic, dir, msgnum);
4433 }
4434 if (storage_conversion_to_odbc) {
4435 /*
4436 * If we're currently storing audio in the database but there was
4437 * pre-existing audio on disk, we need to add the audio back
4438 * into the database overwriting the AUDIO_ON_DISK_MAGIC
4439 * magic number.
4440 */
4441 SCOPE_CALL(-1, odbc_store_message, dir, mailboxuser, mailboxcontext, msgnum);
4442 }
4443 }
4444
4445 SCOPE_EXIT_RTN_VALUE(x - 1, "Done. msg_id: %s RC: %d\n", msg_id, x - 1);
4446 }
4447
4448 /*!
4449 * \brief Determines the highest message number in use for a given user and mailbox folder.
4450 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
4451 *
4452 * This method is used when mailboxes are stored in an ODBC back end.
4453 * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
4454 *
4455 * \return the value of zero or greater to indicate the last message index in use, -1 to indicate none.
4456 */
4457 static int odbc_last_message_index(char *dir)
4458 {
4459 int x = -1;
4460 int res;
4461 SQLHSTMT stmt;
4462 char *sql = MAKE_SQL_PTRA("SELECT msgnum FROM %s WHERE dir=? order by msgnum desc");
4463 char rowdata[20];
4464 char *argv[] = { dir };
4465 struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
4466 struct odbc_obj *obj;
4467 SCOPE_ENTER(3, "dir: %s\n", dir);
4468
4469 obj = ast_odbc_request_obj(odbc_database, 0);
4470 if (!obj) {
4471 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4472 }
4473
4474 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4475 if (!stmt) {
4476 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4477 goto bail;
4478 }
4479
4480 res = SQLFetch(stmt);
4481 if (!SQL_SUCCEEDED(res)) {
4482 if (res == SQL_NO_DATA) {
4483 ast_trace(-1, "Directory '%s' has no messages and therefore no index was retrieved.\n", dir);
4484 } else {
4485 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
4486 }
4487 goto bail_with_handle;
4488 }
4489
4490 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
4491 if (!SQL_SUCCEEDED(res)) {
4492 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
4493 goto bail_with_handle;
4494 }
4495
4496 if (sscanf(rowdata, "%30d", &x) != 1) {
4497 ast_log(AST_LOG_WARNING, "Failed to read message index!\n");
4498 }
4499
4500 bail_with_handle:
4501 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4502
4503 bail:
4504 ast_odbc_release_obj(obj);
4505
4506 SCOPE_EXIT_RTN_VALUE(x, "Done. Last message index: %d\n", x);
4507 }
4508
4509 /*!
4510 * \brief Determines if the specified message exists.
4511 * \param dir the folder the mailbox folder to look for messages.
4512 * \param msgnum the message index to query for.
4513 *
4514 * This method is used when mailboxes are stored in an ODBC back end.
4515 *
4516 * \return greater than zero if the message exists, zero when the message does not exist or on error.
4517 */
4518 static int odbc_message_exists(char *dir, int msgnum)
4519 {
4520 int x = 0;
4521 int res;
4522 SQLHSTMT stmt;
4523 char *sql = MAKE_SQL_PTRA("SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?");
4524 char rowdata[20];
4525 char msgnums[20];
4526 char *argv[] = { dir, msgnums };
4527 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
4528 struct odbc_obj *obj;
4529 SCOPE_ENTER(3, "dir: %s msgnum: %d\n", dir, msgnum);
4530
4531 obj = ast_odbc_request_obj(odbc_database, 0);
4532 if (!obj) {
4533 SCOPE_EXIT_LOG_RTN_VALUE(0, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4534 }
4535
4536 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
4537 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4538 if (!stmt) {
4539 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4540 goto bail;
4541 }
4542
4543 res = SQLFetch(stmt);
4544 if (!SQL_SUCCEEDED(res)) {
4545 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
4546 goto bail_with_handle;
4547 }
4548
4549 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
4550 if (!SQL_SUCCEEDED(res)) {
4551 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
4552 goto bail_with_handle;
4553 }
4554
4555 if (sscanf(rowdata, "%30d", &x) != 1) {
4556 ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
4557 }
4558
4559 bail_with_handle:
4560 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4561
4562 bail:
4563 ast_odbc_release_obj(obj);
4564 SCOPE_EXIT_RTN_VALUE(x, "Done. Msg %s\n", x ? "exists" : "does not exist");
4565 }
4566
4567 /*!
4568 * \brief returns the number of messages found.
4569 * \param vmu
4570 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
4571 *
4572 * This method is used when mailboxes are stored in an ODBC back end.
4573 *
4574 * \return The count of messages being zero or more, less than zero on error.
4575 */
4576 static int odbc_count_messages(struct ast_vm_user *vmu, char *dir)
4577 {
4578 int x = -1;
4579 int res;
4580 SQLHSTMT stmt;
4581 char *sql = MAKE_SQL_PTRA("SELECT COUNT(*) FROM %s WHERE dir=?");
4582 char rowdata[20];
4583 char *argv[] = { dir };
4584 struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
4585 struct odbc_obj *obj;
4586 SCOPE_ENTER(3, "dir: %s\n", dir);
4587
4588 obj = ast_odbc_request_obj(odbc_database, 0);
4589 if (!obj) {
4590 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4591 }
4592
4593 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4594 if (!stmt) {
4595 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4596 goto bail;
4597 }
4598
4599 res = SQLFetch(stmt);
4600 if (!SQL_SUCCEEDED(res)) {
4601 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
4602 goto bail_with_handle;
4603 }
4604
4605 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
4606 if (!SQL_SUCCEEDED(res)) {
4607 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
4608 goto bail_with_handle;
4609 }
4610
4611 if (sscanf(rowdata, "%30d", &x) != 1) {
4612 ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
4613 }
4614
4615 bail_with_handle:
4616 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4617
4618 bail:
4619 ast_odbc_release_obj(obj);
4620 SCOPE_EXIT_RTN_VALUE(x, "Done. Count %d\n", x);
4621 }
4622
4623 /*!
4624 * \brief Deletes a message from the mailbox folder.
4625 * \param sdir The mailbox folder to work in.
4626 * \param smsg The message index to be deleted.
4627 *
4628 * This method is used when mailboxes are stored in an ODBC back end.
4629 * The specified message is directly deleted from the database 'voicemessages' table.
4630 */
4631 #define DELETE_SQL_FMT "DELETE FROM %s WHERE dir=? AND msgnum=?"
4632 static void odbc_delete_message(const char *sdir, int smsg)
4633 {
4634 SQLHSTMT stmt;
4635 char *sql = MAKE_SQL_PTRA(DELETE_SQL_FMT);
4636 char msgnums[20];
4637 char *argv[] = { NULL, msgnums };
4638 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
4639 struct odbc_obj *obj;
4640 SCOPE_ENTER(3, "sdir: %s smsg: %d\n", sdir, smsg);
4641
4642 obj = ast_odbc_request_obj(odbc_database, 0);
4643 if (!obj) {
4644 SCOPE_EXIT_LOG_RTN(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4645 }
4646
4647 argv[0] = ast_strdupa(sdir);
4648
4649 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
4650 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4651 if (!stmt) {
4652 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4653 } else {
4654 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4655 }
4656 ast_odbc_release_obj(obj);
4657
4658 if (ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
4659 char *src_fn = MAKE_FILE_PTRA(sdir, smsg);
4660 ast_trace(-1, "Audio stored on disk. Deleting '%s'\n", src_fn);
4661 ast_filedelete(src_fn, NULL);
4662 }
4663
4664 SCOPE_EXIT_RTN("Done\n");
4665 }
4666
4667 /*!
4668 * \brief Copies a voicemail from one mailbox to another.
4669 * \param sdir the folder for which to look for the message to be copied.
4670 * \param smsg the index of the message to be copied.
4671 * \param ddir the destination folder to copy the message into.
4672 * \param dmsg the index to be used for the copied message.
4673 * \param dmailboxuser The user who owns the mailbox that contains the destination folder.
4674 * \param dmailboxcontext The context for the destination user.
4675 *
4676 * This method is used for the COPY macro when mailboxes are stored in an ODBC back end.
4677 */
4678 #define COPY_SQL_FMT "INSERT INTO %s (dir, msgnum, msg_id, context, callerid, origtime, " \
4679 "duration, recording, flag, mailboxuser, mailboxcontext) " \
4680 "SELECT ?,?,msg_id,context,callerid,origtime,duration,recording,flag,?,? " \
4681 "FROM %s WHERE dir=? AND msgnum=?"
4682 static void odbc_copy_message(char *sdir, int smsg, char *ddir, int dmsg, char *dmailboxuser, char *dmailboxcontext)
4683 {
4684 SQLHSTMT stmt;
4685 char *sql = MAKE_SQL_PTRA2(COPY_SQL_FMT);
4686 char msgnums[20];
4687 char msgnumd[20];
4688 struct odbc_obj *obj;
4689 char *argv[] = { ddir, msgnumd, dmailboxuser, dmailboxcontext, sdir, msgnums };
4690 struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
4691 SCOPE_ENTER(3, "sdir: %s smsg: %d duser: %s dcontext: %s ddir: %s dmsg: %d\n",
4692 sdir, smsg, dmailboxuser, dmailboxcontext, ddir, dmsg);
4693
4694 SCOPE_CALL(-1, odbc_delete_message, ddir, dmsg);
4695
4696 obj = ast_odbc_request_obj(odbc_database, 0);
4697 if (!obj) {
4698 SCOPE_EXIT_LOG_RTN(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4699 }
4700
4701 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
4702 snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
4703
4704 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4705 if (!stmt)
4706 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
4707 else
4708 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4709 ast_odbc_release_obj(obj);
4710
4711 if (ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
4712 char *src_fn = MAKE_FILE_PTRA(sdir, smsg);
4713 char *dst_fn = MAKE_FILE_PTRA(ddir, dmsg);
4714
4715 ast_trace(-1, "Audio stored on disk. Copying '%s' to '%s'\n", src_fn, dst_fn);
4716 ast_filecopy(src_fn, dst_fn, NULL);
4717 }
4718
4719 SCOPE_EXIT_RTN("Done\n");
4720 }
4721 #undef COPY_SQL_FMT
4722
4723 struct insert_data {
4724 const char *dir;
4725 const char *msgnums;
4726 void *data;
4727 SQLLEN datalen;
4728 SQLLEN indlen;
4729 const char *context;
4730 const char *callerid;
4731 const char *origtime;
4732 const char *duration;
4733 const char *mailboxuser;
4734 const char *mailboxcontext;
4735 const char *category;
4736 const char *flag;
4737 const char *msg_id;
4738 };
4739
4740 #define STORE_SQL_FMT_CAT "INSERT INTO %s (dir, msgnum, recording, context, callerid, " \
4741 "origtime, duration, mailboxuser, mailboxcontext, flag, msg_id, category) " \
4742 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
4743 #define STORE_SQL_FMT "INSERT INTO %s (dir, msgnum, recording, context, callerid, "\
4744 "origtime, duration, mailboxuser, mailboxcontext, flag, msg_id) "\
4745 "VALUES (?,?,?,?,?,?,?,?,?,?,?)"
4746
4747 static SQLHSTMT odbc_insert_data_cb(struct odbc_obj *obj, void *vdata)
4748 {
4749 struct insert_data *data = vdata;
4750 char *insert_sql;
4751 char *delete_sql;
4752 int res;
4753 SQLHSTMT stmt;
4754 SCOPE_ENTER(3, "dir: %s msgnums: %s msg_id: %s\n", data->dir, data->msgnums,
4755 data->msg_id);
4756
4757 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
4758 if (!SQL_SUCCEEDED(res)) {
4759 SCOPE_EXIT_LOG_RTN_VALUE(NULL, AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
4760 }
4761
4762 /* Delete any existing row with the same dir and msgnum */
4763 delete_sql = MAKE_SQL_PTRA(DELETE_SQL_FMT);
4764 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->dir), 0, (void *) data->dir, 0, NULL);
4765 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->msgnums), 0, (void *) data->msgnums, 0, NULL);
4766 res = ast_odbc_execute_sql(obj, stmt, delete_sql);
4767 if (!SQL_SUCCEEDED(res)) {
4768 ast_trace(-1, "There wasn't an existing row. Good.\n");
4769 } else {
4770 ast_trace(-1, "There WAS an existing row. This is OK if we're replacing a message.\n");
4771 }
4772 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4773 stmt = NULL;
4774
4775 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
4776 if (!SQL_SUCCEEDED(res)) {
4777 SCOPE_EXIT_LOG_RTN_VALUE(NULL, AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
4778 }
4779
4780 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->dir), 0, (void *) data->dir, 0, NULL);
4781 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->msgnums), 0, (void *) data->msgnums, 0, NULL);
4782 SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, data->datalen, 0, (void *) data->data, data->datalen, &data->indlen);
4783 SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->context), 0, (void *) data->context, 0, NULL);
4784 SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->callerid), 0, (void *) data->callerid, 0, NULL);
4785 SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->origtime), 0, (void *) data->origtime, 0, NULL);
4786 SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->duration), 0, (void *) data->duration, 0, NULL);
4787 SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxuser), 0, (void *) data->mailboxuser, 0, NULL);
4788 SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxcontext), 0, (void *) data->mailboxcontext, 0, NULL);
4789 SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->flag), 0, (void *) data->flag, 0, NULL);
4790 SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->msg_id), 0, (void *) data->msg_id, 0, NULL);
4791 if (!ast_strlen_zero(data->category)) {
4792 insert_sql = MAKE_SQL_PTRA(STORE_SQL_FMT_CAT);
4793 SQLBindParameter(stmt, 12, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->category), 0, (void *) data->category, 0, NULL);
4794 } else {
4795 insert_sql = MAKE_SQL_PTRA(STORE_SQL_FMT);
4796 }
4797 res = ast_odbc_execute_sql(obj, stmt, insert_sql);
4798 if (!SQL_SUCCEEDED(res)) {
4799 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n", insert_sql);
4800 ast_odbc_print_errors(SQL_HANDLE_STMT, stmt, "SQL Execute");
4801 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4802 stmt = NULL;
4803 }
4804
4805 SCOPE_EXIT_RTN_VALUE(stmt, "%s\n", stmt ? "Success" : "Failed");
4806 }
4807
4808 /*!
4809 * \brief Stores a voicemail into the database.
4810 * \param dir the folder the mailbox folder to store the message.
4811 * \param mailboxuser the user owning the mailbox folder.
4812 * \param mailboxcontext
4813 * \param msgnum the message index for the message to be stored.
4814 *
4815 * This method is used when mailboxes are stored in an ODBC back end.
4816 * The message sound file and information file is looked up on the file system.
4817 * A SQL query is invoked to store the message into the (MySQL) database.
4818 *
4819 * \return the zero on success -1 on error.
4820 */
4821 static int odbc_store_message(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum)
4822 {
4823 int res = 0;
4824 int fd = -1;
4825 void *fdm = MAP_FAILED;
4826 off_t fdlen = -1;
4827 SQLHSTMT stmt;
4828 char msgnums[20];
4829 char *fn = MAKE_FILE_PTRA(dir, msgnum);
4830 char *full_fn = MAKE_FILE_EXT_PTRA(dir, msgnum, "txt");
4831 char fmt[80]="";
4832 char *c;
4833 struct ast_config *cfg = NULL;
4834 struct odbc_obj *obj;
4835 struct insert_data idata = { .msgnums = msgnums, .dir = dir, .mailboxuser = mailboxuser, .mailboxcontext = mailboxcontext,
4836 .context = "", .callerid = "", .origtime = "", .duration = "", .category = "", .flag = "", .msg_id = "" };
4837 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
4838 SCOPE_ENTER(3, "dir: %s user: %s context: %s msgnum: %d msgtype: %s\n",
4839 dir, mailboxuser, mailboxcontext, msgnum, msgnum < 0 ? "Greeting" : "Message");
4840
4841 obj = ast_odbc_request_obj(odbc_database, 0);
4842 if (!obj) {
4843 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4844 }
4845
4846 do {
4847 ast_copy_string(fmt, vmfmts, sizeof(fmt));
4848 c = strchr(fmt, '|');
4849 if (c)
4850 *c = '\0';
4851 if (!strcasecmp(fmt, "wav49"))
4852 strcpy(fmt, "WAV");
4853
4854 ast_trace(-1, "Formats: %s Using format: '%s'\n", vmfmts, fmt);
4855 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
4856
4857 ast_trace(-1, "Base path: '%s'\n", fn);
4858 ast_trace(-1, "Opening '%s'\n", full_fn);
4859 cfg = ast_config_load(full_fn, config_flags);
4860 if (!valid_config(cfg)) {
4861 if (msgnum < 0) {
4862 ast_trace(-1, "No information file found for '%s'. This is a greeting so this is OK.\n", full_fn);
4863 } else {
4864 ast_log(AST_LOG_WARNING, "Failed to open '%s'\n", full_fn);
4865 res = -1;
4866 break;
4867 }
4868 }
4869
4870 sprintf(full_fn, "%s.%s", fn, fmt); /* Safe */
4871 if (ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
4872 ast_trace(-1, "Audio stored on disk. No need to open '%s'\n", full_fn);
4873 } else {
4874 ast_trace(-1, "Opening '%s'\n", full_fn);
4875 fd = open(full_fn, O_RDWR);
4876 if (fd < 0) {
4877 ast_log(AST_LOG_WARNING, "Open of sound file '%s' failed: %s\n", full_fn, strerror(errno));
4878 res = -1;
4879 break;
4880 }
4881 }
4882
4883 if (valid_config(cfg)) {
4884 ast_trace(-1, "Using information file '%s'\n", fn);
4885 if (!(idata.context = ast_variable_retrieve(cfg, "message", "context"))) {
4886 idata.context = "";
4887 }
4888 if (!(idata.callerid = ast_variable_retrieve(cfg, "message", "callerid"))) {
4889 idata.callerid = "";
4890 }
4891 if (!(idata.origtime = ast_variable_retrieve(cfg, "message", "origtime"))) {
4892 idata.origtime = "";
4893 }
4894 if (!(idata.duration = ast_variable_retrieve(cfg, "message", "duration"))) {
4895 idata.duration = "";
4896 }
4897 if (!(idata.category = ast_variable_retrieve(cfg, "message", "category"))) {
4898 idata.category = "";
4899 }
4900 if (!(idata.flag = ast_variable_retrieve(cfg, "message", "flag"))) {
4901 idata.flag = "";
4902 }
4903 if (!(idata.msg_id = ast_variable_retrieve(cfg, "message", "msg_id"))) {
4904 idata.msg_id = "";
4905 }
4906 }
4907
4908 if (fd < 0) {
4909 ast_trace(-1, "Audio stored on disk. Not reading sound file '%s' but setting magic number.\n", full_fn);
4910 idata.data = AUDIO_ON_DISK_MAGIC;
4911 idata.datalen = idata.indlen = AUDIO_ON_DISK_MAGIC_LEN;
4912 } else {
4913 ast_trace(-1, "Reading sound file '%s'\n", full_fn);
4914 fdlen = lseek(fd, 0, SEEK_END);
4915 if (fdlen < 0 || lseek(fd, 0, SEEK_SET) < 0) {
4916 ast_log(AST_LOG_WARNING, "Failed to process sound file '%s': %s\n", full_fn, strerror(errno));
4917 res = -1;
4918 break;
4919 }
4920 fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
4921 if (fdm == MAP_FAILED) {
4922 ast_log(AST_LOG_WARNING, "Memory map failed for sound file '%s'!\n", full_fn);
4923 res = -1;
4924 break;
4925 }
4926 idata.data = fdm;
4927 idata.datalen = idata.indlen = fdlen;
4928 }
4929
4930 if (ast_strlen_zero(idata.origtime)) {
4931 idata.origtime = "0";
4932 }
4933
4934 if (ast_strlen_zero(idata.duration)) {
4935 idata.duration = "0";
4936 }
4937
4938 if ((stmt = ast_odbc_direct_execute(obj, odbc_insert_data_cb, &idata))) {
4939 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4940 } else {
4941 res = -1;
4942 }
4943 } while (0);
4944
4945 ast_odbc_release_obj(obj);
4946
4947 if (valid_config(cfg))
4948 ast_config_destroy(cfg);
4949 if (fdm != MAP_FAILED)
4950 munmap(fdm, fdlen);
4951 if (fd > -1)
4952 close(fd);
4953 SCOPE_EXIT_RTN_VALUE(res, "%s\n", res ? "Failed" : "Success");
4954 }
4955 #undef STORE_SQL_FMT
4956 #undef STORE_SQL_FMT_CAT
4957
4958 /*!
4959 * \brief Renames a message in a mailbox folder.
4960 * \param sdir The folder of the message to be renamed.
4961 * \param smsg The index of the message to be renamed.
4962 * \param mailboxuser The user to become the owner of the message after it is renamed. Usually this will be the same as the original owner.
4963 * \param mailboxcontext The context to be set for the message. Usually this will be the same as the original context.
4964 * \param ddir The destination folder for the message to be renamed into
4965 * \param dmsg The destination message for the message to be renamed.
4966 *
4967 * This method is used by the RENAME macro when mailboxes are stored in an ODBC back end.
4968 * The is usually used to resequence the messages in the mailbox, such as to delete message index 0, it would be called successively to slide all the other messages down one index.
4969 * But in theory, because the SQL query performs an update on (dir, msgnum, mailboxuser, mailboxcontext) in the database, it should be possible to have the message relocated to another mailbox or context as well.
4970 */
4971 static void odbc_rename_message(char *sdir, int smsg, char *mailboxuser, char *mailboxcontext, char *ddir, int dmsg)
4972 {
4973 SQLHSTMT stmt;
4974 char *sql = MAKE_SQL_PTRA("UPDATE %s SET dir=?, msgnum=? WHERE mailboxuser=? AND mailboxcontext=? AND dir=? AND msgnum=?");
4975 char msgnums[20];
4976 char msgnumd[20];
4977 struct odbc_obj *obj;
4978 char *argv[] = { ddir, msgnumd, mailboxuser, mailboxcontext, sdir, msgnums };
4979 struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
4980 SCOPE_ENTER(3, "sdir: %s smsg: %d user: %s context: %s ddir: %s dmsg: %d\n", sdir, smsg,
4981 mailboxuser, mailboxcontext, ddir, dmsg);
4982
4983 SCOPE_CALL(-1, odbc_delete_message, ddir, dmsg);
4984
4985 obj = ast_odbc_request_obj(odbc_database, 0);
4986 if (!obj) {
4987 SCOPE_EXIT_LOG_RTN(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
4988 }
4989
4990 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
4991 snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
4992
4993 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
4994 if (!stmt)
4995 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
4996 else
4997 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
4998 ast_odbc_release_obj(obj);
4999
5000 if (ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
5001 char *src_fn = MAKE_FILE_PTRA(sdir, smsg);
5002 char *dst_fn = MAKE_FILE_PTRA(ddir, dmsg);
5003
5004 ast_trace(-1, "Recordings stored on disk. Renaming '%s' to '%s'\n", src_fn, dst_fn);
5005 ast_filerename(src_fn, dst_fn, NULL);
5006 }
5007
5008 SCOPE_EXIT_RTN("Done.\n");
5009 }
5010
5011 /*!
5012 * \brief Removes a voicemail message file.
5013 * \param dir the path to the message file.
5014 * \param msgnum the unique number for the message within the mailbox.
5015 *
5016 * Removes the message content file and the information file.
5017 * This method is used by the DISPOSE macro when mailboxes are stored in an ODBC back end.
5018 * Typical use is to clean up after a RETRIEVE operation.
5019 * Note that this does not remove the message from the mailbox folders, to do that we would use delete_file().
5020 * \return zero on success, -1 on error.
5021 */
5022 static int odbc_remove_files(char *dir, int msgnum)
5023 {
5024 char *fn = MAKE_FILE_PTRA(dir, msgnum);
5025 char *full_fn = MAKE_FILE_EXT_PTRA(dir, msgnum, "txt");
5026 SCOPE_ENTER(3, "dir: %s msgnum: %d\n", dir, msgnum);
5027
5028 if (ast_test_flag((&globalflags), VM_ODBC_AUDIO_ON_DISK)) {
5029 ast_trace(-1, "Audio stored on disk. Keeping '%s' sound files\n", fn);
5030 } else {
5031 ast_trace(-1, "Audio stored in ODBC. Removing '%s' sound files\n", fn);
5032 ast_filedelete(fn, NULL);
5033 }
5034
5035 /* Always remove the information file */
5036 ast_trace(-1, "Removing '%s' information file\n", full_fn);
5037 unlink(full_fn);
5038 SCOPE_EXIT_RTN_VALUE(0, "Done.\n");
5039 }
5040 #else
5041 #ifndef IMAP_STORAGE
5042 /*!
5043 * \brief Find all .txt files - even if they are not in sequence from 0000.
5044 * \param vmu
5045 * \param dir
5046 *
5047 * This method is used when mailboxes are stored on the filesystem. (not ODBC and not IMAP).
5048 *
5049 * \return the count of messages, zero or more.
5050 */
5051 static int count_messages(struct ast_vm_user *vmu, char *dir)
5052 {
5053
5054 int vmcount = 0;
5055 DIR *vmdir = NULL;
5056 struct dirent *vment = NULL;
5057
5058 if (vm_lock_path(dir))
5059 return ERROR_LOCK_PATH;
5060
5061 if ((vmdir = opendir(dir))) {
5062 while ((vment = readdir(vmdir))) {
5063 if (strlen(vment->d_name) > 7 && !strncmp(vment->d_name + 7, ".txt", 4)) {
5064 vmcount++;
5065 }
5066 }
5067 closedir(vmdir);
5068 }
5069 ast_unlock_path(dir);
5070
5071 return vmcount;
5072 }
5073
5074 /*!
5075 * \brief Renames a message in a mailbox folder.
5076 * \param sfn The path to the mailbox information and data file to be renamed.
5077 * \param dfn The path for where the message data and information files will be renamed to.
5078 *
5079 * This method is used by the RENAME macro when mailboxes are stored on the filesystem. (not ODBC and not IMAP).
5080 */
5081 static void rename_file(char *sfn, char *dfn)
5082 {
5083 char stxt[PATH_MAX];
5084 char dtxt[PATH_MAX];
5085 ast_filerename(sfn, dfn, NULL);
5086 snprintf(stxt, sizeof(stxt), "%s.txt", sfn);
5087 snprintf(dtxt, sizeof(dtxt), "%s.txt", dfn);
5088 if (ast_check_realtime("voicemail_data")) {
5089 ast_update_realtime("voicemail_data", "filename", sfn, "filename", dfn, SENTINEL);
5090 }
5091 rename(stxt, dtxt);
5092 }
5093
5094 /*!
5095 * \brief Determines the highest message number in use for a given user and mailbox folder.
5096 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
5097 *
5098 * This method is used when mailboxes are stored on the filesystem. (not ODBC and not IMAP).
5099 * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
5100 *
5101 * \note Should always be called with a lock already set on dir.
5102 * \return the value of zero or greaterto indicate the last message index in use, -1 to indicate none.
5103 */
5104 static int last_message_index(char *dir)
5105 {
5106 int x;
5107 unsigned char map[MAXMSGLIMIT] = "";
5108 DIR *msgdir;
5109 struct dirent *msgdirent;
5110 int msgdirint;
5111 char extension[4];
5112 int stopcount = 0;
5113
5114 /* Reading the entire directory into a file map scales better than
5115 * doing a stat repeatedly on a predicted sequence. I suspect this
5116 * is partially due to stat(2) internally doing a readdir(2) itself to
5117 * find each file. */
5118 if (!(msgdir = opendir(dir))) {
5119 return -1;
5120 }
5121
5122 while ((msgdirent = readdir(msgdir))) {
5123 if (sscanf(msgdirent->d_name, "msg%30d.%3s", &msgdirint, extension) == 2 && !strcmp(extension, "txt") && msgdirint < MAXMSGLIMIT) {
5124 map[msgdirint] = 1;
5125 stopcount++;
5126 ast_debug(4, "%s map[%d] = %d, count = %d\n", dir, msgdirint, map[msgdirint], stopcount);
5127 }
5128 }
5129 closedir(msgdir);
5130
5131 for (x = 0; x < MAXMSGLIMIT && stopcount; x++) {
5132 stopcount -= map[x];
5133 }
5134
5135 return x - 1;
5136 }
5137
5138 #endif /* #ifndef IMAP_STORAGE */
5139 #endif /* #else of #ifdef ODBC_STORAGE */
5140 #ifndef IMAP_STORAGE
5141 /*!
5142 * \brief Utility function to copy a file.
5143 * \param infile The path to the file to be copied. The file must be readable, it is opened in read only mode.
5144 * \param outfile The path for which to copy the file to. The directory permissions must allow the creation (or truncation) of the file, and allow for opening the file in write only mode.
5145 *
5146 * When the compiler option HARDLINK_WHEN_POSSIBLE is set, the copy operation will attempt to use the hard link facility instead of copy the file (to save disk space). If the link operation fails, it falls back to the copy operation.
5147 * The copy operation copies up to 4096 bytes at once.
5148 *
5149 * \return zero on success, -1 on error.
5150 */
5151 static int copy(char *infile, char *outfile)
5152 {
5153 int ifd;
5154 int ofd;
5155 int res = -1;
5156 int len;
5157 char buf[4096];
5158
5159 #ifdef HARDLINK_WHEN_POSSIBLE
5160 /* Hard link if possible; saves disk space & is faster */
5161 if (!link(infile, outfile)) {
5162 return 0;
5163 }
5164 #endif
5165
5166 if ((ifd = open(infile, O_RDONLY)) < 0) {
5167 ast_log(AST_LOG_WARNING, "Unable to open %s in read-only mode: %s\n", infile, strerror(errno));
5168 return -1;
5169 }
5170
5171 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, VOICEMAIL_FILE_MODE)) < 0) {
5172 ast_log(AST_LOG_WARNING, "Unable to open %s in write-only mode: %s\n", outfile, strerror(errno));
5173 close(ifd);
5174 return -1;
5175 }
5176
5177 for (;;) {
5178 int wrlen;
5179
5180 len = read(ifd, buf, sizeof(buf));
5181 if (!len) {
5182 res = 0;
5183 break;
5184 }
5185
5186 if (len < 0) {
5187 ast_log(AST_LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
5188 break;
5189 }
5190
5191 wrlen = write(ofd, buf, len);
5192 if (errno == ENOMEM || errno == ENOSPC || wrlen != len) {
5193 ast_log(AST_LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, wrlen, len, strerror(errno));
5194 break;
5195 }
5196 }
5197
5198 close(ifd);
5199 close(ofd);
5200 if (res) {
5201 unlink(outfile);
5202 }
5203
5204 return res;
5205 }
5206
5207 /*!
5208 * \brief Copies a voicemail information (envelope) file.
5209 * \param frompath
5210 * \param topath
5211 *
5212 * Every voicemail has the data (.wav) file, and the information file.
5213 * This function performs the file system copying of the information file for a voicemail, handling the internal fields and their values.
5214 * This is used by the COPY macro when not using IMAP storage.
5215 */
5216 static void copy_plain_file(char *frompath, char *topath)
5217 {
5218 char frompath2[PATH_MAX], topath2[PATH_MAX];
5219 struct ast_variable *tmp, *var = NULL;
5220 const char *origmailbox = "", *context = "", *exten = "";
5221 const char *priority = "", *callerchan = "", *callerid = "", *origdate = "";
5222 const char *origtime = "", *category = "", *duration = "";
5223
5224 ast_filecopy(frompath, topath, NULL);
5225 snprintf(frompath2, sizeof(frompath2), "%s.txt", frompath);
5226 snprintf(topath2, sizeof(topath2), "%s.txt", topath);
5227
5228 if (ast_check_realtime("voicemail_data")) {
5229 var = ast_load_realtime("voicemail_data", "filename", frompath, SENTINEL);
5230 /* This cycle converts ast_variable linked list, to va_list list of arguments, may be there is a better way to do it? */
5231 for (tmp = var; tmp; tmp = tmp->next) {
5232 if (!strcasecmp(tmp->name, "origmailbox")) {
5233 origmailbox = tmp->value;
5234 } else if (!strcasecmp(tmp->name, "context")) {
5235 context = tmp->value;
5236 } else if (!strcasecmp(tmp->name, "exten")) {
5237 exten = tmp->value;
5238 } else if (!strcasecmp(tmp->name, "priority")) {
5239 priority = tmp->value;
5240 } else if (!strcasecmp(tmp->name, "callerchan")) {
5241 callerchan = tmp->value;
5242 } else if (!strcasecmp(tmp->name, "callerid")) {
5243 callerid = tmp->value;
5244 } else if (!strcasecmp(tmp->name, "origdate")) {
5245 origdate = tmp->value;
5246 } else if (!strcasecmp(tmp->name, "origtime")) {
5247 origtime = tmp->value;
5248 } else if (!strcasecmp(tmp->name, "category")) {
5249 category = tmp->value;
5250 } else if (!strcasecmp(tmp->name, "duration")) {
5251 duration = tmp->value;
5252 }
5253 }
5254 ast_store_realtime("voicemail_data", "filename", topath, "origmailbox", origmailbox, "context", context, "exten", exten, "priority", priority, "callerchan", callerchan, "callerid", callerid, "origdate", origdate, "origtime", origtime, "category", category, "duration", duration, SENTINEL);
5255 }
5256 copy(frompath2, topath2);
5257 ast_variables_destroy(var);
5258 }
5259 #endif
5260
5261 /*!
5262 * \brief Removes the voicemail sound and information file.
5263 * \param file The path to the sound file. This will be the folder and message index, without the extension.
5264 *
5265 * This is used by the DELETE macro when voicemails are stored on the file system.
5266 *
5267 * \return zero on success, -1 on error.
5268 */
5269 static int vm_delete(char *file)
5270 {
5271 char *txt;
5272 int txtsize = 0;
5273 int res = 0;
5274 SCOPE_ENTER(3, "file: %s\n", file);
5275
5276 txtsize = (strlen(file) + 5)*sizeof(char);
5277 txt = ast_alloca(txtsize);
5278 /* Sprintf here would safe because we alloca'd exactly the right length,
5279 * but trying to eliminate all sprintf's anyhow
5280 */
5281 if (ast_check_realtime("voicemail_data")) {
5282 ast_destroy_realtime("voicemail_data", "filename", file, SENTINEL);
5283 }
5284 snprintf(txt, txtsize, "%s.txt", file);
5285 ast_trace(-1, "unlinking '%s'\n", txt);
5286 unlink(txt);
5287 ast_trace(-1, "deleting sound files '%s'\n", file);
5288 res = ast_filedelete(file, NULL);
5289 SCOPE_EXIT_RTN_VALUE(res, "Done. RC: %d\n", res);
5290 }
5291
5292 static void prep_email_sub_vars(struct ast_channel *ast, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, const char *fromfolder, char *cidnum, char *cidname, char *dur, char *date, const char *category, const char *flag)
5293 {
5294 char callerid[256];
5295 char num[12];
5296 char fromdir[256], fromfile[256];
5297 struct ast_config *msg_cfg;
5298 const char *origcallerid, *origtime;
5299 char origcidname[80], origcidnum[80], origdate[80];
5300 int inttime;
5301 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
5302
5303 /* Prepare variables for substitution in email body and subject */
5304 pbx_builtin_setvar_helper(ast, "VM_NAME", vmu->fullname);
5305 pbx_builtin_setvar_helper(ast, "VM_DUR", dur);
5306 snprintf(num, sizeof(num), "%d", msgnum);
5307 pbx_builtin_setvar_helper(ast, "VM_MSGNUM", num);
5308 pbx_builtin_setvar_helper(ast, "VM_CONTEXT", context);
5309 pbx_builtin_setvar_helper(ast, "VM_MAILBOX", mailbox);
5310 pbx_builtin_setvar_helper(ast, "VM_CALLERID", (!ast_strlen_zero(cidname) || !ast_strlen_zero(cidnum)) ?
5311 ast_callerid_merge(callerid, sizeof(callerid), cidname, cidnum, NULL) : "an unknown caller");
5312 pbx_builtin_setvar_helper(ast, "VM_CIDNAME", (!ast_strlen_zero(cidname) ? cidname : "an unknown caller"));
5313 pbx_builtin_setvar_helper(ast, "VM_CIDNUM", (!ast_strlen_zero(cidnum) ? cidnum : "an unknown caller"));
5314 pbx_builtin_setvar_helper(ast, "VM_DATE", date);
5315 pbx_builtin_setvar_helper(ast, "VM_CATEGORY", category ? ast_strdupa(category) : "no category");
5316 pbx_builtin_setvar_helper(ast, "VM_FLAG", flag);
5317
5318 /* Retrieve info from VM attribute file */
5319 make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, fromfolder);
5320 make_file(fromfile, sizeof(fromfile), fromdir, msgnum - 1);
5321 if (strlen(fromfile) < sizeof(fromfile) - 5) {
5322 strcat(fromfile, ".txt");
5323 }
5324 if (!(msg_cfg = ast_config_load(fromfile, config_flags)) || !(valid_config(msg_cfg))) {
5325 ast_debug(1, "Config load for message text file '%s' failed\n", fromfile);
5326 return;
5327 }
5328
5329 if ((origcallerid = ast_variable_retrieve(msg_cfg, "message", "callerid"))) {
5330 pbx_builtin_setvar_helper(ast, "ORIG_VM_CALLERID", origcallerid);
5331 ast_callerid_split(origcallerid, origcidname, sizeof(origcidname), origcidnum, sizeof(origcidnum));
5332 pbx_builtin_setvar_helper(ast, "ORIG_VM_CIDNAME", origcidname);
5333 pbx_builtin_setvar_helper(ast, "ORIG_VM_CIDNUM", origcidnum);
5334 }
5335
5336 if ((origtime = ast_variable_retrieve(msg_cfg, "message", "origtime")) && sscanf(origtime, "%30d", &inttime) == 1) {
5337 struct timeval tv = { inttime, };
5338 struct ast_tm tm;
5339 ast_localtime(&tv, &tm, NULL);
5340 ast_strftime_locale(origdate, sizeof(origdate), emaildateformat, &tm, S_OR(vmu->locale, NULL));
5341 pbx_builtin_setvar_helper(ast, "ORIG_VM_DATE", origdate);
5342 }
5343 ast_config_destroy(msg_cfg);
5344 }
5345
5346 /*!
5347 * \brief Wraps a character sequence in double quotes, escaping occurrences of quotes within the string.
5348 * \param from The string to work with.
5349 * \param buf The buffer into which to write the modified quoted string.
5350 * \param maxlen Always zero, but see \see ast_str
5351 *
5352 * \return The destination string with quotes wrapped on it (the to field).
5353 */
5354 static const char *ast_str_quote(struct ast_str **buf, ssize_t maxlen, const char *from)
5355 {
5356 const char *ptr;
5357
5358 /* We're only ever passing 0 to maxlen, so short output isn't possible */
5359 ast_str_set(buf, maxlen, "\"");
5360 for (ptr = from; *ptr; ptr++) {
5361 if (*ptr == '"' || *ptr == '\\') {
5362 ast_str_append(buf, maxlen, "\\%c", *ptr);
5363 } else {
5364 ast_str_append(buf, maxlen, "%c", *ptr);
5365 }
5366 }
5367 ast_str_append(buf, maxlen, "\"");
5368
5369 return ast_str_buffer(*buf);
5370 }
5371
5372 /*! \brief
5373 * fill in *tm for current time according to the proper timezone, if any.
5374 * \return tm so it can be used as a function argument.
5375 */
5376 static const struct ast_tm *vmu_tm(const struct ast_vm_user *vmu, struct ast_tm *tm)
5377 {
5378 const struct vm_zone *z = NULL;
5379 struct timeval t = ast_tvnow();
5380
5381 /* Does this user have a timezone specified? */
5382 if (!ast_strlen_zero(vmu->zonetag)) {
5383 /* Find the zone in the list */
5384 AST_LIST_LOCK(&zones);
5385 AST_LIST_TRAVERSE(&zones, z, list) {
5386 if (!strcmp(z->name, vmu->zonetag))
5387 break;
5388 }
5389 AST_LIST_UNLOCK(&zones);
5390 }
5391 ast_localtime(&t, tm, z ? z->timezone : NULL);
5392 return tm;
5393 }
5394
5395 /*!\brief Check if the string would need encoding within the MIME standard, to
5396 * avoid confusing certain mail software that expects messages to be 7-bit
5397 * clean.
5398 */
5399 static int check_mime(const char *str)
5400 {
5401 for (; *str; str++) {
5402 if (*str > 126 || *str < 32 || strchr("()<>@,:;/\"[]?.=", *str)) {
5403 return 1;
5404 }
5405 }
5406 return 0;
5407 }
5408
5409 /*!\brief Encode a string according to the MIME rules for encoding strings
5410 * that are not 7-bit clean or contain control characters.
5411 *
5412 * Additionally, if the encoded string would exceed the MIME limit of 76
5413 * characters per line, then the encoding will be broken up into multiple
5414 * sections, separated by a space character, in order to facilitate
5415 * breaking up the associated header across multiple lines.
5416 *
5417 * \param end An expandable buffer for holding the result
5418 * \param maxlen Always zero, but see \see ast_str
5419 * \param start A string to be encoded
5420 * \param preamble The length of the first line already used for this string,
5421 * to ensure that each line maintains a maximum length of 76 chars.
5422 * \param postamble the length of any additional characters appended to the
5423 * line, used to ensure proper field wrapping.
5424 * \retval The encoded string.
5425 */
5426 static const char *ast_str_encode_mime(struct ast_str **end, ssize_t maxlen, const char *start, size_t preamble, size_t postamble)
5427 {
5428 struct ast_str *tmp = ast_str_alloca(80);
5429 int first_section = 1;
5430
5431 ast_str_reset(*end);
5432 ast_str_set(&tmp, -1, "=?%s?Q?", charset);
5433 for (; *start; start++) {
5434 int need_encoding = 0;
5435 if (*start < 33 || *start > 126 || strchr("()<>@,:;/\"[]?.=_", *start)) {
5436 need_encoding = 1;
5437 }
5438 if ((first_section && need_encoding && preamble + ast_str_strlen(tmp) > 70) ||
5439 (first_section && !need_encoding && preamble + ast_str_strlen(tmp) > 72) ||
5440 (!first_section && need_encoding && ast_str_strlen(tmp) > 70) ||
5441 (!first_section && !need_encoding && ast_str_strlen(tmp) > 72)) {
5442 /* Start new line */
5443 ast_str_append(end, maxlen, "%s%s?=", first_section ? "" : " ", ast_str_buffer(tmp));
5444 ast_str_set(&tmp, -1, "=?%s?Q?", charset);
5445 first_section = 0;
5446 }
5447 if (need_encoding && *start == ' ') {
5448 ast_str_append(&tmp, -1, "_");
5449 } else if (need_encoding) {
5450 ast_str_append(&tmp, -1, "=%hhX", *start);
5451 } else {
5452 ast_str_append(&tmp, -1, "%c", *start);
5453 }
5454 }
5455 ast_str_append(end, maxlen, "%s%s?=%s", first_section ? "" : " ", ast_str_buffer(tmp), ast_str_strlen(tmp) + postamble > 74 ? " " : "");
5456 return ast_str_buffer(*end);
5457 }
5458
5459 /*!
5460 * \brief Creates the email file to be sent to indicate a new voicemail exists for a user.
5461 * \param p The output file to generate the email contents into.
5462 * \param srcemail The email address to send the email to, presumably the email address for the owner of the mailbox.
5463 * \param vmu The voicemail user who is sending the voicemail.
5464 * \param msgnum The message index in the mailbox folder.
5465 * \param context
5466 * \param mailbox The voicemail box to read the voicemail to be notified in this email.
5467 * \param fromfolder
5468 * \param cidnum The caller ID number.
5469 * \param cidname The caller ID name.
5470 * \param attach the name of the sound file to be attached to the email, if attach_user_voicemail == 1.
5471 * \param attach2
5472 * \param format The message sound file format. i.e. .wav
5473 * \param duration The time of the message content, in seconds.
5474 * \param attach_user_voicemail if 1, the sound file is attached to the email.
5475 * \param chan
5476 * \param category
5477 * \param imap if == 1, indicates the target folder for the email notification to be sent to will be an IMAP mailstore. This causes additional mailbox headers to be set, which would facilitate searching for the email in the destination IMAP folder.
5478 * \param flag, msg_id
5479 *
5480 * The email body, and base 64 encoded attachment (if any) are stored to the file identified by *p. This method does not actually send the email. That is done by invoking the configure 'mailcmd' and piping this generated file into it, or with the sendemail() function.
5481 */
5482 static void make_email_file(FILE *p,
5483 char *srcemail,
5484 struct ast_vm_user *vmu,
5485 int msgnum,
5486 char *context,
5487 char *mailbox,
5488 const char *fromfolder,
5489 char *cidnum,
5490 char *cidname,
5491 char *attach,
5492 char *attach2,
5493 char *format,
5494 int duration,
5495 int attach_user_voicemail,
5496 struct ast_channel *chan,
5497 const char *category,
5498 int imap,
5499 const char *flag,
5500 const char *msg_id)
5501 {
5502 char date[256];
5503 char host[MAXHOSTNAMELEN] = "";
5504 char who[256];
5505 char bound[256];
5506 char dur[256];
5507 struct ast_tm tm;
5508 char enc_cidnum[256] = "", enc_cidname[256] = "";
5509 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
5510 char *greeting_attachment;
5511 char filename[256];
5512 int first_line;
5513 char *emailsbuf;
5514 char *email;
5515
5516 if (!str1 || !str2) {
5517 ast_free(str1);
5518 ast_free(str2);
5519 return;
5520 }
5521
5522 if (cidnum) {
5523 strip_control_and_high(cidnum, enc_cidnum, sizeof(enc_cidnum));
5524 }
5525 if (cidname) {
5526 strip_control_and_high(cidname, enc_cidname, sizeof(enc_cidname));
5527 }
5528 gethostname(host, sizeof(host) - 1);
5529
5530 if (strchr(srcemail, '@')) {
5531 ast_copy_string(who, srcemail, sizeof(who));
5532 } else {
5533 snprintf(who, sizeof(who), "%s@%s", srcemail, host);
5534 }
5535
5536 greeting_attachment = strrchr(ast_strdupa(attach), '/');
5537 if (greeting_attachment) {
5538 *greeting_attachment++ = '\0';
5539 }
5540
5541 snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
5542 ast_strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm));
5543 fprintf(p, "Date: %s" ENDL, date);
5544
5545 /* Set date format for voicemail mail */
5546 ast_strftime_locale(date, sizeof(date), emaildateformat, &tm, S_OR(vmu->locale, NULL));
5547
5548 if (!ast_strlen_zero(fromstring) || !ast_strlen_zero(vmu->fromstring)) {
5549 struct ast_channel *ast;
5550 char *e_fromstring = !ast_strlen_zero(vmu->fromstring) ? vmu->fromstring : fromstring;
5551 if ((ast = ast_dummy_channel_alloc())) {
5552 char *ptr;
5553 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, enc_cidnum, enc_cidname, dur, date, category, flag);
5554 ast_str_substitute_variables(&str1, 0, ast, e_fromstring);
5555
5556 if (check_mime(ast_str_buffer(str1))) {
5557 first_line = 1;
5558 ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("From: "), strlen(who) + 3);
5559 while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
5560 *ptr = '\0';
5561 fprintf(p, "%s %s" ENDL, first_line ? "From:" : "", ast_str_buffer(str2));
5562 first_line = 0;
5563 /* Substring is smaller, so this will never grow */
5564 ast_str_set(&str2, 0, "%s", ptr + 1);
5565 }
5566 fprintf(p, "%s %s <%s>" ENDL, first_line ? "From:" : "", ast_str_buffer(str2), who);
5567 } else {
5568 fprintf(p, "From: %s <%s>" ENDL, ast_str_quote(&str2, 0, ast_str_buffer(str1)), who);
5569 }
5570 ast = ast_channel_unref(ast);
5571 } else {
5572 ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
5573 }
5574 } else {
5575 fprintf(p, "From: Asterisk PBX <%s>" ENDL, who);
5576 }
5577
5578 emailsbuf = ast_strdupa(vmu->email);
5579 fprintf(p, "To:");
5580 first_line = 1;
5581 while ((email = strsep(&emailsbuf, "|"))) {
5582 char *next = emailsbuf;
5583 if (check_mime(vmu->fullname)) {
5584 char *ptr;
5585 ast_str_encode_mime(&str2, 0, vmu->fullname, first_line ? strlen("To: ") : 0, strlen(email) + 3 + (next ? strlen(",") : 0));
5586 while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
5587 *ptr = '\0';
5588 fprintf(p, " %s" ENDL, ast_str_buffer(str2));
5589 /* Substring is smaller, so this will never grow */
5590 ast_str_set(&str2, 0, "%s", ptr + 1);
5591 }
5592 fprintf(p, " %s <%s>%s" ENDL, ast_str_buffer(str2), email, next ? "," : "");
5593 } else {
5594 fprintf(p, " %s <%s>%s" ENDL, ast_str_quote(&str2, 0, vmu->fullname), email, next ? "," : "");
5595 }
5596 first_line = 0;
5597 }
5598
5599 if (msgnum <= -1) {
5600 fprintf(p, "Subject: New greeting '%s' on %s." ENDL, greeting_attachment, date);
5601 } else if (!ast_strlen_zero(emailsubject) || !ast_strlen_zero(vmu->emailsubject)) {
5602 char *e_subj = !ast_strlen_zero(vmu->emailsubject) ? vmu->emailsubject : emailsubject;
5603 struct ast_channel *ast;
5604 if ((ast = ast_dummy_channel_alloc())) {
5605 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
5606 ast_str_substitute_variables(&str1, 0, ast, e_subj);
5607 if (check_mime(ast_str_buffer(str1))) {
5608 char *ptr;
5609 first_line = 1;
5610 ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("Subject: "), 0);
5611 while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
5612 *ptr = '\0';
5613 fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
5614 first_line = 0;
5615 /* Substring is smaller, so this will never grow */
5616 ast_str_set(&str2, 0, "%s", ptr + 1);
5617 }
5618 fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
5619 } else {
5620 fprintf(p, "Subject: %s" ENDL, ast_str_buffer(str1));
5621 }
5622 ast = ast_channel_unref(ast);
5623 } else {
5624 ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
5625 }
5626 } else if (ast_test_flag((&globalflags), VM_PBXSKIP)) {
5627 if (ast_strlen_zero(flag)) {
5628 fprintf(p, "Subject: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
5629 } else {
5630 fprintf(p, "Subject: New %s message %d in mailbox %s" ENDL, flag, msgnum + 1, mailbox);
5631 }
5632 } else {
5633 if (ast_strlen_zero(flag)) {
5634 fprintf(p, "Subject: [PBX]: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
5635 } else {
5636 fprintf(p, "Subject: [PBX]: New %s message %d in mailbox %s" ENDL, flag, msgnum + 1, mailbox);
5637 }
5638 }
5639
5640 fprintf(p, "Message-ID: <Asterisk-%d-%u-%s-%d@%s>" ENDL, msgnum + 1,
5641 (unsigned int) ast_random(), mailbox, (int) getpid(), host);
5642 if (imap) {
5643 /* additional information needed for IMAP searching */
5644 fprintf(p, "X-Asterisk-VM-Message-Num: %d" ENDL, msgnum + 1);
5645 /* fprintf(p, "X-Asterisk-VM-Orig-Mailbox: %s" ENDL, ext); */
5646 fprintf(p, "X-Asterisk-VM-Server-Name: %s" ENDL, fromstring);
5647 fprintf(p, "X-Asterisk-VM-Context: %s" ENDL, context);
5648 #ifdef IMAP_STORAGE
5649 fprintf(p, "X-Asterisk-VM-Extension: %s" ENDL, (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
5650 #else
5651 fprintf(p, "X-Asterisk-VM-Extension: %s" ENDL, mailbox);
5652 #endif
5653 /* flag added for Urgent */
5654 fprintf(p, "X-Asterisk-VM-Flag: %s" ENDL, S_OR(flag, ""));
5655 fprintf(p, "X-Asterisk-VM-Priority: %d" ENDL, chan ? ast_channel_priority(chan) : 0);
5656 fprintf(p, "X-Asterisk-VM-Caller-ID-Num: %s" ENDL, enc_cidnum);
5657 fprintf(p, "X-Asterisk-VM-Caller-ID-Name: %s" ENDL, enc_cidname);
5658 fprintf(p, "X-Asterisk-VM-Duration: %d" ENDL, duration);
5659 if (!ast_strlen_zero(category)) {
5660 fprintf(p, "X-Asterisk-VM-Category: %s" ENDL, category);
5661 } else {
5662 fprintf(p, "X-Asterisk-VM-Category: " ENDL);
5663 }
5664 fprintf(p, "X-Asterisk-VM-Message-Type: %s" ENDL, msgnum > -1 ? "Message" : greeting_attachment);
5665 fprintf(p, "X-Asterisk-VM-Orig-date: %s" ENDL, date);
5666 fprintf(p, "X-Asterisk-VM-Orig-time: %ld" ENDL, (long) time(NULL));
5667 fprintf(p, "X-Asterisk-VM-Message-ID: %s" ENDL, msg_id);
5668 }
5669 if (!ast_strlen_zero(cidnum)) {
5670 fprintf(p, "X-Asterisk-CallerID: %s" ENDL, enc_cidnum);
5671 }
5672 if (!ast_strlen_zero(cidname)) {
5673 fprintf(p, "X-Asterisk-CallerIDName: %s" ENDL, enc_cidname);
5674 }
5675 fprintf(p, "MIME-Version: 1.0" ENDL);
5676 if (attach_user_voicemail) {
5677 /* Something unique. */
5678 snprintf(bound, sizeof(bound), "----voicemail_%d%s%d%u", msgnum + 1, mailbox,
5679 (int) getpid(), (unsigned int) ast_random());
5680
5681 fprintf(p, "Content-Type: multipart/mixed; boundary=\"%s\"" ENDL, bound);
5682 fprintf(p, ENDL ENDL "This is a multi-part message in MIME format." ENDL ENDL);
5683 fprintf(p, "--%s" ENDL, bound);
5684 }
5685 fprintf(p, "Content-Type: text/plain; charset=%s" ENDL "Content-Transfer-Encoding: 8bit" ENDL ENDL, charset);
5686 if (msgnum <= -1) {
5687 fprintf(p, "This message is to let you know that your greeting '%s' was changed on %s." ENDL
5688 "Please do not delete this message, lest your greeting vanish with it." ENDL ENDL,
5689 greeting_attachment, date);
5690 } else if (emailbody || vmu->emailbody) {
5691 char* e_body = vmu->emailbody ? vmu->emailbody : emailbody;
5692 struct ast_channel *ast;
5693 if ((ast = ast_dummy_channel_alloc())) {
5694 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
5695 ast_str_substitute_variables(&str1, 0, ast, e_body);
5696 #ifdef IMAP_STORAGE
5697 {
5698 /* Convert body to native line terminators for IMAP backend */
5699 char *line = ast_str_buffer(str1), *next;
5700 do {
5701 /* Terminate line before outputting it to the file */
5702 if ((next = strchr(line, '\n'))) {
5703 *next++ = '\0';
5704 }
5705 fprintf(p, "%s" ENDL, line);
5706 line = next;
5707 } while (!ast_strlen_zero(line));
5708 }
5709 #else
5710 fprintf(p, "%s" ENDL, ast_str_buffer(str1));
5711 #endif
5712 ast = ast_channel_unref(ast);
5713 } else {
5714 ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
5715 }
5716 } else {
5717 if (strcmp(vmu->mailbox, mailbox)) {
5718 /* Forwarded type */
5719 struct ast_config *msg_cfg;
5720 const char *v;
5721 int inttime;
5722 char fromdir[256], fromfile[256], origdate[80] = "", origcallerid[80] = "";
5723 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
5724 /* Retrieve info from VM attribute file */
5725 make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, fromfolder);
5726 make_file(fromfile, sizeof(fromfile), fromdir, msgnum);
5727 if (strlen(fromfile) < sizeof(fromfile) - 5) {
5728 strcat(fromfile, ".txt");
5729 }
5730 if ((msg_cfg = ast_config_load(fromfile, config_flags)) && valid_config(msg_cfg)) {
5731 if ((v = ast_variable_retrieve(msg_cfg, "message", "callerid"))) {
5732 ast_copy_string(origcallerid, v, sizeof(origcallerid));
5733 }
5734
5735 /* You might be tempted to do origdate, except that a) it's in the wrong
5736 * format, and b) it's missing for IMAP recordings. */
5737 if ((v = ast_variable_retrieve(msg_cfg, "message", "origtime")) && sscanf(v, "%30d", &inttime) == 1) {
5738 struct timeval tv = { inttime, };
5739 struct ast_tm tm;
5740 ast_localtime(&tv, &tm, NULL);
5741 ast_strftime_locale(origdate, sizeof(origdate), emaildateformat, &tm, S_OR(vmu->locale, NULL));
5742 }
5743 fprintf(p, "Dear %s:" ENDL ENDL "\tJust wanted to let you know you were just forwarded"
5744 " a %s long message (number %d)" ENDL "in mailbox %s from %s, on %s" ENDL
5745 "(originally sent by %s on %s)" ENDL "so you might want to check it when you get a"
5746 " chance. Thanks!" ENDL ENDL "\t\t\t\t--Asterisk" ENDL ENDL, vmu->fullname, dur,
5747 msgnum + 1, mailbox, (cidname ? cidname : (cidnum ? cidnum : "an unknown caller")),
5748 date, origcallerid, origdate);
5749 ast_config_destroy(msg_cfg);
5750 } else {
5751 goto plain_message;
5752 }
5753 } else {
5754 plain_message:
5755 fprintf(p, "Dear %s:" ENDL ENDL "\tJust wanted to let you know you were just left a "
5756 "%s long message (number %d)" ENDL "in mailbox %s from %s, on %s so you might" ENDL
5757 "want to check it when you get a chance. Thanks!" ENDL ENDL "\t\t\t\t--Asterisk"
5758 ENDL ENDL, vmu->fullname, dur, msgnum + 1, mailbox,
5759 (cidname ? cidname : (cidnum ? cidnum : "an unknown caller")), date);
5760 }
5761 }
5762
5763 if (imap || attach_user_voicemail) {
5764 if (!ast_strlen_zero(attach2)) {
5765 snprintf(filename, sizeof(filename), "msg%04d.%s", msgnum, format);
5766 ast_debug(5, "creating second attachment filename %s\n", filename);
5767 add_email_attachment(p, vmu, format, attach, greeting_attachment, mailbox, bound, filename, 0, msgnum);
5768 snprintf(filename, sizeof(filename), "msgintro%04d.%s", msgnum, format);
5769 ast_debug(5, "creating attachment filename %s\n", filename);
5770 add_email_attachment(p, vmu, format, attach2, greeting_attachment, mailbox, bound, filename, 1, msgnum);
5771 } else {
5772 snprintf(filename, sizeof(filename), "msg%04d.%s", msgnum, format);
5773 ast_debug(5, "creating attachment filename %s, no second attachment.\n", filename);
5774 add_email_attachment(p, vmu, format, attach, greeting_attachment, mailbox, bound, filename, 1, msgnum);
5775 }
5776 }
5777 ast_free(str1);
5778 ast_free(str2);
5779 }
5780
5781 static int add_email_attachment(FILE *p, struct ast_vm_user *vmu, char *format, char *attach, char *greeting_attachment, char *mailbox, char *bound, char *filename, int last, int msgnum)
5782 {
5783 char fname[PATH_MAX] = "";
5784 char sox_gain_tmpdir[PATH_MAX];
5785 char *file_to_delete = NULL, *dir_to_delete = NULL;
5786 int res;
5787 char altfname[PATH_MAX] = "";
5788 int altused = 0;
5789 char altformat[80] = "";
5790 char *c = NULL;
5791
5792 /* Eww. We want formats to tell us their own MIME type */
5793 char *mime_type = (!strcasecmp(format, "ogg")) ? "application/" : "audio/x-";
5794
5795 /* Users of multiple file formats need special attention. */
5796 snprintf(fname, sizeof(fname), "%s.%s", attach, format);
5797 if (!ast_file_is_readable(fname)) {
5798 ast_copy_string(altformat, vmfmts, sizeof(altformat));
5799 c = strchr(altformat, '|');
5800 if (c) {
5801 *c = '\0';
5802 }
5803 ast_log(AST_LOG_WARNING, "Failed to open file: %s: %s - trying first/alternate format %s\n", fname, strerror(errno), altformat);
5804 snprintf(altfname, sizeof(altfname), "%s.%s", attach, altformat);
5805 if (!ast_file_is_readable(altfname)) {
5806 ast_log(AST_LOG_WARNING, "Failed to open file: %s: %s - alternate format %s failure\n", altfname, strerror(errno), altformat);
5807 } else {
5808 altused = 1;
5809 }
5810 }
5811
5812 /* This 'while' loop will only execute once. We use it so that we can 'break' */
5813 while (vmu->volgain < -.001 || vmu->volgain > .001 || altused) {
5814 char tmpdir[PATH_MAX];
5815
5816 create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, vmu->mailbox, "tmp");
5817
5818 res = snprintf(sox_gain_tmpdir, sizeof(sox_gain_tmpdir), "%s/vm-gain-XXXXXX", tmpdir);
5819 if (res >= sizeof(sox_gain_tmpdir)) {
5820 ast_log(LOG_ERROR, "Failed to create temporary directory path %s: Out of buffer space\n", tmpdir);
5821 break;
5822 }
5823
5824 if (mkdtemp(sox_gain_tmpdir)) {
5825 int soxstatus = 0;
5826 char sox_gain_cmd[PATH_MAX];
5827
5828 ast_debug(3, "sox_gain_tmpdir: %s\n", sox_gain_tmpdir);
5829
5830 /* Save for later */
5831 dir_to_delete = sox_gain_tmpdir;
5832
5833 res = snprintf(fname, sizeof(fname), "%s/output.%s", sox_gain_tmpdir, format);
5834 if (res >= sizeof(fname)) {
5835 ast_log(LOG_ERROR, "Failed to create filename buffer for %s/output.%s: Too long\n", sox_gain_tmpdir, format);
5836 break;
5837 }
5838
5839 if (!altused) {
5840 res = snprintf(sox_gain_cmd, sizeof(sox_gain_cmd), "sox -v %.4f %s.%s %s",
5841 vmu->volgain, attach, format, fname);
5842 } else {
5843 if (!strcasecmp(format, "wav")) {
5844 if (vmu->volgain < -.001 || vmu->volgain > .001) {
5845 res = snprintf(sox_gain_cmd, sizeof(sox_gain_cmd), "sox -v %.4f %s.%s -e signed-integer -b 16 %s",
5846 vmu->volgain, attach, altformat, fname);
5847 } else {
5848 res = snprintf(sox_gain_cmd, sizeof(sox_gain_cmd), "sox %s.%s -e signed-integer -b 16 %s",
5849 attach, altformat, fname);
5850 }
5851 } else {
5852 if (vmu->volgain < -.001 || vmu->volgain > .001) {
5853 res = snprintf(sox_gain_cmd, sizeof(sox_gain_cmd), "sox -v %.4f %s.%s %s",
5854 vmu->volgain, attach, altformat, fname);
5855 } else {
5856 res = snprintf(sox_gain_cmd, sizeof(sox_gain_cmd), "sox %s.%s %s",
5857 attach, altformat, fname);
5858 }
5859 }
5860 }
5861
5862 if (res >= sizeof(sox_gain_cmd)) {
5863 ast_log(LOG_ERROR, "Failed to generate sox command, out of buffer space\n");
5864 break;
5865 }
5866
5867 soxstatus = ast_safe_system(sox_gain_cmd);
5868 if (!soxstatus) {
5869 /* Save for later */
5870 file_to_delete = fname;
5871 ast_debug(3, "VOLGAIN: Stored at: %s - Level: %.4f - Mailbox: %s\n", fname, vmu->volgain, mailbox);
5872 } else {
5873 ast_log(LOG_WARNING, "Sox failed to re-encode %s: %s (have you installed support for all sox file formats?)\n",
5874 fname,
5875 soxstatus == 1 ? "Problem with command line options" : "An error occurred during file processing");
5876 ast_log(LOG_WARNING, "Voicemail attachment will have no volume gain.\n");
5877 }
5878 }
5879
5880 break;
5881 }
5882
5883 if (!file_to_delete) {
5884 res = snprintf(fname, sizeof(fname), "%s.%s", attach, format);
5885 if (res >= sizeof(fname)) {
5886 ast_log(LOG_ERROR, "Failed to create filename buffer for %s.%s: Too long\n", attach, format);
5887 return -1;
5888 }
5889 }
5890
5891 fprintf(p, "--%s" ENDL, bound);
5892 if (msgnum > -1)
5893 fprintf(p, "Content-Type: %s%s; name=\"%s\"" ENDL, mime_type, format, filename);
5894 else
5895 fprintf(p, "Content-Type: %s%s; name=\"%s.%s\"" ENDL, mime_type, format, greeting_attachment, format);
5896 fprintf(p, "Content-Transfer-Encoding: base64" ENDL);
5897 fprintf(p, "Content-Description: Voicemail sound attachment." ENDL);
5898 if (msgnum > -1)
5899 fprintf(p, "Content-Disposition: attachment; filename=\"%s\"" ENDL ENDL, filename);
5900 else
5901 fprintf(p, "Content-Disposition: attachment; filename=\"%s.%s\"" ENDL ENDL, greeting_attachment, format);
5902 ast_base64_encode_file_path(fname, p, ENDL);
5903 if (last)
5904 fprintf(p, ENDL ENDL "--%s--" ENDL "." ENDL, bound);
5905
5906 if (file_to_delete) {
5907 unlink(file_to_delete);
5908 }
5909
5910 if (dir_to_delete) {
5911 rmdir(dir_to_delete);
5912 }
5913
5914 return 0;
5915 }
5916
5917 static int sendmail(char *srcemail,
5918 struct ast_vm_user *vmu,
5919 int msgnum,
5920 char *context,
5921 char *mailbox,
5922 const char *fromfolder,
5923 char *cidnum,
5924 char *cidname,
5925 char *attach,
5926 char *attach2,
5927 char *format,
5928 int duration,
5929 int attach_user_voicemail,
5930 struct ast_channel *chan,
5931 const char *category,
5932 const char *flag,
5933 const char *msg_id)
5934 {
5935 FILE *p = NULL;
5936 char tmp[80] = "/tmp/astmail-XXXXXX";
5937 char tmp2[256];
5938 char *stringp;
5939
5940 if (vmu && ast_strlen_zero(vmu->email)) {
5941 ast_log(AST_LOG_WARNING, "E-mail address missing for mailbox [%s]. E-mail will not be sent.\n", vmu->mailbox);
5942 return(0);
5943 }
5944
5945 /* Mail only the first format */
5946 format = ast_strdupa(format);
5947 stringp = format;
5948 strsep(&stringp, "|");
5949
5950 if (!strcmp(format, "wav49"))
5951 format = "WAV";
5952 ast_debug(3, "Attaching file '%s', format '%s', uservm is '%d', global is %u\n", attach, format, attach_user_voicemail, ast_test_flag((&globalflags), VM_ATTACH));
5953 /* Make a temporary file instead of piping directly to sendmail, in case the mail
5954 command hangs */
5955 if ((p = ast_file_mkftemp(tmp, VOICEMAIL_FILE_MODE & ~my_umask)) == NULL) {
5956 ast_log(AST_LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
5957 return -1;
5958 } else {
5959 make_email_file(p, srcemail, vmu, msgnum, context, mailbox, fromfolder, cidnum, cidname, attach, attach2, format, duration, attach_user_voicemail, chan, category, 0, flag, msg_id);
5960 fclose(p);
5961 snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
5962 ast_safe_system(tmp2);
5963 ast_debug(1, "Sent mail to %s with command '%s'\n", vmu->email, mailcmd);
5964 }
5965 return 0;
5966 }
5967
5968 static int sendpage(char *srcemail, char *pager, int msgnum, char *context, char *mailbox, const char *fromfolder, char *cidnum, char *cidname, int duration, struct ast_vm_user *vmu, const char *category, const char *flag)
5969 {
5970 char enc_cidnum[256], enc_cidname[256];
5971 char date[256];
5972 char host[MAXHOSTNAMELEN] = "";
5973 char who[256];
5974 char dur[PATH_MAX];
5975 char tmp[80] = "/tmp/astmail-XXXXXX";
5976 char tmp2[PATH_MAX];
5977 struct ast_tm tm;
5978 FILE *p;
5979 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
5980
5981 if (!str1 || !str2) {
5982 ast_free(str1);
5983 ast_free(str2);
5984 return -1;
5985 }
5986
5987 if (cidnum) {
5988 strip_control_and_high(cidnum, enc_cidnum, sizeof(enc_cidnum));
5989 }
5990 if (cidname) {
5991 strip_control_and_high(cidname, enc_cidname, sizeof(enc_cidname));
5992 }
5993
5994 if ((p = ast_file_mkftemp(tmp, VOICEMAIL_FILE_MODE & ~my_umask)) == NULL) {
5995 ast_log(AST_LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
5996 ast_free(str1);
5997 ast_free(str2);
5998 return -1;
5999 }
6000 gethostname(host, sizeof(host)-1);
6001 if (strchr(srcemail, '@')) {
6002 ast_copy_string(who, srcemail, sizeof(who));
6003 } else {
6004 snprintf(who, sizeof(who), "%s@%s", srcemail, host);
6005 }
6006 snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
6007 ast_strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm));
6008 fprintf(p, "Date: %s\n", date);
6009
6010 /* Reformat for custom pager format */
6011 ast_strftime_locale(date, sizeof(date), pagerdateformat, vmu_tm(vmu, &tm), S_OR(vmu->locale, NULL));
6012
6013 if (!ast_strlen_zero(pagerfromstring)) {
6014 struct ast_channel *ast;
6015 if ((ast = ast_dummy_channel_alloc())) {
6016 char *ptr;
6017 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, enc_cidnum, enc_cidname, dur, date, category, flag);
6018 ast_str_substitute_variables(&str1, 0, ast, pagerfromstring);
6019
6020 if (check_mime(ast_str_buffer(str1))) {
6021 int first_line = 1;
6022 ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("From: "), strlen(who) + 3);
6023 while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
6024 *ptr = '\0';
6025 fprintf(p, "%s %s" ENDL, first_line ? "From:" : "", ast_str_buffer(str2));
6026 first_line = 0;
6027 /* Substring is smaller, so this will never grow */
6028 ast_str_set(&str2, 0, "%s", ptr + 1);
6029 }
6030 fprintf(p, "%s %s <%s>" ENDL, first_line ? "From:" : "", ast_str_buffer(str2), who);
6031 } else {
6032 fprintf(p, "From: %s <%s>" ENDL, ast_str_quote(&str2, 0, ast_str_buffer(str1)), who);
6033 }
6034 ast = ast_channel_unref(ast);
6035 } else {
6036 ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
6037 }
6038 } else {
6039 fprintf(p, "From: Asterisk PBX <%s>" ENDL, who);
6040 }
6041
6042 if (check_mime(vmu->fullname)) {
6043 int first_line = 1;
6044 char *ptr;
6045 ast_str_encode_mime(&str2, 0, vmu->fullname, strlen("To: "), strlen(pager) + 3);
6046 while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
6047 *ptr = '\0';
6048 fprintf(p, "%s %s" ENDL, first_line ? "To:" : "", ast_str_buffer(str2));
6049 first_line = 0;
6050 /* Substring is smaller, so this will never grow */
6051 ast_str_set(&str2, 0, "%s", ptr + 1);
6052 }
6053 fprintf(p, "%s %s <%s>" ENDL, first_line ? "To:" : "", ast_str_buffer(str2), pager);
6054 } else {
6055 fprintf(p, "To: %s <%s>" ENDL, ast_str_quote(&str2, 0, vmu->fullname), pager);
6056 }
6057
6058 if (!ast_strlen_zero(pagersubject)) {
6059 struct ast_channel *ast;
6060 if ((ast = ast_dummy_channel_alloc())) {
6061 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
6062 ast_str_substitute_variables(&str1, 0, ast, pagersubject);
6063 if (check_mime(ast_str_buffer(str1))) {
6064 int first_line = 1;
6065 char *ptr;
6066 ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("Subject: "), 0);
6067 while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
6068 *ptr = '\0';
6069 fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
6070 first_line = 0;
6071 /* Substring is smaller, so this will never grow */
6072 ast_str_set(&str2, 0, "%s", ptr + 1);
6073 }
6074 fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
6075 } else {
6076 fprintf(p, "Subject: %s" ENDL, ast_str_buffer(str1));
6077 }
6078 ast = ast_channel_unref(ast);
6079 } else {
6080 ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
6081 }
6082 } else {
6083 if (ast_strlen_zero(flag)) {
6084 fprintf(p, "Subject: New VM" ENDL);
6085 } else {
6086 fprintf(p, "Subject: New %s VM" ENDL, flag);
6087 }
6088 }
6089
6090 /* End of headers */
6091 fputs(ENDL, p);
6092
6093 if (pagerbody) {
6094 struct ast_channel *ast;
6095 if ((ast = ast_dummy_channel_alloc())) {
6096 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
6097 ast_str_substitute_variables(&str1, 0, ast, pagerbody);
6098 fprintf(p, "%s" ENDL, ast_str_buffer(str1));
6099 ast = ast_channel_unref(ast);
6100 } else {
6101 ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
6102 }
6103 } else {
6104 fprintf(p, "New %s long %s msg in box %s\n"
6105 "from %s, on %s", dur, flag, mailbox, (cidname ? cidname : (cidnum ? cidnum : "unknown")), date);
6106 }
6107
6108 fclose(p);
6109 snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
6110 ast_safe_system(tmp2);
6111 ast_debug(1, "Sent page to %s with command '%s'\n", pager, mailcmd);
6112 ast_free(str1);
6113 ast_free(str2);
6114 return 0;
6115 }
6116
6117 /*!
6118 * \brief Gets the current date and time, as formatted string.
6119 * \param s The buffer to hold the output formatted date.
6120 * \param len the length of the buffer. Used to prevent buffer overflow in ast_strftime.
6121 *
6122 * The date format string used is "%a %b %e %r UTC %Y".
6123 *
6124 * \return zero on success, -1 on error.
6125 */
6126 static int get_date(char *s, int len)
6127 {
6128 struct ast_tm tm;
6129 struct timeval t = ast_tvnow();
6130
6131 ast_localtime(&t, &tm, "UTC");
6132
6133 return ast_strftime(s, len, "%a %b %e %r UTC %Y", &tm);
6134 }
6135
6136 static int invent_message(struct ast_channel *chan, char *context, char *ext, int busy, char *ecodes)
6137 {
6138 int res;
6139 char fn[PATH_MAX];
6140 char dest[PATH_MAX];
6141
6142 snprintf(fn, sizeof(fn), "%s%s/%s/greet", VM_SPOOL_DIR, context, ext);
6143
6144 if ((res = create_dirpath(dest, sizeof(dest), context, ext, ""))) {
6145 ast_log(AST_LOG_WARNING, "Failed to make directory(%s)\n", fn);
6146 return -1;
6147 }
6148
6149 RETRIEVE(fn, -1, ext, context);
6150 if (ast_fileexists(fn, NULL, NULL) > 0) {
6151 res = ast_stream_and_wait(chan, fn, ecodes);
6152 if (res) {
6153 DISPOSE(fn, -1);
6154 return res;
6155 }
6156 } else {
6157 /* Dispose just in case */
6158 DISPOSE(fn, -1);
6159 res = ast_stream_and_wait(chan, "vm-theperson", ecodes);
6160 if (res)
6161 return res;
6162 res = ast_say_digit_str(chan, ext, ecodes, ast_channel_language(chan));
6163 if (res)
6164 return res;
6165 }
6166 res = ast_stream_and_wait(chan, busy ? "vm-isonphone" : "vm-isunavail", ecodes);
6167 return res;
6168 }
6169
6170 static void free_zone(struct vm_zone *z)
6171 {
6172 ast_free(z);
6173 }
6174
6175 #ifdef ODBC_STORAGE
6176 #define COUNT_MSGS_SQL_FMT "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'"
6177 static int count_messages_in_folder(struct odbc_obj *odbc, const char *context, const char *mailbox, const char *folder, int *messages)
6178 {
6179 int res;
6180 char sql[sizeof(COUNT_MSGS_SQL_FMT) + odbc_table_len + strlen(VM_SPOOL_DIR)
6181 + strlen(context) + strlen(mailbox) + strlen(folder)];
6182 char rowdata[20];
6183 SQLHSTMT stmt = NULL;
6184 struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
6185 SCOPE_ENTER(3, "context: %s mb: %s folder: %s", context, mailbox, folder);
6186
6187 if (!messages) {
6188 SCOPE_EXIT_RTN_VALUE(0, "No messages pointer\n");
6189 }
6190
6191 snprintf(sql, sizeof(sql), COUNT_MSGS_SQL_FMT, odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
6192 if (!(stmt = ast_odbc_prepare_and_execute(odbc, generic_prepare, &gps))) {
6193 SCOPE_EXIT_LOG_RTN_VALUE(1, LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
6194 }
6195 res = SQLFetch(stmt);
6196 if (!SQL_SUCCEEDED(res)) {
6197 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
6198 SCOPE_EXIT_LOG_RTN_VALUE(1, LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
6199 }
6200 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
6201 if (!SQL_SUCCEEDED(res)) {
6202 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
6203 SCOPE_EXIT_LOG_RTN_VALUE(1, LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
6204 }
6205
6206 *messages = atoi(rowdata);
6207 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
6208
6209 SCOPE_EXIT_RTN_VALUE(0, "messages: %d\n", *messages);
6210 }
6211 #undef COUNT_MSGS_SQL_FMT
6212
6213 static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
6214 {
6215 char tmp[PATH_MAX] = "";
6216 struct odbc_obj *obj;
6217 char *context;
6218 SCOPE_ENTER(3, "mb: %s", mailbox);
6219
6220 if (newmsgs)
6221 *newmsgs = 0;
6222 if (oldmsgs)
6223 *oldmsgs = 0;
6224 if (urgentmsgs)
6225 *urgentmsgs = 0;
6226
6227 /* If no mailbox, return immediately */
6228 if (ast_strlen_zero(mailbox)) {
6229 SCOPE_EXIT_RTN_VALUE(0, "No mailbox\n");
6230 }
6231
6232 ast_copy_string(tmp, mailbox, sizeof(tmp));
6233
6234 if (strchr(mailbox, ' ') || strchr(mailbox, ',')) {
6235 int u, n, o;
6236 char *next, *remaining = tmp;
6237 while ((next = strsep(&remaining, " ,"))) {
6238 if (inboxcount2(next, urgentmsgs ? &u : NULL, &n, &o)) {
6239 SCOPE_EXIT_RTN_VALUE(-1, "Failed to obtain message count for mailbox %s\n", next);
6240 }
6241 if (urgentmsgs) {
6242 *urgentmsgs += u;
6243 }
6244 if (newmsgs) {
6245 *newmsgs += n;
6246 }
6247 if (oldmsgs) {
6248 *oldmsgs += o;
6249 }
6250 }
6251 SCOPE_EXIT_RTN_VALUE(0, "Urgent: %d New: %d Old: %d\n", urgentmsgs ? *urgentmsgs : 0, newmsgs ? *newmsgs : 0, oldmsgs ? *oldmsgs : 0);
6252 }
6253
6254 context = strchr(tmp, '@');
6255 if (context) {
6256 *context = '\0';
6257 context++;
6258 } else
6259 context = "default";
6260
6261 obj = ast_odbc_request_obj(odbc_database, 0);
6262 if (!obj) {
6263 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
6264 }
6265
6266 if (count_messages_in_folder(obj, context, tmp, "INBOX", newmsgs)
6267 || count_messages_in_folder(obj, context, tmp, "Old", oldmsgs)
6268 || count_messages_in_folder(obj, context, tmp, "Urgent", urgentmsgs)) {
6269 ast_log(AST_LOG_WARNING, "Failed to obtain message count for mailbox %s@%s\n",
6270 tmp, context);
6271 }
6272
6273 ast_odbc_release_obj(obj);
6274 SCOPE_EXIT_RTN_VALUE(0, "Urgent: %d New: %d Old: %d\n", urgentmsgs ? *urgentmsgs : 0, newmsgs ? *newmsgs : 0, oldmsgs ? *oldmsgs : 0);
6275 }
6276
6277 /*!
6278 * \brief Gets the number of messages that exist in a mailbox folder.
6279 * \param mailbox_id
6280 * \param folder
6281 *
6282 * This method is used when ODBC backend is used.
6283 * \return The number of messages in this mailbox folder (zero or more).
6284 */
6285 #define MSGCOUNT_SQL_FMT_INBOX "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/INBOX' OR dir = '%s%s/%s/Urgent'"
6286 #define MSGCOUNT_SQL_FMT "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'"
6287 static int messagecount(const char *mailbox_id, const char *folder)
6288 {
6289 struct odbc_obj *obj = NULL;
6290 char *context;
6291 char *mailbox;
6292 int nummsgs = 0;
6293 int res;
6294 SQLHSTMT stmt = NULL;
6295 char rowdata[20];
6296 struct generic_prepare_struct gps = { .argc = 0 };
6297 SCOPE_ENTER(3, "mb: %s folder: %s", mailbox_id, folder);
6298
6299 /* If no mailbox, return immediately */
6300 if (ast_strlen_zero(mailbox_id)
6301 || separate_mailbox(ast_strdupa(mailbox_id), &mailbox, &context)) {
6302 SCOPE_EXIT_RTN_VALUE(0, "Couldn't parse mailbox\n");
6303 }
6304
6305 if (ast_strlen_zero(folder)) {
6306 folder = "INBOX";
6307 }
6308
6309 obj = ast_odbc_request_obj(odbc_database, 0);
6310 if (!obj) {
6311 SCOPE_EXIT_LOG_RTN_VALUE(0, AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
6312 }
6313
6314 if (!strcmp(folder, "INBOX")) {
6315 res = ast_asprintf(&gps.sql, MSGCOUNT_SQL_FMT_INBOX, odbc_table, VM_SPOOL_DIR, context, mailbox, VM_SPOOL_DIR, context, mailbox);
6316 } else {
6317 res = ast_asprintf(&gps.sql, MSGCOUNT_SQL_FMT, odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
6318 }
6319 if (res <= 0) {
6320 SCOPE_EXIT_LOG_RTN_VALUE(0, AST_LOG_WARNING, "Failed to allocate memory for SQL statement for '%s'!\n", odbc_database);
6321 }
6322 ast_trace(-1, "SQL: %s\n", gps.sql);
6323
6324 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
6325 if (!stmt) {
6326 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", gps.sql);
6327 goto bail;
6328 }
6329 res = SQLFetch(stmt);
6330 if (!SQL_SUCCEEDED(res)) {
6331 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", gps.sql);
6332 goto bail_with_handle;
6333 }
6334 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
6335 if (!SQL_SUCCEEDED(res)) {
6336 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", gps.sql);
6337 goto bail_with_handle;
6338 }
6339 nummsgs = atoi(rowdata);
6340
6341 bail_with_handle:
6342 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
6343
6344 bail:
6345 ast_odbc_release_obj(obj);
6346 ast_free(gps.sql);
6347 SCOPE_EXIT_RTN_VALUE(nummsgs, "Messages: %d\n", nummsgs);
6348 }
6349 #undef MSGCOUNT_SQL_FMT
6350 #undef MSGCOUNT_SQL_FMT_INBOX
6351
6352 /*!
6353 * \brief Determines if the given folder has messages.
6354 * \param mailbox The \@ delimited string for user\@context. If no context is found, uses 'default' for the context.
6355 *
6356 * This function is used when the mailbox is stored in an ODBC back end.
6357 * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
6358 * \return 1 if the folder has one or more messages. zero otherwise.
6359 */
6360 static int has_voicemail(const char *mailboxes, const char *folder)
6361 {
6362 char *parse;
6363 char *mailbox;
6364
6365 parse = ast_strdupa(mailboxes);
6366 while ((mailbox = strsep(&parse, ",&"))) {
6367 if (messagecount(mailbox, folder)) {
6368 return 1;
6369 }
6370 }
6371 return 0;
6372 }
6373 #endif
6374 #ifndef IMAP_STORAGE
6375 /*!
6376 * \brief Copies a message from one mailbox to another.
6377 * \param chan
6378 * \param vmu
6379 * \param imbox
6380 * \param msgnum
6381 * \param duration
6382 * \param recip
6383 * \param fmt
6384 * \param dir
6385 * \param flag, dest_folder
6386 *
6387 * This is only used by file storage based mailboxes.
6388 *
6389 * \return zero on success, -1 on error.
6390 */
6391 static int copy_message(struct ast_channel *chan, struct ast_vm_user *vmu, int imbox, int msgnum,
6392 long duration, struct ast_vm_user *recip, char *fmt, char *dir, const char *flag,
6393 const char *dest_folder)
6394 {
6395 char fromdir[PATH_MAX], todir[PATH_MAX], frompath[PATH_MAX], topath[PATH_MAX];
6396 const char *frombox = mbox(vmu, imbox);
6397 const char *userfolder;
6398 int recipmsgnum;
6399 int res = 0;
6400 SCOPE_ENTER(3, "mb: %s imb: %d msgnum: %d recip: %s dir: %s dest_folder: %s",
6401 vmu->mailbox, imbox, msgnum, recip->mailbox, dir, dest_folder);
6402
6403 ast_log(AST_LOG_NOTICE, "Copying message from %s@%s to %s@%s\n", vmu->mailbox, vmu->context, recip->mailbox, recip->context);
6404
6405 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) { /* If urgent, copy to Urgent folder */
6406 userfolder = "Urgent";
6407 } else if (!ast_strlen_zero(dest_folder)) {
6408 userfolder = dest_folder;
6409 } else {
6410 userfolder = "INBOX";
6411 }
6412
6413 create_dirpath(todir, sizeof(todir), recip->context, recip->mailbox, userfolder);
6414 ast_trace(-1, "todir: %s\n", todir);
6415
6416 if (!dir)
6417 make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, frombox);
6418 else
6419 ast_copy_string(fromdir, dir, sizeof(fromdir));
6420
6421 ast_trace(-1, "fromdir: %s\n", fromdir);
6422
6423 make_file(frompath, sizeof(frompath), fromdir, msgnum);
6424 ast_trace(-1, "frompath: %s\n", frompath);
6425
6426 make_dir(todir, sizeof(todir), recip->context, recip->mailbox, userfolder);
6427 ast_trace(-1, "todir: %s\n", todir);
6428
6429 if (vm_lock_path(todir)) {
6430 SCOPE_EXIT_RTN_VALUE(ERROR_LOCK_PATH);
6431 }
6432
6433 recipmsgnum = LAST_MSG_INDEX(todir) + 1;
6434 ast_trace(-1, "recip msgnum: %d\n", recipmsgnum);
6435
6436 if (recipmsgnum < recip->maxmsg - (imbox ? 0 : inprocess_count(vmu->mailbox, vmu->context, 0))) {
6437 int exists = 0;
6438
6439 make_file(topath, sizeof(topath), todir, recipmsgnum);
6440 ast_trace(-1, "topath: %s\n", topath);
6441
6442 exists = SCOPE_CALL_WITH_INT_RESULT(-1, EXISTS, fromdir, msgnum, frompath, chan ? ast_channel_language(chan) : "");
6443 if (exists) {
6444 SCOPE_CALL(-1, COPY, fromdir, msgnum, todir, recipmsgnum, recip->mailbox, recip->context, frompath, topath);
6445 } else {
6446 SCOPE_CALL(-1, copy_plain_file,frompath, topath);
6447 SCOPE_CALL(-1, STORE, todir, recip->mailbox, recip->context, recipmsgnum, chan, recip, fmt, duration, NULL, NULL, NULL);
6448 SCOPE_CALL(-1, vm_delete, topath);
6449
6450 }
6451 } else {
6452 ast_log(AST_LOG_ERROR, "Recipient mailbox %s@%s is full\n", recip->mailbox, recip->context);
6453 res = -1;
6454 }
6455 ast_unlock_path(todir);
6456 if (chan) {
6457 struct ast_party_caller *caller = ast_channel_caller(chan);
6458 notify_new_message(chan, recip, NULL, recipmsgnum, duration, fmt,
6459 S_COR(caller->id.number.valid, caller->id.number.str, NULL),
6460 S_COR(caller->id.name.valid, caller->id.name.str, NULL),
6461 flag);
6462 }
6463
6464 SCOPE_EXIT_RTN_VALUE(res, "Done. RC: %d\n", res);
6465 }
6466 #endif
6467 #if !(defined(IMAP_STORAGE) || defined(ODBC_STORAGE))
6468
6469 static int messagecount(const char *mailbox_id, const char *folder)
6470 {
6471 char *context;
6472 char *mailbox;
6473
6474 if (ast_strlen_zero(mailbox_id)
6475 || separate_mailbox(ast_strdupa(mailbox_id), &mailbox, &context)) {
6476 return 0;
6477 }
6478
6479 return __has_voicemail(context, mailbox, folder, 0) + (folder && strcmp(folder, "INBOX") ? 0 : __has_voicemail(context, mailbox, "Urgent", 0));
6480 }
6481
6482 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit)
6483 {
6484 DIR *dir;
6485 struct dirent *de;
6486 char fn[256];
6487 int ret = 0;
6488 struct alias_mailbox_mapping *mapping;
6489 char *c;
6490 char *m;
6491
6492 /* If no mailbox, return immediately */
6493 if (ast_strlen_zero(mailbox))
6494 return 0;
6495
6496 if (ast_strlen_zero(folder))
6497 folder = "INBOX";
6498 if (ast_strlen_zero(context))
6499 context = "default";
6500
6501 c = (char *)context;
6502 m = (char *)mailbox;
6503
6504 if (!ast_strlen_zero(aliasescontext)) {
6505 char tmp[MAX_VM_MAILBOX_LEN];
6506
6507 snprintf(tmp, MAX_VM_MAILBOX_LEN, "%s@%s", mailbox, context);
6508 mapping = ao2_find(alias_mailbox_mappings, tmp, OBJ_SEARCH_KEY);
6509 if (mapping) {
6510 separate_mailbox(ast_strdupa(mapping->mailbox), &m, &c);
6511 ao2_ref(mapping, -1);
6512 }
6513 }
6514
6515 snprintf(fn, sizeof(fn), "%s%s/%s/%s", VM_SPOOL_DIR, c, m, folder);
6516
6517 if (!(dir = opendir(fn)))
6518 return 0;
6519
6520 while ((de = readdir(dir))) {
6521 if (!strncasecmp(de->d_name, "msg", 3)) {
6522 if (shortcircuit) {
6523 ret = 1;
6524 break;
6525 } else if (!strncasecmp(de->d_name + 8, "txt", 3)) {
6526 ret++;
6527 }
6528 }
6529 }
6530
6531 closedir(dir);
6532
6533 return ret;
6534 }
6535
6536 /*!
6537 * \brief Determines if the given folder has messages.
6538 * \param mailbox The \@ delimited string for user\@context. If no context is found, uses 'default' for the context.
6539 * \param folder the folder to look in
6540 *
6541 * This function is used when the mailbox is stored in a filesystem back end.
6542 * This invokes the __has_voicemail(). Here we are interested in the presence of messages (> 0) only, not the actual count.
6543 * \return 1 if the folder has one or more messages. zero otherwise.
6544 */
6545 static int has_voicemail(const char *mailbox, const char *folder)
6546 {
6547 char tmp[256], *tmp2 = tmp, *box, *context;
6548 ast_copy_string(tmp, mailbox, sizeof(tmp));
6549 if (ast_strlen_zero(folder)) {
6550 folder = "INBOX";
6551 }
6552 while ((box = strsep(&tmp2, ",&"))) {
6553 if ((context = strchr(box, '@')))
6554 *context++ = '\0';
6555 else
6556 context = "default";
6557 if (__has_voicemail(context, box, folder, 1))
6558 return 1;
6559 /* If we are checking INBOX, we should check Urgent as well */
6560 if (!strcmp(folder, "INBOX") && __has_voicemail(context, box, "Urgent", 1)) {
6561 return 1;
6562 }
6563 }
6564 return 0;
6565 }
6566
6567 /*!
6568 * \brief Check the given mailbox's message count.
6569 * \param mailbox The \@ delimited string for user\@context. If no context is found, uses 'default' for the context.
6570 * \param urgentmsgs urgent message count.
6571 * \param newmsgs new message count.
6572 * \param oldmsgs old message count pointer
6573 * \return -1 if error occurred, 0 otherwise.
6574 */
6575 static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
6576 {
6577 char tmp[256];
6578 char *context;
6579
6580 /* If no mailbox, return immediately */
6581 if (ast_strlen_zero(mailbox)) {
6582 return 0;
6583 }
6584
6585 if (newmsgs) {
6586 *newmsgs = 0;
6587 }
6588 if (oldmsgs) {
6589 *oldmsgs = 0;
6590 }
6591 if (urgentmsgs) {
6592 *urgentmsgs = 0;
6593 }
6594
6595 if (strchr(mailbox, ',')) {
6596 int tmpnew, tmpold, tmpurgent;
6597 char *mb, *cur;
6598
6599 ast_copy_string(tmp, mailbox, sizeof(tmp));
6600 mb = tmp;
6601 while ((cur = strsep(&mb, ", "))) {
6602 if (!ast_strlen_zero(cur)) {
6603 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL)) {
6604 return -1;
6605 } else {
6606 if (newmsgs) {
6607 *newmsgs += tmpnew;
6608 }
6609 if (oldmsgs) {
6610 *oldmsgs += tmpold;
6611 }
6612 if (urgentmsgs) {
6613 *urgentmsgs += tmpurgent;
6614 }
6615 }
6616 }
6617 }
6618 return 0;
6619 }
6620
6621 ast_copy_string(tmp, mailbox, sizeof(tmp));
6622
6623 if ((context = strchr(tmp, '@'))) {
6624 *context++ = '\0';
6625 } else {
6626 context = "default";
6627 }
6628
6629 if (newmsgs) {
6630 *newmsgs = __has_voicemail(context, tmp, "INBOX", 0);
6631 }
6632 if (oldmsgs) {
6633 *oldmsgs = __has_voicemail(context, tmp, "Old", 0);
6634 }
6635 if (urgentmsgs) {
6636 *urgentmsgs = __has_voicemail(context, tmp, "Urgent", 0);
6637 }
6638
6639 return 0;
6640 }
6641
6642 #endif
6643
6644 /* Exactly the same function for file-based, ODBC-based, and IMAP-based, so why create 3 different copies? */
6645 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
6646 {
6647 int urgentmsgs = 0;
6648 int res = inboxcount2(mailbox, &urgentmsgs, newmsgs, oldmsgs);
6649 if (newmsgs) {
6650 *newmsgs += urgentmsgs;
6651 }
6652 return res;
6653 }
6654
6655 static void run_externnotify(const char *context, const char *extension, const char *flag)
6656 {
6657 char arguments[255];
6658 char ext_context[256] = "";
6659 int newvoicemails = 0, oldvoicemails = 0, urgentvoicemails = 0;
6660 struct ast_smdi_mwi_message *mwi_msg;
6661
6662 if (!ast_strlen_zero(context))
6663 snprintf(ext_context, sizeof(ext_context), "%s@%s", extension, context);
6664 else
6665 ast_copy_string(ext_context, extension, sizeof(ext_context));
6666
6667 if (smdi_iface) {
6668 if (ast_app_has_voicemail(ext_context, NULL))
6669 ast_smdi_mwi_set(smdi_iface, extension);
6670 else
6671 ast_smdi_mwi_unset(smdi_iface, extension);
6672
6673 if ((mwi_msg = ast_smdi_mwi_message_wait_station(smdi_iface, SMDI_MWI_WAIT_TIMEOUT, extension))) {
6674 ast_log(AST_LOG_ERROR, "Error executing SMDI MWI change for %s\n", extension);
6675 if (!strncmp(mwi_msg->cause, "INV", 3))
6676 ast_log(AST_LOG_ERROR, "Invalid MWI extension: %s\n", mwi_msg->fwd_st);
6677 else if (!strncmp(mwi_msg->cause, "BLK", 3))
6678 ast_log(AST_LOG_WARNING, "MWI light was already on or off for %s\n", mwi_msg->fwd_st);
6679 ast_log(AST_LOG_WARNING, "The switch reported '%s'\n", mwi_msg->cause);
6680 ao2_ref(mwi_msg, -1);
6681 } else {
6682 ast_debug(1, "Successfully executed SMDI MWI change for %s\n", extension);
6683 }
6684 }
6685
6686 if (!ast_strlen_zero(externnotify)) {
6687 if (inboxcount2(ext_context, &urgentvoicemails, &newvoicemails, &oldvoicemails)) {
6688 ast_log(AST_LOG_ERROR, "Problem in calculating number of voicemail messages available for extension %s\n", extension);
6689 } else {
6690 snprintf(arguments, sizeof(arguments), "%s %s %s %d %d %d &",
6691 externnotify, S_OR(context, "\"\""),
6692 extension, newvoicemails,
6693 oldvoicemails, urgentvoicemails);
6694 ast_debug(1, "Executing %s\n", arguments);
6695 ast_safe_system(arguments);
6696 }
6697 }
6698 }
6699
6700 /*!
6701 * \brief Variables used for saving a voicemail.
6702 *
6703 * This includes the record gain, mode flags, and the exit context of the channel that was used for leaving the voicemail.
6704 */
6705 struct leave_vm_options {
6706 unsigned int flags;
6707 signed char record_gain;
6708 char *exitcontext;
6709 char *beeptone;
6710 };
6711
6712 static void generate_msg_id(char *dst)
6713 {
6714 /* msg id is time of msg_id generation plus an incrementing value
6715 * called each time a new msg_id is generated. This should achieve uniqueness,
6716 * but only in single system solutions.
6717 */
6718 unsigned int unique_counter = ast_atomic_fetchadd_int(&msg_id_incrementor, +1);
6719 snprintf(dst, MSG_ID_LEN, "%ld-%08x", (long) time(NULL), unique_counter);
6720 }
6721
6722 /*!
6723 * \internal
6724 * \brief Creates a voicemail based on a specified file to a mailbox.
6725 * \param recdata A vm_recording_data containing filename and voicemail txt info.
6726 * \retval -1 failure
6727 * \retval 0 success
6728 *
6729 * This is installed to the app.h voicemail functions and accommodates all voicemail
6730 * storage methods. It should probably be broken out along with leave_voicemail at
6731 * some point in the future.
6732 *
6733 * This function currently only works for a single recipient and only uses the format
6734 * specified in recording_ext.
6735 */
6736 static int msg_create_from_file(struct ast_vm_recording_data *recdata)
6737 {
6738 /* voicemail recipient structure */
6739 struct ast_vm_user *recipient; /* points to svm once it's been created */
6740 struct ast_vm_user svm; /* struct storing the voicemail recipient */
6741
6742 /* File paths */
6743 char tmpdir[PATH_MAX]; /* directory temp files are stored in */
6744 char tmptxtfile[PATH_MAX]; /* tmp file for voicemail txt file */
6745 char desttxtfile[PATH_MAX]; /* final destination for txt file */
6746 char tmpaudiofile[PATH_MAX]; /* tmp file where audio is stored */
6747 char dir[PATH_MAX]; /* destination for tmp files on completion */
6748 char destination[PATH_MAX]; /* destination with msgXXXX. Basically <dir>/msgXXXX */
6749
6750 /* stuff that only seems to be needed for IMAP */
6751 #ifdef IMAP_STORAGE
6752 struct vm_state *vms = NULL;
6753 char ext_context[256] = "";
6754 int newmsgs = 0;
6755 int oldmsgs = 0;
6756 #endif
6757
6758 /* miscellaneous operational variables */
6759 int res = 0; /* Used to store error codes from functions */
6760 int txtdes /* File descriptor for the text file used to write the voicemail info */;
6761 FILE *txt; /* FILE pointer to text file used to write the voicemail info */
6762 char date[256]; /* string used to hold date of the voicemail (only used for ODBC) */
6763 int msgnum; /* the 4 digit number designated to the voicemail */
6764 int duration = 0; /* Length of the audio being recorded in seconds */
6765 struct ast_filestream *recording_fs; /*used to read the recording to get duration data */
6766
6767 /* We aren't currently doing anything with category, since it comes from a channel variable and
6768 * this function doesn't use channels, but this function could add that as an argument later. */
6769 const char *category = NULL; /* pointless for now */
6770 char msg_id[MSG_ID_LEN];
6771
6772 /* Start by checking to see if the file actually exists... */
6773 if (!(ast_fileexists(recdata->recording_file, recdata->recording_ext, NULL))) {
6774 ast_log(LOG_ERROR, "File: %s not found.\n", recdata->recording_file);
6775 return -1;
6776 }
6777
6778 memset(&svm, 0, sizeof(svm));
6779 if (!(recipient = find_user(&svm, recdata->context, recdata->mailbox))) {
6780 ast_log(LOG_ERROR, "No entry in voicemail config file for '%s@%s'\n", recdata->mailbox, recdata->context);
6781 return -1;
6782 }
6783
6784 /* determine duration in seconds */
6785 if ((recording_fs = ast_readfile(recdata->recording_file, recdata->recording_ext, NULL, 0, 0, VOICEMAIL_DIR_MODE))) {
6786 if (!ast_seekstream(recording_fs, 0, SEEK_END)) {
6787 long framelength = ast_tellstream(recording_fs);
6788 int sample_rate = ast_ratestream(recording_fs);
6789 if (sample_rate) {
6790 duration = (int) (framelength / sample_rate);
6791 } else {
6792 ast_log(LOG_ERROR,"Unable to determine sample rate of recording %s\n", recdata->recording_file);
6793 }
6794 }
6795 ast_closestream(recording_fs);
6796 }
6797
6798 /* If the duration was below the minimum duration for the user, let's just drop the whole thing now */
6799 if (duration < recipient->minsecs) {
6800 ast_log(LOG_NOTICE, "Copying recording to voicemail %s@%s skipped because duration was shorter than "
6801 "minmessage of recipient\n", recdata->mailbox, recdata->context);
6802 return -1;
6803 }
6804
6805 /* Note that this number must be dropped back to a net sum of zero before returning from this function */
6806
6807 if ((res = create_dirpath(tmpdir, sizeof(tmpdir), recipient->context, recdata->mailbox, "tmp"))) {
6808 ast_log(LOG_ERROR, "Failed to make directory.\n");
6809 }
6810
6811 snprintf(tmptxtfile, sizeof(tmptxtfile), "%s/XXXXXX", tmpdir);
6812 txtdes = mkstemp(tmptxtfile);
6813 if (txtdes < 0) {
6814 chmod(tmptxtfile, VOICEMAIL_FILE_MODE & ~my_umask);
6815 /* Something screwed up. Abort. */
6816 ast_log(AST_LOG_ERROR, "Unable to create message file: %s\n", strerror(errno));
6817 free_user(recipient);
6818 return -1;
6819 }
6820
6821 /* Store information */
6822 txt = fdopen(txtdes, "w+");
6823 if (txt) {
6824 generate_msg_id(msg_id);
6825 get_date(date, sizeof(date));
6826 fprintf(txt,
6827 ";\n"
6828 "; Message Information file\n"
6829 ";\n"
6830 "[message]\n"
6831 "origmailbox=%s\n"
6832 "context=%s\n"
6833 "exten=%s\n"
6834 "rdnis=Unknown\n"
6835 "priority=%d\n"
6836 "callerchan=%s\n"
6837 "callerid=%s\n"
6838 "origdate=%s\n"
6839 "origtime=%ld\n"
6840 "category=%s\n"
6841 "msg_id=%s\n"
6842 "flag=\n" /* flags not supported in copy from file yet */
6843 "duration=%d\n", /* Don't have any reliable way to get duration of file. */
6844
6845 recdata->mailbox,
6846 S_OR(recdata->call_context, ""),
6847 S_OR(recdata->call_extension, ""),
6848 recdata->call_priority,
6849 S_OR(recdata->call_callerchan, "Unknown"),
6850 S_OR(recdata->call_callerid, "Unknown"),
6851 date, (long) time(NULL),
6852 S_OR(category, ""),
6853 msg_id,
6854 duration);
6855
6856 /* Since we are recording from a file, we shouldn't need to do anything else with
6857 * this txt file */
6858 fclose(txt);
6859
6860 } else {
6861 ast_log(LOG_WARNING, "Error opening text file for output\n");
6862 if (ast_check_realtime("voicemail_data")) {
6863 ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
6864 }
6865 free_user(recipient);
6866 return -1;
6867 }
6868
6869 /* At this point, the actual creation of a voicemail message should be finished.
6870 * Now we just need to copy the files being recorded into the receiving folder. */
6871
6872 create_dirpath(dir, sizeof(dir), recipient->context, recipient->mailbox, recdata->folder);
6873
6874 #ifdef IMAP_STORAGE
6875 /* make recipient info into an inboxcount friendly string */
6876 snprintf(ext_context, sizeof(ext_context), "%s@%s", recipient->mailbox, recipient->context);
6877
6878 /* Is ext a mailbox? */
6879 /* must open stream for this user to get info! */
6880 res = inboxcount(ext_context, &newmsgs, &oldmsgs);
6881 if (res < 0) {
6882 ast_log(LOG_NOTICE, "Can not leave voicemail, unable to count messages\n");
6883 free_user(recipient);
6884 unlink(tmptxtfile);
6885 return -1;
6886 }
6887 if (!(vms = get_vm_state_by_mailbox(recipient->mailbox, recipient->context, 0))) {
6888 /* It is possible under certain circumstances that inboxcount did not
6889 * create a vm_state when it was needed. This is a catchall which will
6890 * rarely be used.
6891 */
6892 if (!(vms = create_vm_state_from_user(recipient))) {
6893 ast_log(LOG_ERROR, "Couldn't allocate necessary space\n");
6894 free_user(recipient);
6895 unlink(tmptxtfile);
6896 return -1;
6897 }
6898 }
6899 vms->newmessages++;
6900
6901 /* here is a big difference! We add one to it later */
6902 msgnum = newmsgs + oldmsgs;
6903 ast_debug(3, "Messagecount set to %d\n", msgnum);
6904 snprintf(destination, sizeof(destination), "%simap/msg%s%04d", VM_SPOOL_DIR, recipient->mailbox, msgnum);
6905
6906 /* Check to see if we have enough room in the mailbox. If not, spit out an error and end
6907 * Note that imap_check_limits raises inprocess_count if successful */
6908 if ((res = imap_check_limits(NULL, vms, recipient, msgnum))) {
6909 ast_log(LOG_NOTICE, "Didn't copy to voicemail. Mailbox for %s@%s is full.\n", recipient->mailbox, recipient->context);
6910 inprocess_count(recipient->mailbox, recipient->context, -1);
6911 free_user(recipient);
6912 unlink(tmptxtfile);
6913 return -1;
6914 }
6915
6916 #else
6917
6918 /* Check to see if the mailbox is full for ODBC/File storage */
6919 ast_debug(3, "mailbox = %d : inprocess = %d\n", COUNT(recipient, dir),
6920 inprocess_count(recipient->mailbox, recipient->context, 0));
6921 if (COUNT(recipient, dir) > recipient->maxmsg - inprocess_count(recipient->mailbox, recipient->context, +1)) {
6922 ast_log(AST_LOG_WARNING, "Didn't copy to voicemail. Mailbox for %s@%s is full.\n", recipient->mailbox, recipient->context);
6923 inprocess_count(recipient->mailbox, recipient->context, -1);
6924 free_user(recipient);
6925 unlink(tmptxtfile);
6926 return -1;
6927 }
6928
6929 msgnum = LAST_MSG_INDEX(dir) + 1;
6930 #endif
6931
6932 /* Lock the directory receiving the voicemail since we want it to still exist when we attempt to copy the voicemail.
6933 * We need to unlock it before we return. */
6934 if (vm_lock_path(dir)) {
6935 ast_log(LOG_ERROR, "Couldn't lock directory %s. Voicemail will be lost.\n", dir);
6936 /* Delete files */
6937 ast_filedelete(tmptxtfile, NULL);
6938 unlink(tmptxtfile);
6939 free_user(recipient);
6940 return -1;
6941 }
6942
6943 make_file(destination, sizeof(destination), dir, msgnum);
6944
6945 make_file(tmpaudiofile, sizeof(tmpaudiofile), tmpdir, msgnum);
6946
6947 if (ast_filecopy(recdata->recording_file, tmpaudiofile, recdata->recording_ext)) {
6948 ast_log(LOG_ERROR, "Audio file failed to copy to tmp dir. Probably low disk space.\n");
6949
6950 inprocess_count(recipient->mailbox, recipient->context, -1);
6951 ast_unlock_path(dir);
6952 free_user(recipient);
6953 unlink(tmptxtfile);
6954 return -1;
6955 }
6956
6957 /* Alright, try to copy to the destination folder now. */
6958 if (ast_filerename(tmpaudiofile, destination, recdata->recording_ext)) {
6959 ast_log(LOG_ERROR, "Audio file failed to move to destination directory. Permissions/Overlap?\n");
6960 inprocess_count(recipient->mailbox, recipient->context, -1);
6961 ast_unlock_path(dir);
6962 free_user(recipient);
6963 unlink(tmptxtfile);
6964 return -1;
6965 }
6966
6967 snprintf(desttxtfile, sizeof(desttxtfile), "%s.txt", destination);
6968 rename(tmptxtfile, desttxtfile);
6969
6970 if (chmod(desttxtfile, VOICEMAIL_FILE_MODE) < 0) {
6971 ast_log(AST_LOG_ERROR, "Couldn't set permissions on voicemail text file %s: %s", desttxtfile, strerror(errno));
6972 }
6973
6974
6975 ast_unlock_path(dir);
6976 inprocess_count(recipient->mailbox, recipient->context, -1);
6977
6978 /* If we copied something, we should store it either to ODBC or IMAP if we are using those. The STORE macro allows us
6979 * to do both with one line and is also safe to use with file storage mode. Also, if we are using ODBC, now is a good
6980 * time to create the voicemail database entry. */
6981 if (ast_fileexists(destination, NULL, NULL) > 0) {
6982 struct ast_channel *chan = NULL;
6983 char fmt[80];
6984 char clid[80];
6985 char cidnum[80], cidname[80];
6986 int send_email;
6987
6988 if (ast_check_realtime("voicemail_data")) {
6989 get_date(date, sizeof(date));
6990 ast_store_realtime("voicemail_data",
6991 "origmailbox", recdata->mailbox,
6992 "context", S_OR(recdata->context, ""),
6993 "exten", S_OR(recdata->call_extension, ""),
6994 "priority", recdata->call_priority,
6995 "callerchan", S_OR(recdata->call_callerchan, "Unknown"),
6996 "callerid", S_OR(recdata->call_callerid, "Unknown"),
6997 "origdate", date,
6998 "origtime", time(NULL),
6999 "category", S_OR(category, ""),
7000 "filename", tmptxtfile,
7001 "duration", duration,
7002 SENTINEL);
7003 }
7004
7005 STORE(dir, recipient->mailbox, recipient->context, msgnum, NULL, recipient, fmt, 0, vms, "", msg_id);
7006
7007 send_email = ast_test_flag(recipient, VM_EMAIL_EXT_RECS);
7008
7009 if (send_email) {
7010 /* Send an email if possible, fall back to just notifications if not. */
7011 ast_copy_string(fmt, recdata->recording_ext, sizeof(fmt));
7012 ast_copy_string(clid, recdata->call_callerid, sizeof(clid));
7013 ast_callerid_split(clid, cidname, sizeof(cidname), cidnum, sizeof(cidnum));
7014
7015 /* recdata->call_callerchan itself no longer exists, so we can't use the real channel. Use a dummy one. */
7016 chan = ast_dummy_channel_alloc();
7017 }
7018 if (chan) {
7019 notify_new_message(chan, recipient, NULL, msgnum, duration, fmt, cidnum, cidname, "");
7020 ast_channel_unref(chan);
7021 } else {
7022 if (send_email) { /* We tried and failed. */
7023 ast_log(LOG_WARNING, "Failed to allocate dummy channel, email will not be sent\n");
7024 }
7025 notify_new_state(recipient);
7026 }
7027 }
7028
7029 free_user(recipient);
7030 unlink(tmptxtfile);
7031 return 0;
7032 }
7033
7034 /*!
7035 * \brief Prompts the user and records a voicemail to a mailbox.
7036 * \param chan
7037 * \param ext
7038 * \param options OPT_BUSY_GREETING, OPT_UNAVAIL_GREETING
7039 *
7040 *
7041 *
7042 * \return zero on success, -1 on error.
7043 */
7044 static int leave_voicemail(struct ast_channel *chan, char *ext, struct leave_vm_options *options)
7045 {
7046 #ifdef IMAP_STORAGE
7047 int newmsgs, oldmsgs;
7048 #endif
7049 char txtfile[PATH_MAX];
7050 char tmptxtfile[PATH_MAX];
7051 struct vm_state *vms = NULL;
7052 char callerid[256];
7053 FILE *txt;
7054 char date[256];
7055 int txtdes;
7056 int res = 0;
7057 int msgnum;
7058 int duration = 0;
7059 int sound_duration = 0;
7060 int ouseexten = 0;
7061 int greeting_only = 0;
7062 char tmpdur[16];
7063 char priority[16];
7064 char origtime[16];
7065 char dir[PATH_MAX];
7066 char tmpdir[PATH_MAX];
7067 char fn[PATH_MAX];
7068 char prefile[PATH_MAX] = "";
7069 char tempfile[PATH_MAX] = "";
7070 char ext_context[256] = "";
7071 char fmt[80];
7072 char *context;
7073 char ecodes[17] = "#";
7074 struct ast_str *tmp = ast_str_create(16);
7075 char *tmpptr;
7076 struct ast_vm_user *vmu;
7077 struct ast_vm_user svm;
7078 const char *category = NULL;
7079 const char *code;
7080 const char *alldtmf = "0123456789ABCD*#";
7081 char flag[80];
7082 SCOPE_ENTER(3, "%s: %s\n", ast_channel_name(chan), ext);
7083
7084 if (!tmp) {
7085 SCOPE_EXIT_RTN_VALUE(-1, "Failed to allocate memory for tmp\n");
7086 }
7087
7088 ast_str_set(&tmp, 0, "%s", ext);
7089 ext = ast_str_buffer(tmp);
7090 if ((context = strchr(ext, '@'))) {
7091 *context++ = '\0';
7092 tmpptr = strchr(context, '&');
7093 } else {
7094 tmpptr = strchr(ext, '&');
7095 }
7096
7097 if (tmpptr)
7098 *tmpptr++ = '\0';
7099
7100 ast_channel_lock(chan);
7101 if ((category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY"))) {
7102 category = ast_strdupa(category);
7103 }
7104 ast_channel_unlock(chan);
7105
7106 if (ast_test_flag(options, OPT_MESSAGE_Urgent)) {
7107 ast_copy_string(flag, "Urgent", sizeof(flag));
7108 } else if (ast_test_flag(options, OPT_MESSAGE_PRIORITY)) {
7109 ast_copy_string(flag, "PRIORITY", sizeof(flag));
7110 } else {
7111 flag[0] = '\0';
7112 }
7113
7114 ast_debug(3, "Before find_user\n");
7115 memset(&svm, 0, sizeof(svm));
7116 if (!(vmu = find_user(&svm, context, ext))) {
7117 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7118 ast_free(tmp);
7119 SCOPE_EXIT_LOG_RTN_VALUE(res, LOG_WARNING,
7120 "%s: Exten: %s: No entry in voicemail config file for '%s'\n", ast_channel_name(chan), ext, ext);
7121 }
7122
7123 /* If maxmsg is zero, act as a "greetings only" voicemail: Exit successfully without recording */
7124 if (vmu->maxmsg == 0) {
7125 greeting_only = 1;
7126 ast_set_flag(options, OPT_SILENT);
7127 }
7128
7129 /* Setup pre-file if appropriate */
7130 if (strcmp(vmu->context, "default"))
7131 snprintf(ext_context, sizeof(ext_context), "%s@%s", ext, vmu->context);
7132 else
7133 ast_copy_string(ext_context, vmu->mailbox, sizeof(ext_context));
7134
7135 /* Set the path to the prefile. Will be one of
7136 VM_SPOOL_DIRcontext/ext/busy
7137 VM_SPOOL_DIRcontext/ext/unavail
7138 Depending on the flag set in options.
7139 */
7140 if (ast_test_flag(options, OPT_BUSY_GREETING)) {
7141 snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, ext);
7142 } else if (ast_test_flag(options, OPT_UNAVAIL_GREETING)) {
7143 snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, ext);
7144 }
7145 ast_trace(-1, "prefile: %s\n", prefile);
7146 /* Set the path to the tmpfile as
7147 VM_SPOOL_DIR/context/ext/temp
7148 and attempt to create the folder structure.
7149 */
7150 snprintf(tempfile, sizeof(tempfile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, ext);
7151 ast_trace(-1, "tempfile: %s\n", tempfile);
7152 if ((res = create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, ext, "tmp"))) {
7153 free_user(vmu);
7154 ast_free(tmp);
7155 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING,
7156 "%s: Exten: %s: Failed to make directory (%s)\n", ast_channel_name(chan), ext, tempfile);
7157 }
7158 SCOPE_CALL(-1, RETRIEVE, tempfile, -1, vmu->mailbox, vmu->context);
7159 if (ast_fileexists(tempfile, NULL, NULL) > 0) {
7160 ast_copy_string(prefile, tempfile, sizeof(prefile));
7161 ast_trace(-1, "new prefile: %s\n", prefile);
7162 }
7163
7164 SCOPE_CALL(-1, DISPOSE, tempfile, -1);
7165
7166 /* It's easier just to try to make it than to check for its existence */
7167 #ifndef IMAP_STORAGE
7168 create_dirpath(dir, sizeof(dir), vmu->context, ext, "INBOX");
7169 #else
7170 snprintf(dir, sizeof(dir), "%simap", VM_SPOOL_DIR);
7171 if (mkdir(dir, VOICEMAIL_DIR_MODE) && errno != EEXIST) {
7172 ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dir, strerror(errno));
7173 }
7174 #endif
7175
7176 /* Check current context for special extensions */
7177 if (ast_test_flag(vmu, VM_OPERATOR)) {
7178 if (!ast_strlen_zero(vmu->exit)) {
7179 if (ast_exists_extension(chan, vmu->exit, "o", 1,
7180 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
7181 strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
7182 ouseexten = 1;
7183 }
7184 } else if (ast_exists_extension(chan, ast_channel_context(chan), "o", 1,
7185 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
7186 strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
7187 ouseexten = 1;
7188 }
7189 }
7190
7191 if (!ast_strlen_zero(vmu->exit)) {
7192 if (ast_exists_extension(chan, vmu->exit, "a", 1,
7193 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
7194 strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
7195 }
7196 } else if (ast_exists_extension(chan, ast_channel_context(chan), "a", 1,
7197 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
7198 strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
7199 }
7200
7201 if (ast_test_flag(options, OPT_DTMFEXIT)) {
7202 for (code = alldtmf; *code; code++) {
7203 char e[2] = "";
7204 e[0] = *code;
7205 if (strchr(ecodes, e[0]) == NULL
7206 && ast_canmatch_extension(chan,
7207 (!ast_strlen_zero(options->exitcontext) ? options->exitcontext : ast_channel_context(chan)),
7208 e, 1, S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
7209 strncat(ecodes, e, sizeof(ecodes) - strlen(ecodes) - 1);
7210 }
7211 }
7212 }
7213
7214 /* Play the beginning intro if desired */
7215 if (!ast_strlen_zero(prefile)) {
7216 #if defined(ODBC_STORAGE)
7217 int success = SCOPE_CALL_WITH_INT_RESULT(-1, RETRIEVE, prefile, -1, ext, context);
7218 #elif defined(IMAP_STORAGE)
7219 SCOPE_CALL(-1, RETRIEVE, prefile, -1, ext, context);
7220 #endif
7221
7222 if (ast_fileexists(prefile, NULL, NULL) > 0) {
7223 if (ast_streamfile(chan, prefile, ast_channel_language(chan)) > -1) {
7224 /* We know we have a greeting at this point, so squelch the instructions
7225 * if that is what is being asked of us */
7226 if (ast_test_flag(options, OPT_SILENT_IF_GREET)) {
7227 ast_set_flag(options, OPT_SILENT);
7228 }
7229 res = ast_waitstream(chan, ecodes);
7230 }
7231 #ifdef ODBC_STORAGE
7232 if (success == -1) {
7233 /* We couldn't retrieve the file from the database, but we found it on the file system. Let's put it in the database. */
7234 ast_trace(-1, "Greeting '%s' not retrieved from database, but found in file storage. Inserting into database\n", prefile);
7235 SCOPE_CALL(-1, odbc_store_message, prefile, vmu->mailbox, vmu->context, -1);
7236 }
7237 #endif
7238 } else {
7239 ast_trace(-1, "%s doesn't exist, doing what we can\n", prefile);
7240 res = invent_message(chan, vmu->context, ext, ast_test_flag(options, OPT_BUSY_GREETING), ecodes);
7241 }
7242 SCOPE_CALL(-1, DISPOSE, prefile, -1);
7243 if (res < 0) {
7244 free_user(vmu);
7245 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7246 ast_free(tmp);
7247 SCOPE_EXIT_RTN_VALUE(-1, "Hang up during prefile playback\n");
7248 }
7249 }
7250 if (res == '#') {
7251 /* On a '#' we skip the instructions */
7252 ast_set_flag(options, OPT_SILENT);
7253 res = 0;
7254 }
7255 if (!res && !ast_test_flag(options, OPT_SILENT)) {
7256 res = ast_stream_and_wait(chan, INTRO, ecodes);
7257 if (res == '#') {
7258 ast_set_flag(options, OPT_SILENT);
7259 res = 0;
7260 }
7261 }
7262 if (res > 0)
7263 ast_stopstream(chan);
7264 /* Check for a '*' here in case the caller wants to escape from voicemail to something
7265 other than the operator -- an automated attendant or mailbox login for example */
7266 if (res == '*') {
7267 ast_channel_exten_set(chan, "a");
7268 if (!ast_strlen_zero(vmu->exit)) {
7269 ast_channel_context_set(chan, vmu->exit);
7270 }
7271 ast_channel_priority_set(chan, 0);
7272 free_user(vmu);
7273 pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
7274 ast_free(tmp);
7275 SCOPE_EXIT_RTN_VALUE(0, "User escaped with '*'\n");
7276 }
7277
7278 /* Check for a '0' here */
7279 if (ast_test_flag(vmu, VM_OPERATOR) && res == '0') {
7280 transfer:
7281 if (ouseexten) {
7282 ast_channel_exten_set(chan, "o");
7283 if (!ast_strlen_zero(vmu->exit)) {
7284 ast_channel_context_set(chan, vmu->exit);
7285 }
7286 ast_play_and_wait(chan, "transfer");
7287 ast_channel_priority_set(chan, 0);
7288 pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
7289 }
7290 free_user(vmu);
7291 ast_free(tmp);
7292 SCOPE_EXIT_RTN_VALUE(OPERATOR_EXIT, "User escaped with '0'\n");
7293 }
7294
7295 /* Allow all other digits to exit Voicemail and return to the dialplan */
7296 if (ast_test_flag(options, OPT_DTMFEXIT) && res > 0) {
7297 if (!ast_strlen_zero(options->exitcontext)) {
7298 ast_channel_context_set(chan, options->exitcontext);
7299 }
7300 free_user(vmu);
7301 ast_free(tmp);
7302 pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
7303 SCOPE_EXIT_RTN_VALUE(res, "User escaped back to dialplan '%c'\n", res);
7304 }
7305
7306 if (greeting_only) {
7307 ast_debug(3, "Greetings only VM (maxmsg=0), Skipping voicemail recording\n");
7308 pbx_builtin_setvar_helper(chan, "VMSTATUS", "SUCCESS");
7309 res = 0;
7310 goto leave_vm_out;
7311 }
7312
7313 if (res < 0) {
7314 free_user(vmu);
7315 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7316 ast_free(tmp);
7317 SCOPE_EXIT_RTN_VALUE(-1, "Other error '%d'\n", res);
7318 }
7319 /* The meat of recording the message... All the announcements and beeps have been played*/
7320 if (ast_channel_state(chan) != AST_STATE_UP) {
7321 ast_answer(chan);
7322 }
7323 ast_copy_string(fmt, vmfmts, sizeof(fmt));
7324 if (!ast_strlen_zero(fmt)) {
7325 char msg_id[MSG_ID_LEN] = "";
7326 msgnum = 0;
7327
7328 #ifdef IMAP_STORAGE
7329 /* Is ext a mailbox? */
7330 /* must open stream for this user to get info! */
7331 res = inboxcount(ext_context, &newmsgs, &oldmsgs);
7332 if (res < 0) {
7333 ast_log(AST_LOG_NOTICE, "Can not leave voicemail, unable to count messages\n");
7334 free_user(vmu);
7335 ast_free(tmp);
7336 return -1;
7337 }
7338 if (!(vms = get_vm_state_by_mailbox(ext, context, 0))) {
7339 /* It is possible under certain circumstances that inboxcount did not
7340 * create a vm_state when it was needed. This is a catchall which will
7341 * rarely be used.
7342 */
7343 if (!(vms = create_vm_state_from_user(vmu))) {
7344 ast_log(AST_LOG_ERROR, "Couldn't allocate necessary space\n");
7345 free_user(vmu);
7346 ast_free(tmp);
7347 return -1;
7348 }
7349 }
7350 vms->newmessages++;
7351
7352 /* here is a big difference! We add one to it later */
7353 msgnum = newmsgs + oldmsgs;
7354 ast_debug(3, "Messagecount set to %d\n", msgnum);
7355 snprintf(fn, sizeof(fn), "%simap/msg%s%04d", VM_SPOOL_DIR, vmu->mailbox, msgnum);
7356 /* set variable for compatibility */
7357 pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", "IMAP_STORAGE");
7358
7359 if ((res = imap_check_limits(chan, vms, vmu, msgnum))) {
7360 goto leave_vm_out;
7361 }
7362 #else
7363 if (COUNT(vmu, dir) >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
7364 res = ast_streamfile(chan, "vm-mailboxfull", ast_channel_language(chan));
7365 if (!res)
7366 res = ast_waitstream(chan, "");
7367 ast_log(AST_LOG_WARNING, "No more messages possible\n");
7368 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7369 inprocess_count(vmu->mailbox, vmu->context, -1);
7370 goto leave_vm_out;
7371 }
7372
7373 #endif
7374 snprintf(tmptxtfile, sizeof(tmptxtfile), "%s/XXXXXX", tmpdir);
7375 ast_trace(-1, "Tempfile: %s\n", tmptxtfile);
7376 txtdes = mkstemp(tmptxtfile);
7377 chmod(tmptxtfile, VOICEMAIL_FILE_MODE & ~my_umask);
7378 if (txtdes < 0) {
7379 res = ast_streamfile(chan, "vm-mailboxfull", ast_channel_language(chan));
7380 if (!res)
7381 res = ast_waitstream(chan, "");
7382 ast_log(AST_LOG_ERROR, "Unable to create message file: %s\n", strerror(errno));
7383 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7384 inprocess_count(vmu->mailbox, vmu->context, -1);
7385 goto leave_vm_out;
7386 }
7387
7388 /* Now play the beep once we have the message number for our next message. */
7389 if (res >= 0) {
7390 /* Unless we're *really* silent, try to send the beep */
7391 /* Play default or custom beep, unless no beep desired */
7392 if (!ast_strlen_zero(options->beeptone)) {
7393 res = ast_stream_and_wait(chan, options->beeptone, "");
7394 }
7395 }
7396
7397 /* Store information in real-time storage */
7398 if (ast_check_realtime("voicemail_data")) {
7399 snprintf(priority, sizeof(priority), "%d", ast_channel_priority(chan));
7400 snprintf(origtime, sizeof(origtime), "%ld", (long) time(NULL));
7401 get_date(date, sizeof(date));
7402 ast_callerid_merge(callerid, sizeof(callerid),
7403 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL),
7404 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL),
7405 "Unknown");
7406 ast_store_realtime("voicemail_data",
7407 "origmailbox", ext,
7408 "context", ast_channel_context(chan),
7409 "exten", ast_channel_exten(chan),
7410 "priority", priority,
7411 "callerchan", ast_channel_name(chan),
7412 "callerid", callerid,
7413 "origdate", date,
7414 "origtime", origtime,
7415 "category", S_OR(category, ""),
7416 "filename", tmptxtfile,
7417 SENTINEL);
7418 }
7419
7420 /* Store information */
7421 txt = fdopen(txtdes, "w+");
7422 if (txt) {
7423 generate_msg_id(msg_id);
7424 get_date(date, sizeof(date));
7425 ast_callerid_merge(callerid, sizeof(callerid),
7426 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL),
7427 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL),
7428 "Unknown");
7429 fprintf(txt,
7430 ";\n"
7431 "; Message Information file\n"
7432 ";\n"
7433 "[message]\n"
7434 "origmailbox=%s\n"
7435 "context=%s\n"
7436 "exten=%s\n"
7437 "rdnis=%s\n"
7438 "priority=%d\n"
7439 "callerchan=%s\n"
7440 "callerid=%s\n"
7441 "origdate=%s\n"
7442 "origtime=%ld\n"
7443 "category=%s\n"
7444 "msg_id=%s\n",
7445 ext,
7446 ast_channel_context(chan),
7447 ast_channel_exten(chan),
7448 S_COR(ast_channel_redirecting(chan)->from.number.valid,
7449 ast_channel_redirecting(chan)->from.number.str, "unknown"),
7450 ast_channel_priority(chan),
7451 ast_channel_name(chan),
7452 callerid,
7453 date, (long) time(NULL),
7454 category ? category : "",
7455 msg_id);
7456 ast_trace(-1, "Saving txt file mbox: %s msg_id: %s\n", ext, msg_id);
7457 } else {
7458 ast_log(AST_LOG_WARNING, "Error opening text file for output\n");
7459 inprocess_count(vmu->mailbox, vmu->context, -1);
7460 if (ast_check_realtime("voicemail_data")) {
7461 ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
7462 }
7463 res = ast_streamfile(chan, "vm-mailboxfull", ast_channel_language(chan));
7464 goto leave_vm_out;
7465 }
7466
7467 res = SCOPE_CALL_WITH_INT_RESULT(-1, play_record_review, chan, NULL, tmptxtfile, vmu->maxsecs, fmt, 1, vmu, &duration, &sound_duration, NULL, options->record_gain, vms, flag, msg_id, 0);
7468
7469 /* At this point, either we were instructed to make the message Urgent
7470 by arguments to VoiceMail or during the review process by the person
7471 leaving the message. So we update the directory where we want this
7472 message to go. */
7473 if (!strcmp(flag, "Urgent")) {
7474 create_dirpath(dir, sizeof(dir), vmu->context, ext, "Urgent");
7475 }
7476
7477 if (txt) {
7478 fprintf(txt, "flag=%s\n", flag);
7479 if (sound_duration < vmu->minsecs) {
7480 fclose(txt);
7481 ast_verb(3, "Recording was %d seconds long but needs to be at least %d - abandoning\n", sound_duration, vmu->minsecs);
7482 ast_filedelete(tmptxtfile, NULL);
7483 unlink(tmptxtfile);
7484 if (ast_check_realtime("voicemail_data")) {
7485 ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
7486 }
7487 inprocess_count(vmu->mailbox, vmu->context, -1);
7488 } else {
7489 fprintf(txt, "duration=%d\n", duration);
7490 fclose(txt);
7491 if (vm_lock_path(dir)) {
7492 ast_log(AST_LOG_ERROR, "Couldn't lock directory %s. Voicemail will be lost.\n", dir);
7493 /* Delete files */
7494 ast_filedelete(tmptxtfile, NULL);
7495 unlink(tmptxtfile);
7496 inprocess_count(vmu->mailbox, vmu->context, -1);
7497 } else if (ast_fileexists(tmptxtfile, NULL, NULL) <= 0) {
7498 ast_debug(1, "The recorded media file is gone, so we should remove the .txt file too!\n");
7499 unlink(tmptxtfile);
7500 ast_unlock_path(dir);
7501 inprocess_count(vmu->mailbox, vmu->context, -1);
7502 if (ast_check_realtime("voicemail_data")) {
7503 ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
7504 }
7505 } else {
7506 #ifndef IMAP_STORAGE
7507 msgnum = LAST_MSG_INDEX(dir) + 1;
7508 #endif
7509 make_file(fn, sizeof(fn), dir, msgnum);
7510
7511 /* assign a variable with the name of the voicemail file */
7512 #ifndef IMAP_STORAGE
7513 pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", fn);
7514 #else
7515 pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", "IMAP_STORAGE");
7516 #endif
7517
7518 snprintf(txtfile, sizeof(txtfile), "%s.txt", fn);
7519
7520 ast_trace(-1, "Renaming recordings '%s' -> fn '%s'\n", tmptxtfile, fn);
7521 /* ast_filerename renames the recordings but not the txt file */
7522 ast_filerename(tmptxtfile, fn, NULL);
7523
7524 ast_trace(-1, "Renaming txt file '%s' -> fn '%s'\n", tmptxtfile, txtfile);
7525 rename(tmptxtfile, txtfile);
7526 inprocess_count(vmu->mailbox, vmu->context, -1);
7527
7528 /* Properly set permissions on voicemail text descriptor file.
7529 Unfortunately mkstemp() makes this file 0600 on most unix systems. */
7530 if (chmod(txtfile, VOICEMAIL_FILE_MODE) < 0)
7531 ast_log(AST_LOG_ERROR, "Couldn't set permissions on voicemail text file %s: %s", txtfile, strerror(errno));
7532
7533 if (ast_check_realtime("voicemail_data")) {
7534 snprintf(tmpdur, sizeof(tmpdur), "%d", duration);
7535 ast_update_realtime("voicemail_data", "filename", tmptxtfile, "filename", fn, "duration", tmpdur, SENTINEL);
7536 }
7537 /* We must store the file first, before copying the message, because
7538 * ODBC storage does the entire copy with SQL.
7539 * Hold the path lock until after STORE so that concurrent callers
7540 * cannot read the same LAST_MSG_INDEX before the INSERT is committed.
7541 */
7542 if (ast_fileexists(fn, NULL, NULL) > 0) {
7543 #ifdef ODBC_STORAGE
7544 int store_failed;
7545 store_failed = odbc_store_message(dir, vmu->mailbox, vmu->context, msgnum);
7546 ast_unlock_path(dir);
7547 if (store_failed) {
7548 ast_log(LOG_ERROR, "Failed to store voicemail for %s/%s msgnum %d, skipping notification\n", vmu->context, vmu->mailbox, msgnum);
7549 if (ast_check_realtime("voicemail_data")) {
7550 ast_destroy_realtime("voicemail_data", "filename", fn, SENTINEL);
7551 }
7552 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7553 goto leave_vm_out;
7554 }
7555 #else
7556 ast_unlock_path(dir);
7557 SCOPE_CALL(-1, STORE, dir, vmu->mailbox, vmu->context, msgnum, chan, vmu, fmt, duration, vms, flag, msg_id);
7558 #endif
7559 } else {
7560 ast_unlock_path(dir);
7561 }
7562
7563 /* Are there to be more recipients of this message? */
7564 while (tmpptr) {
7565 struct ast_vm_user recipu, *recip;
7566 char *exten, *cntx;
7567
7568 exten = strsep(&tmpptr, "&");
7569 cntx = strchr(exten, '@');
7570 if (cntx) {
7571 *cntx = '\0';
7572 cntx++;
7573 }
7574 memset(&recipu, 0, sizeof(recipu));
7575 if ((recip = find_user(&recipu, cntx, exten))) {
7576 copy_message(chan, vmu, 0, msgnum, duration, recip, fmt, dir, flag, NULL);
7577 free_user(recip);
7578 }
7579 }
7580
7581 /* Notification needs to happen after the copy, though. */
7582 if (ast_fileexists(fn, NULL, NULL)) {
7583 #ifdef IMAP_STORAGE
7584 notify_new_message(chan, vmu, vms, msgnum, duration, fmt,
7585 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL),
7586 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL),
7587 flag);
7588 #else
7589 notify_new_message(chan, vmu, NULL, msgnum, duration, fmt,
7590 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL),
7591 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL),
7592 flag);
7593 #endif
7594 }
7595
7596 /* Disposal needs to happen after the optional move and copy */
7597 if (ast_fileexists(fn, NULL, NULL)) {
7598 SCOPE_CALL(-1, DISPOSE, dir, msgnum);
7599 }
7600 }
7601 }
7602 } else {
7603 inprocess_count(vmu->mailbox, vmu->context, -1);
7604 }
7605 if (res == '0') {
7606 goto transfer;
7607 } else if (res > 0 && res != 't')
7608 res = 0;
7609
7610 if (sound_duration < vmu->minsecs)
7611 /* XXX We should really give a prompt too short/option start again, with leave_vm_out called only after a timeout XXX */
7612 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
7613 else
7614 pbx_builtin_setvar_helper(chan, "VMSTATUS", "SUCCESS");
7615 } else
7616 ast_log(AST_LOG_WARNING, "No format for saving voicemail?\n");
7617 leave_vm_out:
7618 free_user(vmu);
7619
7620 #ifdef IMAP_STORAGE
7621 /* expunge message - use UID Expunge if supported on IMAP server*/
7622 ast_debug(3, "*** Checking if we can expunge, expungeonhangup set to %d\n", expungeonhangup);
7623 if (expungeonhangup == 1 && vms->mailstream != NULL) {
7624 ast_mutex_lock(&vms->lock);
7625 #ifdef HAVE_IMAP_TK2006
7626 if (LEVELUIDPLUS (vms->mailstream)) {
7627 mail_expunge_full(vms->mailstream, NIL, EX_UID);
7628 } else
7629 #endif
7630 mail_expunge(vms->mailstream);
7631 ast_mutex_unlock(&vms->lock);
7632 }
7633 #endif
7634
7635 ast_free(tmp);
7636 SCOPE_EXIT_RTN_VALUE(res, "Done: '%d'\n", res);
7637 }
7638
7639 #if !defined(IMAP_STORAGE)
7640 static int resequence_mailbox(struct ast_vm_user *vmu, char *dir, int stopcount)
7641 {
7642 /* we know the actual number of messages, so stop process when number is hit */
7643
7644 int x, dest;
7645 char sfn[PATH_MAX];
7646 char dfn[PATH_MAX];
7647
7648 if (vm_lock_path(dir)) {
7649 return ERROR_LOCK_PATH;
7650 }
7651
7652 for (x = 0, dest = 0; dest != stopcount && x < MAXMSGLIMIT; x++) {
7653 make_file(sfn, sizeof(sfn), dir, x);
7654 if (EXISTS(dir, x, sfn, NULL)) {
7655
7656 if (x != dest) {
7657 make_file(dfn, sizeof(dfn), dir, dest);
7658 RENAME(dir, x, vmu->mailbox, vmu->context, dir, dest, sfn, dfn);
7659 }
7660
7661 dest++;
7662 }
7663 }
7664 ast_unlock_path(dir);
7665
7666 return dest;
7667 }
7668 #endif
7669
7670 static int say_and_wait(struct ast_channel *chan, int num, const char *language)
7671 {
7672 int d;
7673 d = ast_say_number(chan, num, AST_DIGIT_ANY, language, NULL);
7674 return d;
7675 }
7676
7677 static int save_to_folder(struct ast_vm_user *vmu, struct vm_state *vms, int msg, int box, int *newmsg, int move)
7678 {
7679 #ifdef IMAP_STORAGE
7680 /* we must use mbox(x) folder names, and copy the message there */
7681 /* simple. huh? */
7682 char sequence[10];
7683 char mailbox[256];
7684 int res;
7685 int curr_mbox;
7686
7687 /* get the real IMAP message number for this message */
7688 snprintf(sequence, sizeof(sequence), "%ld", vms->msgArray[msg]);
7689
7690 ast_debug(3, "Copying sequence %s to mailbox %s\n", sequence, mbox(vmu, box));
7691 ast_mutex_lock(&vms->lock);
7692 /* if save to Old folder, put in INBOX as read */
7693 if (box == OLD_FOLDER) {
7694 mail_setflag(vms->mailstream, sequence, "\\Seen");
7695 } else if (box == NEW_FOLDER) {
7696 mail_clearflag(vms->mailstream, sequence, "\\Seen");
7697 }
7698 if (!strcasecmp(mbox(vmu, NEW_FOLDER), vms->curbox) && (box == NEW_FOLDER || box == OLD_FOLDER)) {
7699 ast_mutex_unlock(&vms->lock);
7700 return 0;
7701 }
7702
7703 /* get the current mailbox so that we can point the mailstream back to it later */
7704 curr_mbox = get_folder_by_name(vms->curbox);
7705
7706 /* Create the folder if it doesn't exist */
7707 imap_mailbox_name(mailbox, sizeof(mailbox), vms, box, 1); /* Get the full mailbox name */
7708 if (vms->mailstream && !mail_status(vms->mailstream, mailbox, SA_UIDNEXT)) {
7709 if (mail_create(vms->mailstream, mailbox) != NIL) {
7710 ast_log(AST_LOG_NOTICE, "Folder %s created!\n", mbox(vmu, box));
7711 }
7712 }
7713
7714 /* restore previous mbox stream */
7715 if (init_mailstream(vms, curr_mbox) || !vms->mailstream) {
7716 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
7717 res = -1;
7718 } else {
7719 if (move) {
7720 res = !mail_move(vms->mailstream, sequence, (char *) mbox(vmu, box));
7721 } else {
7722 res = !mail_copy(vms->mailstream, sequence, (char *) mbox(vmu, box));
7723 }
7724 }
7725 ast_mutex_unlock(&vms->lock);
7726 return res;
7727 #else
7728 char *dir = vms->curdir;
7729 char *username = vms->username;
7730 char *context = vmu->context;
7731 char sfn[PATH_MAX];
7732 char dfn[PATH_MAX];
7733 char ddir[PATH_MAX];
7734 const char *dbox = mbox(vmu, box);
7735 int x, i;
7736 SCOPE_ENTER(3, "dir: %s msg: %d box: %d dbox: %s move? %d \n", dir, msg, box, dbox, move);
7737
7738 create_dirpath(ddir, sizeof(ddir), context, username, dbox);
7739 ast_trace(-1, "ddir: %s\n", ddir);
7740
7741 if (vm_lock_path(ddir)) {
7742 SCOPE_EXIT_RTN_VALUE(ERROR_LOCK_PATH, "Failed to lock path %s\n", ddir);
7743 }
7744
7745 x = LAST_MSG_INDEX(ddir) + 1;
7746
7747 if (box == 10 && x >= vmu->maxdeletedmsg) { /* "Deleted" folder*/
7748 ast_trace(-1, "Deleting message %d\n", msg);
7749 x--;
7750 for (i = 1; i <= x; i++) {
7751 /* Push files down a "slot". The oldest file (msg0000) will be deleted. */
7752 make_file(sfn, sizeof(sfn), ddir, i);
7753 make_file(dfn, sizeof(dfn), ddir, i - 1);
7754 if (EXISTS(ddir, i, sfn, NULL)) {
7755 SCOPE_CALL(-1, RENAME, ddir, i, vmu->mailbox, vmu->context, ddir, i - 1, sfn, dfn);
7756 } else
7757 break;
7758 }
7759 } else {
7760 if (x >= vmu->maxmsg) {
7761 ast_unlock_path(ddir);
7762 SCOPE_EXIT_RTN_VALUE(ERROR_MAX_MSGS, "Max messages reached\n");
7763 }
7764 }
7765 make_file(sfn, sizeof(sfn), dir, msg);
7766 make_file(dfn, sizeof(dfn), ddir, x);
7767 if (strcmp(sfn, dfn)) {
7768 ast_trace(-1, "Copying message '%s' to '%s'\n", sfn, dfn);
7769 SCOPE_CALL(-1, COPY, dir, msg, ddir, x, username, context, sfn, dfn);
7770 }
7771 ast_unlock_path(ddir);
7772
7773 if (newmsg) {
7774 *newmsg = x;
7775 }
7776 SCOPE_EXIT_RTN_VALUE(0, "Done\n");
7777 #endif
7778 }
7779
7780 static int adsi_logo(unsigned char *buf)
7781 {
7782 int bytes = 0;
7783 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_CENT, 0, "Comedian Mail", "");
7784 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_CENT, 0, "(C)2002-2006 Digium, Inc.", "");
7785 return bytes;
7786 }
7787
7788 static int adsi_load_vmail(struct ast_channel *chan, int *useadsi)
7789 {
7790 unsigned char buf[256];
7791 int bytes = 0;
7792 int x;
7793 char num[5];
7794
7795 *useadsi = 0;
7796 bytes += ast_adsi_data_mode(buf + bytes);
7797 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7798
7799 bytes = 0;
7800 bytes += adsi_logo(buf);
7801 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Downloading Scripts", "");
7802 #ifdef DISPLAY
7803 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, " .", "");
7804 #endif
7805 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7806 bytes += ast_adsi_data_mode(buf + bytes);
7807 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7808
7809 if (ast_adsi_begin_download(chan, addesc, adsifdn, adsisec, adsiver)) {
7810 bytes = 0;
7811 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Load Cancelled.", "");
7812 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "ADSI Unavailable", "");
7813 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7814 bytes += ast_adsi_voice_mode(buf + bytes, 0);
7815 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7816 return 0;
7817 }
7818
7819 #ifdef DISPLAY
7820 /* Add a dot */
7821 bytes = 0;
7822 bytes += ast_adsi_logo(buf);
7823 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Downloading Scripts", "");
7824 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, " ..", "");
7825 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7826 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7827 #endif
7828 bytes = 0;
7829 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 0, "Listen", "Listen", "1", 1);
7830 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 1, "Folder", "Folder", "2", 1);
7831 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 2, "Advanced", "Advanced", "3", 1);
7832 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 3, "Options", "Options", "0", 1);
7833 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 4, "Help", "Help", "*", 1);
7834 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 5, "Exit", "Exit", "#", 1);
7835 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
7836
7837 #ifdef DISPLAY
7838 /* Add another dot */
7839 bytes = 0;
7840 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, " ...", "");
7841 bytes += ast_adsi_voice_mode(buf + bytes, 0);
7842
7843 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7844 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7845 #endif
7846
7847 bytes = 0;
7848 /* These buttons we load but don't use yet */
7849 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 6, "Previous", "Prev", "4", 1);
7850 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 8, "Repeat", "Repeat", "5", 1);
7851 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 7, "Delete", "Delete", "7", 1);
7852 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 9, "Next", "Next", "6", 1);
7853 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 10, "Save", "Save", "9", 1);
7854 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 11, "Undelete", "Restore", "7", 1);
7855 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
7856
7857 #ifdef DISPLAY
7858 /* Add another dot */
7859 bytes = 0;
7860 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, " ....", "");
7861 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7862 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7863 #endif
7864
7865 bytes = 0;
7866 for (x = 0; x < 5; x++) {
7867 snprintf(num, sizeof(num), "%d", x);
7868 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 12 + x, mbox(NULL, x), mbox(NULL, x), num, 1);
7869 }
7870 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 12 + 5, "Cancel", "Cancel", "#", 1);
7871 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
7872
7873 #ifdef DISPLAY
7874 /* Add another dot */
7875 bytes = 0;
7876 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, " .....", "");
7877 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7878 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7879 #endif
7880
7881 if (ast_adsi_end_download(chan)) {
7882 bytes = 0;
7883 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Download Unsuccessful.", "");
7884 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "ADSI Unavailable", "");
7885 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7886 bytes += ast_adsi_voice_mode(buf + bytes, 0);
7887 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7888 return 0;
7889 }
7890 bytes = 0;
7891 bytes += ast_adsi_download_disconnect(buf + bytes);
7892 bytes += ast_adsi_voice_mode(buf + bytes, 0);
7893 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
7894
7895 ast_debug(1, "Done downloading scripts...\n");
7896
7897 #ifdef DISPLAY
7898 /* Add last dot */
7899 bytes = 0;
7900 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, " ......", "");
7901 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7902 #endif
7903 ast_debug(1, "Restarting session...\n");
7904
7905 bytes = 0;
7906 /* Load the session now */
7907 if (ast_adsi_load_session(chan, adsifdn, adsiver, 1) == 1) {
7908 *useadsi = 1;
7909 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Scripts Loaded!", "");
7910 } else
7911 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Load Failed!", "");
7912
7913 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7914 return 0;
7915 }
7916
7917 static void adsi_begin(struct ast_channel *chan, int *useadsi)
7918 {
7919 int x;
7920 if (!ast_adsi_available(chan))
7921 return;
7922 x = ast_adsi_load_session(chan, adsifdn, adsiver, 1);
7923 if (x < 0) {
7924 *useadsi = 0;
7925 ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
7926 return;
7927 }
7928 if (!x) {
7929 if (adsi_load_vmail(chan, useadsi)) {
7930 ast_log(AST_LOG_WARNING, "Unable to upload voicemail scripts\n");
7931 return;
7932 }
7933 } else
7934 *useadsi = 1;
7935 }
7936
7937 static void adsi_login(struct ast_channel *chan)
7938 {
7939 unsigned char buf[256];
7940 int bytes = 0;
7941 unsigned char keys[8];
7942 int x;
7943 if (!ast_adsi_available(chan))
7944 return;
7945
7946 for (x = 0; x < 8; x++)
7947 keys[x] = 0;
7948 /* Set one key for next */
7949 keys[3] = ADSI_KEY_APPS + 3;
7950
7951 bytes += adsi_logo(buf + bytes);
7952 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, " ", "");
7953 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, " ", "");
7954 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7955 bytes += ast_adsi_input_format(buf + bytes, 1, ADSI_DIR_FROM_LEFT, 0, "Mailbox: ******", "");
7956 bytes += ast_adsi_input_control(buf + bytes, ADSI_COMM_PAGE, 4, 1, 1, ADSI_JUST_LEFT);
7957 bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 3, "Enter", "Enter", "#", 1);
7958 bytes += ast_adsi_set_keys(buf + bytes, keys);
7959 bytes += ast_adsi_voice_mode(buf + bytes, 0);
7960 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7961 }
7962
7963 static void adsi_password(struct ast_channel *chan)
7964 {
7965 unsigned char buf[256];
7966 int bytes = 0;
7967 unsigned char keys[8];
7968 int x;
7969 if (!ast_adsi_available(chan))
7970 return;
7971
7972 for (x = 0; x < 8; x++)
7973 keys[x] = 0;
7974 /* Set one key for next */
7975 keys[3] = ADSI_KEY_APPS + 3;
7976
7977 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
7978 bytes += ast_adsi_input_format(buf + bytes, 1, ADSI_DIR_FROM_LEFT, 0, "Password: ******", "");
7979 bytes += ast_adsi_input_control(buf + bytes, ADSI_COMM_PAGE, 4, 0, 1, ADSI_JUST_LEFT);
7980 bytes += ast_adsi_set_keys(buf + bytes, keys);
7981 bytes += ast_adsi_voice_mode(buf + bytes, 0);
7982 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
7983 }
7984
7985 static void adsi_folders(struct ast_channel *chan, int start, char *label)
7986 {
7987 unsigned char buf[256];
7988 int bytes = 0;
7989 unsigned char keys[8];
7990 int x, y;
7991
7992 if (!ast_adsi_available(chan))
7993 return;
7994
7995 for (x = 0; x < 5; x++) {
7996 y = ADSI_KEY_APPS + 12 + start + x;
7997 if (y > ADSI_KEY_APPS + 12 + 4)
7998 y = 0;
7999 keys[x] = ADSI_KEY_SKT | y;
8000 }
8001 keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 17);
8002 keys[6] = 0;
8003 keys[7] = 0;
8004
8005 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_CENT, 0, label, "");
8006 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_CENT, 0, " ", "");
8007 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
8008 bytes += ast_adsi_set_keys(buf + bytes, keys);
8009 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8010
8011 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8012 }
8013
8014 static void adsi_message(struct ast_channel *chan, struct vm_state *vms)
8015 {
8016 int bytes = 0;
8017 unsigned char buf[256];
8018 char buf1[256], buf2[256];
8019 char fn2[PATH_MAX];
8020
8021 char cid[256] = "";
8022 char *val;
8023 char *name, *num;
8024 char datetime[21] = "";
8025 FILE *f;
8026
8027 unsigned char keys[8];
8028
8029 int x;
8030
8031 if (!ast_adsi_available(chan))
8032 return;
8033
8034 /* Retrieve important info */
8035 snprintf(fn2, sizeof(fn2), "%s.txt", vms->fn);
8036 f = fopen(fn2, "r");
8037 if (f) {
8038 while (!feof(f)) {
8039 if (!fgets((char *) buf, sizeof(buf), f)) {
8040 continue;
8041 }
8042 if (!feof(f)) {
8043 char *stringp = NULL;
8044 stringp = (char *) buf;
8045 strsep(&stringp, "=");
8046 val = strsep(&stringp, "=");
8047 if (!ast_strlen_zero(val)) {
8048 if (!strcmp((char *) buf, "callerid"))
8049 ast_copy_string(cid, val, sizeof(cid));
8050 if (!strcmp((char *) buf, "origdate"))
8051 ast_copy_string(datetime, val, sizeof(datetime));
8052 }
8053 }
8054 }
8055 fclose(f);
8056 }
8057 /* New meaning for keys */
8058 for (x = 0; x < 5; x++)
8059 keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 6 + x);
8060 keys[6] = 0x0;
8061 keys[7] = 0x0;
8062
8063 if (!vms->curmsg) {
8064 /* No prev key, provide "Folder" instead */
8065 keys[0] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
8066 }
8067 if (vms->curmsg >= vms->lastmsg) {
8068 /* If last message ... */
8069 if (vms->curmsg) {
8070 /* but not only message, provide "Folder" instead */
8071 keys[3] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
8072 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8073
8074 } else {
8075 /* Otherwise if only message, leave blank */
8076 keys[3] = 1;
8077 }
8078 }
8079
8080 if (!ast_strlen_zero(cid)) {
8081 ast_callerid_parse(cid, &name, &num);
8082 if (!name)
8083 name = num;
8084 } else {
8085 name = "Unknown Caller";
8086 }
8087
8088 /* If deleted, show "undeleted" */
8089 #ifdef IMAP_STORAGE
8090 ast_mutex_lock(&vms->lock);
8091 #endif
8092 if (vms->deleted[vms->curmsg]) {
8093 keys[1] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 11);
8094 }
8095 #ifdef IMAP_STORAGE
8096 ast_mutex_unlock(&vms->lock);
8097 #endif
8098
8099 /* Except "Exit" */
8100 keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 5);
8101 snprintf(buf1, sizeof(buf1), "%s%s", vms->curbox,
8102 strcasecmp(vms->curbox, "INBOX") ? " Messages" : "");
8103 snprintf(buf2, sizeof(buf2), "Message %d of %d", vms->curmsg + 1, vms->lastmsg + 1);
8104
8105 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
8106 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
8107 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, name, "");
8108 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, datetime, "");
8109 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
8110 bytes += ast_adsi_set_keys(buf + bytes, keys);
8111 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8112
8113 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8114 }
8115
8116 static void adsi_delete(struct ast_channel *chan, struct vm_state *vms)
8117 {
8118 int bytes = 0;
8119 unsigned char buf[256];
8120 unsigned char keys[8];
8121
8122 int x;
8123
8124 if (!ast_adsi_available(chan))
8125 return;
8126
8127 /* New meaning for keys */
8128 for (x = 0; x < 5; x++)
8129 keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 6 + x);
8130
8131 keys[6] = 0x0;
8132 keys[7] = 0x0;
8133
8134 if (!vms->curmsg) {
8135 /* No prev key, provide "Folder" instead */
8136 keys[0] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
8137 }
8138 if (vms->curmsg >= vms->lastmsg) {
8139 /* If last message ... */
8140 if (vms->curmsg) {
8141 /* but not only message, provide "Folder" instead */
8142 keys[3] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
8143 } else {
8144 /* Otherwise if only message, leave blank */
8145 keys[3] = 1;
8146 }
8147 }
8148
8149 /* If deleted, show "undeleted" */
8150 #ifdef IMAP_STORAGE
8151 ast_mutex_lock(&vms->lock);
8152 #endif
8153 if (vms->deleted[vms->curmsg]) {
8154 keys[1] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 11);
8155 }
8156 #ifdef IMAP_STORAGE
8157 ast_mutex_unlock(&vms->lock);
8158 #endif
8159
8160 /* Except "Exit" */
8161 keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 5);
8162 bytes += ast_adsi_set_keys(buf + bytes, keys);
8163 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8164
8165 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8166 }
8167
8168 static void adsi_status(struct ast_channel *chan, struct vm_state *vms)
8169 {
8170 unsigned char buf[256] = "";
8171 char buf1[256] = "", buf2[256] = "";
8172 int bytes = 0;
8173 unsigned char keys[8];
8174 int x;
8175
8176 char *newm = (vms->newmessages == 1) ? "message" : "messages";
8177 char *oldm = (vms->oldmessages == 1) ? "message" : "messages";
8178 if (!ast_adsi_available(chan))
8179 return;
8180 if (vms->newmessages) {
8181 snprintf(buf1, sizeof(buf1), "You have %d new", vms->newmessages);
8182 if (vms->oldmessages) {
8183 strncat(buf1, " and", sizeof(buf1) - strlen(buf1) - 1);
8184 snprintf(buf2, sizeof(buf2), "%d old %s.", vms->oldmessages, oldm);
8185 } else {
8186 snprintf(buf2, sizeof(buf2), "%s.", newm);
8187 }
8188 } else if (vms->oldmessages) {
8189 snprintf(buf1, sizeof(buf1), "You have %d old", vms->oldmessages);
8190 snprintf(buf2, sizeof(buf2), "%s.", oldm);
8191 } else {
8192 strcpy(buf1, "You have no messages.");
8193 buf2[0] = ' ';
8194 buf2[1] = '\0';
8195 }
8196 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
8197 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
8198 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
8199
8200 for (x = 0; x < 6; x++)
8201 keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + x);
8202 keys[6] = 0;
8203 keys[7] = 0;
8204
8205 /* Don't let them listen if there are none */
8206 if (vms->lastmsg < 0)
8207 keys[0] = 1;
8208 bytes += ast_adsi_set_keys(buf + bytes, keys);
8209
8210 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8211
8212 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8213 }
8214
8215 static void adsi_status2(struct ast_channel *chan, struct vm_state *vms)
8216 {
8217 unsigned char buf[256] = "";
8218 char buf1[256] = "", buf2[256] = "";
8219 int bytes = 0;
8220 unsigned char keys[8];
8221 int x;
8222
8223 char *mess = (vms->lastmsg == 0) ? "message" : "messages";
8224
8225 if (!ast_adsi_available(chan))
8226 return;
8227
8228 /* Original command keys */
8229 for (x = 0; x < 6; x++)
8230 keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + x);
8231
8232 keys[6] = 0;
8233 keys[7] = 0;
8234
8235 if ((vms->lastmsg + 1) < 1)
8236 keys[0] = 0;
8237
8238 snprintf(buf1, sizeof(buf1), "%s%s has", vms->curbox,
8239 strcasecmp(vms->curbox, "INBOX") ? " folder" : "");
8240
8241 if (vms->lastmsg + 1)
8242 snprintf(buf2, sizeof(buf2), "%d %s.", vms->lastmsg + 1, mess);
8243 else
8244 strcpy(buf2, "no messages.");
8245 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
8246 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
8247 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, "", "");
8248 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
8249 bytes += ast_adsi_set_keys(buf + bytes, keys);
8250
8251 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8252
8253 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8254
8255 }
8256
8257 /*
8258 static void adsi_clear(struct ast_channel *chan)
8259 {
8260 char buf[256];
8261 int bytes=0;
8262 if (!ast_adsi_available(chan))
8263 return;
8264 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
8265 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8266
8267 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8268 }
8269 */
8270
8271 static void adsi_goodbye(struct ast_channel *chan)
8272 {
8273 unsigned char buf[256];
8274 int bytes = 0;
8275
8276 if (!ast_adsi_available(chan))
8277 return;
8278 bytes += adsi_logo(buf + bytes);
8279 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, " ", "");
8280 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Goodbye", "");
8281 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
8282 bytes += ast_adsi_voice_mode(buf + bytes, 0);
8283
8284 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
8285 }
8286
8287 /*!\brief get_folder: Folder menu
8288 * Plays "press 1 for INBOX messages" etc.
8289 * Should possibly be internationalized
8290 */
8291 static int get_folder(struct ast_channel *chan, int start)
8292 {
8293 int x;
8294 int d;
8295 char fn[PATH_MAX];
8296 d = ast_play_and_wait(chan, "vm-press"); /* "Press" */
8297 if (d)
8298 return d;
8299 for (x = start; x < 5; x++) { /* For all folders */
8300 if ((d = ast_say_number(chan, x, AST_DIGIT_ANY, ast_channel_language(chan), NULL)))
8301 return d;
8302 d = ast_play_and_wait(chan, "vm-for"); /* "for" */
8303 if (d)
8304 return d;
8305 snprintf(fn, sizeof(fn), "vm-%s", mbox(NULL, x)); /* Folder name */
8306
8307 /* The inbox folder can have its name changed under certain conditions
8308 * so this checks if the sound file exists for the inbox folder name and
8309 * if it doesn't, plays the default name instead. */
8310 if (x == 0) {
8311 if (ast_fileexists(fn, NULL, NULL)) {
8312 d = vm_play_folder_name(chan, fn);
8313 } else {
8314 ast_verb(4, "Failed to find file %s; falling back to INBOX\n", fn);
8315 d = vm_play_folder_name(chan, "vm-INBOX");
8316 }
8317 } else {
8318 ast_test_suite_event_notify("PLAYBACK", "Message: folder name %s", fn);
8319 d = vm_play_folder_name(chan, fn);
8320 }
8321
8322 if (d)
8323 return d;
8324 d = ast_waitfordigit(chan, 500);
8325 if (d)
8326 return d;
8327 }
8328
8329 d = ast_play_and_wait(chan, "vm-tocancel"); /* "or pound to cancel" */
8330 if (d)
8331 return d;
8332 d = ast_waitfordigit(chan, 4000);
8333 return d;
8334 }
8335
8336 /* Japanese Syntax */
8337 static int get_folder_ja(struct ast_channel *chan, int start)
8338 {
8339 int x;
8340 int d;
8341 char fn[256];
8342 for (x = start; x < 5; x++) { /* For all folders */
8343 if ((d = ast_say_number(chan, x, AST_DIGIT_ANY, ast_channel_language(chan), (char *) NULL))) {
8344 return d;
8345 }
8346 snprintf(fn, sizeof(fn), "vm-%s", mbox(NULL, x)); /* Folder name */
8347 d = vm_play_folder_name(chan, fn);
8348 if (d) {
8349 return d;
8350 }
8351 d = ast_waitfordigit(chan, 500);
8352 if (d) {
8353 return d;
8354 }
8355 }
8356 d = ast_play_and_wait(chan, "vm-tocancel"); /* "or pound to cancel" */
8357 if (d) {
8358 return d;
8359 }
8360 d = ast_waitfordigit(chan, 4000);
8361 return d;
8362 }
8363
8364 /*!
8365 * \brief plays a prompt and waits for a keypress.
8366 * \param chan
8367 * \param fn the name of the voice prompt file to be played. For example, 'vm-changeto', 'vm-savefolder'
8368 * \param start Does not appear to be used at this time.
8369 *
8370 * This is used by the main menu option to move a message to a folder or to save a message into a folder.
8371 * After playing the message identified by the fn parameter value, it calls get_folder(), which plays the
8372 * prompting for the number inputs that correspond to the available folders.
8373 *
8374 * \return zero on success, or -1 on error.
8375 */
8376 static int get_folder2(struct ast_channel *chan, char *fn, int start)
8377 {
8378 int res = 0;
8379 int loops = 0;
8380
8381 res = ast_play_and_wait(chan, fn); /* Folder name */
8382 while (((res < '0') || (res > '9')) &&
8383 (res != '#') && (res >= 0) &&
8384 loops < 4) {
8385 /* res = get_folder(chan, 0); */
8386 if (!strcasecmp(ast_channel_language(chan), "ja")) { /* Japanese syntax */
8387 res = get_folder_ja(chan, 0);
8388 } else { /* Default syntax */
8389 res = get_folder(chan, 0);
8390 }
8391 loops++;
8392 }
8393 if (loops == 4) { /* give up */
8394 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c", '#', '#');
8395 return '#';
8396 }
8397 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
8398 isprint(res) ? res : '?', isprint(res) ? res : '?');
8399 return res;
8400 }
8401
8402 /*!
8403 * \brief presents the option to prepend to an existing message when forwarding it.
8404 * \param chan
8405 * \param vmu
8406 * \param curdir
8407 * \param curmsg
8408 * \param vm_fmts
8409 * \param context
8410 * \param record_gain
8411 * \param duration
8412 * \param vms
8413 * \param flag
8414 *
8415 * Presents a prompt for 1 to prepend the current message, 2 to forward the message without prepending, or * to return to the main menu.
8416 *
8417 * This is invoked from forward_message() when performing a forward operation (option 8 from main menu).
8418 * \return zero on success, -1 on error.
8419 */
8420 static int vm_forwardoptions(struct ast_channel *chan, struct ast_vm_user *vmu, char *curdir,
8421 int curmsg, char *vm_fmts, char *context, signed char record_gain, long *duration,
8422 struct vm_state *vms, char *flag)
8423 {
8424 int cmd = 0;
8425 int retries = 0, prepend_duration = 0, already_recorded = 0;
8426 char msgfile[PATH_MAX], backup[PATH_MAX], backup_textfile[PATH_MAX];
8427 char textfile[PATH_MAX];
8428 struct ast_config *msg_cfg;
8429 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
8430 #ifndef IMAP_STORAGE
8431 signed char zero_gain = 0;
8432 #else
8433 const char *msg_id = NULL;
8434 #endif
8435 const char *duration_str;
8436 SCOPE_ENTER(3, "mbox: %s msgnum: %d curdir: %s", vmu->mailbox, curmsg, curdir);
8437
8438 /* Must always populate duration correctly */
8439 make_file(msgfile, sizeof(msgfile), curdir, curmsg);
8440 ast_trace(-1, "msgfile: %s\n", msgfile);
8441 strcpy(textfile, msgfile);
8442 strcpy(backup, msgfile);
8443 strcpy(backup_textfile, msgfile);
8444 strncat(textfile, ".txt", sizeof(textfile) - strlen(textfile) - 1);
8445 strncat(backup, "-bak", sizeof(backup) - strlen(backup) - 1);
8446 strncat(backup_textfile, "-bak.txt", sizeof(backup_textfile) - strlen(backup_textfile) - 1);
8447
8448 if ((msg_cfg = ast_config_load(textfile, config_flags)) && valid_config(msg_cfg) && (duration_str = ast_variable_retrieve(msg_cfg, "message", "duration"))) {
8449 *duration = atoi(duration_str);
8450 } else {
8451 *duration = 0;
8452 }
8453
8454 while ((cmd >= 0) && (cmd != 't') && (cmd != '*')) {
8455 if (cmd)
8456 retries = 0;
8457 switch (cmd) {
8458 case '1':
8459
8460 #ifdef IMAP_STORAGE
8461 /* Record new intro file */
8462 if (msg_cfg && msg_cfg != CONFIG_STATUS_FILEINVALID) {
8463 msg_id = ast_variable_retrieve(msg_cfg, "message", "msg_id");
8464 }
8465 make_file(vms->introfn, sizeof(vms->introfn), curdir, curmsg);
8466 strncat(vms->introfn, "intro", sizeof(vms->introfn));
8467 ast_play_and_wait(chan, "vm-record-prepend");
8468 ast_play_and_wait(chan, "beep");
8469 cmd = play_record_review(chan, NULL, vms->introfn, vmu->maxsecs, vm_fmts, 1, vmu, (int *) duration, NULL, NULL, record_gain, vms, flag, msg_id, 1);
8470 if (cmd == -1) {
8471 break;
8472 }
8473 cmd = 't';
8474 #else
8475
8476 /* prepend a message to the current message, update the metadata and return */
8477 ast_trace(-1, "Prepending to message %d\n", curmsg);
8478
8479 make_file(msgfile, sizeof(msgfile), curdir, curmsg);
8480 ast_trace(-1, "msgfile: %s\n", msgfile);
8481
8482 strcpy(textfile, msgfile);
8483 strncat(textfile, ".txt", sizeof(textfile) - 1);
8484 *duration = 0;
8485
8486 /* if we can't read the message metadata, stop now */
8487 if (!valid_config(msg_cfg)) {
8488 cmd = 0;
8489 break;
8490 }
8491
8492 /* Back up the original file, so we can retry the prepend and restore it after forward. */
8493 #ifndef IMAP_STORAGE
8494 if (already_recorded) {
8495 ast_trace(-1, "Restoring '%s' to '%s'\n", backup, msgfile);
8496 ast_filecopy(backup, msgfile, NULL);
8497 copy(backup_textfile, textfile);
8498 }
8499 else {
8500 ast_trace(-1, "Backing up '%s' to '%s'\n", backup, msgfile);
8501 ast_filecopy(msgfile, backup, NULL);
8502 copy(textfile, backup_textfile);
8503 }
8504 #endif
8505 already_recorded = 1;
8506
8507 if (record_gain)
8508 ast_channel_setoption(chan, AST_OPTION_RXGAIN, &record_gain, sizeof(record_gain), 0);
8509
8510 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, ast_play_and_prepend, chan, NULL, msgfile, 0, vm_fmts, &prepend_duration, NULL, 1, silencethreshold, maxsilence);
8511
8512 if (cmd == 'S') { /* If we timed out, tell the user it didn't work properly and clean up the files */
8513 ast_stream_and_wait(chan, vm_pls_try_again, ""); /* this might be removed if a proper vm_prepend_timeout is ever recorded */
8514 ast_stream_and_wait(chan, vm_prepend_timeout, "");
8515 ast_filerename(backup, msgfile, NULL);
8516 }
8517
8518 if (record_gain)
8519 ast_channel_setoption(chan, AST_OPTION_RXGAIN, &zero_gain, sizeof(zero_gain), 0);
8520
8521
8522 if ((duration_str = ast_variable_retrieve(msg_cfg, "message", "duration")))
8523 *duration = atoi(duration_str);
8524
8525 if (prepend_duration) {
8526 struct ast_category *msg_cat;
8527 /* need enough space for a maximum-length message duration */
8528 char duration_buf[12];
8529
8530 *duration += prepend_duration;
8531 ast_trace(-1, "Prepending duration: %d total duration: %ld\n", prepend_duration, *duration);
8532 msg_cat = ast_category_get(msg_cfg, "message", NULL);
8533 snprintf(duration_buf, sizeof(duration_buf), "%ld", *duration);
8534 if (!ast_variable_update(msg_cat, "duration", duration_buf, NULL, 0)) {
8535 ast_config_text_file_save(textfile, msg_cfg, "app_voicemail");
8536 }
8537 }
8538
8539 #endif
8540 break;
8541 case '2':
8542 /* NULL out introfile so we know there is no intro! */
8543 #ifdef IMAP_STORAGE
8544 *vms->introfn = '\0';
8545 #endif
8546 cmd = 't';
8547 break;
8548 case '*':
8549 cmd = '*';
8550 break;
8551 default:
8552 /* If time_out and return to menu, reset already_recorded */
8553 already_recorded = 0;
8554
8555 cmd = ast_play_and_wait(chan, "vm-forwardoptions");
8556 /* "Press 1 to prepend a message or 2 to forward the message without prepending" */
8557 if (!cmd) {
8558 cmd = ast_play_and_wait(chan, "vm-starmain");
8559 /* "press star to return to the main menu" */
8560 }
8561 if (!cmd) {
8562 cmd = ast_waitfordigit(chan, 6000);
8563 }
8564 if (!cmd) {
8565 retries++;
8566 }
8567 if (retries > 3) {
8568 cmd = '*'; /* Let's cancel this beast */
8569 }
8570 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
8571 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
8572 }
8573 }
8574
8575 if (valid_config(msg_cfg))
8576 ast_config_destroy(msg_cfg);
8577 if (prepend_duration)
8578 *duration = prepend_duration;
8579
8580 if (already_recorded && cmd == -1) {
8581 /* restore original message if prepention cancelled */
8582 ast_trace(-1, "Restoring '%s' to '%s'\n", backup, msgfile);
8583 ast_filerename(backup, msgfile, NULL);
8584 rename(backup_textfile, textfile);
8585 }
8586
8587 if (cmd == 't' || cmd == 'S') { /* XXX entering this block with a value of 'S' is probably no longer possible. */
8588 cmd = 0;
8589 }
8590 SCOPE_EXIT_RTN_VALUE(cmd, "Done. CMD: %d %c\n", cmd, cmd >= 32 && cmd < 127 ? cmd : '?');
8591 }
8592
8593 static void queue_mwi_event(const char *channel_id, const char *box, int urgent, int new, int old)
8594 {
8595 char *mailbox;
8596 char *context;
8597
8598 if (separate_mailbox(ast_strdupa(box), &mailbox, &context)) {
8599 return;
8600 }
8601
8602 ast_debug(3, "Queueing event for mailbox %s New: %d Old: %d\n", box, new + urgent, old);
8603 ast_publish_mwi_state_channel(mailbox, context, new + urgent, old, channel_id);
8604
8605 if (!ast_strlen_zero(aliasescontext)) {
8606 struct ao2_iterator *aliases;
8607 struct mailbox_alias_mapping *mapping;
8608
8609 aliases = ao2_find(mailbox_alias_mappings, box, OBJ_SEARCH_KEY | OBJ_MULTIPLE);
8610 while ((mapping = ao2_iterator_next(aliases))) {
8611 char alias[strlen(mapping->alias) + 1];
8612 strcpy(alias, mapping->alias); /* safe */
8613 mailbox = NULL;
8614 context = NULL;
8615 ast_debug(3, "Found alias mapping: %s -> %s\n", mapping->alias, box);
8616 separate_mailbox(alias, &mailbox, &context);
8617 ast_publish_mwi_state_channel(mailbox, context, new + urgent, old, channel_id);
8618 ao2_ref(mapping, -1);
8619 }
8620 ao2_iterator_destroy(aliases);
8621 }
8622 }
8623
8624 /*!
8625 * \brief Sends email notification that a user has a new voicemail waiting for them.
8626 * \param chan
8627 * \param vmu
8628 * \param vms
8629 * \param msgnum
8630 * \param duration
8631 * \param fmt
8632 * \param cidnum The Caller ID phone number value.
8633 * \param cidname The Caller ID name value.
8634 * \param flag
8635 *
8636 * \return zero on success, -1 on error.
8637 */
8638 static int notify_new_message(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int msgnum, long duration, char *fmt, char *cidnum, char *cidname, const char *flag)
8639 {
8640 char todir[PATH_MAX], fn[PATH_MAX], ext_context[PATH_MAX], *stringp;
8641 int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;
8642 const char *category;
8643 char *myserveremail = serveremail;
8644
8645 ast_channel_lock(chan);
8646 if ((category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY"))) {
8647 category = ast_strdupa(category);
8648 }
8649 ast_channel_unlock(chan);
8650
8651 #ifndef IMAP_STORAGE
8652 make_dir(todir, sizeof(todir), vmu->context, vmu->mailbox, !ast_strlen_zero(flag) && !strcmp(flag, "Urgent") ? "Urgent" : "INBOX");
8653 #else
8654 snprintf(todir, sizeof(todir), "%simap", VM_SPOOL_DIR);
8655 #endif
8656 make_file(fn, sizeof(fn), todir, msgnum);
8657 snprintf(ext_context, sizeof(ext_context), "%s@%s", vmu->mailbox, vmu->context);
8658
8659 if (!ast_strlen_zero(vmu->attachfmt)) {
8660 if (strstr(fmt, vmu->attachfmt))
8661 fmt = vmu->attachfmt;
8662 else
8663 ast_log(AST_LOG_WARNING, "Attachment format '%s' is not one of the recorded formats '%s'. Falling back to default format for '%s@%s'.\n", vmu->attachfmt, fmt, vmu->mailbox, vmu->context);
8664 }
8665
8666 /* Attach only the first format */
8667 fmt = ast_strdupa(fmt);
8668 stringp = fmt;
8669 strsep(&stringp, "|");
8670
8671 if (!ast_strlen_zero(vmu->serveremail))
8672 myserveremail = vmu->serveremail;
8673
8674 if (!ast_strlen_zero(vmu->email)) {
8675 int attach_user_voicemail = ast_test_flag(vmu, VM_ATTACH);
8676 char *msg_id = NULL;
8677 #ifdef IMAP_STORAGE
8678 struct ast_config *msg_cfg;
8679 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
8680 char filename[PATH_MAX];
8681
8682 snprintf(filename, sizeof(filename), "%s.txt", fn);
8683 msg_cfg = ast_config_load(filename, config_flags);
8684 if (msg_cfg && msg_cfg != CONFIG_STATUS_FILEINVALID) {
8685 msg_id = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "msg_id"));
8686 ast_config_destroy(msg_cfg);
8687 }
8688 #endif
8689
8690 if (attach_user_voicemail)
8691 RETRIEVE(todir, msgnum, vmu->mailbox, vmu->context);
8692
8693 /* XXX possible imap issue, should category be NULL XXX */
8694 sendmail(myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, mbox(vmu, 0), cidnum, cidname, fn, NULL, fmt, duration, attach_user_voicemail, chan, category, flag, msg_id);
8695
8696 if (attach_user_voicemail)
8697 DISPOSE(todir, msgnum);
8698 }
8699
8700 if (!ast_strlen_zero(vmu->pager)) {
8701 sendpage(myserveremail, vmu->pager, msgnum, vmu->context, vmu->mailbox, mbox(vmu, 0), cidnum, cidname, duration, vmu, category, flag);
8702 }
8703
8704 if (ast_test_flag(vmu, VM_DELETE))
8705 DELETE(todir, msgnum, fn, vmu);
8706
8707 /* Leave voicemail for someone */
8708 if (ast_app_has_voicemail(ext_context, NULL))
8709 ast_app_inboxcount2(ext_context, &urgentmsgs, &newmsgs, &oldmsgs);
8710
8711 queue_mwi_event(ast_channel_uniqueid(chan), ext_context, urgentmsgs, newmsgs, oldmsgs);
8712 run_externnotify(vmu->context, vmu->mailbox, flag);
8713
8714 #ifdef IMAP_STORAGE
8715 vm_delete(fn); /* Delete the file, but not the IMAP message */
8716 if (ast_test_flag(vmu, VM_DELETE)) { /* Delete the IMAP message if delete = yes */
8717 vm_imap_delete(NULL, vms->curmsg, vmu);
8718 vms->newmessages--; /* Fix new message count */
8719 }
8720 #endif
8721
8722 return 0;
8723 }
8724
8725 /*!
8726 * \brief Sends a voicemail message to a mailbox recipient.
8727 * \param chan
8728 * \param context
8729 * \param vms
8730 * \param sender
8731 * \param fmt
8732 * \param is_new_message Used to indicate the mode for which this method was invoked.
8733 * Will be 0 when called to forward an existing message (option 8)
8734 * Will be 1 when called to leave a message (option 3->5)
8735 * \param record_gain
8736 * \param urgent
8737 *
8738 * Reads the destination mailbox(es) from keypad input for CID, or if use_directory feature is enabled, the Directory.
8739 *
8740 * When in the leave message mode (is_new_message == 1):
8741 * - allow the leaving of a message for ourselves. (Will not allow us to forward a message to ourselves, when is_new_message == 0).
8742 * - attempt to determine the context and mailbox, and then invoke leave_message() function to record and store the message.
8743 *
8744 * When in the forward message mode (is_new_message == 0):
8745 * - retrieves the current message to be forwarded
8746 * - copies the original message to a temporary file, so updates to the envelope can be done.
8747 * - determines the target mailbox and folders
8748 * - copies the message into the target mailbox, using copy_message() or by generating the message into an email attachment if using imap folders.
8749 *
8750 * \return zero on success, -1 on error.
8751 */
8752 static int forward_message(struct ast_channel *chan, char *context, struct vm_state *vms, struct ast_vm_user *sender, char *fmt, int is_new_message, signed char record_gain, int urgent)
8753 {
8754 #ifdef IMAP_STORAGE
8755 int todircount = 0;
8756 struct vm_state *dstvms;
8757 #endif
8758 char username[70]="";
8759 char fn[PATH_MAX]; /* for playback of name greeting */
8760 char ecodes[16] = "#";
8761 int res = 0, cmd = 0;
8762 struct ast_vm_user *receiver = NULL, *vmtmp;
8763 AST_LIST_HEAD_NOLOCK_STATIC(extensions, ast_vm_user);
8764 char *stringp;
8765 const char *s;
8766 const char mailbox_context[256];
8767 int saved_messages = 0;
8768 int valid_extensions = 0;
8769 char *dir;
8770 int curmsg;
8771 char urgent_str[7] = "";
8772 int prompt_played = 0;
8773 #ifndef IMAP_STORAGE
8774 char msgfile[PATH_MAX], textfile[PATH_MAX], backup[PATH_MAX], backup_textfile[PATH_MAX];
8775 #endif
8776 SCOPE_ENTER(3, "%s: user: %s dir: %s msg: %d\n", ast_channel_name(chan),
8777 vms->username, vms->curdir, vms->curmsg);
8778
8779 if (ast_test_flag((&globalflags), VM_FWDURGAUTO)) {
8780 ast_copy_string(urgent_str, urgent ? "Urgent" : "", sizeof(urgent_str));
8781 }
8782
8783 if (vms == NULL) {
8784 SCOPE_EXIT_RTN_VALUE(-1, "vms is NULL\n");
8785 }
8786 dir = vms->curdir;
8787 curmsg = vms->curmsg;
8788
8789 ast_test_suite_event_notify("FORWARD", "Message: entering forward message menu");
8790 while (!res && !valid_extensions) {
8791 int use_directory = 0;
8792 if (ast_test_flag((&globalflags), VM_DIRECTFORWARD)) {
8793 int done = 0;
8794 int retries = 0;
8795 cmd = 0;
8796 while ((cmd >= 0) && !done ){
8797 if (cmd)
8798 retries = 0;
8799 switch (cmd) {
8800 case '1':
8801 use_directory = 0;
8802 done = 1;
8803 break;
8804 case '2':
8805 use_directory = 1;
8806 done = 1;
8807 break;
8808 case '*':
8809 cmd = 't';
8810 done = 1;
8811 break;
8812 default:
8813 /* Press 1 to enter an extension press 2 to use the directory */
8814 cmd = ast_play_and_wait(chan, "vm-forward");
8815 if (!cmd) {
8816 cmd = ast_waitfordigit(chan, 3000);
8817 }
8818 if (!cmd) {
8819 retries++;
8820 }
8821 if (retries > 3) {
8822 cmd = 't';
8823 done = 1;
8824 }
8825 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
8826 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
8827 }
8828 }
8829 if (cmd < 0 || cmd == 't')
8830 break;
8831 }
8832
8833 if (use_directory) {
8834 /* use app_directory */
8835
8836 struct ast_app* directory_app;
8837
8838 directory_app = pbx_findapp("Directory");
8839 if (directory_app) {
8840 char vmcontext[256];
8841 char old_context[strlen(ast_channel_context(chan)) + 1];
8842 char old_exten[strlen(ast_channel_exten(chan)) + 1];
8843 int old_priority;
8844 /* make backup copies */
8845 strcpy(old_context, ast_channel_context(chan)); /* safe */
8846 strcpy(old_exten, ast_channel_exten(chan)); /* safe */
8847 old_priority = ast_channel_priority(chan);
8848
8849 /* call the Directory, changes the channel */
8850 snprintf(vmcontext, sizeof(vmcontext), "%s,,v", context ? context : "default");
8851 res = pbx_exec(chan, directory_app, vmcontext);
8852
8853 ast_copy_string(username, ast_channel_exten(chan), sizeof(username));
8854
8855 /* restore the old context, exten, and priority */
8856 ast_channel_context_set(chan, old_context);
8857 ast_channel_exten_set(chan, old_exten);
8858 ast_channel_priority_set(chan, old_priority);
8859 } else {
8860 ast_log(AST_LOG_WARNING, "Could not find the Directory application, disabling directory_forward\n");
8861 ast_clear_flag((&globalflags), VM_DIRECTFORWARD);
8862 }
8863 } else {
8864 /* Ask for an extension */
8865 res = ast_streamfile(chan, "vm-extension", ast_channel_language(chan)); /* "extension" */
8866 prompt_played++;
8867 if (res || prompt_played > 4)
8868 break;
8869 if ((res = ast_readstring(chan, username, sizeof(username) - 1, 2000, 10000, "#")) < 0)
8870 break;
8871 }
8872
8873 /* start all over if no username */
8874 if (ast_strlen_zero(username))
8875 continue;
8876 stringp = username;
8877 s = strsep(&stringp, "*");
8878 /* start optimistic */
8879 valid_extensions = 1;
8880 while (s) {
8881 snprintf((char*)mailbox_context, sizeof(mailbox_context), "%s@%s", s, context ? context : "default");
8882 if ((is_new_message == 1 || strcmp(s, sender->mailbox)) && (receiver = find_user(NULL, context, s))) {
8883 int oldmsgs;
8884 int newmsgs;
8885 int capacity;
8886
8887 if (inboxcount(mailbox_context, &newmsgs, &oldmsgs)) {
8888 ast_log(LOG_ERROR, "Problem in calculating number of voicemail messages available for extension %s\n", mailbox_context);
8889 /* Shouldn't happen, but allow trying another extension if it does */
8890 res = ast_play_and_wait(chan, "pbx-invalid");
8891 valid_extensions = 0;
8892 break;
8893 }
8894 #ifdef IMAP_STORAGE
8895 if (!(dstvms = get_vm_state_by_mailbox(s, context, 0))) {
8896 if (!(dstvms = create_vm_state_from_user(receiver))) {
8897 ast_log(AST_LOG_ERROR, "Couldn't allocate necessary space\n");
8898 /* Shouldn't happen, but allow trying another extension if it does */
8899 res = ast_play_and_wait(chan, "pbx-invalid");
8900 valid_extensions = 0;
8901 break;
8902 }
8903 }
8904 check_quota(dstvms, imapfolder);
8905 if (dstvms->quota_limit && dstvms->quota_usage >= dstvms->quota_limit) {
8906 ast_log(LOG_NOTICE, "Mailbox '%s' is exceeded quota %u >= %u\n", mailbox_context, dstvms->quota_usage, dstvms->quota_limit);
8907 res = ast_play_and_wait(chan, "vm-mailboxfull");
8908 valid_extensions = 0;
8909 while ((vmtmp = AST_LIST_REMOVE_HEAD(&extensions, list))) {
8910 inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
8911 free_user(vmtmp);
8912 }
8913 break;
8914 }
8915 #endif
8916 capacity = receiver->maxmsg - inprocess_count(receiver->mailbox, receiver->context, +1);
8917 if ((newmsgs + oldmsgs) >= capacity) {
8918 ast_log(LOG_NOTICE, "Mailbox '%s' is full with capacity of %d, prompting for another extension.\n", mailbox_context, capacity);
8919 res = ast_play_and_wait(chan, "vm-mailboxfull");
8920 valid_extensions = 0;
8921 while ((vmtmp = AST_LIST_REMOVE_HEAD(&extensions, list))) {
8922 inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
8923 free_user(vmtmp);
8924 }
8925 inprocess_count(receiver->mailbox, receiver->context, -1);
8926 break;
8927 }
8928 AST_LIST_INSERT_HEAD(&extensions, receiver, list);
8929 } else {
8930 /* XXX Optimization for the future. When we encounter a single bad extension,
8931 * bailing out on all of the extensions may not be the way to go. We should
8932 * probably just bail on that single extension, then allow the user to enter
8933 * several more. XXX
8934 */
8935 while ((receiver = AST_LIST_REMOVE_HEAD(&extensions, list))) {
8936 free_user(receiver);
8937 }
8938 ast_log(LOG_NOTICE, "'%s' is not a valid mailbox\n", mailbox_context);
8939 /* "I am sorry, that's not a valid extension. Please try again." */
8940 res = ast_play_and_wait(chan, "pbx-invalid");
8941 valid_extensions = 0;
8942 break;
8943 }
8944
8945 /* play name if available, else play extension number */
8946 snprintf(fn, sizeof(fn), "%s%s/%s/greet", VM_SPOOL_DIR, receiver->context, s);
8947 SCOPE_CALL(-1, RETRIEVE, fn, -1, s, receiver->context);
8948 if (ast_fileexists(fn, NULL, NULL) > 0) {
8949 res = ast_stream_and_wait(chan, fn, ecodes);
8950 if (res) {
8951 SCOPE_CALL(-1, DISPOSE, fn, -1);
8952 return res;
8953 }
8954 } else {
8955 res = ast_say_digit_str(chan, s, ecodes, ast_channel_language(chan));
8956 }
8957 SCOPE_CALL(-1, DISPOSE, fn, -1);
8958
8959 s = strsep(&stringp, "*");
8960 }
8961 /* break from the loop of reading the extensions */
8962 if (valid_extensions)
8963 break;
8964 }
8965 /* check if we're clear to proceed */
8966 if (AST_LIST_EMPTY(&extensions) || !valid_extensions)
8967 return res;
8968 if (is_new_message == 1) {
8969 struct leave_vm_options leave_options;
8970 char mailbox[AST_MAX_EXTENSION * 2 + 2];
8971 snprintf(mailbox, sizeof(mailbox), "%s@%s", username, context);
8972
8973 /* Send VoiceMail */
8974 memset(&leave_options, 0, sizeof(leave_options));
8975 leave_options.record_gain = record_gain;
8976 leave_options.beeptone = "beep";
8977 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, leave_voicemail, chan, mailbox, &leave_options);
8978 } else {
8979 /* Forward VoiceMail */
8980 long duration = 0;
8981 struct vm_state vmstmp;
8982 int copy_msg_result = 0;
8983 #ifdef IMAP_STORAGE
8984 char filename[PATH_MAX];
8985 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
8986 const char *msg_id = NULL;
8987 struct ast_config *msg_cfg;
8988 #endif
8989 memcpy(&vmstmp, vms, sizeof(vmstmp));
8990
8991 SCOPE_CALL(-1, RETRIEVE, dir, curmsg, sender->mailbox, sender->context);
8992 #ifdef IMAP_STORAGE
8993 make_file(filename, sizeof(filename), dir, curmsg);
8994 strncat(filename, ".txt", sizeof(filename) - strlen(filename) - 1);
8995 msg_cfg = ast_config_load(filename, config_flags);
8996 if (msg_cfg && msg_cfg == CONFIG_STATUS_FILEINVALID) {
8997 msg_id = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "msg_id"));
8998 ast_config_destroy(msg_cfg);
8999 }
9000 #endif
9001
9002 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, vm_forwardoptions, chan, sender, vmstmp.curdir, curmsg, vmfmts, S_OR(context, "default"), record_gain, &duration, &vmstmp, urgent_str);
9003 if (!cmd) {
9004 AST_LIST_TRAVERSE_SAFE_BEGIN(&extensions, vmtmp, list) {
9005 #ifdef IMAP_STORAGE
9006 int attach_user_voicemail;
9007 char *myserveremail = serveremail;
9008
9009 /* get destination mailbox */
9010 dstvms = get_vm_state_by_mailbox(vmtmp->mailbox, vmtmp->context, 0);
9011 if (!dstvms) {
9012 dstvms = create_vm_state_from_user(vmtmp);
9013 }
9014 if (dstvms) {
9015 init_mailstream(dstvms, 0);
9016 if (!dstvms->mailstream) {
9017 ast_log(AST_LOG_ERROR, "IMAP mailstream for %s is NULL\n", vmtmp->mailbox);
9018 } else {
9019 copy_msg_result = STORE(vmstmp.curdir, vmtmp->mailbox, vmtmp->context, curmsg, chan, vmtmp, fmt, duration, dstvms, urgent_str, msg_id);
9020 run_externnotify(vmtmp->context, vmtmp->mailbox, urgent_str);
9021 }
9022 } else {
9023 ast_log(AST_LOG_ERROR, "Could not find state information for mailbox %s\n", vmtmp->mailbox);
9024 }
9025 if (!ast_strlen_zero(vmtmp->serveremail))
9026 myserveremail = vmtmp->serveremail;
9027 attach_user_voicemail = ast_test_flag(vmtmp, VM_ATTACH);
9028 /* NULL category for IMAP storage */
9029 sendmail(myserveremail, vmtmp, todircount, vmtmp->context, vmtmp->mailbox,
9030 dstvms->curbox,
9031 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL),
9032 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL),
9033 vmstmp.fn, vmstmp.introfn, fmt, duration, attach_user_voicemail, chan,
9034 NULL, urgent_str, msg_id);
9035 #else
9036 copy_msg_result = SCOPE_CALL_WITH_INT_RESULT(-1, copy_message, chan, sender, 0, curmsg, duration, vmtmp, fmt, dir, urgent_str, NULL);
9037 #endif
9038 saved_messages++;
9039 AST_LIST_REMOVE_CURRENT(list);
9040 inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
9041 free_user(vmtmp);
9042 if (res)
9043 break;
9044 }
9045 AST_LIST_TRAVERSE_SAFE_END;
9046 if (saved_messages > 0 && !copy_msg_result) {
9047 /* give confirmation that the message was saved */
9048 /* commented out since we can't forward batches yet
9049 if (saved_messages == 1)
9050 res = ast_play_and_wait(chan, "vm-message");
9051 else
9052 res = ast_play_and_wait(chan, "vm-messages");
9053 if (!res)
9054 res = ast_play_and_wait(chan, "vm-saved"); */
9055 res = ast_play_and_wait(chan, "vm-msgforwarded");
9056 }
9057 #ifndef IMAP_STORAGE
9058 else {
9059 /* with IMAP, mailbox full warning played by imap_check_limits */
9060 res = ast_play_and_wait(chan, "vm-mailboxfull");
9061 }
9062 /* Restore original message without prepended message if backup exists */
9063 make_file(msgfile, sizeof(msgfile), dir, curmsg);
9064 strcpy(textfile, msgfile);
9065 strcpy(backup, msgfile);
9066 strcpy(backup_textfile, msgfile);
9067 strncat(textfile, ".txt", sizeof(textfile) - strlen(textfile) - 1);
9068 strncat(backup, "-bak", sizeof(backup) - strlen(backup) - 1);
9069 strncat(backup_textfile, "-bak.txt", sizeof(backup_textfile) - strlen(backup_textfile) - 1);
9070 if (ast_fileexists(backup, NULL, NULL) > 0) {
9071 ast_filerename(backup, msgfile, NULL);
9072 rename(backup_textfile, textfile);
9073 }
9074 #endif
9075 }
9076 SCOPE_CALL(-1, DISPOSE, dir, curmsg);
9077 #ifndef IMAP_STORAGE
9078 if (cmd) { /* assuming hangup, cleanup backup file */
9079 make_file(msgfile, sizeof(msgfile), dir, curmsg);
9080 strcpy(textfile, msgfile);
9081 strcpy(backup_textfile, msgfile);
9082 strncat(textfile, ".txt", sizeof(textfile) - strlen(textfile) - 1);
9083 strncat(backup_textfile, "-bak.txt", sizeof(backup_textfile) - strlen(backup_textfile) - 1);
9084 rename(backup_textfile, textfile);
9085 }
9086 #endif
9087 }
9088
9089 /* If anything failed above, we still have this list to free */
9090 while ((vmtmp = AST_LIST_REMOVE_HEAD(&extensions, list))) {
9091 inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
9092 free_user(vmtmp);
9093 }
9094 SCOPE_EXIT_RTN_VALUE(res ? res : cmd, "Done. res: %d cmd: %d\n", res, cmd);
9095 }
9096
9097 static int wait_file2(struct ast_channel *chan, struct vm_state *vms, char *file)
9098 {
9099 int res;
9100 if ((res = ast_stream_and_wait(chan, file, AST_DIGIT_ANY)) < 0)
9101 ast_log(AST_LOG_WARNING, "Unable to play message %s\n", file);
9102 return res;
9103 }
9104
9105 static int wait_file(struct ast_channel *chan, struct vm_state *vms, char *file)
9106 {
9107 ast_test_suite_event_notify("PLAYVOICE", "Message: Playing %s", file);
9108 return ast_control_streamfile(chan, file, listen_control_forward_key, listen_control_reverse_key, listen_control_stop_key, listen_control_pause_key, listen_control_restart_key, skipms, NULL);
9109 }
9110
9111 static int play_message_category(struct ast_channel *chan, const char *category)
9112 {
9113 int res = 0;
9114
9115 if (!ast_strlen_zero(category))
9116 res = ast_play_and_wait(chan, category);
9117
9118 if (res) {
9119 ast_log(AST_LOG_WARNING, "No sound file for category '%s' was found.\n", category);
9120 res = 0;
9121 }
9122
9123 return res;
9124 }
9125
9126 static int play_message_datetime(struct ast_channel *chan, struct ast_vm_user *vmu, const char *origtime, const char *filename)
9127 {
9128 int res = 0;
9129 struct vm_zone *the_zone = NULL;
9130 time_t t;
9131
9132 if (ast_get_time_t(origtime, &t, 0, NULL)) {
9133 ast_log(AST_LOG_WARNING, "Couldn't find origtime in %s\n", filename);
9134 return 0;
9135 }
9136
9137 /* Does this user have a timezone specified? */
9138 if (!ast_strlen_zero(vmu->zonetag)) {
9139 /* Find the zone in the list */
9140 struct vm_zone *z;
9141 AST_LIST_LOCK(&zones);
9142 AST_LIST_TRAVERSE(&zones, z, list) {
9143 if (!strcmp(z->name, vmu->zonetag)) {
9144 the_zone = z;
9145 break;
9146 }
9147 }
9148 AST_LIST_UNLOCK(&zones);
9149 }
9150
9151 /* No internal variable parsing for now, so we'll comment it out for the time being */
9152 #if 0
9153 /* Set the DIFF_* variables */
9154 ast_localtime(&t, &time_now, NULL);
9155 tv_now = ast_tvnow();
9156 ast_localtime(&tv_now, &time_then, NULL);
9157
9158 /* Day difference */
9159 if (time_now.tm_year == time_then.tm_year)
9160 snprintf(temp, sizeof(temp), "%d", time_now.tm_yday);
9161 else
9162 snprintf(temp, sizeof(temp), "%d", (time_now.tm_year - time_then.tm_year) * 365 + (time_now.tm_yday - time_then.tm_yday));
9163 pbx_builtin_setvar_helper(chan, "DIFF_DAY", temp);
9164
9165 /* Can't think of how other diffs might be helpful, but I'm sure somebody will think of something. */
9166 #endif
9167 if (the_zone) {
9168 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), the_zone->msg_format, the_zone->timezone);
9169 } else if (!strncasecmp(ast_channel_language(chan), "de", 2)) { /* GERMAN syntax */
9170 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' Q 'digits/at' HM", NULL);
9171 } else if (!strncasecmp(ast_channel_language(chan), "gr", 2)) { /* GREEK syntax */
9172 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' q H 'digits/kai' M ", NULL);
9173 } else if (!strncasecmp(ast_channel_language(chan), "is", 2)) { /* ICELANDIC syntax */
9174 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' Q 'digits/at' HM", NULL);
9175 } else if (!strncasecmp(ast_channel_language(chan), "it", 2)) { /* ITALIAN syntax */
9176 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' q 'digits/at' 'digits/hours' k 'digits/e' M 'digits/minutes'", NULL);
9177 } else if (!strcasecmp(ast_channel_language(chan),"ja")) { /* Japanese syntax */
9178 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "PHM q 'jp-ni' 'vm-received'", NULL);
9179 } else if (!strncasecmp(ast_channel_language(chan), "nl", 2)) { /* DUTCH syntax */
9180 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' q 'digits/nl-om' HM", NULL);
9181 } else if (!strncasecmp(ast_channel_language(chan), "no", 2)) { /* NORWEGIAN syntax */
9182 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' Q 'digits/at' HM", NULL);
9183 } else if (!strncasecmp(ast_channel_language(chan), "pl", 2)) { /* POLISH syntax */
9184 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' Q HM", NULL);
9185 } else if (!strncasecmp(ast_channel_language(chan), "pt_BR", 5)) { /* Brazilian PORTUGUESE syntax */
9186 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' Ad 'digits/pt-de' B 'digits/pt-de' Y 'digits/pt-as' HM ", NULL);
9187 } else if (!strncasecmp(ast_channel_language(chan), "se", 2)) { /* SWEDISH syntax */
9188 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' dB 'digits/at' k 'and' M", NULL);
9189 } else if (!strncasecmp(ast_channel_language(chan), "zh", 2)) { /* CHINESE (Taiwan) syntax */
9190 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "qR 'vm-received'", NULL);
9191 } else if (!strncasecmp(ast_channel_language(chan), "vi", 2)) { /* VIETNAMESE syntax */
9192 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' A 'digits/day' dB 'digits/year' Y 'digits/at' k 'hours' M 'minutes'", NULL);
9193 } else {
9194 res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, ast_channel_language(chan), "'vm-received' q 'digits/at' IMp", NULL);
9195 }
9196 #if 0
9197 pbx_builtin_setvar_helper(chan, "DIFF_DAY", NULL);
9198 #endif
9199 return res;
9200 }
9201
9202
9203
9204 static int play_message_callerid(struct ast_channel *chan, struct vm_state *vms, char *cid, const char *context, int callback, int saycidnumber)
9205 {
9206 int res = 0;
9207 int i;
9208 char *callerid, *name;
9209 char prefile[PATH_MAX] = "";
9210
9211 /* If voicemail cid is not enabled, or we didn't get cid or context from
9212 * the attribute file, leave now.
9213 *
9214 * TODO Still need to change this so that if this function is called by the
9215 * message envelope (and someone is explicitly requesting to hear the CID),
9216 * it does not check to see if CID is enabled in the config file.
9217 */
9218 if ((cid == NULL)||(context == NULL))
9219 return res;
9220
9221 /* Strip off caller ID number from name */
9222 ast_debug(1, "VM-CID: composite caller ID received: %s, context: %s\n", cid, context);
9223 ast_callerid_parse(cid, &name, &callerid);
9224 if ((!ast_strlen_zero(callerid)) && strcmp(callerid, "Unknown")) {
9225 /* Check for internal contexts and only */
9226 /* say extension when the call didn't come from an internal context in the list */
9227 for (i = 0 ; i < MAX_NUM_CID_CONTEXTS ; i++){
9228 ast_debug(1, "VM-CID: comparing internalcontext: %s\n", cidinternalcontexts[i]);
9229 if ((strcmp(cidinternalcontexts[i], context) == 0))
9230 break;
9231 }
9232 if (i != MAX_NUM_CID_CONTEXTS){ /* internal context? */
9233 if (!res) {
9234 snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, context, callerid);
9235 if (!ast_strlen_zero(prefile)) {
9236 /* See if we can find a recorded name for this callerid
9237 * and if found, use that instead of saying number. */
9238 if (ast_fileexists(prefile, NULL, NULL) > 0) {
9239 ast_verb(3, "Playing envelope info: CID number '%s' matches mailbox number, playing recorded name\n", callerid);
9240 if (!callback)
9241 res = wait_file2(chan, vms, "vm-from");
9242 res = ast_stream_and_wait(chan, prefile, "");
9243 } else {
9244 ast_verb(3, "Playing envelope info: message from '%s'\n", callerid);
9245 /* Say "from extension" as one saying to sound smoother */
9246 if (!callback)
9247 res = wait_file2(chan, vms, "vm-from-extension");
9248 res = ast_say_digit_str(chan, callerid, "", ast_channel_language(chan));
9249 }
9250 }
9251 }
9252 } else if (!res) {
9253 ast_debug(1, "VM-CID: Numeric caller id: (%s)\n", callerid);
9254 /* If there is a recording for this numeric callerid then play that */
9255 if (!callback) {
9256 /* See if we can find a recorded name for this person instead of their extension number */
9257 snprintf(prefile, sizeof(prefile), "%s/recordings/callerids/%s", ast_config_AST_SPOOL_DIR, callerid);
9258 if (!saycidnumber && ast_fileexists(prefile, NULL, NULL) > 0) {
9259 ast_verb(3, "Playing recorded name for CID number '%s' - '%s'\n", callerid,prefile);
9260 wait_file2(chan, vms, "vm-from");
9261 res = ast_stream_and_wait(chan, prefile, "");
9262 ast_verb(3, "Played recorded name result '%d'\n", res);
9263 } else {
9264 /* Since this is all nicely figured out, why not say "from phone number" in this case" */
9265 wait_file2(chan, vms, "vm-from-phonenumber");
9266 res = ast_say_digit_str(chan, callerid, AST_DIGIT_ANY, ast_channel_language(chan));
9267 }
9268 } else {
9269 res = ast_say_digit_str(chan, callerid, AST_DIGIT_ANY, ast_channel_language(chan));
9270 }
9271 }
9272 } else {
9273 /* Number unknown */
9274 ast_debug(1, "VM-CID: From an unknown number\n");
9275 /* Say "from an unknown caller" as one phrase - it is already recorded by "the voice" anyhow */
9276 res = wait_file2(chan, vms, "vm-unknown-caller");
9277 }
9278 return res;
9279 }
9280
9281 static int play_message_duration(struct ast_channel *chan, struct vm_state *vms, const char *duration, int minduration)
9282 {
9283 int res = 0;
9284 int durationm;
9285 int durations;
9286 /* Verify that we have a duration for the message */
9287 if (duration == NULL)
9288 return res;
9289
9290 /* Convert from seconds to minutes */
9291 durations = atoi(duration);
9292 durationm = (durations / 60);
9293
9294 ast_debug(1, "VM-Duration: duration is: %d seconds converted to: %d minutes\n", durations, durationm);
9295
9296 if ((!res) && (durationm >= minduration)) {
9297 res = wait_file2(chan, vms, "vm-duration");
9298
9299 /* POLISH syntax */
9300 if (!strncasecmp(ast_channel_language(chan), "pl", 2)) {
9301 div_t num = div(durationm, 10);
9302
9303 if (durationm == 1) {
9304 res = ast_play_and_wait(chan, "digits/1z");
9305 res = res ? res : ast_play_and_wait(chan, "vm-minute-ta");
9306 } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
9307 if (num.rem == 2) {
9308 if (!num.quot) {
9309 res = ast_play_and_wait(chan, "digits/2-ie");
9310 } else {
9311 res = say_and_wait(chan, durationm - 2 , ast_channel_language(chan));
9312 res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
9313 }
9314 } else {
9315 res = say_and_wait(chan, durationm, ast_channel_language(chan));
9316 }
9317 res = res ? res : ast_play_and_wait(chan, "vm-minute-ty");
9318 } else {
9319 res = say_and_wait(chan, durationm, ast_channel_language(chan));
9320 res = res ? res : ast_play_and_wait(chan, "vm-minute-t");
9321 }
9322 /* DEFAULT syntax */
9323 } else {
9324 res = ast_say_number(chan, durationm, AST_DIGIT_ANY, ast_channel_language(chan), NULL);
9325 res = wait_file2(chan, vms, "vm-minutes");
9326 }
9327 }
9328 return res;
9329 }
9330
9331 static int play_message(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms)
9332 {
9333 int res = 0;
9334 char filename[PATH_MAX], *cid;
9335 const char *origtime, *context, *category, *duration, *flag;
9336 struct ast_config *msg_cfg;
9337 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
9338 SCOPE_ENTER(3, "%s: user: %s dir: %s msg: %d\n", ast_channel_name(chan),
9339 vms->username, vms->curdir, vms->curmsg);
9340
9341 vms->starting = 0;
9342 make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
9343 adsi_message(chan, vms);
9344 if (!vms->curmsg) {
9345 res = wait_file2(chan, vms, "vm-first"); /* "First" */
9346 } else if (vms->curmsg == vms->lastmsg) {
9347 res = wait_file2(chan, vms, "vm-last"); /* "last" */
9348 }
9349
9350 snprintf(filename, sizeof(filename), "%s.txt", vms->fn);
9351 SCOPE_CALL(-1, RETRIEVE, vms->curdir, vms->curmsg, vmu->mailbox, vmu->context);
9352 msg_cfg = ast_config_load(filename, config_flags);
9353 if (!valid_config(msg_cfg)) {
9354 ast_log(LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
9355 return 0;
9356 }
9357 flag = ast_variable_retrieve(msg_cfg, "message", "flag");
9358
9359 /* Play the word urgent if we are listening to urgent messages */
9360 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
9361 res = wait_file2(chan, vms, "vm-Urgent"); /* "urgent" */
9362 }
9363
9364 if (!res) {
9365 /* XXX Why are we playing messages above, and then playing the same language-specific stuff here? */
9366 /* POLISH syntax */
9367 if (!strncasecmp(ast_channel_language(chan), "pl", 2)) {
9368 if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
9369 int ten, one;
9370 char nextmsg[256];
9371 ten = (vms->curmsg + 1) / 10;
9372 one = (vms->curmsg + 1) % 10;
9373
9374 if (vms->curmsg < 20) {
9375 snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", vms->curmsg + 1);
9376 res = wait_file2(chan, vms, nextmsg);
9377 } else {
9378 snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", ten * 10);
9379 res = wait_file2(chan, vms, nextmsg);
9380 if (one > 0) {
9381 if (!res) {
9382 snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", one);
9383 res = wait_file2(chan, vms, nextmsg);
9384 }
9385 }
9386 }
9387 }
9388 if (!res)
9389 res = wait_file2(chan, vms, "vm-message");
9390 /* HEBREW syntax */
9391 } else if (!strncasecmp(ast_channel_language(chan), "he", 2)) {
9392 if (!vms->curmsg) {
9393 res = wait_file2(chan, vms, "vm-message");
9394 res = wait_file2(chan, vms, "vm-first");
9395 } else if (vms->curmsg == vms->lastmsg) {
9396 res = wait_file2(chan, vms, "vm-message");
9397 res = wait_file2(chan, vms, "vm-last");
9398 } else {
9399 res = wait_file2(chan, vms, "vm-message");
9400 res = wait_file2(chan, vms, "vm-number");
9401 res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, ast_channel_language(chan), "f");
9402 }
9403 /* ICELANDIC syntax */
9404 } else if (!strncasecmp(ast_channel_language(chan), "is", 2)) {
9405 res = wait_file2(chan, vms, "vm-message");
9406 if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
9407 res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, ast_channel_language(chan), "n");
9408 }
9409 /* VIETNAMESE syntax */
9410 } else if (!strncasecmp(ast_channel_language(chan), "vi", 2)) {
9411 if (!vms->curmsg) {
9412 res = wait_file2(chan, vms, "vm-message");
9413 res = wait_file2(chan, vms, "vm-first");
9414 } else if (vms->curmsg == vms->lastmsg) {
9415 res = wait_file2(chan, vms, "vm-message");
9416 res = wait_file2(chan, vms, "vm-last");
9417 } else {
9418 res = wait_file2(chan, vms, "vm-message");
9419 res = wait_file2(chan, vms, "vm-number");
9420 res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, ast_channel_language(chan), "f");
9421 }
9422 } else {
9423 if (!strncasecmp(ast_channel_language(chan), "se", 2)) { /* SWEDISH syntax */
9424 res = wait_file2(chan, vms, "vm-meddelandet"); /* "message" */
9425 } else { /* DEFAULT syntax */
9426 res = wait_file2(chan, vms, "vm-message");
9427 }
9428 if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
9429 if (!res) {
9430 ast_test_suite_event_notify("PLAYBACK", "Message: message number");
9431 res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, ast_channel_language(chan), NULL);
9432 }
9433 }
9434 }
9435 }
9436
9437 if (!valid_config(msg_cfg)) {
9438 SCOPE_EXIT_LOG_RTN_VALUE(0, AST_LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
9439 }
9440
9441 if (!(origtime = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
9442 SCOPE_CALL(-1, DISPOSE, vms->curdir, vms->curmsg);
9443 ast_config_destroy(msg_cfg);
9444 SCOPE_EXIT_LOG_RTN_VALUE(0, AST_LOG_WARNING, "No origtime?!\n");
9445 }
9446
9447 cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
9448 duration = ast_variable_retrieve(msg_cfg, "message", "duration");
9449 category = ast_variable_retrieve(msg_cfg, "message", "category");
9450
9451 context = ast_variable_retrieve(msg_cfg, "message", "context");
9452 if (!res) {
9453 res = play_message_category(chan, category);
9454 }
9455 if ((!res) && (ast_test_flag(vmu, VM_ENVELOPE))) {
9456 res = play_message_datetime(chan, vmu, origtime, filename);
9457 }
9458 if ((!res) && (ast_test_flag(vmu, VM_SAYCID))) {
9459 res = play_message_callerid(chan, vms, cid, context, 0, 0);
9460 }
9461 if ((!res) && (ast_test_flag(vmu, VM_SAYDURATION))) {
9462 res = play_message_duration(chan, vms, duration, vmu->saydurationm);
9463 }
9464 /* Allow pressing '1' to skip envelope / callerid */
9465 if (res == '1') {
9466 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c", res, res);
9467 res = 0;
9468 }
9469 ast_config_destroy(msg_cfg);
9470
9471 if (!res) {
9472 make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
9473 #ifdef IMAP_STORAGE
9474 ast_mutex_lock(&vms->lock);
9475 #endif
9476 vms->heard[vms->curmsg] = 1;
9477 #ifdef IMAP_STORAGE
9478 ast_mutex_unlock(&vms->lock);
9479 /*IMAP storage stores any prepended message from a forward
9480 * as a separate file from the rest of the message
9481 */
9482 if (!ast_strlen_zero(vms->introfn) && ast_fileexists(vms->introfn, NULL, NULL) > 0) {
9483 wait_file(chan, vms, vms->introfn);
9484 }
9485 #endif
9486 if ((res = wait_file(chan, vms, vms->fn)) < 0) {
9487 ast_log(AST_LOG_WARNING, "Playback of message %s failed\n", vms->fn);
9488 res = 0;
9489 }
9490 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
9491 isprint(res) ? res : '?', isprint(res) ? res : '?');
9492 }
9493 SCOPE_CALL(-1, DISPOSE, vms->curdir, vms->curmsg);
9494 SCOPE_EXIT_RTN_VALUE(res, "Done: RC: %d\n", res);
9495 }
9496
9497 #ifdef IMAP_STORAGE
9498 static int imap_remove_file(char *dir, int msgnum)
9499 {
9500 char fn[PATH_MAX];
9501 char full_fn[PATH_MAX];
9502 char intro[PATH_MAX] = {0,};
9503
9504 if (msgnum > -1) {
9505 make_file(fn, sizeof(fn), dir, msgnum);
9506 snprintf(intro, sizeof(intro), "%sintro", fn);
9507 } else
9508 ast_copy_string(fn, dir, sizeof(fn));
9509
9510 if ((msgnum < 0 && imapgreetings) || msgnum > -1) {
9511 ast_filedelete(fn, NULL);
9512 if (!ast_strlen_zero(intro)) {
9513 ast_filedelete(intro, NULL);
9514 }
9515 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
9516 unlink(full_fn);
9517 }
9518 return 0;
9519 }
9520
9521
9522
9523 static int imap_delete_old_greeting (char *dir, struct vm_state *vms)
9524 {
9525 char *file, *filename;
9526 char arg[11];
9527 int i;
9528 BODY* body;
9529 int curr_mbox;
9530
9531 file = strrchr(ast_strdupa(dir), '/');
9532 if (file) {
9533 *file++ = '\0';
9534 } else {
9535 ast_log(AST_LOG_ERROR, "Failed to procure file name from directory passed. You should never see this.\n");
9536 return -1;
9537 }
9538
9539 ast_mutex_lock(&vms->lock);
9540
9541 /* get the current mailbox so that we can point the mailstream back to it later */
9542 curr_mbox = get_folder_by_name(vms->curbox);
9543
9544 if (init_mailstream(vms, GREETINGS_FOLDER) || !vms->mailstream) {
9545 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
9546 ast_mutex_unlock(&vms->lock);
9547 return -1;
9548 }
9549
9550 for (i = 0; i < vms->mailstream->nmsgs; i++) {
9551 mail_fetchstructure(vms->mailstream, i + 1, &body);
9552 /* We have the body, now we extract the file name of the first attachment. */
9553 if (body->nested.part->next && body->nested.part->next->body.parameter->value) {
9554 char *attachment = body->nested.part->next->body.parameter->value;
9555 char copy[strlen(attachment) + 1];
9556
9557 strcpy(copy, attachment); /* safe */
9558 attachment = copy;
9559
9560 filename = strsep(&attachment, ".");
9561 if (!strcmp(filename, file)) {
9562 snprintf(arg, sizeof(arg), "%d", i + 1);
9563 mail_setflag(vms->mailstream, arg, "\\DELETED");
9564 }
9565 } else {
9566 ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
9567 ast_mutex_unlock(&vms->lock);
9568 return -1;
9569 }
9570 }
9571 mail_expunge(vms->mailstream);
9572
9573 if (curr_mbox != -1) {
9574 /* restore previous mbox stream */
9575 if (init_mailstream(vms, curr_mbox) || !vms->mailstream) {
9576 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
9577 }
9578 }
9579
9580 ast_mutex_unlock(&vms->lock);
9581 return 0;
9582 }
9583
9584 #elif !defined(IMAP_STORAGE)
9585 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
9586 {
9587 int count_msg, last_msg;
9588 SCOPE_ENTER(3, "user: %s dir: %s msg: %d box %d\n",
9589 vms->username, vms->curdir, vms->curmsg, box);
9590
9591 ast_copy_string(vms->curbox, mbox(vmu, box), sizeof(vms->curbox));
9592
9593 /* Rename the member vmbox HERE so that we don't try to return before
9594 * we know what's going on.
9595 */
9596 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", vms->curbox);
9597
9598 /* Faster to make the directory than to check if it exists. */
9599 create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
9600
9601 /* traverses directory using readdir (or select query for ODBC) */
9602 count_msg = COUNT(vmu, vms->curdir);
9603 if (count_msg < 0) {
9604 SCOPE_EXIT_RTN_VALUE(count_msg, "msgs: %d\n", count_msg);
9605 } else {
9606 vms->lastmsg = count_msg - 1;
9607 }
9608
9609 if (vm_allocate_dh(vms, vmu, count_msg)) {
9610 SCOPE_EXIT_RTN_VALUE(-1, "failed to allocate dh\n");
9611 }
9612
9613 /*
9614 The following test is needed in case sequencing gets messed up.
9615 There appears to be more than one way to mess up sequence, so
9616 we will not try to find all of the root causes--just fix it when
9617 detected.
9618 */
9619
9620 if (vm_lock_path(vms->curdir)) {
9621 SCOPE_EXIT_LOG_RTN_VALUE(ERROR_LOCK_PATH, AST_LOG_ERROR, "Could not open mailbox %s: mailbox is locked\n", vms->curdir);
9622 }
9623
9624 /* for local storage, checks directory for messages up to MAXMSGLIMIT */
9625 last_msg = LAST_MSG_INDEX(vms->curdir);
9626 ast_unlock_path(vms->curdir);
9627
9628 if (last_msg < -1) {
9629 SCOPE_EXIT_RTN_VALUE(last_msg, "last msg: %d\n", last_msg);
9630 } else if (vms->lastmsg != last_msg) {
9631 ast_log(LOG_NOTICE, "Resequencing Mailbox: %s, expected %d but found %d message(s) in box with max threshold of %d.\n", vms->curdir, last_msg + 1, vms->lastmsg + 1, vmu->maxmsg);
9632 resequence_mailbox(vmu, vms->curdir, count_msg);
9633 }
9634
9635 SCOPE_EXIT_RTN_VALUE(0, "Done\n");
9636 }
9637 #endif
9638
9639 static int close_mailbox(struct vm_state *vms, struct ast_vm_user *vmu)
9640 {
9641 int x = 0;
9642 int last_msg_idx = 0;
9643
9644 #ifndef IMAP_STORAGE
9645 int res = 0, nummsg;
9646 char fn2[PATH_MAX];
9647 #endif
9648 SCOPE_ENTER(3, "user: %s dir: %s msg: %d\n",
9649 vms->username, vms->curdir, vms->curmsg);
9650
9651 if (vms->lastmsg <= -1) {
9652 ast_trace(-1, "No messages in mailbox\n");
9653 goto done;
9654 }
9655
9656 vms->curmsg = -1;
9657 #ifndef IMAP_STORAGE
9658 /* Get the deleted messages fixed */
9659 if (vm_lock_path(vms->curdir)) {
9660 SCOPE_EXIT_RTN_VALUE(ERROR_LOCK_PATH, "Could not open mailbox %s: mailbox is locked\n", vms->curdir);
9661 }
9662
9663 /* update count as message may have arrived while we've got mailbox open */
9664 last_msg_idx = LAST_MSG_INDEX(vms->curdir);
9665 if (last_msg_idx != vms->lastmsg) {
9666 ast_log(AST_LOG_NOTICE, "%d messages received after mailbox opened.\n", last_msg_idx - vms->lastmsg);
9667 }
9668
9669 /* must check up to last detected message, just in case it is erroneously greater than maxmsg */
9670 for (x = 0; x < last_msg_idx + 1; x++) {
9671 if (!vms->deleted[x] && ((strcasecmp(vms->curbox, "INBOX") && strcasecmp(vms->curbox, "Urgent")) || !vms->heard[x] || (vms->heard[x] && !ast_test_flag(vmu, VM_MOVEHEARD)))) {
9672 /* Save this message. It's not in INBOX or hasn't been heard */
9673 make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
9674 if (!EXISTS(vms->curdir, x, vms->fn, NULL)) {
9675 break;
9676 }
9677 vms->curmsg++;
9678 make_file(fn2, sizeof(fn2), vms->curdir, vms->curmsg);
9679 if (strcmp(vms->fn, fn2)) {
9680 SCOPE_CALL(-1, RENAME, vms->curdir, x, vmu->mailbox, vmu->context, vms->curdir, vms->curmsg, vms->fn, fn2);
9681 }
9682 } else if ((!strcasecmp(vms->curbox, "INBOX") || !strcasecmp(vms->curbox, "Urgent")) && vms->heard[x] && ast_test_flag(vmu, VM_MOVEHEARD) && !vms->deleted[x]) {
9683 /* Move to old folder before deleting */
9684 res = SCOPE_CALL_WITH_INT_RESULT(-1, save_to_folder, vmu, vms, x, 1, NULL, 0);
9685 if (res == ERROR_LOCK_PATH || res == ERROR_MAX_MSGS) {
9686 /* If save failed do not delete the message */
9687 ast_log(AST_LOG_WARNING, "Save failed. Not moving message: %s.\n", res == ERROR_LOCK_PATH ? "unable to lock path" : "destination folder full");
9688 vms->deleted[x] = 0;
9689 vms->heard[x] = 0;
9690 --x;
9691 }
9692 } else if (vms->deleted[x] && vmu->maxdeletedmsg) {
9693 /* Move to deleted folder */
9694 res = SCOPE_CALL_WITH_INT_RESULT(-1, save_to_folder, vmu, vms, x, 10, NULL, 0);
9695 if (res == ERROR_LOCK_PATH) {
9696 ast_trace(-1, "Unable to lock path. Not moving message to deleted folder.\n");
9697 /* If save failed do not delete the message */
9698 vms->deleted[x] = 0;
9699 vms->heard[x] = 0;
9700 --x;
9701 }
9702 } else if (vms->deleted[x] && ast_check_realtime("voicemail_data")) {
9703 /* If realtime storage enabled - we should explicitly delete this message,
9704 cause RENAME() will overwrite files, but will keep duplicate records in RT-storage */
9705 make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
9706 res = SCOPE_CALL_WITH_INT_RESULT(-1, EXISTS, vms->curdir, x, vms->fn, NULL);
9707 if (res) {
9708 SCOPE_CALL(-1, DELETE, vms->curdir, x, vms->fn, vmu);
9709 }
9710 }
9711 }
9712
9713 /* Delete ALL remaining messages */
9714 nummsg = x - 1;
9715 for (x = vms->curmsg + 1; x <= nummsg; x++) {
9716 make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
9717 res = SCOPE_CALL_WITH_INT_RESULT(-1, EXISTS, vms->curdir, x, vms->fn, NULL);
9718 if (res) {
9719 SCOPE_CALL(-1, DELETE, vms->curdir, x, vms->fn, vmu);
9720 }
9721 }
9722 ast_unlock_path(vms->curdir);
9723 #else /* defined(IMAP_STORAGE) */
9724 ast_mutex_lock(&vms->lock);
9725 if (vms->deleted) {
9726 /* Since we now expunge after each delete, deleting in reverse order
9727 * ensures that no reordering occurs between each step. */
9728 last_msg_idx = vms->dh_arraysize;
9729 for (x = last_msg_idx - 1; x >= 0; x--) {
9730 if (vms->deleted[x]) {
9731 ast_debug(3, "IMAP delete of %d\n", x);
9732 DELETE(vms->curdir, x, vms->fn, vmu);
9733 }
9734 }
9735 }
9736 #endif
9737
9738 done:
9739 if (vms->deleted) {
9740 ast_free(vms->deleted);
9741 vms->deleted = NULL;
9742 }
9743 if (vms->heard) {
9744 ast_free(vms->heard);
9745 vms->heard = NULL;
9746 }
9747 vms->dh_arraysize = 0;
9748 #ifdef IMAP_STORAGE
9749 ast_mutex_unlock(&vms->lock);
9750 #endif
9751
9752 SCOPE_EXIT_RTN_VALUE(0, "Done\n");
9753 }
9754
9755 /* In Greek even though we CAN use a syntax like "friends messages"
9756 * ("filika mynhmata") it is not elegant. This also goes for "work/family messages"
9757 * ("ergasiaka/oikogeniaka mynhmata"). Therefore it is better to use a reversed
9758 * syntax for the above three categories which is more elegant.
9759 */
9760
9761 static int vm_play_folder_name_gr(struct ast_channel *chan, char *box)
9762 {
9763 int cmd;
9764 char *buf;
9765
9766 buf = ast_alloca(strlen(box) + 2);
9767 strcpy(buf, box);
9768 strcat(buf, "s");
9769
9770 if (!strcasecmp(box, "vm-INBOX") || !strcasecmp(box, "vm-Old")){
9771 cmd = ast_play_and_wait(chan, buf); /* "NEA / PALIA" */
9772 return cmd ? cmd : ast_play_and_wait(chan, "vm-messages"); /* "messages" -> "MYNHMATA" */
9773 } else {
9774 cmd = ast_play_and_wait(chan, "vm-messages"); /* "messages" -> "MYNHMATA" */
9775 return cmd ? cmd : ast_play_and_wait(chan, box); /* friends/family/work... -> "FILWN"/"OIKOGENIAS"/"DOULEIAS"*/
9776 }
9777 }
9778
9779 static int vm_play_folder_name_ja(struct ast_channel *chan, char *box)
9780 {
9781 int cmd;
9782
9783 if (!strcasecmp(box, "vm-INBOX") || !strcasecmp(box, "vm-Old")) {
9784 cmd = ast_play_and_wait(chan, box);
9785 return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
9786 } else {
9787 cmd = ast_play_and_wait(chan, box);
9788 return cmd;
9789 }
9790 }
9791
9792 static int vm_play_folder_name_pl(struct ast_channel *chan, char *box)
9793 {
9794 int cmd;
9795
9796 if (!strcasecmp(box, "vm-INBOX") || !strcasecmp(box, "vm-Old")) {
9797 if (!strcasecmp(box, "vm-INBOX"))
9798 cmd = ast_play_and_wait(chan, "vm-new-e");
9799 else
9800 cmd = ast_play_and_wait(chan, "vm-old-e");
9801 return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
9802 } else {
9803 cmd = ast_play_and_wait(chan, "vm-messages");
9804 return cmd ? cmd : ast_play_and_wait(chan, box);
9805 }
9806 }
9807
9808 static int vm_play_folder_name_ua(struct ast_channel *chan, char *box)
9809 {
9810 int cmd;
9811
9812 if (!strcasecmp(box, "vm-Family") || !strcasecmp(box, "vm-Friends") || !strcasecmp(box, "vm-Work")){
9813 cmd = ast_play_and_wait(chan, "vm-messages");
9814 return cmd ? cmd : ast_play_and_wait(chan, box);
9815 } else {
9816 cmd = ast_play_and_wait(chan, box);
9817 return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
9818 }
9819 }
9820
9821 static int vm_play_folder_name(struct ast_channel *chan, char *box)
9822 {
9823 int cmd;
9824
9825 if ( !strncasecmp(ast_channel_language(chan), "it", 2) ||
9826 !strncasecmp(ast_channel_language(chan), "es", 2) ||
9827 !strncasecmp(ast_channel_language(chan), "pt", 2)) { /* Italian, Spanish, or Portuguese syntax */
9828 cmd = ast_play_and_wait(chan, "vm-messages"); /* "messages */
9829 return cmd ? cmd : ast_play_and_wait(chan, box);
9830 } else if (!strncasecmp(ast_channel_language(chan), "gr", 2)) {
9831 return vm_play_folder_name_gr(chan, box);
9832 } else if (!strncasecmp(ast_channel_language(chan), "he", 2)) { /* Hebrew syntax */
9833 return ast_play_and_wait(chan, box);
9834 } else if (!strncasecmp(ast_channel_language(chan), "ja", 2)) { /* Japanese syntax */
9835 return vm_play_folder_name_ja(chan, box);
9836 } else if (!strncasecmp(ast_channel_language(chan), "pl", 2)) {
9837 return vm_play_folder_name_pl(chan, box);
9838 } else if (!strncasecmp(ast_channel_language(chan), "ua", 2)) { /* Ukrainian syntax */
9839 return vm_play_folder_name_ua(chan, box);
9840 } else if (!strncasecmp(ast_channel_language(chan), "vi", 2)) {
9841 return ast_play_and_wait(chan, box);
9842 } else { /* Default English */
9843 cmd = ast_play_and_wait(chan, box);
9844 return cmd ? cmd : ast_play_and_wait(chan, "vm-messages"); /* "messages */
9845 }
9846 }
9847
9848 /* GREEK SYNTAX
9849 In greek the plural for old/new is
9850 different so we need the following files
9851 We also need vm-denExeteMynhmata because
9852 this syntax is different.
9853
9854 -> vm-Olds.wav : "Palia"
9855 -> vm-INBOXs.wav : "Nea"
9856 -> vm-denExeteMynhmata : "den exete mynhmata"
9857 */
9858
9859
9860 static int vm_intro_gr(struct ast_channel *chan, struct vm_state *vms)
9861 {
9862 int res = 0;
9863
9864 if (vms->newmessages) {
9865 res = ast_play_and_wait(chan, "vm-youhave");
9866 if (!res)
9867 res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, ast_channel_language(chan), NULL);
9868 if (!res) {
9869 if (vms->newmessages == 1) {
9870 res = ast_play_and_wait(chan, "vm-INBOX");
9871 if (!res)
9872 res = ast_play_and_wait(chan, "vm-message");
9873 } else {
9874 res = ast_play_and_wait(chan, "vm-INBOXs");
9875 if (!res)
9876 res = ast_play_and_wait(chan, "vm-messages");
9877 }
9878 }
9879 } else if (vms->oldmessages){
9880 res = ast_play_and_wait(chan, "vm-youhave");
9881 if (!res)
9882 res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, ast_channel_language(chan), NULL);
9883 if (vms->oldmessages == 1){
9884 res = ast_play_and_wait(chan, "vm-Old");
9885 if (!res)
9886 res = ast_play_and_wait(chan, "vm-message");
9887 } else {
9888 res = ast_play_and_wait(chan, "vm-Olds");
9889 if (!res)
9890 res = ast_play_and_wait(chan, "vm-messages");
9891 }
9892 } else if (!vms->oldmessages && !vms->newmessages)
9893 res = ast_play_and_wait(chan, "vm-denExeteMynhmata");
9894 return res;
9895 }
9896
9897 /* Version of vm_intro() designed to work for many languages.
9898 *
9899 * It is hoped that this function can prevent the proliferation of
9900 * language-specific vm_intro() functions and in time replace the language-
9901 * specific functions which already exist. An examination of the language-
9902 * specific functions revealed that they all corrected the same deficiencies
9903 * in vm_intro_en() (which was the default function). Namely:
9904 *
9905 * 1) The vm-Old and vm-INBOX sound files were overloaded. The English
9906 * wording of the voicemail greeting hides this problem. For example,
9907 * vm-INBOX contains only the word "new". This means that both of these
9908 * sequences produce valid utterances:
9909 * * vm-youhave digit/1 vm-INBOX vm-message (you have one new message)
9910 * * vm-press digit/1 vm-for vm-INBOX vm-messages (press 1 for new messages)
9911 * However, if we rerecord vm-INBOX to say "the new" (which is unavoidable
9912 * in many languages) the first utterance becomes "you have 1 the new message".
9913 * 2) The function contains hardcoded rules for pluralizing the word "message".
9914 * These rules are correct for English, but not for many other languages.
9915 * 3) No attempt is made to pluralize the adjectives ("old" and "new") as
9916 * required in many languages.
9917 * 4) The gender of the word for "message" is not specified. This is a problem
9918 * because in many languages the gender of the number in phrases such
9919 * as "you have one new message" must match the gender of the word
9920 * meaning "message".
9921 *
9922 * Fixing these problems for each new language has meant duplication of effort.
9923 * This new function solves the problems in the following general ways:
9924 * 1) Add new sound files vm-new and vm-old. These can be linked to vm-INBOX
9925 * and vm-Old respectively for those languages where it makes sense.
9926 * 2) Call ast_say_counted_noun() to put the proper gender and number prefix
9927 * on vm-message.
9928 * 3) Call ast_say_counted_adjective() to put the proper gender and number
9929 * prefix on vm-new and vm-old (none for English).
9930 * 4) Pass the gender of the language's word for "message" as an argument to
9931 * this function which is can in turn pass on to the functions which
9932 * say numbers and put endings on nouns and adjectives.
9933 *
9934 * All languages require these messages:
9935 * vm-youhave "You have..."
9936 * vm-and "and"
9937 * vm-no "no" (in the sense of "none", as in "you have no messages")
9938 *
9939 * To use it for English, you will need these additional sound files:
9940 * vm-new "new"
9941 * vm-message "message", singular
9942 * vm-messages "messages", plural
9943 *
9944 * If you use it for Russian and other slavic languages, you will need these additional sound files:
9945 *
9946 * vm-newn "novoye" (singular, neuter)
9947 * vm-newx "novikh" (counting plural form, genative plural)
9948 * vm-message "sobsheniye" (singular form)
9949 * vm-messagex1 "sobsheniya" (first counting plural form, genative singular)
9950 * vm-messagex2 "sobsheniy" (second counting plural form, genative plural)
9951 * digits/1n "odno" (neuter singular for phrases such as "one message" or "thirty one messages")
9952 * digits/2n "dva" (neuter singular)
9953 */
9954 static int vm_intro_multilang(struct ast_channel *chan, struct vm_state *vms, const char message_gender[])
9955 {
9956 int res;
9957 int lastnum = 0;
9958
9959 res = ast_play_and_wait(chan, "vm-youhave");
9960
9961 if (!res && vms->newmessages) {
9962 lastnum = vms->newmessages;
9963
9964 if (!(res = ast_say_number(chan, lastnum, AST_DIGIT_ANY, ast_channel_language(chan), message_gender))) {
9965 res = ast_say_counted_adjective(chan, lastnum, "vm-new", message_gender);
9966 }
9967
9968 if (!res && vms->oldmessages) {
9969 res = ast_play_and_wait(chan, "vm-and");
9970 }
9971 }
9972
9973 if (!res && vms->oldmessages) {
9974 lastnum = vms->oldmessages;
9975
9976 if (!(res = ast_say_number(chan, lastnum, AST_DIGIT_ANY, ast_channel_language(chan), message_gender))) {
9977 res = ast_say_counted_adjective(chan, lastnum, "vm-old", message_gender);
9978 }
9979 }
9980
9981 if (!res) {
9982 if (lastnum == 0) {
9983 res = ast_play_and_wait(chan, "vm-no");
9984 }
9985 if (!res) {
9986 res = ast_say_counted_noun(chan, lastnum, "vm-message");
9987 }
9988 }
9989
9990 return res;
9991 }
9992
9993 /* Default Hebrew syntax */
9994 static int vm_intro_he(struct ast_channel *chan, struct vm_state *vms)
9995 {
9996 int res = 0;
9997
9998 /* Introduce messages they have */
9999 if (!res) {
10000 if ((vms->newmessages) || (vms->oldmessages)) {
10001 res = ast_play_and_wait(chan, "vm-youhave");
10002 }
10003 /*
10004 * The word "shtei" refers to the number 2 in hebrew when performing a count
10005 * of elements. In Hebrew, there are 6 forms of enumerating the number 2 for
10006 * an element, this is one of them.
10007 */
10008 if (vms->newmessages) {
10009 if (!res) {
10010 if (vms->newmessages == 1) {
10011 res = ast_play_and_wait(chan, "vm-INBOX1");
10012 } else {
10013 if (vms->newmessages == 2) {
10014 res = ast_play_and_wait(chan, "vm-shtei");
10015 } else {
10016 res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10017 }
10018 res = ast_play_and_wait(chan, "vm-INBOX");
10019 }
10020 }
10021 if (vms->oldmessages && !res) {
10022 res = ast_play_and_wait(chan, "vm-and");
10023 if (vms->oldmessages == 1) {
10024 res = ast_play_and_wait(chan, "vm-Old1");
10025 } else {
10026 if (vms->oldmessages == 2) {
10027 res = ast_play_and_wait(chan, "vm-shtei");
10028 } else {
10029 res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10030 }
10031 res = ast_play_and_wait(chan, "vm-Old");
10032 }
10033 }
10034 }
10035 if (!res && vms->oldmessages && !vms->newmessages) {
10036 if (!res) {
10037 if (vms->oldmessages == 1) {
10038 res = ast_play_and_wait(chan, "vm-Old1");
10039 } else {
10040 if (vms->oldmessages == 2) {
10041 res = ast_play_and_wait(chan, "vm-shtei");
10042 } else {
10043 res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10044 }
10045 res = ast_play_and_wait(chan, "vm-Old");
10046 }
10047 }
10048 }
10049 if (!res) {
10050 if (!vms->oldmessages && !vms->newmessages) {
10051 if (!res) {
10052 res = ast_play_and_wait(chan, "vm-nomessages");
10053 }
10054 }
10055 }
10056 }
10057 return res;
10058 }
10059
10060 /* Japanese syntax */
10061 static int vm_intro_ja(struct ast_channel *chan,struct vm_state *vms)
10062 {
10063 /* Introduce messages they have */
10064 int res;
10065 if (vms->newmessages) {
10066 res = ast_play_and_wait(chan, "vm-INBOX");
10067 if (!res)
10068 res = ast_play_and_wait(chan, "vm-message");
10069 if (!res)
10070 res = ast_play_and_wait(chan, "jp-ga");
10071 if (!res)
10072 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10073 if (vms->oldmessages && !res)
10074 res = ast_play_and_wait(chan, "silence/1");
10075
10076 }
10077 if (vms->oldmessages) {
10078 res = ast_play_and_wait(chan, "vm-Old");
10079 if (!res)
10080 res = ast_play_and_wait(chan, "vm-message");
10081 if (!res)
10082 res = ast_play_and_wait(chan, "jp-ga");
10083 if (!res)
10084 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10085 }
10086 if (!vms->oldmessages && !vms->newmessages) {
10087 res = ast_play_and_wait(chan, "vm-messages");
10088 if (!res)
10089 res = ast_play_and_wait(chan, "jp-wa");
10090 if (!res)
10091 res = ast_play_and_wait(chan, "jp-arimasen");
10092 }
10093 else {
10094 res = ast_play_and_wait(chan, "jp-arimasu");
10095 }
10096 return res;
10097 } /* Japanese */
10098
10099 /* Default English syntax */
10100 static int vm_intro_en(struct ast_channel *chan, struct vm_state *vms)
10101 {
10102 int res;
10103
10104 /* Introduce messages they have */
10105 res = ast_play_and_wait(chan, "vm-youhave");
10106 if (!res) {
10107 if (vms->urgentmessages) {
10108 res = say_and_wait(chan, vms->urgentmessages, ast_channel_language(chan));
10109 if (!res)
10110 res = ast_play_and_wait(chan, "vm-Urgent");
10111 if ((vms->oldmessages || vms->newmessages) && !res) {
10112 res = ast_play_and_wait(chan, "vm-and");
10113 } else if (!res) {
10114 if (vms->urgentmessages == 1)
10115 res = ast_play_and_wait(chan, "vm-message");
10116 else
10117 res = ast_play_and_wait(chan, "vm-messages");
10118 }
10119 }
10120 if (vms->newmessages) {
10121 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10122 if (!res)
10123 res = ast_play_and_wait(chan, "vm-INBOX");
10124 if (vms->oldmessages && !res)
10125 res = ast_play_and_wait(chan, "vm-and");
10126 else if (!res) {
10127 if (vms->newmessages == 1)
10128 res = ast_play_and_wait(chan, "vm-message");
10129 else
10130 res = ast_play_and_wait(chan, "vm-messages");
10131 }
10132
10133 }
10134 if (!res && vms->oldmessages) {
10135 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10136 if (!res)
10137 res = ast_play_and_wait(chan, "vm-Old");
10138 if (!res) {
10139 if (vms->oldmessages == 1)
10140 res = ast_play_and_wait(chan, "vm-message");
10141 else
10142 res = ast_play_and_wait(chan, "vm-messages");
10143 }
10144 }
10145 if (!res) {
10146 if (!vms->urgentmessages && !vms->oldmessages && !vms->newmessages) {
10147 res = ast_play_and_wait(chan, "vm-no");
10148 if (!res)
10149 res = ast_play_and_wait(chan, "vm-messages");
10150 }
10151 }
10152 }
10153 return res;
10154 }
10155
10156 /* ICELANDIC syntax */
10157 static int vm_intro_is(struct ast_channel *chan, struct vm_state *vms)
10158 {
10159 int res;
10160
10161 /* Introduce messages they have */
10162 res = ast_play_and_wait(chan, "vm-youhave");
10163 if (!res) {
10164 if (vms->urgentmessages) {
10165 /* Digits 1-4 are spoken in neutral and plural when talking about messages,
10166 however, feminine is used for 1 as it is the same as the neutral for plural,
10167 and singular neutral is the same after 1. */
10168 if (vms->urgentmessages < 5) {
10169 char recname[16];
10170 if (vms->urgentmessages == 1)
10171 snprintf(recname, sizeof(recname), "digits/1kvk");
10172 else
10173 snprintf(recname, sizeof(recname), "digits/%dhk", vms->urgentmessages);
10174 res = ast_play_and_wait(chan, recname);
10175 } else if (!res)
10176 res = ast_play_and_wait(chan, "vm-Urgent");
10177 if ((vms->oldmessages || vms->newmessages) && !res) {
10178 res = ast_play_and_wait(chan, "vm-and");
10179 } else if (!res)
10180 res = ast_play_and_wait(chan, "vm-messages");
10181 }
10182 if (vms->newmessages) {
10183 if (vms->newmessages < 5) {
10184 char recname[16];
10185 if (vms->newmessages == 1)
10186 snprintf(recname, sizeof(recname), "digits/1kvk");
10187 else
10188 snprintf(recname, sizeof(recname), "digits/%dhk", vms->newmessages);
10189 res = ast_play_and_wait(chan, recname);
10190 } else
10191 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10192 if (!res)
10193 res = ast_play_and_wait(chan, "vm-INBOX");
10194 if (vms->oldmessages && !res)
10195 res = ast_play_and_wait(chan, "vm-and");
10196 else if (!res)
10197 res = ast_play_and_wait(chan, "vm-messages");
10198 }
10199 if (!res && vms->oldmessages) {
10200 if (vms->oldmessages < 5) {
10201 char recname[16];
10202 if (vms->oldmessages == 1)
10203 snprintf(recname, sizeof(recname), "digits/1kvk");
10204 else
10205 snprintf(recname, sizeof(recname), "digits/%dhk", vms->oldmessages);
10206 res = ast_play_and_wait(chan, recname);
10207 } else
10208 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10209 if (!res)
10210 res = ast_play_and_wait(chan, "vm-Old");
10211 if (!res)
10212 res = ast_play_and_wait(chan, "vm-messages");
10213 }
10214 if (!res) {
10215 if (!vms->urgentmessages && !vms->oldmessages && !vms->newmessages) {
10216 res = ast_play_and_wait(chan, "vm-no");
10217 if (!res)
10218 res = ast_play_and_wait(chan, "vm-messages");
10219 }
10220 }
10221 }
10222 return res;
10223 }
10224
10225 /* ITALIAN syntax */
10226 static int vm_intro_it(struct ast_channel *chan, struct vm_state *vms)
10227 {
10228 /* Introduce messages they have */
10229 int res;
10230 if (!vms->oldmessages && !vms->newmessages &&!vms->urgentmessages)
10231 res = ast_play_and_wait(chan, "vm-no") ||
10232 ast_play_and_wait(chan, "vm-message");
10233 else
10234 res = ast_play_and_wait(chan, "vm-youhave");
10235 if (!res && vms->newmessages) {
10236 res = (vms->newmessages == 1) ?
10237 ast_play_and_wait(chan, "digits/un") ||
10238 ast_play_and_wait(chan, "vm-nuovo") ||
10239 ast_play_and_wait(chan, "vm-message") :
10240 /* 2 or more new messages */
10241 say_and_wait(chan, vms->newmessages, ast_channel_language(chan)) ||
10242 ast_play_and_wait(chan, "vm-nuovi") ||
10243 ast_play_and_wait(chan, "vm-messages");
10244 if (!res && vms->oldmessages)
10245 res = ast_play_and_wait(chan, "vm-and");
10246 }
10247 if (!res && vms->oldmessages) {
10248 res = (vms->oldmessages == 1) ?
10249 ast_play_and_wait(chan, "digits/un") ||
10250 ast_play_and_wait(chan, "vm-vecchio") ||
10251 ast_play_and_wait(chan, "vm-message") :
10252 /* 2 or more old messages */
10253 say_and_wait(chan, vms->oldmessages, ast_channel_language(chan)) ||
10254 ast_play_and_wait(chan, "vm-vecchi") ||
10255 ast_play_and_wait(chan, "vm-messages");
10256 }
10257 return res;
10258 }
10259
10260 /* POLISH syntax */
10261 static int vm_intro_pl(struct ast_channel *chan, struct vm_state *vms)
10262 {
10263 /* Introduce messages they have */
10264 int res;
10265 div_t num;
10266
10267 if (!vms->oldmessages && !vms->newmessages) {
10268 res = ast_play_and_wait(chan, "vm-no");
10269 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10270 return res;
10271 } else {
10272 res = ast_play_and_wait(chan, "vm-youhave");
10273 }
10274
10275 if (vms->newmessages) {
10276 num = div(vms->newmessages, 10);
10277 if (vms->newmessages == 1) {
10278 res = ast_play_and_wait(chan, "digits/1-a");
10279 res = res ? res : ast_play_and_wait(chan, "vm-new-a");
10280 res = res ? res : ast_play_and_wait(chan, "vm-message");
10281 } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
10282 if (num.rem == 2) {
10283 if (!num.quot) {
10284 res = ast_play_and_wait(chan, "digits/2-ie");
10285 } else {
10286 res = say_and_wait(chan, vms->newmessages - 2 , ast_channel_language(chan));
10287 res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
10288 }
10289 } else {
10290 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10291 }
10292 res = res ? res : ast_play_and_wait(chan, "vm-new-e");
10293 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10294 } else {
10295 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10296 res = res ? res : ast_play_and_wait(chan, "vm-new-ych");
10297 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10298 }
10299 if (!res && vms->oldmessages)
10300 res = ast_play_and_wait(chan, "vm-and");
10301 }
10302 if (!res && vms->oldmessages) {
10303 num = div(vms->oldmessages, 10);
10304 if (vms->oldmessages == 1) {
10305 res = ast_play_and_wait(chan, "digits/1-a");
10306 res = res ? res : ast_play_and_wait(chan, "vm-old-a");
10307 res = res ? res : ast_play_and_wait(chan, "vm-message");
10308 } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
10309 if (num.rem == 2) {
10310 if (!num.quot) {
10311 res = ast_play_and_wait(chan, "digits/2-ie");
10312 } else {
10313 res = say_and_wait(chan, vms->oldmessages - 2 , ast_channel_language(chan));
10314 res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
10315 }
10316 } else {
10317 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10318 }
10319 res = res ? res : ast_play_and_wait(chan, "vm-old-e");
10320 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10321 } else {
10322 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10323 res = res ? res : ast_play_and_wait(chan, "vm-old-ych");
10324 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10325 }
10326 }
10327
10328 return res;
10329 }
10330
10331 /* SWEDISH syntax */
10332 static int vm_intro_se(struct ast_channel *chan, struct vm_state *vms)
10333 {
10334 /* Introduce messages they have */
10335 int res;
10336
10337 res = ast_play_and_wait(chan, "vm-youhave");
10338 if (res)
10339 return res;
10340
10341 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10342 res = ast_play_and_wait(chan, "vm-no");
10343 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10344 return res;
10345 }
10346
10347 if (vms->newmessages) {
10348 if (vms->newmessages == 1) {
10349 res = ast_play_and_wait(chan, "digits/ett");
10350 res = res ? res : ast_play_and_wait(chan, "vm-nytt");
10351 res = res ? res : ast_play_and_wait(chan, "vm-message");
10352 } else {
10353 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10354 res = res ? res : ast_play_and_wait(chan, "vm-nya");
10355 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10356 }
10357 if (!res && vms->oldmessages)
10358 res = ast_play_and_wait(chan, "vm-and");
10359 }
10360 if (!res && vms->oldmessages) {
10361 if (vms->oldmessages == 1) {
10362 res = ast_play_and_wait(chan, "digits/ett");
10363 res = res ? res : ast_play_and_wait(chan, "vm-gammalt");
10364 res = res ? res : ast_play_and_wait(chan, "vm-message");
10365 } else {
10366 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10367 res = res ? res : ast_play_and_wait(chan, "vm-gamla");
10368 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10369 }
10370 }
10371
10372 return res;
10373 }
10374
10375 /* NORWEGIAN syntax */
10376 static int vm_intro_no(struct ast_channel *chan, struct vm_state *vms)
10377 {
10378 /* Introduce messages they have */
10379 int res;
10380
10381 res = ast_play_and_wait(chan, "vm-youhave");
10382 if (res)
10383 return res;
10384
10385 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10386 res = ast_play_and_wait(chan, "vm-no");
10387 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10388 return res;
10389 }
10390
10391 if (vms->newmessages) {
10392 if (vms->newmessages == 1) {
10393 res = ast_play_and_wait(chan, "digits/1");
10394 res = res ? res : ast_play_and_wait(chan, "vm-ny");
10395 res = res ? res : ast_play_and_wait(chan, "vm-message");
10396 } else {
10397 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10398 res = res ? res : ast_play_and_wait(chan, "vm-nye");
10399 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10400 }
10401 if (!res && vms->oldmessages)
10402 res = ast_play_and_wait(chan, "vm-and");
10403 }
10404 if (!res && vms->oldmessages) {
10405 if (vms->oldmessages == 1) {
10406 res = ast_play_and_wait(chan, "digits/1");
10407 res = res ? res : ast_play_and_wait(chan, "vm-gamel");
10408 res = res ? res : ast_play_and_wait(chan, "vm-message");
10409 } else {
10410 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10411 res = res ? res : ast_play_and_wait(chan, "vm-gamle");
10412 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10413 }
10414 }
10415
10416 return res;
10417 }
10418
10419 /* Danish syntax */
10420 static int vm_intro_da(struct ast_channel *chan, struct vm_state *vms)
10421 {
10422 /* Introduce messages they have */
10423 int res;
10424
10425 res = ast_play_and_wait(chan, "vm-youhave");
10426 if (res)
10427 return res;
10428
10429 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10430 res = ast_play_and_wait(chan, "vm-no");
10431 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10432 return res;
10433 }
10434
10435 if (vms->newmessages) {
10436 if ((vms->newmessages == 1)) {
10437 res = ast_play_and_wait(chan, "digits/1");
10438 res = res ? res : ast_play_and_wait(chan, "vm-INBOX");
10439 res = res ? res : ast_play_and_wait(chan, "vm-message");
10440 } else {
10441 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10442 res = res ? res : ast_play_and_wait(chan, "vm-INBOXs");
10443 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10444 }
10445 if (!res && vms->oldmessages)
10446 res = ast_play_and_wait(chan, "vm-and");
10447 }
10448 if (!res && vms->oldmessages) {
10449 if (vms->oldmessages == 1) {
10450 res = ast_play_and_wait(chan, "digits/1");
10451 res = res ? res : ast_play_and_wait(chan, "vm-Old");
10452 res = res ? res : ast_play_and_wait(chan, "vm-message");
10453 } else {
10454 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10455 res = res ? res : ast_play_and_wait(chan, "vm-Olds");
10456 res = res ? res : ast_play_and_wait(chan, "vm-messages");
10457 }
10458 }
10459
10460 return res;
10461 }
10462
10463
10464 /* GERMAN syntax */
10465 static int vm_intro_de(struct ast_channel *chan, struct vm_state *vms)
10466 {
10467 /* Introduce messages they have */
10468 int res;
10469 res = ast_play_and_wait(chan, "vm-youhave");
10470 if (!res) {
10471 if (vms->newmessages) {
10472 if (vms->newmessages == 1)
10473 res = ast_play_and_wait(chan, "digits/1F");
10474 else
10475 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10476 if (!res)
10477 res = ast_play_and_wait(chan, "vm-INBOX");
10478 if (vms->oldmessages && !res)
10479 res = ast_play_and_wait(chan, "vm-and");
10480 else if (!res) {
10481 if (vms->newmessages == 1)
10482 res = ast_play_and_wait(chan, "vm-message");
10483 else
10484 res = ast_play_and_wait(chan, "vm-messages");
10485 }
10486
10487 }
10488 if (!res && vms->oldmessages) {
10489 if (vms->oldmessages == 1)
10490 res = ast_play_and_wait(chan, "digits/1F");
10491 else
10492 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10493 if (!res)
10494 res = ast_play_and_wait(chan, "vm-Old");
10495 if (!res) {
10496 if (vms->oldmessages == 1)
10497 res = ast_play_and_wait(chan, "vm-message");
10498 else
10499 res = ast_play_and_wait(chan, "vm-messages");
10500 }
10501 }
10502 if (!res) {
10503 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10504 res = ast_play_and_wait(chan, "vm-no");
10505 if (!res)
10506 res = ast_play_and_wait(chan, "vm-messages");
10507 }
10508 }
10509 }
10510 return res;
10511 }
10512
10513 /* SPANISH syntax */
10514 static int vm_intro_es(struct ast_channel *chan, struct vm_state *vms)
10515 {
10516 /* Introduce messages they have */
10517 int res;
10518 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10519 res = ast_play_and_wait(chan, "vm-youhaveno");
10520 if (!res)
10521 res = ast_play_and_wait(chan, "vm-messages");
10522 } else {
10523 res = ast_play_and_wait(chan, "vm-youhave");
10524 }
10525 if (!res) {
10526 if (vms->newmessages) {
10527 if (!res) {
10528 if (vms->newmessages == 1) {
10529 res = ast_play_and_wait(chan, "digits/1M");
10530 if (!res)
10531 res = ast_play_and_wait(chan, "vm-message");
10532 if (!res)
10533 res = ast_play_and_wait(chan, "vm-INBOXs");
10534 } else {
10535 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10536 if (!res)
10537 res = ast_play_and_wait(chan, "vm-messages");
10538 if (!res)
10539 res = ast_play_and_wait(chan, "vm-INBOX");
10540 }
10541 }
10542 if (vms->oldmessages && !res)
10543 res = ast_play_and_wait(chan, "vm-and");
10544 }
10545 if (vms->oldmessages) {
10546 if (!res) {
10547 if (vms->oldmessages == 1) {
10548 res = ast_play_and_wait(chan, "digits/1M");
10549 if (!res)
10550 res = ast_play_and_wait(chan, "vm-message");
10551 if (!res)
10552 res = ast_play_and_wait(chan, "vm-Olds");
10553 } else {
10554 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10555 if (!res)
10556 res = ast_play_and_wait(chan, "vm-messages");
10557 if (!res)
10558 res = ast_play_and_wait(chan, "vm-Old");
10559 }
10560 }
10561 }
10562 }
10563 return res;
10564 }
10565
10566 /* BRAZILIAN PORTUGUESE syntax */
10567 static int vm_intro_pt_BR(struct ast_channel *chan, struct vm_state *vms) {
10568 /* Introduce messages they have */
10569 int res;
10570 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10571 res = ast_play_and_wait(chan, "vm-nomessages");
10572 return res;
10573 } else {
10574 res = ast_play_and_wait(chan, "vm-youhave");
10575 }
10576 if (vms->newmessages) {
10577 if (!res)
10578 res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10579 if (vms->newmessages == 1) {
10580 if (!res)
10581 res = ast_play_and_wait(chan, "vm-message");
10582 if (!res)
10583 res = ast_play_and_wait(chan, "vm-INBOXs");
10584 } else {
10585 if (!res)
10586 res = ast_play_and_wait(chan, "vm-messages");
10587 if (!res)
10588 res = ast_play_and_wait(chan, "vm-INBOX");
10589 }
10590 if (vms->oldmessages && !res)
10591 res = ast_play_and_wait(chan, "vm-and");
10592 }
10593 if (vms->oldmessages) {
10594 if (!res)
10595 res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10596 if (vms->oldmessages == 1) {
10597 if (!res)
10598 res = ast_play_and_wait(chan, "vm-message");
10599 if (!res)
10600 res = ast_play_and_wait(chan, "vm-Olds");
10601 } else {
10602 if (!res)
10603 res = ast_play_and_wait(chan, "vm-messages");
10604 if (!res)
10605 res = ast_play_and_wait(chan, "vm-Old");
10606 }
10607 }
10608 return res;
10609 }
10610
10611 /* FRENCH syntax */
10612 static int vm_intro_fr(struct ast_channel *chan, struct vm_state *vms)
10613 {
10614 /* Introduce messages they have */
10615 int res;
10616 res = ast_play_and_wait(chan, "vm-youhave");
10617 if (!res) {
10618 if (vms->newmessages) {
10619 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10620 if (!res)
10621 res = ast_play_and_wait(chan, "vm-INBOX");
10622 if (vms->oldmessages && !res)
10623 res = ast_play_and_wait(chan, "vm-and");
10624 else if (!res) {
10625 if (vms->newmessages == 1)
10626 res = ast_play_and_wait(chan, "vm-message");
10627 else
10628 res = ast_play_and_wait(chan, "vm-messages");
10629 }
10630
10631 }
10632 if (!res && vms->oldmessages) {
10633 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10634 if (!res)
10635 res = ast_play_and_wait(chan, "vm-Old");
10636 if (!res) {
10637 if (vms->oldmessages == 1)
10638 res = ast_play_and_wait(chan, "vm-message");
10639 else
10640 res = ast_play_and_wait(chan, "vm-messages");
10641 }
10642 }
10643 if (!res) {
10644 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10645 res = ast_play_and_wait(chan, "vm-no");
10646 if (!res)
10647 res = ast_play_and_wait(chan, "vm-messages");
10648 }
10649 }
10650 }
10651 return res;
10652 }
10653
10654 /* DUTCH syntax */
10655 static int vm_intro_nl(struct ast_channel *chan, struct vm_state *vms)
10656 {
10657 /* Introduce messages they have */
10658 int res;
10659 res = ast_play_and_wait(chan, "vm-youhave");
10660 if (!res) {
10661 if (vms->newmessages) {
10662 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10663 if (!res) {
10664 if (vms->newmessages == 1)
10665 res = ast_play_and_wait(chan, "vm-INBOXs");
10666 else
10667 res = ast_play_and_wait(chan, "vm-INBOX");
10668 }
10669 if (vms->oldmessages && !res)
10670 res = ast_play_and_wait(chan, "vm-and");
10671 else if (!res) {
10672 if (vms->newmessages == 1)
10673 res = ast_play_and_wait(chan, "vm-message");
10674 else
10675 res = ast_play_and_wait(chan, "vm-messages");
10676 }
10677
10678 }
10679 if (!res && vms->oldmessages) {
10680 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10681 if (!res) {
10682 if (vms->oldmessages == 1)
10683 res = ast_play_and_wait(chan, "vm-Olds");
10684 else
10685 res = ast_play_and_wait(chan, "vm-Old");
10686 }
10687 if (!res) {
10688 if (vms->oldmessages == 1)
10689 res = ast_play_and_wait(chan, "vm-message");
10690 else
10691 res = ast_play_and_wait(chan, "vm-messages");
10692 }
10693 }
10694 if (!res) {
10695 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10696 res = ast_play_and_wait(chan, "vm-no");
10697 if (!res)
10698 res = ast_play_and_wait(chan, "vm-messages");
10699 }
10700 }
10701 }
10702 return res;
10703 }
10704
10705 /* PORTUGUESE syntax */
10706 static int vm_intro_pt(struct ast_channel *chan, struct vm_state *vms)
10707 {
10708 /* Introduce messages they have */
10709 int res;
10710 res = ast_play_and_wait(chan, "vm-youhave");
10711 if (!res) {
10712 if (vms->newmessages) {
10713 res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10714 if (!res) {
10715 if (vms->newmessages == 1) {
10716 res = ast_play_and_wait(chan, "vm-message");
10717 if (!res)
10718 res = ast_play_and_wait(chan, "vm-INBOXs");
10719 } else {
10720 res = ast_play_and_wait(chan, "vm-messages");
10721 if (!res)
10722 res = ast_play_and_wait(chan, "vm-INBOX");
10723 }
10724 }
10725 if (vms->oldmessages && !res)
10726 res = ast_play_and_wait(chan, "vm-and");
10727 }
10728 if (!res && vms->oldmessages) {
10729 res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, ast_channel_language(chan), "f");
10730 if (!res) {
10731 if (vms->oldmessages == 1) {
10732 res = ast_play_and_wait(chan, "vm-message");
10733 if (!res)
10734 res = ast_play_and_wait(chan, "vm-Olds");
10735 } else {
10736 res = ast_play_and_wait(chan, "vm-messages");
10737 if (!res)
10738 res = ast_play_and_wait(chan, "vm-Old");
10739 }
10740 }
10741 }
10742 if (!res) {
10743 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10744 res = ast_play_and_wait(chan, "vm-no");
10745 if (!res)
10746 res = ast_play_and_wait(chan, "vm-messages");
10747 }
10748 }
10749 }
10750 return res;
10751 }
10752
10753
10754 /* CZECH syntax */
10755 /* in czech there must be declension of word new and message
10756 * czech : english : czech : english
10757 * --------------------------------------------------------
10758 * vm-youhave : you have
10759 * vm-novou : one new : vm-zpravu : message
10760 * vm-nove : 2-4 new : vm-zpravy : messages
10761 * vm-novych : 5-infinite new : vm-zprav : messages
10762 * vm-starou : one old
10763 * vm-stare : 2-4 old
10764 * vm-starych : 5-infinite old
10765 * jednu : one - falling 4.
10766 * vm-no : no ( no messages )
10767 */
10768
10769 static int vm_intro_cs(struct ast_channel *chan, struct vm_state *vms)
10770 {
10771 int res;
10772 res = ast_play_and_wait(chan, "vm-youhave");
10773 if (!res) {
10774 if (vms->newmessages) {
10775 if (vms->newmessages == 1) {
10776 res = ast_play_and_wait(chan, "digits/jednu");
10777 } else {
10778 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10779 }
10780 if (!res) {
10781 if (vms->newmessages == 1)
10782 res = ast_play_and_wait(chan, "vm-novou");
10783 if ((vms->newmessages) > 1 && (vms->newmessages < 5))
10784 res = ast_play_and_wait(chan, "vm-nove");
10785 if (vms->newmessages > 4)
10786 res = ast_play_and_wait(chan, "vm-novych");
10787 }
10788 if (vms->oldmessages && !res)
10789 res = ast_play_and_wait(chan, "vm-and");
10790 else if (!res) {
10791 if (vms->newmessages == 1)
10792 res = ast_play_and_wait(chan, "vm-zpravu");
10793 if ((vms->newmessages) > 1 && (vms->newmessages < 5))
10794 res = ast_play_and_wait(chan, "vm-zpravy");
10795 if (vms->newmessages > 4)
10796 res = ast_play_and_wait(chan, "vm-zprav");
10797 }
10798 }
10799 if (!res && vms->oldmessages) {
10800 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10801 if (!res) {
10802 if (vms->oldmessages == 1)
10803 res = ast_play_and_wait(chan, "vm-starou");
10804 if ((vms->oldmessages) > 1 && (vms->oldmessages < 5))
10805 res = ast_play_and_wait(chan, "vm-stare");
10806 if (vms->oldmessages > 4)
10807 res = ast_play_and_wait(chan, "vm-starych");
10808 }
10809 if (!res) {
10810 if (vms->oldmessages == 1)
10811 res = ast_play_and_wait(chan, "vm-zpravu");
10812 if ((vms->oldmessages) > 1 && (vms->oldmessages < 5))
10813 res = ast_play_and_wait(chan, "vm-zpravy");
10814 if (vms->oldmessages > 4)
10815 res = ast_play_and_wait(chan, "vm-zprav");
10816 }
10817 }
10818 if (!res) {
10819 if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
10820 res = ast_play_and_wait(chan, "vm-no");
10821 if (!res)
10822 res = ast_play_and_wait(chan, "vm-zpravy");
10823 }
10824 }
10825 }
10826 return res;
10827 }
10828
10829 /* CHINESE (Taiwan) syntax */
10830 static int vm_intro_zh(struct ast_channel *chan, struct vm_state *vms)
10831 {
10832 int res;
10833 /* Introduce messages they have */
10834 res = ast_play_and_wait(chan, "vm-you");
10835
10836 if (!res && vms->newmessages) {
10837 res = ast_play_and_wait(chan, "vm-have");
10838 if (!res)
10839 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10840 if (!res)
10841 res = ast_play_and_wait(chan, "vm-tong");
10842 if (!res)
10843 res = ast_play_and_wait(chan, "vm-INBOX");
10844 if (vms->oldmessages && !res)
10845 res = ast_play_and_wait(chan, "vm-and");
10846 else if (!res)
10847 res = ast_play_and_wait(chan, "vm-messages");
10848 }
10849 if (!res && vms->oldmessages) {
10850 res = ast_play_and_wait(chan, "vm-have");
10851 if (!res)
10852 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10853 if (!res)
10854 res = ast_play_and_wait(chan, "vm-tong");
10855 if (!res)
10856 res = ast_play_and_wait(chan, "vm-Old");
10857 if (!res)
10858 res = ast_play_and_wait(chan, "vm-messages");
10859 }
10860 if (!res && !vms->oldmessages && !vms->newmessages) {
10861 res = ast_play_and_wait(chan, "vm-haveno");
10862 if (!res)
10863 res = ast_play_and_wait(chan, "vm-messages");
10864 }
10865 return res;
10866 }
10867
10868 /* Vietnamese syntax */
10869 static int vm_intro_vi(struct ast_channel *chan, struct vm_state *vms)
10870 {
10871 int res;
10872
10873 /* Introduce messages they have */
10874 res = ast_play_and_wait(chan, "vm-youhave");
10875 if (!res) {
10876 if (vms->newmessages) {
10877 res = say_and_wait(chan, vms->newmessages, ast_channel_language(chan));
10878 if (!res)
10879 res = ast_play_and_wait(chan, "vm-INBOX");
10880 if (vms->oldmessages && !res)
10881 res = ast_play_and_wait(chan, "vm-and");
10882 }
10883 if (!res && vms->oldmessages) {
10884 res = say_and_wait(chan, vms->oldmessages, ast_channel_language(chan));
10885 if (!res)
10886 res = ast_play_and_wait(chan, "vm-Old");
10887 }
10888 if (!res) {
10889 if (!vms->oldmessages && !vms->newmessages) {
10890 res = ast_play_and_wait(chan, "vm-no");
10891 if (!res)
10892 res = ast_play_and_wait(chan, "vm-message");
10893 }
10894 }
10895 }
10896 return res;
10897 }
10898
10899 static int vm_intro(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms)
10900 {
10901 char prefile[256];
10902
10903 /* Notify the user that the temp greeting is set and give them the option to remove it */
10904 snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
10905 if (ast_test_flag(vmu, VM_TEMPGREETWARN)) {
10906 RETRIEVE(prefile, -1, vmu->mailbox, vmu->context);
10907 if (ast_fileexists(prefile, NULL, NULL) > 0) {
10908 ast_play_and_wait(chan, "vm-tempgreetactive");
10909 }
10910 DISPOSE(prefile, -1);
10911 }
10912
10913 /* Play voicemail intro - syntax is different for different languages */
10914 if (0) {
10915 return 0;
10916 } else if (!strncasecmp(ast_channel_language(chan), "cs", 2)) { /* CZECH syntax */
10917 return vm_intro_cs(chan, vms);
10918 } else if (!strncasecmp(ast_channel_language(chan), "cz", 2)) { /* deprecated CZECH syntax */
10919 static int deprecation_warning = 0;
10920 if (deprecation_warning++ % 10 == 0) {
10921 ast_log(LOG_WARNING, "cz is not a standard language code. Please switch to using cs instead.\n");
10922 }
10923 return vm_intro_cs(chan, vms);
10924 } else if (!strncasecmp(ast_channel_language(chan), "de", 2)) { /* GERMAN syntax */
10925 return vm_intro_de(chan, vms);
10926 } else if (!strncasecmp(ast_channel_language(chan), "es", 2)) { /* SPANISH syntax */
10927 return vm_intro_es(chan, vms);
10928 } else if (!strncasecmp(ast_channel_language(chan), "fr", 2)) { /* FRENCH syntax */
10929 return vm_intro_fr(chan, vms);
10930 } else if (!strncasecmp(ast_channel_language(chan), "gr", 2)) { /* GREEK syntax */
10931 return vm_intro_gr(chan, vms);
10932 } else if (!strncasecmp(ast_channel_language(chan), "he", 2)) { /* HEBREW syntax */
10933 return vm_intro_he(chan, vms);
10934 } else if (!strncasecmp(ast_channel_language(chan), "is", 2)) { /* ICELANDIC syntax */
10935 return vm_intro_is(chan, vms);
10936 } else if (!strncasecmp(ast_channel_language(chan), "it", 2)) { /* ITALIAN syntax */
10937 return vm_intro_it(chan, vms);
10938 } else if (!strncasecmp(ast_channel_language(chan), "ja", 2)) { /* JAPANESE syntax */
10939 return vm_intro_ja(chan, vms);
10940 } else if (!strncasecmp(ast_channel_language(chan), "nl", 2)) { /* DUTCH syntax */
10941 return vm_intro_nl(chan, vms);
10942 } else if (!strncasecmp(ast_channel_language(chan), "no", 2)) { /* NORWEGIAN syntax */
10943 return vm_intro_no(chan, vms);
10944 } else if (!strncasecmp(ast_channel_language(chan), "da", 2)) { /* DANISH syntax */
10945 return vm_intro_da(chan, vms);
10946 } else if (!strncasecmp(ast_channel_language(chan), "pl", 2)) { /* POLISH syntax */
10947 return vm_intro_pl(chan, vms);
10948 } else if (!strncasecmp(ast_channel_language(chan), "pt_BR", 5)) { /* BRAZILIAN PORTUGUESE syntax */
10949 return vm_intro_pt_BR(chan, vms);
10950 } else if (!strncasecmp(ast_channel_language(chan), "pt", 2)) { /* PORTUGUESE syntax */
10951 return vm_intro_pt(chan, vms);
10952 } else if (!strncasecmp(ast_channel_language(chan), "ru", 2)) { /* RUSSIAN syntax */
10953 return vm_intro_multilang(chan, vms, "n");
10954 } else if (!strncasecmp(ast_channel_language(chan), "se", 2)) { /* SWEDISH syntax */
10955 return vm_intro_se(chan, vms);
10956 } else if (!strncasecmp(ast_channel_language(chan), "ua", 2)) { /* UKRAINIAN syntax */
10957 return vm_intro_multilang(chan, vms, "n");
10958 } else if (!strncasecmp(ast_channel_language(chan), "vi", 2)) { /* VIETNAMESE syntax */
10959 return vm_intro_vi(chan, vms);
10960 } else if (!strncasecmp(ast_channel_language(chan), "zh", 2)) { /* CHINESE (Taiwan) syntax */
10961 return vm_intro_zh(chan, vms);
10962 } else { /* Default to ENGLISH */
10963 return vm_intro_en(chan, vms);
10964 }
10965 }
10966
10967 static int vm_instructions_en(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int skipadvanced, int in_urgent, int nodelete)
10968 {
10969 int res = 0;
10970 /* Play instructions and wait for new command */
10971 while (!res) {
10972 if (vms->starting) {
10973 if (vms->lastmsg > -1) {
10974 if (skipadvanced)
10975 res = ast_play_and_wait(chan, "vm-onefor-full");
10976 else
10977 res = ast_play_and_wait(chan, "vm-onefor");
10978 if (!res)
10979 res = vm_play_folder_name(chan, vms->vmbox);
10980 }
10981 if (!res) {
10982 if (skipadvanced)
10983 res = ast_play_and_wait(chan, "vm-opts-full");
10984 else
10985 res = ast_play_and_wait(chan, "vm-opts");
10986 }
10987 } else {
10988 /* Added for additional help */
10989 if (skipadvanced) {
10990 res = ast_play_and_wait(chan, "vm-onefor-full");
10991 if (!res)
10992 res = vm_play_folder_name(chan, vms->vmbox);
10993 res = ast_play_and_wait(chan, "vm-opts-full");
10994 }
10995 /* Logic:
10996 * If the current message is not the first OR
10997 * if we're listening to the first new message and there are
10998 * also urgent messages, then prompt for navigation to the
10999 * previous message
11000 */
11001 if (vms->curmsg || (!in_urgent && vms->urgentmessages > 0) || (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms->lastmsg > 0)) {
11002 res = ast_play_and_wait(chan, "vm-prev");
11003 }
11004 if (!res && !skipadvanced)
11005 res = ast_play_and_wait(chan, "vm-advopts");
11006 if (!res)
11007 res = ast_play_and_wait(chan, "vm-repeat");
11008 /* Logic:
11009 * If we're not listening to the last message OR
11010 * we're listening to the last urgent message and there are
11011 * also new non-urgent messages, then prompt for navigation
11012 * to the next message
11013 */
11014 if (!res && ((vms->curmsg != vms->lastmsg) || (in_urgent && vms->newmessages > 0) ||
11015 (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms->lastmsg > 0) )) {
11016 res = ast_play_and_wait(chan, "vm-next");
11017 }
11018 if (!res) {
11019 int curmsg_deleted;
11020 #ifdef IMAP_STORAGE
11021 ast_mutex_lock(&vms->lock);
11022 #endif
11023 curmsg_deleted = vms->deleted[vms->curmsg];
11024 #ifdef IMAP_STORAGE
11025 ast_mutex_unlock(&vms->lock);
11026 #endif
11027 if (!nodelete) {
11028 if (!curmsg_deleted) {
11029 res = ast_play_and_wait(chan, "vm-delete");
11030 } else {
11031 res = ast_play_and_wait(chan, "vm-undelete");
11032 }
11033 }
11034 if (!res) {
11035 res = ast_play_and_wait(chan, "vm-toforward");
11036 }
11037 if (!res) {
11038 res = ast_play_and_wait(chan, "vm-savemessage");
11039 }
11040 }
11041 }
11042 if (!res) {
11043 res = ast_play_and_wait(chan, "vm-helpexit");
11044 }
11045 if (!res)
11046 res = ast_waitfordigit(chan, 6000);
11047 if (!res) {
11048 vms->repeats++;
11049 if (vms->repeats > 2) {
11050 res = 't';
11051 }
11052 }
11053 }
11054 return res;
11055 }
11056
11057 static int vm_instructions_ja(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int skipadvanced, int in_urgent, int nodelete)
11058 {
11059 int res = 0;
11060 /* Play instructions and wait for new command */
11061 while (!res) {
11062 if (vms->starting) {
11063 if (vms->lastmsg > -1) {
11064 res = vm_play_folder_name(chan, vms->vmbox);
11065 if (!res)
11066 res = ast_play_and_wait(chan, "jp-wa");
11067 if (!res)
11068 res = ast_play_and_wait(chan, "digits/1");
11069 if (!res)
11070 res = ast_play_and_wait(chan, "jp-wo");
11071 if (!res)
11072 res = ast_play_and_wait(chan, "silence/1");
11073 }
11074 if (!res)
11075 res = ast_play_and_wait(chan, "vm-opts");
11076 } else {
11077 /* Added for additional help */
11078 if (skipadvanced) {
11079 res = vm_play_folder_name(chan, vms->vmbox);
11080 if (!res)
11081 res = ast_play_and_wait(chan, "jp-wa");
11082 if (!res)
11083 res = ast_play_and_wait(chan, "digits/1");
11084 if (!res)
11085 res = ast_play_and_wait(chan, "jp-wo");
11086 if (!res)
11087 res = ast_play_and_wait(chan, "silence/1");
11088 res = ast_play_and_wait(chan, "vm-opts-full");
11089 }
11090 /* Logic:
11091 * If the current message is not the first OR
11092 * if we're listening to the first new message and there are
11093 * also urgent messages, then prompt for navigation to the
11094 * previous message
11095 */
11096 if (vms->curmsg || (!in_urgent && vms->urgentmessages > 0) || (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms->lastmsg > 0)) {
11097 res = ast_play_and_wait(chan, "vm-prev");
11098 }
11099 if (!res && !skipadvanced)
11100 res = ast_play_and_wait(chan, "vm-advopts");
11101 if (!res)
11102 res = ast_play_and_wait(chan, "vm-repeat");
11103 /* Logic:
11104 * If we're not listening to the last message OR
11105 * we're listening to the last urgent message and there are
11106 * also new non-urgent messages, then prompt for navigation
11107 * to the next message
11108 */
11109 if (!res && ((vms->curmsg != vms->lastmsg) || (in_urgent && vms->newmessages > 0) ||
11110 (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms->lastmsg > 0) )) {
11111 res = ast_play_and_wait(chan, "vm-next");
11112 }
11113 if (!res) {
11114 int curmsg_deleted;
11115 #ifdef IMAP_STORAGE
11116 ast_mutex_lock(&vms->lock);
11117 #endif
11118 curmsg_deleted = vms->deleted[vms->curmsg];
11119 #ifdef IMAP_STORAGE
11120 ast_mutex_unlock(&vms->lock);
11121 #endif
11122 if (!curmsg_deleted) {
11123 res = ast_play_and_wait(chan, "vm-delete");
11124 } else {
11125 res = ast_play_and_wait(chan, "vm-undelete");
11126 }
11127 if (!res) {
11128 res = ast_play_and_wait(chan, "vm-toforward");
11129 }
11130 if (!res) {
11131 res = ast_play_and_wait(chan, "vm-savemessage");
11132 }
11133 }
11134 }
11135
11136 if (!res) {
11137 res = ast_play_and_wait(chan, "vm-helpexit");
11138 }
11139 if (!res)
11140 res = ast_waitfordigit(chan, 6000);
11141 if (!res) {
11142 vms->repeats++;
11143 if (vms->repeats > 2) {
11144 res = 't';
11145 }
11146 }
11147
11148 }
11149
11150 return res;
11151 }
11152
11153 static int vm_instructions_zh(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int skipadvanced, int in_urgent, int nodelete)
11154 {
11155 int res = 0;
11156 /* Play instructions and wait for new command */
11157 while (!res) {
11158 if (vms->lastmsg > -1) {
11159 res = ast_play_and_wait(chan, "vm-listen");
11160 if (!res)
11161 res = vm_play_folder_name(chan, vms->vmbox);
11162 if (!res)
11163 res = ast_play_and_wait(chan, "press");
11164 if (!res)
11165 res = ast_play_and_wait(chan, "digits/1");
11166 }
11167 if (!res)
11168 res = ast_play_and_wait(chan, "vm-opts");
11169 if (!res) {
11170 vms->starting = 0;
11171 return vm_instructions_en(chan, vmu, vms, skipadvanced, in_urgent, nodelete);
11172 }
11173 }
11174 return res;
11175 }
11176
11177 static int vm_instructions(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int skipadvanced, int in_urgent, int nodelete)
11178 {
11179 if (!strncasecmp(ast_channel_language(chan), "ja", 2)) { /* Japanese syntax */
11180 return vm_instructions_ja(chan, vmu, vms, skipadvanced, in_urgent, nodelete);
11181 } else if (vms->starting && !strncasecmp(ast_channel_language(chan), "zh", 2)) { /* CHINESE (Taiwan) syntax */
11182 return vm_instructions_zh(chan, vmu, vms, skipadvanced, in_urgent, nodelete);
11183 } else { /* Default to ENGLISH */
11184 return vm_instructions_en(chan, vmu, vms, skipadvanced, in_urgent, nodelete);
11185 }
11186 }
11187
11188 static int vm_newuser_setup(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
11189 {
11190 int cmd = 0;
11191 int duration = 0;
11192 int tries = 0;
11193 char newpassword[80] = "";
11194 char newpassword2[80] = "";
11195 char prefile[PATH_MAX] = "";
11196 unsigned char buf[256];
11197 int bytes = 0;
11198
11199 ast_test_suite_event_notify("NEWUSER", "Message: entering new user state");
11200 if (ast_adsi_available(chan)) {
11201 bytes += adsi_logo(buf + bytes);
11202 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "New User Setup", "");
11203 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
11204 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
11205 bytes += ast_adsi_voice_mode(buf + bytes, 0);
11206 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
11207 }
11208
11209 /* If forcename is set, have the user record their name */
11210 if (ast_test_flag(vmu, VM_FORCENAME)) {
11211 snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, vms->username);
11212 if (ast_fileexists(prefile, NULL, NULL) < 1) {
11213 cmd = play_record_review(chan, "vm-rec-name", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11214 if (cmd < 0 || cmd == 't' || cmd == '#')
11215 return cmd;
11216 }
11217 }
11218
11219 /* If forcegreetings is set, have the user record their greetings */
11220 if (ast_test_flag(vmu, VM_FORCEGREET)) {
11221 snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, vms->username);
11222 if (ast_fileexists(prefile, NULL, NULL) < 1) {
11223 cmd = play_record_review(chan, "vm-rec-unv", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11224 if (cmd < 0 || cmd == 't' || cmd == '#')
11225 return cmd;
11226 }
11227
11228 snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, vms->username);
11229 if (ast_fileexists(prefile, NULL, NULL) < 1) {
11230 cmd = play_record_review(chan, "vm-rec-busy", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11231 if (cmd < 0 || cmd == 't' || cmd == '#')
11232 return cmd;
11233 }
11234 }
11235
11236 /*
11237 * Change the password last since new users will be able to skip over any steps this one comes before
11238 * by hanging up and calling back to voicemail main since the password is used to verify new user status.
11239 */
11240 for (;;) {
11241 newpassword[1] = '\0';
11242 newpassword[0] = cmd = ast_play_and_wait(chan, vm_newpassword);
11243 if (cmd == '#')
11244 newpassword[0] = '\0';
11245 if (cmd < 0 || cmd == 't' || cmd == '#')
11246 return cmd;
11247 cmd = ast_readstring(chan, newpassword + strlen(newpassword), sizeof(newpassword) - 1, 2000, 10000, "#");
11248 if (cmd < 0 || cmd == 't' || cmd == '#')
11249 return cmd;
11250 cmd = check_password(vmu, newpassword); /* perform password validation */
11251 if (cmd != 0) {
11252 ast_log(AST_LOG_NOTICE, "Invalid password for user %s (%s)\n", vms->username, newpassword);
11253 cmd = ast_play_and_wait(chan, vm_invalid_password);
11254 } else {
11255 newpassword2[1] = '\0';
11256 newpassword2[0] = cmd = ast_play_and_wait(chan, vm_reenterpassword);
11257 if (cmd == '#')
11258 newpassword2[0] = '\0';
11259 if (cmd < 0 || cmd == 't' || cmd == '#')
11260 return cmd;
11261 cmd = ast_readstring(chan, newpassword2 + strlen(newpassword2), sizeof(newpassword2) - 1, 2000, 10000, "#");
11262 if (cmd < 0 || cmd == 't' || cmd == '#')
11263 return cmd;
11264 if (!strcmp(newpassword, newpassword2))
11265 break;
11266 ast_log(AST_LOG_NOTICE, "Password mismatch for user %s (%s != %s)\n", vms->username, newpassword, newpassword2);
11267 cmd = ast_play_and_wait(chan, vm_mismatch);
11268 }
11269 if (++tries == 3)
11270 return -1;
11271 if (cmd != 0) {
11272 cmd = ast_play_and_wait(chan, vm_pls_try_again);
11273 }
11274 }
11275 if (pwdchange & PWDCHANGE_INTERNAL)
11276 vm_change_password(vmu, newpassword);
11277 if ((pwdchange & PWDCHANGE_EXTERNAL) && !ast_strlen_zero(ext_pass_cmd))
11278 vm_change_password_shell(vmu, newpassword);
11279
11280 ast_debug(1, "User %s set password to %s of length %d\n", vms->username, newpassword, (int) strlen(newpassword));
11281 cmd = ast_play_and_wait(chan, vm_passchanged);
11282
11283 return cmd;
11284 }
11285
11286 static int vm_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
11287 {
11288 int cmd = 0;
11289 int retries = 0;
11290 int duration = 0;
11291 char newpassword[80] = "";
11292 char newpassword2[80] = "";
11293 char prefile[PATH_MAX] = "";
11294 unsigned char buf[256];
11295 int bytes = 0;
11296 SCOPE_ENTER(3, "%s: %s entering mailbox options", ast_channel_name(chan), vms->username);
11297
11298 ast_test_suite_event_notify("VMOPTIONS", "Message: entering mailbox options");
11299 if (ast_adsi_available(chan)) {
11300 bytes += adsi_logo(buf + bytes);
11301 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Options Menu", "");
11302 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
11303 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
11304 bytes += ast_adsi_voice_mode(buf + bytes, 0);
11305 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
11306 }
11307 while ((cmd >= 0) && (cmd != 't')) {
11308 if (cmd)
11309 retries = 0;
11310 switch (cmd) {
11311 case '1': /* Record your unavailable message */
11312 snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, vms->username);
11313 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_record_review, chan, "vm-rec-unv", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11314 break;
11315 case '2': /* Record your busy message */
11316 snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, vms->username);
11317 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_record_review, chan, "vm-rec-busy", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11318 break;
11319 case '3': /* Record greeting */
11320 snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, vms->username);
11321 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_record_review, chan, "vm-rec-name", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11322 break;
11323 case '4': /* manage the temporary greeting */
11324 cmd = vm_tempgreeting(chan, vmu, vms, fmtc, record_gain);
11325 break;
11326 case '5': /* change password */
11327 if (vmu->password[0] == '-') {
11328 cmd = ast_play_and_wait(chan, "vm-no");
11329 break;
11330 }
11331 newpassword[1] = '\0';
11332 newpassword[0] = cmd = ast_play_and_wait(chan, vm_newpassword);
11333 if (cmd == '#')
11334 newpassword[0] = '\0';
11335 else {
11336 if (cmd < 0)
11337 break;
11338 if ((cmd = ast_readstring(chan, newpassword + strlen(newpassword), sizeof(newpassword) - 1, 2000, 10000, "#")) < 0) {
11339 break;
11340 }
11341 }
11342 cmd = check_password(vmu, newpassword); /* perform password validation */
11343 if (cmd != 0) {
11344 ast_log(AST_LOG_NOTICE, "Invalid password for user %s (%s)\n", vms->username, newpassword);
11345 cmd = ast_play_and_wait(chan, vm_invalid_password);
11346 if (!cmd) {
11347 cmd = ast_play_and_wait(chan, vm_pls_try_again);
11348 }
11349 break;
11350 }
11351 newpassword2[1] = '\0';
11352 newpassword2[0] = cmd = ast_play_and_wait(chan, vm_reenterpassword);
11353 if (cmd == '#')
11354 newpassword2[0] = '\0';
11355 else {
11356 if (cmd < 0)
11357 break;
11358
11359 if ((cmd = ast_readstring(chan, newpassword2 + strlen(newpassword2), sizeof(newpassword2) - 1, 2000, 10000, "#")) < 0) {
11360 break;
11361 }
11362 }
11363 if (strcmp(newpassword, newpassword2)) {
11364 ast_log(AST_LOG_NOTICE, "Password mismatch for user %s (%s != %s)\n", vms->username, newpassword, newpassword2);
11365 cmd = ast_play_and_wait(chan, vm_mismatch);
11366 if (!cmd) {
11367 cmd = ast_play_and_wait(chan, vm_pls_try_again);
11368 }
11369 break;
11370 }
11371
11372 if (pwdchange & PWDCHANGE_INTERNAL) {
11373 vm_change_password(vmu, newpassword);
11374 }
11375 if ((pwdchange & PWDCHANGE_EXTERNAL) && !ast_strlen_zero(ext_pass_cmd)) {
11376 vm_change_password_shell(vmu, newpassword);
11377 }
11378
11379 ast_debug(1, "User %s set password to %s of length %d\n",
11380 vms->username, newpassword, (int) strlen(newpassword));
11381 cmd = ast_play_and_wait(chan, vm_passchanged);
11382 break;
11383 case '*':
11384 cmd = 't';
11385 break;
11386 default:
11387 cmd = 0;
11388 snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
11389 SCOPE_CALL(-1, RETRIEVE, prefile, -1, vmu->mailbox, vmu->context);
11390 if (ast_fileexists(prefile, NULL, NULL)) {
11391 cmd = ast_play_and_wait(chan, "vm-tmpexists");
11392 }
11393 SCOPE_CALL(-1, DISPOSE, prefile, -1);
11394 if (!cmd) {
11395 cmd = ast_play_and_wait(chan, "vm-options");
11396 }
11397 if (!cmd) {
11398 cmd = ast_waitfordigit(chan, 6000);
11399 }
11400 if (!cmd) {
11401 retries++;
11402 }
11403 if (retries > 3) {
11404 cmd = 't';
11405 }
11406 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
11407 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
11408 }
11409 }
11410 if (cmd == 't')
11411 cmd = 0;
11412 SCOPE_EXIT_RTN_VALUE(cmd, "Done\n");
11413 }
11414
11415 /*!
11416 * \brief The handler for 'record a temporary greeting'.
11417 * \param chan
11418 * \param vmu
11419 * \param vms
11420 * \param fmtc
11421 * \param record_gain
11422 *
11423 * This is option 4 from the mailbox options menu.
11424 * This function manages the following promptings:
11425 * 1: play / record / review the temporary greeting. : invokes play_record_review().
11426 * 2: remove (delete) the temporary greeting.
11427 * *: return to the main menu.
11428 *
11429 * \return zero on success, -1 on error.
11430 */
11431 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
11432 {
11433 int cmd = 0;
11434 int retries = 0;
11435 int duration = 0;
11436 char prefile[PATH_MAX] = "";
11437 unsigned char buf[256];
11438 int bytes = 0;
11439
11440 if (ast_adsi_available(chan)) {
11441 bytes += adsi_logo(buf + bytes);
11442 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Temp Greeting Menu", "");
11443 bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
11444 bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
11445 bytes += ast_adsi_voice_mode(buf + bytes, 0);
11446 ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
11447 }
11448
11449 ast_test_suite_event_notify("TEMPGREETING", "Message: entering temp greeting options");
11450 snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
11451 while ((cmd >= 0) && (cmd != 't')) {
11452 if (cmd)
11453 retries = 0;
11454 RETRIEVE(prefile, -1, vmu->mailbox, vmu->context);
11455 if (ast_fileexists(prefile, NULL, NULL) <= 0) {
11456 cmd = play_record_review(chan, "vm-rec-temp", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11457 if (cmd == -1) {
11458 break;
11459 }
11460 cmd = 't';
11461 } else {
11462 switch (cmd) {
11463 case '1':
11464 cmd = play_record_review(chan, "vm-rec-temp", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, NULL, record_gain, vms, NULL, NULL, 0);
11465 break;
11466 case '2':
11467 DELETE(prefile, -1, prefile, vmu);
11468 ast_play_and_wait(chan, "vm-tempremoved");
11469 cmd = 't';
11470 break;
11471 case '*':
11472 cmd = 't';
11473 break;
11474 default:
11475 cmd = ast_play_and_wait(chan,
11476 ast_fileexists(prefile, NULL, NULL) > 0 ? /* XXX always true ? */
11477 "vm-tempgreeting2" : "vm-tempgreeting");
11478 if (!cmd) {
11479 cmd = ast_waitfordigit(chan, 6000);
11480 }
11481 if (!cmd) {
11482 retries++;
11483 }
11484 if (retries > 3) {
11485 cmd = 't';
11486 }
11487 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
11488 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
11489 }
11490 }
11491 DISPOSE(prefile, -1);
11492 }
11493 if (cmd == 't')
11494 cmd = 0;
11495 return cmd;
11496 }
11497
11498 /*!
11499 * \brief Greek syntax for 'You have N messages' greeting.
11500 * \param chan
11501 * \param vms
11502 * \param vmu
11503 *
11504 * \return zero on success, -1 on error.
11505 */
11506 static int vm_browse_messages_gr(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11507 {
11508 int cmd = 0;
11509
11510 if (vms->lastmsg > -1) {
11511 cmd = play_message(chan, vmu, vms);
11512 } else {
11513 cmd = ast_play_and_wait(chan, "vm-youhaveno");
11514 if (!strcasecmp(vms->vmbox, "vm-INBOX") ||!strcasecmp(vms->vmbox, "vm-Old")){
11515 if (!cmd) {
11516 snprintf(vms->fn, sizeof(vms->fn), "vm-%ss", vms->curbox);
11517 cmd = ast_play_and_wait(chan, vms->fn);
11518 }
11519 if (!cmd)
11520 cmd = ast_play_and_wait(chan, "vm-messages");
11521 } else {
11522 if (!cmd)
11523 cmd = ast_play_and_wait(chan, "vm-messages");
11524 if (!cmd) {
11525 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11526 cmd = ast_play_and_wait(chan, vms->fn);
11527 }
11528 }
11529 }
11530 return cmd;
11531 }
11532
11533 /* Hebrew Syntax */
11534 static int vm_browse_messages_he(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11535 {
11536 int cmd = 0;
11537
11538 if (vms->lastmsg > -1) {
11539 cmd = play_message(chan, vmu, vms);
11540 } else {
11541 if (!strcasecmp(vms->fn, "INBOX")) {
11542 cmd = ast_play_and_wait(chan, "vm-nonewmessages");
11543 } else {
11544 cmd = ast_play_and_wait(chan, "vm-nomessages");
11545 }
11546 }
11547 return cmd;
11548 }
11549
11550 /*!
11551 * \brief Default English syntax for 'You have N messages' greeting.
11552 * \param chan
11553 * \param vms
11554 * \param vmu
11555 *
11556 * \return zero on success, -1 on error.
11557 */
11558 static int vm_browse_messages_en(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11559 {
11560 int cmd = 0;
11561
11562 if (vms->lastmsg > -1) {
11563 cmd = play_message(chan, vmu, vms);
11564 } else {
11565 cmd = ast_play_and_wait(chan, "vm-youhave");
11566 if (!cmd)
11567 cmd = ast_play_and_wait(chan, "vm-no");
11568 if (!cmd) {
11569 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11570 cmd = ast_play_and_wait(chan, vms->fn);
11571 }
11572 if (!cmd)
11573 cmd = ast_play_and_wait(chan, "vm-messages");
11574 }
11575 return cmd;
11576 }
11577
11578 /*!
11579 *\brief Italian syntax for 'You have N messages' greeting.
11580 * \param chan
11581 * \param vms
11582 * \param vmu
11583 *
11584 * \return zero on success, -1 on error.
11585 */
11586 static int vm_browse_messages_it(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11587 {
11588 int cmd;
11589
11590 if (vms->lastmsg > -1) {
11591 cmd = play_message(chan, vmu, vms);
11592 } else {
11593 cmd = ast_play_and_wait(chan, "vm-no");
11594 if (!cmd)
11595 cmd = ast_play_and_wait(chan, "vm-message");
11596 if (!cmd) {
11597 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11598 cmd = ast_play_and_wait(chan, vms->fn);
11599 }
11600 }
11601 return cmd;
11602 }
11603
11604 /*!
11605 * \brief Japanese syntax for 'You have N messages' greeting.
11606 * \param chan
11607 * \param vms
11608 * \param vmu
11609 *
11610 * \return zero on success, -1 on error.
11611 */
11612 static int vm_browse_messages_ja(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11613 {
11614 int cmd = 0;
11615
11616 if (vms->lastmsg > -1) {
11617 cmd = play_message(chan, vmu, vms);
11618 } else {
11619 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11620 cmd = ast_play_and_wait(chan, vms->fn);
11621 if (!cmd)
11622 cmd = ast_play_and_wait(chan, "vm-messages");
11623 if (!cmd)
11624 cmd = ast_play_and_wait(chan, "jp-wa");
11625 if (!cmd)
11626 cmd = ast_play_and_wait(chan, "jp-arimasen");
11627 }
11628 return cmd;
11629 }
11630
11631 /*!
11632 * \brief Spanish syntax for 'You have N messages' greeting.
11633 * \param chan
11634 * \param vms
11635 * \param vmu
11636 *
11637 * \return zero on success, -1 on error.
11638 */
11639 static int vm_browse_messages_es(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11640 {
11641 int cmd;
11642
11643 if (vms->lastmsg > -1) {
11644 cmd = play_message(chan, vmu, vms);
11645 } else {
11646 cmd = ast_play_and_wait(chan, "vm-youhaveno");
11647 if (!cmd)
11648 cmd = ast_play_and_wait(chan, "vm-messages");
11649 if (!cmd) {
11650 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11651 cmd = ast_play_and_wait(chan, vms->fn);
11652 }
11653 }
11654 return cmd;
11655 }
11656
11657 /*!
11658 * \brief Portuguese syntax for 'You have N messages' greeting.
11659 * \param chan
11660 * \param vms
11661 * \param vmu
11662 *
11663 * \return zero on success, -1 on error.
11664 */
11665 static int vm_browse_messages_pt(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11666 {
11667 int cmd;
11668
11669 if (vms->lastmsg > -1) {
11670 cmd = play_message(chan, vmu, vms);
11671 } else {
11672 cmd = ast_play_and_wait(chan, "vm-no");
11673 if (!cmd) {
11674 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11675 cmd = ast_play_and_wait(chan, vms->fn);
11676 }
11677 if (!cmd)
11678 cmd = ast_play_and_wait(chan, "vm-messages");
11679 }
11680 return cmd;
11681 }
11682
11683 /*!
11684 * \brief Chinese (Taiwan)syntax for 'You have N messages' greeting.
11685 * \param chan
11686 * \param vms
11687 * \param vmu
11688 *
11689 * \return zero on success, -1 on error.
11690 */
11691 static int vm_browse_messages_zh(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11692 {
11693 int cmd;
11694
11695 if (vms->lastmsg > -1) {
11696 cmd = play_message(chan, vmu, vms);
11697 } else {
11698 cmd = ast_play_and_wait(chan, "vm-you");
11699 if (!cmd)
11700 cmd = ast_play_and_wait(chan, "vm-haveno");
11701 if (!cmd)
11702 cmd = ast_play_and_wait(chan, "vm-messages");
11703 if (!cmd) {
11704 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11705 cmd = ast_play_and_wait(chan, vms->fn);
11706 }
11707 }
11708 return cmd;
11709 }
11710
11711 /*!
11712 * \brief Vietnamese syntax for 'You have N messages' greeting.
11713 * \param chan
11714 * \param vms
11715 * \param vmu
11716 *
11717 * \return zero on success, -1 on error.
11718 */
11719 static int vm_browse_messages_vi(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11720 {
11721 int cmd = 0;
11722
11723 if (vms->lastmsg > -1) {
11724 cmd = play_message(chan, vmu, vms);
11725 } else {
11726 cmd = ast_play_and_wait(chan, "vm-no");
11727 if (!cmd) {
11728 snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
11729 cmd = ast_play_and_wait(chan, vms->fn);
11730 }
11731 }
11732 return cmd;
11733 }
11734
11735 /*!
11736 * \brief Top level method to invoke the language variant vm_browse_messages_XX function.
11737 * \param chan The channel for the current user. We read the language property from this.
11738 * \param vms passed into the language-specific vm_browse_messages function.
11739 * \param vmu passed into the language-specific vm_browse_messages function.
11740 *
11741 * The method to be invoked is determined by the value of language code property in the user's channel.
11742 * The default (when unable to match) is to use english.
11743 *
11744 * \return zero on success, -1 on error.
11745 */
11746 static int vm_browse_messages(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
11747 {
11748 if (!strncasecmp(ast_channel_language(chan), "es", 2)) { /* SPANISH */
11749 return vm_browse_messages_es(chan, vms, vmu);
11750 } else if (!strncasecmp(ast_channel_language(chan), "gr", 2)) { /* GREEK */
11751 return vm_browse_messages_gr(chan, vms, vmu);
11752 } else if (!strncasecmp(ast_channel_language(chan), "he", 2)) { /* HEBREW */
11753 return vm_browse_messages_he(chan, vms, vmu);
11754 } else if (!strncasecmp(ast_channel_language(chan), "it", 2)) { /* ITALIAN */
11755 return vm_browse_messages_it(chan, vms, vmu);
11756 } else if (!strncasecmp(ast_channel_language(chan), "ja", 2)) { /* JAPANESE */
11757 return vm_browse_messages_ja(chan, vms, vmu);
11758 } else if (!strncasecmp(ast_channel_language(chan), "pt", 2)) { /* PORTUGUESE */
11759 return vm_browse_messages_pt(chan, vms, vmu);
11760 } else if (!strncasecmp(ast_channel_language(chan), "vi", 2)) { /* VIETNAMESE */
11761 return vm_browse_messages_vi(chan, vms, vmu);
11762 } else if (!strncasecmp(ast_channel_language(chan), "zh", 2)) { /* CHINESE (Taiwan) */
11763 return vm_browse_messages_zh(chan, vms, vmu);
11764 } else { /* Default to English syntax */
11765 return vm_browse_messages_en(chan, vms, vmu);
11766 }
11767 }
11768
11769 static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_size,
11770 struct ast_vm_user *res_vmu, const char *context, const char *prefix,
11771 int skipuser, int max_logins, int silent)
11772 {
11773 int useadsi = 0, valid = 0, logretries = 0;
11774 char password[AST_MAX_EXTENSION], *passptr = NULL;
11775 struct ast_vm_user vmus, *vmu = NULL;
11776
11777 /* If ADSI is supported, setup login screen */
11778 adsi_begin(chan, &useadsi);
11779 if (!skipuser && useadsi)
11780 adsi_login(chan);
11781 if (!silent && !skipuser && ast_streamfile(chan, vm_login, ast_channel_language(chan))) {
11782 ast_log(AST_LOG_WARNING, "Couldn't stream login file\n");
11783 return -1;
11784 }
11785
11786 /* Authenticate them and get their mailbox/password */
11787
11788 while (!valid && (logretries < max_logins)) {
11789 /* Prompt for, and read in the username */
11790 if (!skipuser && ast_readstring(chan, mailbox, mailbox_size - 1, 2000, 10000, "#") < 0) {
11791 ast_log(AST_LOG_WARNING, "Couldn't read username\n");
11792 return -1;
11793 }
11794 if (ast_strlen_zero(mailbox)) {
11795 if (ast_channel_caller(chan)->id.number.valid && ast_channel_caller(chan)->id.number.str) {
11796 ast_copy_string(mailbox, ast_channel_caller(chan)->id.number.str, mailbox_size);
11797 } else {
11798 ast_verb(3, "Username not entered\n");
11799 return -1;
11800 }
11801 } else if (mailbox[0] == '*') {
11802 /* user entered '*' */
11803 ast_verb(4, "Mailbox begins with '*', attempting jump to extension 'a'\n");
11804 if (ast_exists_extension(chan, ast_channel_context(chan), "a", 1,
11805 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
11806 return -1;
11807 }
11808 ast_verb(4, "Jump to extension 'a' failed; setting mailbox to NULL\n");
11809 mailbox[0] = '\0';
11810 }
11811
11812 if (useadsi)
11813 adsi_password(chan);
11814
11815 if (!ast_strlen_zero(prefix)) {
11816 char fullusername[80];
11817
11818 ast_copy_string(fullusername, prefix, sizeof(fullusername));
11819 strncat(fullusername, mailbox, sizeof(fullusername) - 1 - strlen(fullusername));
11820 ast_copy_string(mailbox, fullusername, mailbox_size);
11821 }
11822
11823 ast_debug(1, "Before find user for mailbox %s\n", mailbox);
11824 memset(&vmus, 0, sizeof(vmus));
11825 vmu = find_user(&vmus, context, mailbox);
11826 if (vmu && (vmu->password[0] == '\0' || (vmu->password[0] == '-' && vmu->password[1] == '\0'))) {
11827 /* saved password is blank, so don't bother asking */
11828 password[0] = '\0';
11829 } else {
11830 if (ast_streamfile(chan, vm_password, ast_channel_language(chan))) {
11831 if (!ast_check_hangup(chan)) {
11832 ast_log(AST_LOG_WARNING, "Unable to stream password file\n");
11833 }
11834 free_user(vmu);
11835 return -1;
11836 }
11837 if (ast_readstring(chan, password, sizeof(password) - 1, 2000, 10000, "#") < 0) {
11838 ast_log(AST_LOG_NOTICE, "Unable to read password\n");
11839 free_user(vmu);
11840 return -1;
11841 } else if (password[0] == '*') {
11842 /* user entered '*' */
11843 ast_verb(4, "Password begins with '*', attempting jump to extension 'a'\n");
11844 if (ast_exists_extension(chan, ast_channel_context(chan), "a", 1,
11845 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
11846 mailbox[0] = '*';
11847 free_user(vmu);
11848 return -1;
11849 }
11850 ast_verb(4, "Jump to extension 'a' failed; setting mailbox and user to NULL\n");
11851 mailbox[0] = '\0';
11852 /* if the password entered was '*', do not let a user mailbox be created if the extension 'a' is not defined */
11853 free_user(vmu);
11854 vmu = NULL;
11855 }
11856 }
11857
11858 if (vmu) {
11859 passptr = vmu->password;
11860 if (passptr[0] == '-') passptr++;
11861 }
11862 if (vmu && !strcmp(passptr, password))
11863 valid++;
11864 else {
11865 ast_verb(3, "Incorrect password '%s' for user '%s' (context = %s)\n", password, mailbox, context ? context : "default");
11866 if (!ast_strlen_zero(prefix))
11867 mailbox[0] = '\0';
11868 }
11869 logretries++;
11870 if (!valid) {
11871 if (skipuser || logretries >= max_logins) {
11872 if (ast_streamfile(chan, "vm-incorrect", ast_channel_language(chan))) {
11873 ast_log(AST_LOG_WARNING, "Unable to stream incorrect message\n");
11874 free_user(vmu);
11875 return -1;
11876 }
11877 if (ast_waitstream(chan, "")) { /* Channel is hung up */
11878 free_user(vmu);
11879 return -1;
11880 }
11881 } else {
11882 if (useadsi)
11883 adsi_login(chan);
11884 if (ast_streamfile(chan, "vm-incorrect-mailbox", ast_channel_language(chan))) {
11885 ast_log(AST_LOG_WARNING, "Unable to stream incorrect mailbox message\n");
11886 free_user(vmu);
11887 return -1;
11888 }
11889 }
11890 }
11891 }
11892 if (!valid && (logretries >= max_logins)) {
11893 ast_stopstream(chan);
11894 ast_play_and_wait(chan, "vm-goodbye");
11895 free_user(vmu);
11896 return -1;
11897 }
11898 if (vmu && !skipuser) {
11899 *res_vmu = *vmu;
11900 }
11901 return 0;
11902 }
11903
11904 static int play_message_by_id_helper(struct ast_channel *chan,
11905 struct ast_vm_user *vmu,
11906 struct vm_state *vms,
11907 const char *msg_id)
11908 {
11909 if (message_range_and_existence_check(vms, &msg_id, 1, &vms->curmsg, vmu)) {
11910 return -1;
11911 }
11912 /* Found the msg, so play it back */
11913
11914 make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
11915
11916 #ifdef IMAP_STORAGE
11917 /*IMAP storage stores any prepended message from a forward
11918 * as a separate file from the rest of the message
11919 */
11920 if (!ast_strlen_zero(vms->introfn) && ast_fileexists(vms->introfn, NULL, NULL) > 0) {
11921 wait_file(chan, vms, vms->introfn);
11922 }
11923 #endif
11924 RETRIEVE(vms->curdir,vms->curmsg,vmu->mailbox, vmu->context);
11925
11926 if ((wait_file(chan, vms, vms->fn)) < 0) {
11927 ast_log(AST_LOG_WARNING, "Playback of message %s failed\n", vms->fn);
11928 } else {
11929 #ifdef IMAP_STORAGE
11930 ast_mutex_lock(&vms->lock);
11931 #endif
11932 vms->heard[vms->curmsg] = 1;
11933 #ifdef IMAP_STORAGE
11934 ast_mutex_unlock(&vms->lock);
11935 #endif
11936 }
11937 DISPOSE(vms->curdir, vms->curmsg);
11938 return 0;
11939 }
11940
11941 /*!
11942 * \brief Finds a message in a specific mailbox by msg_id and plays it to the channel
11943 *
11944 * \retval 0 Success
11945 * \retval -1 Failure
11946 */
11947 static int play_message_by_id(struct ast_channel *chan, const char *mailbox, const char *context, const char *msg_id)
11948 {
11949 struct vm_state vms;
11950 struct ast_vm_user *vmu = NULL, vmus;
11951 int res = 0;
11952 int open = 0;
11953 int played = 0;
11954 int i;
11955
11956 memset(&vmus, 0, sizeof(vmus));
11957 memset(&vms, 0, sizeof(vms));
11958
11959 if (!(vmu = find_user(&vmus, context, mailbox))) {
11960 goto play_msg_cleanup;
11961 }
11962
11963 /* Iterate through every folder, find the msg, and play it */
11964 for (i = 0; i < ARRAY_LEN(mailbox_folders) && !played; i++) {
11965 ast_copy_string(vms.username, mailbox, sizeof(vms.username));
11966 vms.lastmsg = -1;
11967
11968 /* open the mailbox state */
11969 if ((res = open_mailbox(&vms, vmu, i)) < 0) {
11970 ast_log(LOG_WARNING, "Could not open mailbox %s\n", mailbox);
11971 res = -1;
11972 goto play_msg_cleanup;
11973 }
11974 open = 1;
11975
11976 /* play msg if it exists in this mailbox */
11977 if ((vms.lastmsg != -1) && !(play_message_by_id_helper(chan, vmu, &vms, msg_id))) {
11978 played = 1;
11979 }
11980
11981 /* close mailbox */
11982 if ((res = close_mailbox(&vms, vmu) == ERROR_LOCK_PATH)) {
11983 res = -1;
11984 goto play_msg_cleanup;
11985 }
11986 open = 0;
11987 }
11988
11989 play_msg_cleanup:
11990 if (!played) {
11991 res = -1;
11992 }
11993
11994 if (vmu && open) {
11995 close_mailbox(&vms, vmu);
11996 }
11997
11998 #ifdef IMAP_STORAGE
11999 if (vmu) {
12000 vmstate_delete(&vms);
12001 }
12002 #endif
12003
12004 free_user(vmu);
12005
12006 return res;
12007 }
12008
12009 static int vm_playmsgexec(struct ast_channel *chan, const char *data)
12010 {
12011 char *parse;
12012 char *mailbox = NULL;
12013 char *context = NULL;
12014 int res;
12015
12016 AST_DECLARE_APP_ARGS(args,
12017 AST_APP_ARG(mailbox);
12018 AST_APP_ARG(msg_id);
12019 );
12020
12021 if (ast_channel_state(chan) != AST_STATE_UP) {
12022 ast_debug(1, "Before ast_answer\n");
12023 ast_answer(chan);
12024 }
12025
12026 if (ast_strlen_zero(data)) {
12027 return -1;
12028 }
12029
12030 parse = ast_strdupa(data);
12031 AST_STANDARD_APP_ARGS(args, parse);
12032
12033 if (ast_strlen_zero(args.mailbox) || ast_strlen_zero(args.msg_id)) {
12034 return -1;
12035 }
12036
12037 if ((context = strchr(args.mailbox, '@'))) {
12038 *context++ = '\0';
12039 }
12040 mailbox = args.mailbox;
12041
12042 res = play_message_by_id(chan, mailbox, context, args.msg_id);
12043 pbx_builtin_setvar_helper(chan, "VOICEMAIL_PLAYBACKSTATUS", res ? "FAILED" : "SUCCESS");
12044
12045 return 0;
12046 }
12047
12048 static int show_mailbox_details(struct ast_cli_args *a)
12049 {
12050 #define VMBOX_STRING_HEADER_FORMAT "%-32.32s %-32.32s %-16.16s %-16.16s %-16.16s %-16.16s\n"
12051 #define VMBOX_STRING_DATA_FORMAT "%-32.32s %-32.32s %-16.16s %-16.16s %-16.16s %-16.16s\n"
12052
12053 const char *mailbox = a->argv[3];
12054 const char *context = a->argv[4];
12055 struct vm_state vms;
12056 struct ast_vm_user *vmu = NULL, vmus;
12057 memset(&vmus, 0, sizeof(vmus));
12058 memset(&vms, 0, sizeof(vms));
12059
12060 if (!(vmu = find_user(&vmus, context, mailbox))) {
12061 ast_cli(a->fd, "Can't find voicemail user %s@%s\n", mailbox, context);
12062 return -1;
12063 }
12064
12065 ast_cli(a->fd, VMBOX_STRING_HEADER_FORMAT, "Full Name", "Email", "Pager", "Language", "Locale", "Time Zone");
12066 ast_cli(a->fd, VMBOX_STRING_DATA_FORMAT, vmu->fullname, vmu->email, vmu->pager, vmu->language, vmu->locale, vmu->zonetag);
12067
12068 return 0;
12069 }
12070
12071 static int show_mailbox_snapshot(struct ast_cli_args *a)
12072 {
12073 #define VM_STRING_HEADER_FORMAT "%-8.8s %-32.32s %-32.32s %-9.9s %-6.6s %-30.30s\n"
12074 const char *mailbox = a->argv[3];
12075 const char *context = a->argv[4];
12076 struct ast_vm_mailbox_snapshot *mailbox_snapshot;
12077 struct ast_vm_msg_snapshot *msg;
12078 int i;
12079
12080 /* Take a snapshot of the mailbox and walk through each folder's contents */
12081 mailbox_snapshot = ast_vm_mailbox_snapshot_create(mailbox, context, NULL, 0, AST_VM_SNAPSHOT_SORT_BY_ID, 0);
12082 if (!mailbox_snapshot) {
12083 ast_cli(a->fd, "Can't create snapshot for voicemail user %s@%s\n", mailbox, context);
12084 return -1;
12085 }
12086
12087 ast_cli(a->fd, VM_STRING_HEADER_FORMAT, "Folder", "Caller ID", "Date", "Duration", "Flag", "ID");
12088
12089 for (i = 0; i < mailbox_snapshot->folders; i++) {
12090 AST_LIST_TRAVERSE(&((mailbox_snapshot)->snapshots[i]), msg, msg) {
12091 ast_cli(a->fd, VM_STRING_HEADER_FORMAT, msg->folder_name, msg->callerid, msg->origdate, msg->duration,
12092 msg->flag, msg->msg_id);
12093 }
12094 }
12095
12096 ast_cli(a->fd, "%d Message%s Total\n", mailbox_snapshot->total_msg_num, ESS(mailbox_snapshot->total_msg_num));
12097 /* done, destroy. */
12098 mailbox_snapshot = ast_vm_mailbox_snapshot_destroy(mailbox_snapshot);
12099
12100 return 0;
12101 }
12102
12103 static int show_messages_for_mailbox(struct ast_cli_args *a)
12104 {
12105 if (show_mailbox_details(a)){
12106 return -1;
12107 }
12108 ast_cli(a->fd, "\n");
12109 return show_mailbox_snapshot(a);
12110 }
12111
12112 static int forward_message_from_mailbox(struct ast_cli_args *a)
12113 {
12114 const char *from_mailbox = a->argv[2];
12115 const char *from_context = a->argv[3];
12116 const char *from_folder = a->argv[4];
12117 const char *id[] = { a->argv[5] };
12118 const char *to_mailbox = a->argv[6];
12119 const char *to_context = a->argv[7];
12120 const char *to_folder = a->argv[8];
12121 int ret = vm_msg_forward(from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder, 1, id, 0);
12122 if (ret) {
12123 ast_cli(a->fd, "Error forwarding message %s from mailbox %s@%s %s to mailbox %s@%s %s\n",
12124 id[0], from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder);
12125 } else {
12126 ast_cli(a->fd, "Forwarded message %s from mailbox %s@%s %s to mailbox %s@%s %s\n",
12127 id[0], from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder);
12128 }
12129 return ret;
12130 }
12131
12132 static int move_message_from_mailbox(struct ast_cli_args *a)
12133 {
12134 const char *mailbox = a->argv[2];
12135 const char *context = a->argv[3];
12136 const char *from_folder = a->argv[4];
12137 const char *id[] = { a->argv[5] };
12138 const char *to_folder = a->argv[6];
12139 int ret = vm_msg_move(mailbox, context, 1, from_folder, id, to_folder);
12140 if (ret) {
12141 ast_cli(a->fd, "Error moving message %s from mailbox %s@%s %s to %s\n",
12142 id[0], mailbox, context, from_folder, to_folder);
12143 } else {
12144 ast_cli(a->fd, "Moved message %s from mailbox %s@%s %s to %s\n",
12145 id[0], mailbox, context, from_folder, to_folder);
12146 }
12147 return ret;
12148 }
12149
12150 static int remove_message_from_mailbox(struct ast_cli_args *a)
12151 {
12152 const char *mailbox = a->argv[2];
12153 const char *context = a->argv[3];
12154 const char *folder = a->argv[4];
12155 const char *id[] = { a->argv[5] };
12156 int ret = vm_msg_remove(mailbox, context, 1, folder, id);
12157 if (ret) {
12158 ast_cli(a->fd, "Error removing message %s from mailbox %s@%s %s\n",
12159 id[0], mailbox, context, folder);
12160 } else {
12161 ast_cli(a->fd, "Removed message %s from mailbox %s@%s %s\n",
12162 id[0], mailbox, context, folder);
12163 }
12164 return ret;
12165 }
12166
12167 static char *complete_voicemail_show_mailbox(struct ast_cli_args *a)
12168 {
12169 const char *word = a->word;
12170 int pos = a->pos;
12171 int state = a->n;
12172 int which = 0;
12173 int wordlen;
12174 struct ast_vm_user *vmu;
12175 const char *context = "", *mailbox = "";
12176 char *ret = NULL;
12177
12178 /* 0 - voicemail; 1 - show; 2 - mailbox; 3 - <mailbox>; 4 - <context> */
12179 if (pos == 3) {
12180 wordlen = strlen(word);
12181 AST_LIST_LOCK(&users);
12182 AST_LIST_TRAVERSE(&users, vmu, list) {
12183 if (!strncasecmp(word, vmu->mailbox , wordlen)) {
12184 if (mailbox && strcmp(mailbox, vmu->mailbox) && ++which > state) {
12185 ret = ast_strdup(vmu->mailbox);
12186 AST_LIST_UNLOCK(&users);
12187 return ret;
12188 }
12189 mailbox = vmu->mailbox;
12190 }
12191 }
12192 AST_LIST_UNLOCK(&users);
12193 } else if (pos == 4) {
12194 /* Only display contexts that match the user in pos 3 */
12195 const char *box = a->argv[3];
12196 wordlen = strlen(word);
12197 AST_LIST_LOCK(&users);
12198 AST_LIST_TRAVERSE(&users, vmu, list) {
12199 if (!strncasecmp(word, vmu->context, wordlen) && !strcasecmp(box, vmu->mailbox)) {
12200 if (context && strcmp(context, vmu->context) && ++which > state) {
12201 ret = ast_strdup(vmu->context);
12202 AST_LIST_UNLOCK(&users);
12203 return ret;
12204 }
12205 context = vmu->context;
12206 }
12207 }
12208 AST_LIST_UNLOCK(&users);
12209 }
12210
12211 return ret;
12212 }
12213
12214 static char *handle_voicemail_show_mailbox(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12215 {
12216 switch (cmd) {
12217 case CLI_INIT:
12218 e->command = "voicemail show mailbox";
12219 e->usage =
12220 "Usage: voicemail show mailbox <mailbox> <context>\n"
12221 " Show contents of mailbox <mailbox>@<context>\n";
12222 return NULL;
12223 case CLI_GENERATE:
12224 return complete_voicemail_show_mailbox(a);
12225 case CLI_HANDLER:
12226 break;
12227 }
12228
12229 if (a->argc != 5) {
12230 return CLI_SHOWUSAGE;
12231 }
12232
12233 if (show_messages_for_mailbox(a)) {
12234 return CLI_FAILURE;
12235 }
12236
12237 return CLI_SUCCESS;
12238 }
12239
12240 /* Handles filling in data for one of the following three formats (based on maxpos = 5|6|8):
12241
12242 maxpos = 5
12243 0 - voicemail; 1 - forward; 2 - <from_mailbox>; 3 - <from_context>; 4 - <from_folder>; 5 - <messageid>;
12244 maxpos = 6
12245 0 - voicemail; 1 - forward; 2 - <from_mailbox>; 3 - <from_context>; 4 - <from_folder>; 5 - <messageid>;
12246 6 - <to_folder>;
12247 maxpos = 8
12248 0 - voicemail; 1 - forward; 2 - <from_mailbox>; 3 - <from_context>; 4 - <from_folder>; 5 - <messageid>;
12249 6 - <to_mailbox>; 7 - <to_context>; 8 - <to_folder>;
12250
12251 Passing in the maximum expected position 'maxpos' helps us fill in the missing entries in one function
12252 instead of three by taking advantage of the overlap in the command sequence between forward, move and
12253 remove as each of these use nearly the same syntax up until their maximum number of arguments.
12254 The value of pos = 6 changes to be either <messageid> or <folder> based on maxpos being 6 or 8.
12255 */
12256
12257 static char *complete_voicemail_move_message(struct ast_cli_args *a, int maxpos)
12258 {
12259 const char *word = a->word;
12260 int pos = a->pos;
12261 int state = a->n;
12262 int which = 0;
12263 int wordlen;
12264 struct ast_vm_user *vmu;
12265 const char *context = "", *mailbox = "", *folder = "", *id = "";
12266 char *ret = NULL;
12267
12268 if (pos > maxpos) {
12269 /* If the passed in pos is above the max, return NULL to avoid 'over-filling' the cli */
12270 return NULL;
12271 }
12272
12273 /* if we are in pos 2 or pos 6 in 'forward' mode */
12274 if (pos == 2 || (pos == 6 && maxpos == 8)) {
12275 /* find users */
12276 wordlen = strlen(word);
12277 AST_LIST_LOCK(&users);
12278 AST_LIST_TRAVERSE(&users, vmu, list) {
12279 if (!strncasecmp(word, vmu->mailbox , wordlen)) {
12280 if (mailbox && strcmp(mailbox, vmu->mailbox) && ++which > state) {
12281 ret = ast_strdup(vmu->mailbox);
12282 AST_LIST_UNLOCK(&users);
12283 return ret;
12284 }
12285 mailbox = vmu->mailbox;
12286 }
12287 }
12288 AST_LIST_UNLOCK(&users);
12289 } else if (pos == 3 || pos == 7) {
12290 /* find contexts that match the user */
12291 mailbox = (pos == 3) ? a->argv[2] : a->argv[6];
12292 wordlen = strlen(word);
12293 AST_LIST_LOCK(&users);
12294 AST_LIST_TRAVERSE(&users, vmu, list) {
12295 if (!strncasecmp(word, vmu->context, wordlen) && !strcasecmp(mailbox, vmu->mailbox)) {
12296 if (context && strcmp(context, vmu->context) && ++which > state) {
12297 ret = ast_strdup(vmu->context);
12298 AST_LIST_UNLOCK(&users);
12299 return ret;
12300 }
12301 context = vmu->context;
12302 }
12303 }
12304 AST_LIST_UNLOCK(&users);
12305 } else if (pos == 4 || pos == 8 || (pos == 6 && maxpos == 6) ) {
12306 int i;
12307 /* Walk through the standard folders */
12308 wordlen = strlen(word);
12309 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
12310 if (folder && !strncasecmp(word, mailbox_folders[i], wordlen) && ++which > state) {
12311 return ast_strdup(mailbox_folders[i]);
12312 }
12313 folder = mailbox_folders[i];
12314 }
12315 } else if (pos == 5) {
12316 /* find messages in the folder */
12317 struct ast_vm_mailbox_snapshot *mailbox_snapshot;
12318 struct ast_vm_msg_snapshot *msg;
12319 mailbox = a->argv[2];
12320 context = a->argv[3];
12321 folder = a->argv[4];
12322 wordlen = strlen(word);
12323
12324 /* Take a snapshot of the mailbox and snag the individual info */
12325 if ((mailbox_snapshot = ast_vm_mailbox_snapshot_create(mailbox, context, folder, 0, AST_VM_SNAPSHOT_SORT_BY_ID, 0))) {
12326 int i;
12327 /* we are only requesting the one folder, but we still need to know it's index */
12328 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
12329 if (!strcasecmp(mailbox_folders[i], folder)) {
12330 break;
12331 }
12332 }
12333 AST_LIST_TRAVERSE(&((mailbox_snapshot)->snapshots[i]), msg, msg) {
12334 if (id && !strncasecmp(word, msg->msg_id, wordlen) && ++which > state) {
12335 ret = ast_strdup(msg->msg_id);
12336 break;
12337 }
12338 id = msg->msg_id;
12339 }
12340 /* done, destroy. */
12341 mailbox_snapshot = ast_vm_mailbox_snapshot_destroy(mailbox_snapshot);
12342 }
12343 }
12344
12345 return ret;
12346 }
12347
12348 static char *handle_voicemail_forward_message(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12349 {
12350 switch (cmd) {
12351 case CLI_INIT:
12352 e->command = "voicemail forward";
12353 e->usage =
12354 "Usage: voicemail forward <from_mailbox> <from_context> <from_folder> <messageid> <to_mailbox> <to_context> <to_folder>\n"
12355 " Forward message <messageid> in mailbox <mailbox>@<context> <from_folder>\n"
12356 " to mailbox <mailbox>@<context> <to_folder>\n";
12357 return NULL;
12358 case CLI_GENERATE:
12359 return complete_voicemail_move_message(a, 8);
12360 case CLI_HANDLER:
12361 break;
12362 }
12363
12364 if (a->argc != 9) {
12365 return CLI_SHOWUSAGE;
12366 }
12367
12368 if (forward_message_from_mailbox(a)) {
12369 return CLI_FAILURE;
12370 }
12371
12372 return CLI_SUCCESS;
12373 }
12374
12375 static char *handle_voicemail_move_message(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12376 {
12377 switch (cmd) {
12378 case CLI_INIT:
12379 e->command = "voicemail move";
12380 e->usage =
12381 "Usage: voicemail move <mailbox> <context> <from_folder> <messageid> <to_folder>\n"
12382 " Move message <messageid> in mailbox <mailbox>&<context> from <from_folder> to <to_folder>\n";
12383 return NULL;
12384 case CLI_GENERATE:
12385 return complete_voicemail_move_message(a, 6);
12386 case CLI_HANDLER:
12387 break;
12388 }
12389
12390 if (a->argc != 7) {
12391 return CLI_SHOWUSAGE;
12392 }
12393
12394 if (move_message_from_mailbox(a)) {
12395 return CLI_FAILURE;
12396 }
12397
12398 return CLI_SUCCESS;
12399 }
12400
12401 static char *handle_voicemail_remove_message(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12402 {
12403 switch (cmd) {
12404 case CLI_INIT:
12405 e->command = "voicemail remove";
12406 e->usage =
12407 "Usage: voicemail remove <mailbox> <context> <from_folder> <messageid>\n"
12408 " Remove message <messageid> from <from_folder> in mailbox <mailbox>@<context>\n";
12409 return NULL;
12410 case CLI_GENERATE:
12411 return complete_voicemail_move_message(a, 5);
12412 case CLI_HANDLER:
12413 break;
12414 }
12415
12416 if (a->argc != 6) {
12417 return CLI_SHOWUSAGE;
12418 }
12419
12420 if (remove_message_from_mailbox(a)) {
12421 return CLI_FAILURE;
12422 }
12423
12424 return CLI_SUCCESS;
12425 }
12426
12427 static int vm_execmain(struct ast_channel *chan, const char *data)
12428 {
12429 /* XXX This is, admittedly, some pretty horrendous code. For some
12430 reason it just seemed a lot easier to do with GOTO's. I feel
12431 like I'm back in my GWBASIC days. XXX */
12432 int res = -1;
12433 int cmd = 0;
12434 int valid = 0;
12435 char prefixstr[80] ="";
12436 char ext_context[256]="";
12437 int box;
12438 int useadsi = 0;
12439 int skipuser = 0;
12440 struct vm_state vms = {{0}};
12441 struct ast_vm_user *vmu = NULL, vmus = {{0}};
12442 char *context = NULL;
12443 int silentexit = 0;
12444 struct ast_flags flags = { 0 };
12445 signed char record_gain = 0;
12446 int play_auto = 0;
12447 int play_folder = 0;
12448 int in_urgent = 0;
12449 int nodelete = 0;
12450 #ifdef IMAP_STORAGE
12451 int deleted = 0;
12452 #endif
12453 SCOPE_ENTER(3, "%s:\n", ast_channel_name(chan));
12454
12455 /* Add the vm_state to the active list and keep it active */
12456 vms.lastmsg = -1;
12457
12458 ast_test_suite_event_notify("START", "Message: vm_execmain started");
12459 if (ast_channel_state(chan) != AST_STATE_UP) {
12460 ast_debug(1, "Before ast_answer\n");
12461 ast_answer(chan);
12462 }
12463
12464 if (!ast_strlen_zero(data)) {
12465 char *opts[OPT_ARG_ARRAY_SIZE];
12466 char *parse;
12467 AST_DECLARE_APP_ARGS(args,
12468 AST_APP_ARG(argv0);
12469 AST_APP_ARG(argv1);
12470 );
12471
12472 parse = ast_strdupa(data);
12473
12474 AST_STANDARD_APP_ARGS(args, parse);
12475
12476 if (args.argc == 2) {
12477 if (ast_app_parse_options(vm_app_options, &flags, opts, args.argv1)) {
12478 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Invalid option string '%s'\n", args.argv1);
12479 }
12480 if (ast_test_flag(&flags, OPT_RECORDGAIN)) {
12481 int gain;
12482 if (!ast_strlen_zero(opts[OPT_ARG_RECORDGAIN])) {
12483 if (sscanf(opts[OPT_ARG_RECORDGAIN], "%30d", &gain) != 1) {
12484 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Invalid value '%s' provided for record gain option\n", opts[OPT_ARG_RECORDGAIN]);
12485 } else {
12486 record_gain = (signed char) gain;
12487 }
12488 } else {
12489 ast_log(AST_LOG_WARNING, "Invalid Gain level set with option g\n");
12490 }
12491 }
12492 if (ast_test_flag(&flags, OPT_AUTOPLAY) ) {
12493 play_auto = 1;
12494 if (!ast_strlen_zero(opts[OPT_ARG_PLAYFOLDER])) {
12495 /* See if it is a folder name first */
12496 if (isdigit(opts[OPT_ARG_PLAYFOLDER][0])) {
12497 if (sscanf(opts[OPT_ARG_PLAYFOLDER], "%30d", &play_folder) != 1) {
12498 play_folder = -1;
12499 }
12500 } else {
12501 play_folder = get_folder_by_name(opts[OPT_ARG_PLAYFOLDER]);
12502 }
12503 } else {
12504 ast_log(AST_LOG_WARNING, "Invalid folder set with option a\n");
12505 }
12506 if (play_folder > 9 || play_folder < 0) {
12507 ast_log(AST_LOG_WARNING,
12508 "Invalid value '%s' provided for folder autoplay option. Defaulting to 'INBOX'\n",
12509 opts[OPT_ARG_PLAYFOLDER]);
12510 play_folder = 0;
12511 }
12512 }
12513 if (ast_test_flag(&flags, OPT_READONLY)) {
12514 nodelete = 1;
12515 }
12516 } else {
12517 /* old style options parsing */
12518 while (*(args.argv0)) {
12519 if (*(args.argv0) == 's')
12520 ast_set_flag(&flags, OPT_SILENT);
12521 else if (*(args.argv0) == 'p')
12522 ast_set_flag(&flags, OPT_PREPEND_MAILBOX);
12523 else
12524 break;
12525 (args.argv0)++;
12526 }
12527
12528 }
12529
12530 valid = ast_test_flag(&flags, OPT_SILENT);
12531
12532 if ((context = strchr(args.argv0, '@')))
12533 *context++ = '\0';
12534
12535 if (ast_test_flag(&flags, OPT_PREPEND_MAILBOX))
12536 ast_copy_string(prefixstr, args.argv0, sizeof(prefixstr));
12537 else
12538 ast_copy_string(vms.username, args.argv0, sizeof(vms.username));
12539
12540 if (!ast_strlen_zero(vms.username)) {
12541 if ((vmu = find_user(&vmus, context ,vms.username))) {
12542 skipuser++;
12543 } else {
12544 ast_log(LOG_WARNING, "Mailbox '%s%s%s' doesn't exist\n", vms.username, context ? "@": "", context ? context : "");
12545 valid = 0;
12546 }
12547 } else {
12548 valid = 0;
12549 }
12550 }
12551
12552 if (!valid)
12553 res = vm_authenticate(chan, vms.username, sizeof(vms.username), &vmus, context, prefixstr, skipuser, maxlogins, 0);
12554
12555 ast_trace(-1, "vm_authenticate user: %s\n", vms.username);
12556
12557 if (vms.username[0] == '*') {
12558 ast_trace(-1, "user pressed * in context '%s'\n", ast_channel_context(chan));
12559
12560 /* user entered '*' */
12561 if (!ast_goto_if_exists(chan, ast_channel_context(chan), "a", 1)) {
12562 ast_test_suite_event_notify("REDIRECT", "Message: redirecting user to 'a' extension");
12563 res = 0; /* prevent hangup */
12564 goto out;
12565 }
12566 }
12567
12568 if (!res) {
12569 valid = 1;
12570 if (!skipuser)
12571 vmu = &vmus;
12572 } else {
12573 res = 0;
12574 }
12575
12576 /* If ADSI is supported, setup login screen */
12577 adsi_begin(chan, &useadsi);
12578
12579 if (!valid) {
12580 ast_trace(-1, "Invalid user\n");
12581 goto out;
12582 }
12583 ast_test_suite_event_notify("AUTHENTICATED", "Message: vm_user authenticated");
12584
12585 #ifdef IMAP_STORAGE
12586 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
12587 pthread_setspecific(ts_vmstate.key, &vms);
12588
12589 vms.interactive = 1;
12590 vms.updated = 1;
12591 if (vmu)
12592 ast_copy_string(vms.context, vmu->context, sizeof(vms.context));
12593 vmstate_insert(&vms);
12594 init_vm_state(&vms);
12595 #endif
12596
12597 /* Set language from config to override channel language */
12598 if (!ast_strlen_zero(vmu->language)) {
12599 ast_channel_lock(chan);
12600 ast_channel_language_set(chan, vmu->language);
12601 ast_channel_unlock(chan);
12602 }
12603
12604 /* Retrieve urgent, old and new message counts */
12605 ast_trace(-1, "Before open_mailbox\n");
12606 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, OLD_FOLDER); /* Count all messages, even Urgent */
12607 if (res < 0) {
12608 ast_trace(-1, "open mailbox: %d\n", res);
12609 goto out;
12610 }
12611 vms.oldmessages = vms.lastmsg + 1;
12612 ast_trace(-1, "Number of old messages: %d\n", vms.oldmessages);
12613 /* check INBOX */
12614 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, NEW_FOLDER);
12615 if (res < 0) {
12616 ast_trace(-1, "open mailbox: %d\n", res);
12617 goto out;
12618 }
12619 vms.newmessages = vms.lastmsg + 1;
12620 ast_trace(-1, "Number of new messages: %d\n", vms.newmessages);
12621 /* Start in Urgent */
12622 in_urgent = 1;
12623 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, 11); /*11 is the Urgent folder */
12624 if (res < 0) {
12625 ast_trace(-1, "open mailbox: %d\n", res);
12626 goto out;
12627 }
12628 vms.urgentmessages = vms.lastmsg + 1;
12629 ast_trace(-1, "Number of urgent messages: %d\n", vms.urgentmessages);
12630
12631 /* Select proper mailbox FIRST!! */
12632 if (play_auto) {
12633 ast_test_suite_event_notify("AUTOPLAY", "Message: auto-playing messages");
12634 if (vms.urgentmessages) {
12635 in_urgent = 1;
12636 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, 11);
12637 } else {
12638 in_urgent = 0;
12639 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, play_folder);
12640 }
12641 if (res < 0) {
12642 ast_trace(-1, "open mailbox: %d\n", res);
12643 goto out;
12644 }
12645
12646 /* If there are no new messages, inform the user and hangup */
12647 if (vms.lastmsg == -1) {
12648 in_urgent = 0;
12649 cmd = vm_browse_messages(chan, &vms, vmu);
12650 res = 0;
12651 goto out;
12652 }
12653 } else {
12654 if (!vms.newmessages && !vms.urgentmessages && vms.oldmessages) {
12655 /* If we only have old messages start here */
12656 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, OLD_FOLDER); /* Count all messages, even Urgent */
12657 in_urgent = 0;
12658 play_folder = 1;
12659 if (res < 0)
12660 goto out;
12661 } else if (!vms.urgentmessages && vms.newmessages) {
12662 /* If we have new messages but none are urgent */
12663 in_urgent = 0;
12664 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, NEW_FOLDER);
12665 if (res < 0)
12666 goto out;
12667 }
12668 }
12669
12670 if (useadsi)
12671 adsi_status(chan, &vms);
12672 res = 0;
12673
12674 /* Check to see if this is a new user */
12675 if (!strcasecmp(vmu->mailbox, vmu->password) &&
12676 (ast_test_flag(vmu, VM_FORCENAME | VM_FORCEGREET))) {
12677 if (ast_play_and_wait(chan, vm_newuser) == -1)
12678 ast_log(AST_LOG_WARNING, "Couldn't stream new user file\n");
12679 cmd = vm_newuser_setup(chan, vmu, &vms, vmfmts, record_gain);
12680 if ((cmd == 't') || (cmd == '#')) {
12681 /* Timeout */
12682 ast_test_suite_event_notify("TIMEOUT", "Message: response from user timed out");
12683 res = 0;
12684 ast_trace(-1, "Timeout\n");
12685 goto out;
12686 } else if (cmd < 0) {
12687 /* Hangup */
12688 ast_test_suite_event_notify("HANGUP", "Message: hangup detected");
12689 res = -1;
12690 ast_trace(-1, "Hangup\n");
12691 goto out;
12692 }
12693 }
12694 #ifdef IMAP_STORAGE
12695 ast_debug(3, "Checking quotas: comparing %u to %u\n", vms.quota_usage, vms.quota_limit);
12696 if (vms.quota_limit && vms.quota_usage >= vms.quota_limit) {
12697 ast_debug(1, "*** QUOTA EXCEEDED!!\n");
12698 cmd = ast_play_and_wait(chan, "vm-mailboxfull");
12699 }
12700 ast_debug(3, "Checking quotas: User has %d messages and limit is %d.\n", (vms.newmessages + vms.oldmessages), vmu->maxmsg);
12701 if ((vms.newmessages + vms.oldmessages) >= vmu->maxmsg) {
12702 ast_log(AST_LOG_WARNING, "No more messages possible. User has %d messages and limit is %d.\n", (vms.newmessages + vms.oldmessages), vmu->maxmsg);
12703 cmd = ast_play_and_wait(chan, "vm-mailboxfull");
12704 }
12705 #endif
12706
12707 ast_test_suite_event_notify("INTRO", "Message: playing intro menu");
12708 if (play_auto) {
12709 cmd = '1';
12710 } else {
12711 cmd = vm_intro(chan, vmu, &vms);
12712 }
12713 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
12714 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
12715
12716 vms.repeats = 0;
12717 vms.starting = 1;
12718 while ((cmd > -1) && (cmd != 't') && (cmd != '#')) {
12719 /* Run main menu */
12720 ast_trace(-1, "Main menu: %d %c\n", cmd, (cmd >= 32 && cmd <= 126 ? cmd : ' '));
12721 switch (cmd) {
12722 case '1': /* First message */
12723 vms.curmsg = 0;
12724 /* Fall through */
12725 case '5': /* Play current message */
12726 ast_test_suite_event_notify("BROWSE", "Message: browsing message %d\r\nVoicemail: %d", vms.curmsg, vms.curmsg);
12727 cmd = vm_browse_messages(chan, &vms, vmu);
12728 break;
12729 case '2': /* Change folders */
12730 ast_test_suite_event_notify("CHANGEFOLDER", "Message: browsing to a different folder");
12731 if (useadsi)
12732 adsi_folders(chan, 0, "Change to folder...");
12733
12734 cmd = get_folder2(chan, "vm-changeto", 0);
12735 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
12736 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
12737 if (cmd == '#') {
12738 cmd = 0;
12739 } else if (cmd > 0) {
12740 cmd = cmd - '0';
12741 res = SCOPE_CALL_WITH_INT_RESULT(-1, close_mailbox, &vms, vmu);
12742 if (res == ERROR_LOCK_PATH) {
12743 ast_trace(-1, "close mailbox: %d\n", res);
12744 goto out;
12745 }
12746 /* If folder is not urgent, set in_urgent to zero! */
12747 if (cmd != 11) in_urgent = 0;
12748 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, cmd);
12749 if (res < 0) {
12750 ast_trace(-1, "open mailbox: %d\n", res);
12751 goto out;
12752 }
12753 play_folder = cmd;
12754 cmd = 0;
12755 }
12756 if (useadsi)
12757 adsi_status2(chan, &vms);
12758
12759 if (!cmd) {
12760 cmd = vm_play_folder_name(chan, vms.vmbox);
12761 }
12762
12763 vms.starting = 1;
12764 vms.curmsg = 0;
12765 break;
12766 case '3': /* Advanced options */
12767 ast_test_suite_event_notify("ADVOPTIONS", "Message: entering advanced options menu");
12768 cmd = 0;
12769 vms.repeats = 0;
12770 while ((cmd > -1) && (cmd != 't') && (cmd != '#')) {
12771 switch (cmd) {
12772 case '1': /* Reply */
12773 if (vms.lastmsg > -1 && !vms.starting) {
12774 cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 1, record_gain);
12775 if (cmd == ERROR_LOCK_PATH || cmd == OPERATOR_EXIT) {
12776 res = cmd;
12777 ast_trace(-1, "advanced options: %d\n", cmd);
12778 goto out;
12779 }
12780 } else {
12781 cmd = ast_play_and_wait(chan, "vm-sorry");
12782 }
12783 cmd = 't';
12784 break;
12785 case '2': /* Callback */
12786 if (!vms.starting)
12787 ast_verb(3, "Callback Requested\n");
12788 if (!ast_strlen_zero(vmu->callback) && vms.lastmsg > -1 && !vms.starting) {
12789 cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 2, record_gain);
12790 ast_trace(-1, "advanced options: %d\n", cmd);
12791 if (cmd == 9) {
12792 silentexit = 1;
12793 goto out;
12794 } else if (cmd == ERROR_LOCK_PATH) {
12795 res = cmd;
12796 goto out;
12797 }
12798 } else {
12799 cmd = ast_play_and_wait(chan, "vm-sorry");
12800 }
12801 cmd = 't';
12802 break;
12803 case '3': /* Envelope */
12804 if (vms.lastmsg > -1 && !vms.starting) {
12805 cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 3, record_gain);
12806 if (cmd == ERROR_LOCK_PATH) {
12807 res = cmd;
12808 ast_trace(-1, "advanced options: %d\n", cmd);
12809 goto out;
12810 }
12811 } else {
12812 cmd = ast_play_and_wait(chan, "vm-sorry");
12813 }
12814 cmd = 't';
12815 break;
12816 case '4': /* Dialout */
12817 if (!ast_strlen_zero(vmu->dialout)) {
12818 cmd = dialout(chan, vmu, NULL, vmu->dialout);
12819 if (cmd == 9) {
12820 silentexit = 1;
12821 ast_trace(-1, "dialout: %d\n", cmd);
12822 goto out;
12823 }
12824 } else {
12825 cmd = ast_play_and_wait(chan, "vm-sorry");
12826 }
12827 cmd = 't';
12828 break;
12829
12830 case '5': /* Leave VoiceMail */
12831 if (ast_test_flag(vmu, VM_SVMAIL)) {
12832 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, forward_message, chan, context, &vms, vmu, vmfmts, 1, record_gain, 0);
12833 if (cmd == ERROR_LOCK_PATH || cmd == OPERATOR_EXIT) {
12834 res = cmd;
12835 ast_trace(-1, "forward message: %d\n", cmd);
12836 goto out;
12837 }
12838 } else {
12839 cmd = ast_play_and_wait(chan, "vm-sorry");
12840 }
12841 cmd = 't';
12842 break;
12843
12844 case '*': /* Return to main menu */
12845 cmd = 't';
12846 break;
12847
12848 default:
12849 cmd = 0;
12850 if (!vms.starting) {
12851 cmd = ast_play_and_wait(chan, "vm-toreply");
12852 }
12853 if (!ast_strlen_zero(vmu->callback) && !vms.starting && !cmd) {
12854 cmd = ast_play_and_wait(chan, "vm-tocallback");
12855 }
12856 if (!cmd && !vms.starting) {
12857 cmd = ast_play_and_wait(chan, "vm-tohearenv");
12858 }
12859 if (!ast_strlen_zero(vmu->dialout) && !cmd) {
12860 cmd = ast_play_and_wait(chan, "vm-tomakecall");
12861 }
12862 if (ast_test_flag(vmu, VM_SVMAIL) && !cmd) {
12863 cmd = ast_play_and_wait(chan, "vm-leavemsg");
12864 }
12865 if (!cmd) {
12866 cmd = ast_play_and_wait(chan, "vm-starmain");
12867 }
12868 if (!cmd) {
12869 cmd = ast_waitfordigit(chan, 6000);
12870 }
12871 if (!cmd) {
12872 vms.repeats++;
12873 }
12874 if (vms.repeats > 3) {
12875 cmd = 't';
12876 }
12877 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
12878 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
12879 }
12880 }
12881 if (cmd == 't') {
12882 cmd = 0;
12883 vms.repeats = 0;
12884 }
12885 break;
12886 case '4': /* Go to the previous message */
12887 ast_test_suite_event_notify("PREVMSG", "Message: browsing message %d\r\nVoicemail: %d", vms.curmsg - 1, vms.curmsg - 1);
12888 if (vms.curmsg > 0) {
12889 vms.curmsg--;
12890 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
12891 } else {
12892 /* Check if we were listening to new
12893 messages. If so, go to Urgent messages
12894 instead of saying "no more messages"
12895 */
12896 if (in_urgent == 0 && vms.urgentmessages > 0) {
12897 /* Check for Urgent messages */
12898 in_urgent = 1;
12899 res = SCOPE_CALL_WITH_INT_RESULT(-1, close_mailbox, &vms, vmu);
12900 if (res == ERROR_LOCK_PATH) {
12901 ast_trace(-1, "close mailbox: %d\n", res);
12902 goto out;
12903 }
12904 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, 11); /* Open Urgent folder */
12905 if (res < 0) {
12906 ast_trace(-1, "open mailbox: %d\n", res);
12907 goto out;
12908 }
12909 ast_debug(1, "No more new messages, opened INBOX and got %d Urgent messages\n", vms.lastmsg + 1);
12910 vms.curmsg = vms.lastmsg;
12911 if (vms.lastmsg < 0) {
12912 cmd = ast_play_and_wait(chan, "vm-nomore");
12913 }
12914 } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
12915 vms.curmsg = vms.lastmsg;
12916 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
12917 } else {
12918 cmd = ast_play_and_wait(chan, "vm-nomore");
12919 }
12920 }
12921 break;
12922 case '6': /* Go to the next message */
12923 ast_test_suite_event_notify("PREVMSG", "Message: browsing message %d\r\nVoicemail: %d", vms.curmsg + 1, vms.curmsg + 1);
12924 if (vms.curmsg < vms.lastmsg) {
12925 vms.curmsg++;
12926 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
12927 } else {
12928 if (in_urgent && vms.newmessages > 0) {
12929 /* Check if we were listening to urgent
12930 * messages. If so, go to regular new messages
12931 * instead of saying "no more messages"
12932 */
12933 in_urgent = 0;
12934 res = SCOPE_CALL_WITH_INT_RESULT(-1, close_mailbox, &vms, vmu);
12935 if (res == ERROR_LOCK_PATH) {
12936 ast_trace(-1, "close mailbox: %d\n", res);
12937 goto out;
12938 }
12939 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, NEW_FOLDER);
12940 if (res < 0) {
12941 ast_trace(-1, "open mailbox: %d\n", res);
12942 goto out;
12943 }
12944 ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
12945 vms.curmsg = -1;
12946 if (vms.lastmsg < 0) {
12947 cmd = ast_play_and_wait(chan, "vm-nomore");
12948 }
12949 } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
12950 vms.curmsg = 0;
12951 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
12952 } else {
12953 cmd = ast_play_and_wait(chan, "vm-nomore");
12954 }
12955 }
12956 break;
12957 case '7': /* Delete the current message */
12958 if (!nodelete && vms.curmsg >= 0 && vms.curmsg <= vms.lastmsg) {
12959 vms.deleted[vms.curmsg] = !vms.deleted[vms.curmsg];
12960 if (useadsi)
12961 adsi_delete(chan, &vms);
12962 if (vms.deleted[vms.curmsg]) {
12963 if (play_folder == 0) {
12964 if (in_urgent) {
12965 vms.urgentmessages--;
12966 } else {
12967 vms.newmessages--;
12968 }
12969 }
12970 else if (play_folder == 1)
12971 vms.oldmessages--;
12972 cmd = ast_play_and_wait(chan, "vm-deleted");
12973 } else {
12974 if (play_folder == 0) {
12975 if (in_urgent) {
12976 vms.urgentmessages++;
12977 } else {
12978 vms.newmessages++;
12979 }
12980 }
12981 else if (play_folder == 1)
12982 vms.oldmessages++;
12983 cmd = ast_play_and_wait(chan, "vm-undeleted");
12984 }
12985 if (ast_test_flag(vmu, VM_SKIPAFTERCMD)) {
12986 if (vms.curmsg < vms.lastmsg) {
12987 vms.curmsg++;
12988 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
12989 } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
12990 vms.curmsg = 0;
12991 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
12992 } else {
12993 /* Check if we were listening to urgent
12994 messages. If so, go to regular new messages
12995 instead of saying "no more messages"
12996 */
12997 if (in_urgent == 1) {
12998 /* Check for new messages */
12999 in_urgent = 0;
13000 res = SCOPE_CALL_WITH_INT_RESULT(-1, close_mailbox, &vms, vmu);
13001 if (res == ERROR_LOCK_PATH) {
13002 ast_trace(-1, "close mailbox: %d\n", res);
13003 goto out;
13004 }
13005 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, NEW_FOLDER);
13006 if (res < 0) {
13007 ast_trace(-1, "open mailbox: %d\n", res);
13008 goto out;
13009 }
13010 ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
13011 vms.curmsg = -1;
13012 if (vms.lastmsg < 0) {
13013 cmd = ast_play_and_wait(chan, "vm-nomore");
13014 }
13015 } else {
13016 cmd = ast_play_and_wait(chan, "vm-nomore");
13017 }
13018 }
13019 }
13020 } else /* Delete not valid if we haven't selected a message */
13021 cmd = 0;
13022 #ifdef IMAP_STORAGE
13023 deleted = 1;
13024 #endif
13025 break;
13026
13027 case '8': /* Forward the current message */
13028 if (vms.lastmsg > -1) {
13029 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, forward_message, chan, context, &vms, vmu, vmfmts, 0, record_gain, in_urgent);
13030 if (cmd == ERROR_LOCK_PATH) {
13031 res = cmd;
13032 ast_trace(-1, "forward message: %d\n", res);
13033 goto out;
13034 }
13035 } else {
13036 /* Check if we were listening to urgent
13037 messages. If so, go to regular new messages
13038 instead of saying "no more messages"
13039 */
13040 if (in_urgent == 1 && vms.newmessages > 0) {
13041 /* Check for new messages */
13042 in_urgent = 0;
13043 res = SCOPE_CALL_WITH_INT_RESULT(-1, close_mailbox, &vms, vmu);
13044 if (res == ERROR_LOCK_PATH) {
13045 ast_trace(-1, "close mailbox: %d\n", res);
13046 goto out;
13047 }
13048 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, NEW_FOLDER);
13049 if (res < 0) {
13050 ast_trace(-1, "open mailbox: %d\n", res);
13051 goto out;
13052 }
13053 ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
13054 vms.curmsg = -1;
13055 if (vms.lastmsg < 0) {
13056 cmd = ast_play_and_wait(chan, "vm-nomore");
13057 }
13058 } else {
13059 cmd = ast_play_and_wait(chan, "vm-nomore");
13060 }
13061 }
13062 break;
13063 case '9': /* Save message to folder */
13064 ast_test_suite_event_notify("SAVEMSG", "Message: saving message %d\r\nVoicemail: %d", vms.curmsg, vms.curmsg);
13065 if (vms.curmsg < 0 || vms.curmsg > vms.lastmsg) {
13066 /* No message selected */
13067 cmd = 0;
13068 break;
13069 }
13070 if (useadsi)
13071 adsi_folders(chan, 1, "Save to folder...");
13072 cmd = get_folder2(chan, "vm-savefolder", 1);
13073 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
13074 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
13075 box = 0; /* Shut up compiler */
13076 if (cmd == '#') {
13077 cmd = 0;
13078 break;
13079 } else if (cmd > 0) {
13080 box = cmd = cmd - '0';
13081 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, save_to_folder, vmu, &vms, vms.curmsg, cmd, NULL, 0);
13082 if (cmd == ERROR_LOCK_PATH) {
13083 res = cmd;
13084 ast_trace(-1, "save to folder: %d\n", res);
13085 goto out;
13086 #ifndef IMAP_STORAGE
13087 } else if (!cmd) {
13088 vms.deleted[vms.curmsg] = 1;
13089 #endif
13090 } else {
13091 vms.deleted[vms.curmsg] = 0;
13092 vms.heard[vms.curmsg] = 0;
13093 }
13094 }
13095 make_file(vms.fn, sizeof(vms.fn), vms.curdir, vms.curmsg);
13096 if (useadsi)
13097 adsi_message(chan, &vms);
13098 snprintf(vms.fn, sizeof(vms.fn), "vm-%s", mbox(vmu, box));
13099 if (!cmd) {
13100 cmd = ast_play_and_wait(chan, "vm-message");
13101 if (!cmd)
13102 cmd = say_and_wait(chan, vms.curmsg + 1, ast_channel_language(chan));
13103 if (!cmd)
13104 cmd = ast_play_and_wait(chan, "vm-savedto");
13105 if (!cmd)
13106 cmd = vm_play_folder_name(chan, vms.fn);
13107 } else {
13108 cmd = ast_play_and_wait(chan, "vm-mailboxfull");
13109 }
13110 if (ast_test_flag((&globalflags), VM_SKIPAFTERCMD)) {
13111 if (vms.curmsg < vms.lastmsg) {
13112 vms.curmsg++;
13113 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
13114 } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
13115 vms.curmsg = 0;
13116 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, play_message, chan, vmu, &vms);
13117 } else {
13118 /* Check if we were listening to urgent
13119 messages. If so, go to regular new messages
13120 instead of saying "no more messages"
13121 */
13122 if (in_urgent == 1 && vms.newmessages > 0) {
13123 /* Check for new messages */
13124 in_urgent = 0;
13125 res = SCOPE_CALL_WITH_INT_RESULT(-1, close_mailbox, &vms, vmu);
13126 if (res == ERROR_LOCK_PATH) {
13127 ast_trace(-1, "close mailbox: %d\n", res);
13128 goto out;
13129 }
13130 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, NEW_FOLDER);
13131 if (res < 0) {
13132 ast_trace(-1, "open mailbox: %d\n", res);
13133 goto out;
13134 }
13135 ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
13136 vms.curmsg = -1;
13137 if (vms.lastmsg < 0) {
13138 cmd = ast_play_and_wait(chan, "vm-nomore");
13139 }
13140 } else {
13141 cmd = ast_play_and_wait(chan, "vm-nomore");
13142 }
13143 }
13144 }
13145 break;
13146 case '*': /* Help */
13147 if (!vms.starting) {
13148 if (!strncasecmp(ast_channel_language(chan), "ja", 2)) {
13149 cmd = vm_play_folder_name(chan, vms.vmbox);
13150 if (!cmd)
13151 cmd = ast_play_and_wait(chan, "jp-wa");
13152 if (!cmd)
13153 cmd = ast_play_and_wait(chan, "digits/1");
13154 if (!cmd)
13155 cmd = ast_play_and_wait(chan, "jp-wo");
13156 if (!cmd)
13157 cmd = ast_play_and_wait(chan, "silence/1");
13158 if (!cmd)
13159 cmd = ast_play_and_wait(chan, "vm-opts");
13160 if (!cmd)
13161 cmd = vm_instructions(chan, vmu, &vms, 1, in_urgent, nodelete);
13162 break;
13163 }
13164 cmd = ast_play_and_wait(chan, "vm-onefor");
13165 if (!strncasecmp(ast_channel_language(chan), "he", 2)) {
13166 cmd = ast_play_and_wait(chan, "vm-for");
13167 }
13168 if (!cmd)
13169 cmd = vm_play_folder_name(chan, vms.vmbox);
13170 if (!cmd)
13171 cmd = ast_play_and_wait(chan, "vm-opts");
13172 if (!cmd)
13173 cmd = vm_instructions(chan, vmu, &vms, 1, in_urgent, nodelete);
13174 } else
13175 cmd = 0;
13176 break;
13177 case '0': /* Mailbox options */
13178 cmd = SCOPE_CALL_WITH_INT_RESULT(-1, vm_options,chan, vmu, &vms, vmfmts, record_gain);
13179 if (useadsi)
13180 adsi_status(chan, &vms);
13181 /* Reopen play_folder */
13182 res = SCOPE_CALL_WITH_INT_RESULT(-1, open_mailbox, &vms, vmu, play_folder);
13183 if (res < 0) {
13184 ast_trace(-1, "open mailbox: %d\n", res);
13185 goto out;
13186 }
13187 vms.starting = 1;
13188 break;
13189 default: /* Nothing */
13190 ast_test_suite_event_notify("PLAYBACK", "Message: instructions");
13191 cmd = vm_instructions(chan, vmu, &vms, 0, in_urgent, nodelete);
13192 break;
13193 }
13194 }
13195 if ((cmd == 't') || (cmd == '#')) {
13196 /* Timeout */
13197 res = 0;
13198 } else {
13199 /* Hangup */
13200 res = -1;
13201 }
13202
13203 out:
13204 if (res > -1) {
13205 ast_stopstream(chan);
13206 adsi_goodbye(chan);
13207 if (valid && res != OPERATOR_EXIT) {
13208 if (silentexit)
13209 res = ast_play_and_wait(chan, "vm-dialout");
13210 else
13211 res = ast_play_and_wait(chan, "vm-goodbye");
13212 }
13213 if ((valid && res > 0) || res == OPERATOR_EXIT) {
13214 res = 0;
13215 }
13216 if (useadsi)
13217 ast_adsi_unload_session(chan);
13218 }
13219 if (vmu) {
13220 SCOPE_CALL(-1, close_mailbox, &vms, vmu);
13221 }
13222 if (valid) {
13223 int new = 0, old = 0, urgent = 0;
13224 snprintf(ext_context, sizeof(ext_context), "%s@%s", vms.username, vmu->context);
13225 /* Urgent flag not passwd to externnotify here */
13226 run_externnotify(vmu->context, vmu->mailbox, NULL);
13227 ast_app_inboxcount2(ext_context, &urgent, &new, &old);
13228 queue_mwi_event(ast_channel_uniqueid(chan), ext_context, urgent, new, old);
13229 }
13230 #ifdef IMAP_STORAGE
13231 /* expunge message - use UID Expunge if supported on IMAP server*/
13232 ast_debug(3, "*** Checking if we can expunge, deleted set to %d, expungeonhangup set to %d\n", deleted, expungeonhangup);
13233 if (vmu && deleted == 1 && expungeonhangup == 1 && vms.mailstream != NULL) {
13234 ast_mutex_lock(&vms.lock);
13235 #ifdef HAVE_IMAP_TK2006
13236 if (LEVELUIDPLUS (vms.mailstream)) {
13237 mail_expunge_full(vms.mailstream, NIL, EX_UID);
13238 } else
13239 #endif
13240 mail_expunge(vms.mailstream);
13241 ast_mutex_unlock(&vms.lock);
13242 }
13243 /* before we delete the state, we should copy pertinent info
13244 * back to the persistent model */
13245 if (vmu) {
13246 vmstate_delete(&vms);
13247 }
13248 #endif
13249 if (vmu)
13250 free_user(vmu);
13251
13252 #ifdef IMAP_STORAGE
13253 pthread_setspecific(ts_vmstate.key, NULL);
13254 #endif
13255 SCOPE_EXIT_RTN_VALUE(res, "Done. RC: %d\n", res);
13256 }
13257
13258 static int vm_exec(struct ast_channel *chan, const char *data)
13259 {
13260 int res = 0;
13261 char *tmp;
13262 struct leave_vm_options leave_options;
13263 struct ast_flags flags = { 0 };
13264 char *opts[OPT_ARG_ARRAY_SIZE];
13265 AST_DECLARE_APP_ARGS(args,
13266 AST_APP_ARG(argv0);
13267 AST_APP_ARG(argv1);
13268 );
13269 SCOPE_ENTER(3, "%s\n", ast_channel_name(chan));
13270
13271 memset(&leave_options, 0, sizeof(leave_options));
13272
13273 if (!ast_strlen_zero(data)) {
13274 tmp = ast_strdupa(data);
13275 AST_STANDARD_APP_ARGS(args, tmp);
13276 if (args.argc == 2) {
13277 if (ast_app_parse_options(vm_app_options, &flags, opts, args.argv1)) {
13278 SCOPE_EXIT_RTN_VALUE(-1, "parse options failed for '%s'\n", args.argv1);
13279 }
13280 ast_copy_flags(&leave_options, &flags, OPT_SILENT | OPT_SILENT_IF_GREET | OPT_BUSY_GREETING | OPT_UNAVAIL_GREETING | OPT_MESSAGE_Urgent | OPT_MESSAGE_PRIORITY | OPT_DTMFEXIT);
13281 if (ast_test_flag(&flags, OPT_RECORDGAIN)) {
13282 int gain;
13283
13284 if (sscanf(opts[OPT_ARG_RECORDGAIN], "%30d", &gain) != 1) {
13285 SCOPE_EXIT_LOG_RTN_VALUE(-1, AST_LOG_WARNING, "Invalid value '%s' provided for record gain option\n", opts[OPT_ARG_RECORDGAIN]);
13286 } else {
13287 leave_options.record_gain = (signed char) gain;
13288 }
13289 }
13290 if (ast_test_flag(&flags, OPT_DTMFEXIT)) {
13291 if (!ast_strlen_zero(opts[OPT_ARG_DTMFEXIT]))
13292 leave_options.exitcontext = opts[OPT_ARG_DTMFEXIT];
13293 }
13294 }
13295 if (ast_test_flag(&flags, OPT_BEEP)) { /* Use custom beep (or none at all) */
13296 leave_options.beeptone = opts[OPT_ARG_BEEP_TONE];
13297 } else { /* Use default beep */
13298 leave_options.beeptone = "beep";
13299 }
13300 } else {
13301 char temp[256];
13302 res = ast_app_getdata(chan, "vm-whichbox", temp, sizeof(temp) - 1, 0);
13303 if (res < 0) {
13304 SCOPE_EXIT_RTN_VALUE(res, "getdata failed. RC: %d", res);
13305 }
13306 if (ast_strlen_zero(temp)) {
13307 SCOPE_EXIT_RTN_VALUE(0);
13308 }
13309 args.argv0 = ast_strdupa(temp);
13310 }
13311
13312 if (ast_channel_state(chan) != AST_STATE_UP) {
13313 if (ast_test_flag(&flags, OPT_EARLYM_GREETING)) {
13314 ast_indicate(chan, AST_CONTROL_PROGRESS);
13315 } else {
13316 ast_answer(chan);
13317 }
13318 }
13319
13320 res = SCOPE_CALL_WITH_INT_RESULT(-1, leave_voicemail, chan, args.argv0, &leave_options);
13321 if (res == 't') {
13322 ast_play_and_wait(chan, "vm-goodbye");
13323 res = 0;
13324 }
13325
13326 if (res == OPERATOR_EXIT) {
13327 res = 0;
13328 }
13329
13330 if (res == ERROR_LOCK_PATH) {
13331 ast_log(AST_LOG_ERROR, "Could not leave voicemail. The path is already locked.\n");
13332 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
13333 res = 0;
13334 }
13335
13336 SCOPE_EXIT_RTN_VALUE(res, "Done. RC: %d", res);
13337 }
13338
13339 static int add_message_id(struct ast_config *msg_cfg, char *dir, int msg, char *filename, char *id, size_t id_size, struct ast_vm_user *vmu, int folder)
13340 {
13341 struct ast_variable *var;
13342 struct ast_category *cat;
13343 generate_msg_id(id);
13344
13345 var = ast_variable_new("msg_id", id, "");
13346 if (!var) {
13347 return -1;
13348 }
13349
13350 cat = ast_category_get(msg_cfg, "message", NULL);
13351 if (!cat) {
13352 ast_log(LOG_ERROR, "Voicemail data file %s/%d.txt has no [message] category?\n", dir, msg);
13353 ast_variables_destroy(var);
13354 return -1;
13355 }
13356
13357 ast_variable_append(cat, var);
13358
13359 if (ast_config_text_file_save(filename, msg_cfg, "app_voicemail")) {
13360 ast_log(LOG_WARNING, "Unable to update %s to have a message ID\n", filename);
13361 return -1;
13362 }
13363
13364 UPDATE_MSG_ID(dir, msg, id, vmu, msg_cfg, folder);
13365 return 0;
13366 }
13367
13368 static struct ast_vm_user *find_or_create(const char *context, const char *box)
13369 {
13370 struct ast_vm_user *vmu;
13371
13372 if (!ast_strlen_zero(box) && box[0] == '*') {
13373 ast_log(LOG_WARNING, "Mailbox %s in context %s begins with '*' character. The '*' character,"
13374 "\n\twhen it is the first character in a mailbox or password, is used to jump to a"
13375 "\n\tpredefined extension 'a'. A mailbox or password beginning with '*' is not valid"
13376 "\n\tand will be ignored.\n", box, context);
13377 return NULL;
13378 }
13379
13380 AST_LIST_TRAVERSE(&users, vmu, list) {
13381 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(box, vmu->mailbox)) {
13382 if (strcasecmp(vmu->context, context)) {
13383 ast_log(LOG_WARNING, "\nIt has been detected that you have defined mailbox '%s' in separate\
13384 \n\tcontexts and that you have the 'searchcontexts' option on. This type of\
13385 \n\tconfiguration creates an ambiguity that you likely do not want. Please\
13386 \n\tamend your voicemail.conf file to avoid this situation.\n", box);
13387 }
13388 ast_log(LOG_WARNING, "Ignoring duplicated mailbox %s\n", box);
13389 return NULL;
13390 }
13391 if (!strcasecmp(context, vmu->context) && !strcasecmp(box, vmu->mailbox)) {
13392 ast_log(LOG_WARNING, "Ignoring duplicated mailbox %s in context %s\n", box, context);
13393 return NULL;
13394 }
13395 }
13396
13397 if (!(vmu = ast_calloc(1, sizeof(*vmu))))
13398 return NULL;
13399
13400 ast_copy_string(vmu->context, context, sizeof(vmu->context));
13401 ast_copy_string(vmu->mailbox, box, sizeof(vmu->mailbox));
13402
13403 AST_LIST_INSERT_TAIL(&users, vmu, list);
13404
13405 return vmu;
13406 }
13407
13408 static int append_mailbox(const char *context, const char *box, const char *data)
13409 {
13410 /* Assumes lock is already held */
13411 char *tmp;
13412 char *stringp;
13413 char *s;
13414 struct ast_vm_user *vmu;
13415 char mailbox_full[MAX_VM_MAILBOX_LEN];
13416 int new = 0, old = 0, urgent = 0;
13417 char secretfn[PATH_MAX] = "";
13418
13419 tmp = ast_strdupa(data);
13420
13421 if (!(vmu = find_or_create(context, box)))
13422 return -1;
13423
13424 populate_defaults(vmu);
13425
13426 stringp = tmp;
13427 if ((s = strsep(&stringp, ","))) {
13428 if (!ast_strlen_zero(s) && s[0] == '*') {
13429 ast_log(LOG_WARNING, "Invalid password detected for mailbox %s. The password"
13430 "\n\tmust be reset in voicemail.conf.\n", box);
13431 }
13432 /* assign password regardless of validity to prevent NULL password from being assigned */
13433 ast_copy_string(vmu->password, s, sizeof(vmu->password));
13434 }
13435 if (stringp && (s = strsep(&stringp, ","))) {
13436 ast_copy_string(vmu->fullname, s, sizeof(vmu->fullname));
13437 }
13438 if (stringp && (s = strsep(&stringp, ","))) {
13439 vmu->email = ast_strdup(s);
13440 }
13441 if (stringp && (s = strsep(&stringp, ","))) {
13442 ast_copy_string(vmu->pager, s, sizeof(vmu->pager));
13443 }
13444 if (stringp) {
13445 apply_options(vmu, stringp);
13446 }
13447
13448 switch (vmu->passwordlocation) {
13449 case OPT_PWLOC_SPOOLDIR:
13450 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
13451 read_password_from_file(secretfn, vmu->password, sizeof(vmu->password));
13452 }
13453
13454 snprintf(mailbox_full, MAX_VM_MAILBOX_LEN, "%s%s%s",
13455 box,
13456 ast_strlen_zero(context) ? "" : "@",
13457 context);
13458
13459 inboxcount2(mailbox_full, &urgent, &new, &old);
13460 #ifdef IMAP_STORAGE
13461 imap_logout(mailbox_full);
13462 #endif
13463 queue_mwi_event(NULL, mailbox_full, urgent, new, old);
13464
13465 return 0;
13466 }
13467
13468 #ifdef TEST_FRAMEWORK
13469 AST_TEST_DEFINE(test_voicemail_vmuser)
13470 {
13471 int res = 0;
13472 struct ast_vm_user *vmu;
13473 /* language parameter seems to only be used for display in manager action */
13474 static const char options_string[] = "attach=yes|attachfmt=wav49|"
13475 "[email protected]|fromstring=Voicemail System|tz=central|delete=yes|saycid=yes|"
13476 "sendvoicemail=yes|review=yes|tempgreetwarn=yes|messagewrap=yes|operator=yes|leaveurgent=yes|"
13477 "envelope=yes|moveheard=yes|sayduration=yes|saydurationm=5|forcename=yes|"
13478 "forcegreetings=yes|callback=somecontext|dialout=somecontext2|"
13479 "exitcontext=somecontext3|minsecs=10|maxsecs=100|nextaftercmd=yes|"
13480 "backupdeleted=50|volgain=1.3|passwordlocation=spooldir|emailbody="
13481 "Dear ${VM_NAME}:\n\n\tYou were just left a ${VM_DUR} long message|emailsubject="
13482 "[PBX]: New message \\\\${VM_MSGNUM}\\\\ in mailbox ${VM_MAILBOX}";
13483 #ifdef IMAP_STORAGE
13484 static const char option_string2[] = "imapuser=imapuser|imappassword=imappasswd|"
13485 "imapfolder=INBOX|imapvmshareid=6000|imapserver=imapserver|imapport=1234|imapflags=flagged";
13486 #endif
13487
13488 switch (cmd) {
13489 case TEST_INIT:
13490 info->name = "vmuser";
13491 info->category = "/apps/app_voicemail/";
13492 info->summary = "Vmuser unit test";
13493 info->description =
13494 "This tests passing all supported parameters to apply_options, the voicemail user config parser";
13495 return AST_TEST_NOT_RUN;
13496 case TEST_EXECUTE:
13497 break;
13498 }
13499
13500 if (!(vmu = ast_calloc(1, sizeof(*vmu)))) {
13501 return AST_TEST_NOT_RUN;
13502 }
13503 populate_defaults(vmu);
13504 ast_set_flag(vmu, VM_ALLOCED);
13505
13506 apply_options(vmu, options_string);
13507
13508 if (!ast_test_flag(vmu, VM_ATTACH)) {
13509 ast_test_status_update(test, "Parse failure for attach option\n");
13510 res = 1;
13511 }
13512 if (strcasecmp(vmu->attachfmt, "wav49")) {
13513 ast_test_status_update(test, "Parse failure for attachfmt option\n");
13514 res = 1;
13515 }
13516 if (strcasecmp(vmu->fromstring, "Voicemail System")) {
13517 ast_test_status_update(test, "Parse failure for fromstring option\n");
13518 res = 1;
13519 }
13520 if (strcasecmp(vmu->serveremail, "[email protected]")) {
13521 ast_test_status_update(test, "Parse failure for serveremail option\n");
13522 res = 1;
13523 }
13524 if (!vmu->emailsubject || strcasecmp(vmu->emailsubject, "[PBX]: New message \\${VM_MSGNUM}\\ in mailbox ${VM_MAILBOX}")) {
13525 ast_test_status_update(test, "Parse failure for emailsubject option\n");
13526 res = 1;
13527 }
13528 if (!vmu->emailbody || strcasecmp(vmu->emailbody, "Dear ${VM_NAME}:\n\n\tYou were just left a ${VM_DUR} long message")) {
13529 ast_test_status_update(test, "Parse failure for emailbody option\n");
13530 res = 1;
13531 }
13532 if (strcasecmp(vmu->zonetag, "central")) {
13533 ast_test_status_update(test, "Parse failure for tz option\n");
13534 res = 1;
13535 }
13536 if (!ast_test_flag(vmu, VM_DELETE)) {
13537 ast_test_status_update(test, "Parse failure for delete option\n");
13538 res = 1;
13539 }
13540 if (!ast_test_flag(vmu, VM_SAYCID)) {
13541 ast_test_status_update(test, "Parse failure for saycid option\n");
13542 res = 1;
13543 }
13544 if (!ast_test_flag(vmu, VM_SVMAIL)) {
13545 ast_test_status_update(test, "Parse failure for sendvoicemail option\n");
13546 res = 1;
13547 }
13548 if (!ast_test_flag(vmu, VM_REVIEW)) {
13549 ast_test_status_update(test, "Parse failure for review option\n");
13550 res = 1;
13551 }
13552 if (!ast_test_flag(vmu, VM_MARK_URGENT)) {
13553 ast_test_status_update(test, "Parse failure for leaveurgent option\n");
13554 res = 1;
13555 }
13556 if (!ast_test_flag(vmu, VM_TEMPGREETWARN)) {
13557 ast_test_status_update(test, "Parse failure for tempgreetwarm option\n");
13558 res = 1;
13559 }
13560 if (!ast_test_flag(vmu, VM_MESSAGEWRAP)) {
13561 ast_test_status_update(test, "Parse failure for messagewrap option\n");
13562 res = 1;
13563 }
13564 if (!ast_test_flag(vmu, VM_OPERATOR)) {
13565 ast_test_status_update(test, "Parse failure for operator option\n");
13566 res = 1;
13567 }
13568 if (!ast_test_flag(vmu, VM_ENVELOPE)) {
13569 ast_test_status_update(test, "Parse failure for envelope option\n");
13570 res = 1;
13571 }
13572 if (!ast_test_flag(vmu, VM_MOVEHEARD)) {
13573 ast_test_status_update(test, "Parse failure for moveheard option\n");
13574 res = 1;
13575 }
13576 if (!ast_test_flag(vmu, VM_SAYDURATION)) {
13577 ast_test_status_update(test, "Parse failure for sayduration option\n");
13578 res = 1;
13579 }
13580 if (vmu->saydurationm != 5) {
13581 ast_test_status_update(test, "Parse failure for saydurationm option\n");
13582 res = 1;
13583 }
13584 if (!ast_test_flag(vmu, VM_FORCENAME)) {
13585 ast_test_status_update(test, "Parse failure for forcename option\n");
13586 res = 1;
13587 }
13588 if (!ast_test_flag(vmu, VM_FORCEGREET)) {
13589 ast_test_status_update(test, "Parse failure for forcegreetings option\n");
13590 res = 1;
13591 }
13592 if (strcasecmp(vmu->callback, "somecontext")) {
13593 ast_test_status_update(test, "Parse failure for callbacks option\n");
13594 res = 1;
13595 }
13596 if (strcasecmp(vmu->dialout, "somecontext2")) {
13597 ast_test_status_update(test, "Parse failure for dialout option\n");
13598 res = 1;
13599 }
13600 if (strcasecmp(vmu->exit, "somecontext3")) {
13601 ast_test_status_update(test, "Parse failure for exitcontext option\n");
13602 res = 1;
13603 }
13604 if (vmu->minsecs != 10) {
13605 ast_test_status_update(test, "Parse failure for minsecs option\n");
13606 res = 1;
13607 }
13608 if (vmu->maxsecs != 100) {
13609 ast_test_status_update(test, "Parse failure for maxsecs option\n");
13610 res = 1;
13611 }
13612 if (!ast_test_flag(vmu, VM_SKIPAFTERCMD)) {
13613 ast_test_status_update(test, "Parse failure for nextaftercmd option\n");
13614 res = 1;
13615 }
13616 if (vmu->maxdeletedmsg != 50) {
13617 ast_test_status_update(test, "Parse failure for backupdeleted option\n");
13618 res = 1;
13619 }
13620 if (vmu->volgain != 1.3) {
13621 ast_test_status_update(test, "Parse failure for volgain option\n");
13622 res = 1;
13623 }
13624 if (vmu->passwordlocation != OPT_PWLOC_SPOOLDIR) {
13625 ast_test_status_update(test, "Parse failure for passwordlocation option\n");
13626 res = 1;
13627 }
13628 #ifdef IMAP_STORAGE
13629 apply_options(vmu, option_string2);
13630
13631 if (strcasecmp(vmu->imapuser, "imapuser")) {
13632 ast_test_status_update(test, "Parse failure for imapuser option\n");
13633 res = 1;
13634 }
13635 if (strcasecmp(vmu->imappassword, "imappasswd")) {
13636 ast_test_status_update(test, "Parse failure for imappasswd option\n");
13637 res = 1;
13638 }
13639 if (strcasecmp(vmu->imapfolder, "INBOX")) {
13640 ast_test_status_update(test, "Parse failure for imapfolder option\n");
13641 res = 1;
13642 }
13643 if (strcasecmp(vmu->imapvmshareid, "6000")) {
13644 ast_test_status_update(test, "Parse failure for imapvmshareid option\n");
13645 res = 1;
13646 }
13647 if (strcasecmp(vmu->imapserver, "imapserver")) {
13648 ast_test_status_update(test, "Parse failure for imapserver option\n");
13649 res = 1;
13650 }
13651 if (strcasecmp(vmu->imapport, "1234")) {
13652 ast_test_status_update(test, "Parse failure for imapport option\n");
13653 res = 1;
13654 }
13655 if (strcasecmp(vmu->imapflags, "flagged")) {
13656 ast_test_status_update(test, "Parse failure for imapflags option\n");
13657 res = 1;
13658 }
13659 #endif
13660
13661 free_user(vmu);
13662 force_reload_config(); /* Restore original config */
13663 return res ? AST_TEST_FAIL : AST_TEST_PASS;
13664 }
13665 #endif
13666
13667 static int acf_vm_info(struct ast_channel *chan, const char *cmd, char *args, char *buf, size_t len)
13668 {
13669 struct ast_vm_user svm;
13670 struct ast_vm_user *vmu = NULL;
13671 char *parse;
13672 char *mailbox;
13673 char *context;
13674 int res = 0;
13675
13676 AST_DECLARE_APP_ARGS(arg,
13677 AST_APP_ARG(mailbox_context);
13678 AST_APP_ARG(attribute);
13679 AST_APP_ARG(folder);
13680 );
13681
13682 buf[0] = '\0';
13683
13684 if (ast_strlen_zero(args)) {
13685 ast_log(LOG_ERROR, "VM_INFO requires an argument (<mailbox>[@<context>],attribute[,folder])\n");
13686 return -1;
13687 }
13688
13689 parse = ast_strdupa(args);
13690 AST_STANDARD_APP_ARGS(arg, parse);
13691
13692 if (ast_strlen_zero(arg.mailbox_context)
13693 || ast_strlen_zero(arg.attribute)
13694 || separate_mailbox(ast_strdupa(arg.mailbox_context), &mailbox, &context)) {
13695 ast_log(LOG_ERROR, "VM_INFO requires an argument (<mailbox>[@<context>],attribute[,folder])\n");
13696 return -1;
13697 }
13698
13699 memset(&svm, 0, sizeof(svm));
13700 vmu = find_user(&svm, context, mailbox);
13701
13702 if (!strncasecmp(arg.attribute, "exists", 5)) {
13703 ast_copy_string(buf, vmu ? "1" : "0", len);
13704 free_user(vmu);
13705 return 0;
13706 }
13707
13708 if (vmu) {
13709 if (!strncasecmp(arg.attribute, "password", 8)) {
13710 ast_copy_string(buf, vmu->password, len);
13711 } else if (!strncasecmp(arg.attribute, "fullname", 8)) {
13712 ast_copy_string(buf, vmu->fullname, len);
13713 } else if (!strncasecmp(arg.attribute, "email", 5)) {
13714 ast_copy_string(buf, vmu->email, len);
13715 } else if (!strncasecmp(arg.attribute, "pager", 5)) {
13716 ast_copy_string(buf, vmu->pager, len);
13717 } else if (!strncasecmp(arg.attribute, "language", 8)) {
13718 ast_copy_string(buf, S_OR(vmu->language, ast_channel_language(chan)), len);
13719 } else if (!strncasecmp(arg.attribute, "locale", 6)) {
13720 ast_copy_string(buf, vmu->locale, len);
13721 } else if (!strncasecmp(arg.attribute, "tz", 2)) {
13722 ast_copy_string(buf, vmu->zonetag, len);
13723 } else if (!strncasecmp(arg.attribute, "count", 5)) {
13724 char *mailbox_id;
13725
13726 mailbox_id = ast_alloca(strlen(mailbox) + strlen(context) + 2);
13727 sprintf(mailbox_id, "%s@%s", mailbox, context);/* Safe */
13728
13729 /* If mbxfolder is empty messagecount will default to INBOX */
13730 res = messagecount(mailbox_id, arg.folder);
13731 if (res < 0) {
13732 ast_log(LOG_ERROR, "Unable to retrieve message count for mailbox %s\n", arg.mailbox_context);
13733 free_user(vmu);
13734 return -1;
13735 }
13736 snprintf(buf, len, "%d", res);
13737 } else {
13738 ast_log(LOG_ERROR, "Unknown attribute '%s' for VM_INFO\n", arg.attribute);
13739 free_user(vmu);
13740 return -1;
13741 }
13742 free_user(vmu);
13743 }
13744
13745 return 0;
13746 }
13747
13748 static struct ast_custom_function vm_info_acf = {
13749 .name = "VM_INFO",
13750 .read = acf_vm_info,
13751 };
13752
13753 static int vmauthenticate(struct ast_channel *chan, const char *data)
13754 {
13755 char *s, *user = NULL, *context = NULL, mailbox[AST_MAX_EXTENSION] = "";
13756 struct ast_vm_user vmus = {{0}};
13757 char *options = NULL;
13758 int silent = 0, skipuser = 0;
13759 int res = -1;
13760
13761 if (data) {
13762 s = ast_strdupa(data);
13763 user = strsep(&s, ",");
13764 options = strsep(&s, ",");
13765 if (user) {
13766 s = user;
13767 user = strsep(&s, "@");
13768 context = strsep(&s, "");
13769 if (!ast_strlen_zero(user))
13770 skipuser++;
13771 ast_copy_string(mailbox, user, sizeof(mailbox));
13772 }
13773 }
13774
13775 if (options) {
13776 silent = (strchr(options, 's')) != NULL;
13777 }
13778
13779 if (!vm_authenticate(chan, mailbox, sizeof(mailbox), &vmus, context, NULL, skipuser, 3, silent)) {
13780 pbx_builtin_setvar_helper(chan, "AUTH_MAILBOX", mailbox);
13781 pbx_builtin_setvar_helper(chan, "AUTH_CONTEXT", vmus.context);
13782 ast_play_and_wait(chan, "auth-thankyou");
13783 res = 0;
13784 } else if (mailbox[0] == '*') {
13785 /* user entered '*' */
13786 if (!ast_goto_if_exists(chan, ast_channel_context(chan), "a", 1)) {
13787 res = 0; /* prevent hangup */
13788 }
13789 }
13790
13791 return res;
13792 }
13793
13794 static char *show_users_realtime(int fd, const char *context)
13795 {
13796 struct ast_config *cfg;
13797 const char *cat = NULL;
13798
13799 if (!(cfg = ast_load_realtime_multientry("voicemail",
13800 "context", context, SENTINEL))) {
13801 return CLI_FAILURE;
13802 }
13803
13804 ast_cli(fd,
13805 "\n"
13806 "=============================================================\n"
13807 "=== Configured Voicemail Users ==============================\n"
13808 "=============================================================\n"
13809 "===\n");
13810
13811 while ((cat = ast_category_browse(cfg, cat))) {
13812 struct ast_variable *var = NULL;
13813 ast_cli(fd,
13814 "=== Mailbox ...\n"
13815 "===\n");
13816 for (var = ast_variable_browse(cfg, cat); var; var = var->next)
13817 ast_cli(fd, "=== ==> %s: %s\n", var->name, var->value);
13818 ast_cli(fd,
13819 "===\n"
13820 "=== ---------------------------------------------------------\n"
13821 "===\n");
13822 }
13823
13824 ast_cli(fd,
13825 "=============================================================\n"
13826 "\n");
13827
13828 ast_config_destroy(cfg);
13829
13830 return CLI_SUCCESS;
13831 }
13832
13833 static char *complete_voicemail_show_users(const char *line, const char *word, int pos, int state)
13834 {
13835 int which = 0;
13836 int wordlen;
13837 struct ast_vm_user *vmu;
13838 const char *context = "";
13839 char *ret;
13840
13841 /* 0 - voicemail; 1 - show; 2 - users; 3 - for; 4 - <context> */
13842 if (pos > 4)
13843 return NULL;
13844 wordlen = strlen(word);
13845 AST_LIST_LOCK(&users);
13846 AST_LIST_TRAVERSE(&users, vmu, list) {
13847 if (!strncasecmp(word, vmu->context, wordlen)) {
13848 if (context && strcmp(context, vmu->context) && ++which > state) {
13849 ret = ast_strdup(vmu->context);
13850 AST_LIST_UNLOCK(&users);
13851 return ret;
13852 }
13853 /* ignore repeated contexts ? */
13854 context = vmu->context;
13855 }
13856 }
13857 AST_LIST_UNLOCK(&users);
13858 return NULL;
13859 }
13860
13861 /*! \brief Show a list of voicemail users in the CLI */
13862 static char *handle_voicemail_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13863 {
13864 struct ast_vm_user *vmu;
13865 #define HVSU_OUTPUT_FORMAT "%-10s %-5s %-25s %-10s %6s\n"
13866 const char *context = NULL;
13867 int users_counter = 0;
13868
13869 switch (cmd) {
13870 case CLI_INIT:
13871 e->command = "voicemail show users [for]";
13872 e->usage =
13873 "Usage: voicemail show users [for <context>]\n"
13874 " Lists all mailboxes currently set up\n";
13875 return NULL;
13876 case CLI_GENERATE:
13877 return complete_voicemail_show_users(a->line, a->word, a->pos, a->n);
13878 }
13879
13880 if ((a->argc < 3) || (a->argc > 5) || (a->argc == 4))
13881 return CLI_SHOWUSAGE;
13882 if (a->argc == 5) {
13883 if (strcmp(a->argv[3],"for"))
13884 return CLI_SHOWUSAGE;
13885 context = a->argv[4];
13886 }
13887
13888 if (ast_check_realtime("voicemail")) {
13889 if (!context) {
13890 ast_cli(a->fd, "You must specify a specific context to show users from realtime!\n");
13891 return CLI_SHOWUSAGE;
13892 }
13893 return show_users_realtime(a->fd, context);
13894 }
13895
13896 AST_LIST_LOCK(&users);
13897 if (AST_LIST_EMPTY(&users)) {
13898 ast_cli(a->fd, "There are no voicemail users currently defined\n");
13899 AST_LIST_UNLOCK(&users);
13900 return CLI_FAILURE;
13901 }
13902 if (!context) {
13903 ast_cli(a->fd, HVSU_OUTPUT_FORMAT, "Context", "Mbox", "User", "Zone", "NewMsg");
13904 } else {
13905 int count = 0;
13906 AST_LIST_TRAVERSE(&users, vmu, list) {
13907 if (!strcmp(context, vmu->context)) {
13908 count++;
13909 break;
13910 }
13911 }
13912 if (count) {
13913 ast_cli(a->fd, HVSU_OUTPUT_FORMAT, "Context", "Mbox", "User", "Zone", "NewMsg");
13914 } else {
13915 ast_cli(a->fd, "No such voicemail context \"%s\"\n", context);
13916 AST_LIST_UNLOCK(&users);
13917 return CLI_FAILURE;
13918 }
13919 }
13920 AST_LIST_TRAVERSE(&users, vmu, list) {
13921 int newmsgs = 0, oldmsgs = 0;
13922 char count[12], tmp[256] = "";
13923
13924 if (!context || !strcmp(context, vmu->context)) {
13925 snprintf(tmp, sizeof(tmp), "%s@%s", vmu->mailbox, ast_strlen_zero(vmu->context) ? "default" : vmu->context);
13926 inboxcount(tmp, &newmsgs, &oldmsgs);
13927 snprintf(count, sizeof(count), "%d", newmsgs);
13928 ast_cli(a->fd, HVSU_OUTPUT_FORMAT, vmu->context, vmu->mailbox, vmu->fullname, vmu->zonetag, count);
13929 users_counter++;
13930 }
13931 }
13932 AST_LIST_UNLOCK(&users);
13933 ast_cli(a->fd, "%d voicemail users configured.\n", users_counter);
13934 return CLI_SUCCESS;
13935 }
13936
13937 /*! \brief Show a list of voicemail zones in the CLI */
13938 static char *handle_voicemail_show_zones(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13939 {
13940 struct vm_zone *zone;
13941 #define HVSZ_OUTPUT_FORMAT "%-15s %-20s %-45s\n"
13942 char *res = CLI_SUCCESS;
13943
13944 switch (cmd) {
13945 case CLI_INIT:
13946 e->command = "voicemail show zones";
13947 e->usage =
13948 "Usage: voicemail show zones\n"
13949 " Lists zone message formats\n";
13950 return NULL;
13951 case CLI_GENERATE:
13952 return NULL;
13953 }
13954
13955 if (a->argc != 3)
13956 return CLI_SHOWUSAGE;
13957
13958 AST_LIST_LOCK(&zones);
13959 if (!AST_LIST_EMPTY(&zones)) {
13960 ast_cli(a->fd, HVSZ_OUTPUT_FORMAT, "Zone", "Timezone", "Message Format");
13961 AST_LIST_TRAVERSE(&zones, zone, list) {
13962 ast_cli(a->fd, HVSZ_OUTPUT_FORMAT, zone->name, zone->timezone, zone->msg_format);
13963 }
13964 } else {
13965 ast_cli(a->fd, "There are no voicemail zones currently defined\n");
13966 res = CLI_FAILURE;
13967 }
13968 AST_LIST_UNLOCK(&zones);
13969
13970 return res;
13971 }
13972
13973 /*! \brief Show a list of voicemail zones in the CLI */
13974 static char *handle_voicemail_show_aliases(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13975 {
13976 struct ao2_iterator aliases;
13977 struct alias_mailbox_mapping *mapping;
13978 #define ALIASES_OUTPUT_FORMAT "%-32s %-32s\n"
13979 char *res = CLI_SUCCESS;
13980
13981 switch (cmd) {
13982 case CLI_INIT:
13983 e->command = "voicemail show aliases";
13984 e->usage =
13985 "Usage: voicemail show aliases\n"
13986 " Lists mailbox aliases\n";
13987 return NULL;
13988 case CLI_GENERATE:
13989 return NULL;
13990 }
13991
13992 if (a->argc != 3)
13993 return CLI_SHOWUSAGE;
13994
13995 if (ast_strlen_zero(aliasescontext)) {
13996 ast_cli(a->fd, "Aliases are not enabled\n");
13997 return res;
13998 }
13999
14000 ast_cli(a->fd, "Aliases context: %s\n", aliasescontext);
14001 ast_cli(a->fd, ALIASES_OUTPUT_FORMAT, "Alias", "Mailbox");
14002
14003 aliases = ao2_iterator_init(alias_mailbox_mappings, 0);
14004 while ((mapping = ao2_iterator_next(&aliases))) {
14005 ast_cli(a->fd, ALIASES_OUTPUT_FORMAT, mapping->alias, mapping->mailbox);
14006 ao2_ref(mapping, -1);
14007 }
14008 ao2_iterator_destroy(&aliases);
14009
14010 return res;
14011 }
14012
14013 /*! \brief Reload voicemail configuration from the CLI */
14014 static char *handle_voicemail_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14015 {
14016 switch (cmd) {
14017 case CLI_INIT:
14018 e->command = "voicemail reload";
14019 e->usage =
14020 "Usage: voicemail reload\n"
14021 " Reload voicemail configuration\n";
14022 return NULL;
14023 case CLI_GENERATE:
14024 return NULL;
14025 }
14026
14027 if (a->argc != 2)
14028 return CLI_SHOWUSAGE;
14029
14030 ast_cli(a->fd, "Reloading voicemail configuration...\n");
14031 load_config(1);
14032
14033 return CLI_SUCCESS;
14034 }
14035
14036 static struct ast_cli_entry cli_voicemail[] = {
14037 AST_CLI_DEFINE(handle_voicemail_show_users, "List defined voicemail boxes"),
14038 AST_CLI_DEFINE(handle_voicemail_show_zones, "List zone message formats"),
14039 AST_CLI_DEFINE(handle_voicemail_show_aliases, "List mailbox aliases"),
14040 AST_CLI_DEFINE(handle_voicemail_reload, "Reload voicemail configuration"),
14041 AST_CLI_DEFINE(handle_voicemail_show_mailbox, "Display a mailbox's content details"),
14042 AST_CLI_DEFINE(handle_voicemail_forward_message, "Forward message to another folder"),
14043 AST_CLI_DEFINE(handle_voicemail_move_message, "Move message to another folder"),
14044 AST_CLI_DEFINE(handle_voicemail_remove_message, "Remove message"),
14045 };
14046
14047 static int poll_subscribed_mailbox(struct ast_mwi_state *mwi_state, void *data)
14048 {
14049 int new = 0, old = 0, urgent = 0;
14050
14051 if (!mwi_state) {
14052 /* This should only occur due to allocation failure of a default mwi state object */
14053 return 0;
14054 }
14055
14056 inboxcount2(mwi_state->uniqueid, &urgent, &new, &old);
14057
14058 #ifdef IMAP_STORAGE
14059 if (imap_poll_logout) {
14060 imap_logout(mwi_state->uniqueid);
14061 }
14062 #endif
14063
14064 if (urgent != mwi_state->urgent_msgs || new != mwi_state->new_msgs || old != mwi_state->old_msgs) {
14065 queue_mwi_event(NULL, mwi_state->uniqueid, urgent, new, old);
14066 run_externnotify(NULL, mwi_state->uniqueid, NULL);
14067 }
14068
14069 return 0;
14070 }
14071
14072 static void *mb_poll_thread(void *data)
14073 {
14074 while (poll_thread_run) {
14075 struct timespec ts = { 0, };
14076 struct timeval wait;
14077
14078 ast_mwi_state_callback_subscribed(poll_subscribed_mailbox, NULL);
14079
14080 if (!poll_thread_run) {
14081 break;
14082 }
14083
14084 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(poll_freq, 1));
14085 ts.tv_sec = wait.tv_sec;
14086 ts.tv_nsec = wait.tv_usec * 1000;
14087
14088 ast_mutex_lock(&poll_lock);
14089 ast_cond_timedwait(&poll_cond, &poll_lock, &ts);
14090 ast_mutex_unlock(&poll_lock);
14091 }
14092
14093 return NULL;
14094 }
14095
14096 #ifdef IMAP_STORAGE
14097 static void imap_logout(const char *mailbox_id)
14098 {
14099 char *context;
14100 char *mailbox;
14101 struct ast_vm_user vmus;
14102 RAII_VAR(struct ast_vm_user *, vmu, NULL, free_user);
14103 struct vm_state *vms = NULL;
14104
14105 if (ast_strlen_zero(mailbox_id)
14106 || separate_mailbox(ast_strdupa(mailbox_id), &mailbox, &context)) {
14107 return;
14108 }
14109
14110 memset(&vmus, 0, sizeof(vmus));
14111
14112 if (!(vmu = find_user(&vmus, context, mailbox)) || vmu->imapuser[0] == '\0') {
14113 return;
14114 }
14115
14116 vms = get_vm_state_by_imapuser(vmu->imapuser, 0);
14117 if (!vms) {
14118 vms = get_vm_state_by_mailbox(mailbox, context, 0);
14119 }
14120 if (!vms) {
14121 return;
14122 }
14123
14124 ast_mutex_lock(&vms->lock);
14125 vms->mailstream = mail_close(vms->mailstream);
14126 ast_mutex_unlock(&vms->lock);
14127
14128 vmstate_delete(vms);
14129 }
14130
14131 static int imap_close_subscribed_mailbox(struct ast_mwi_state *mwi_state, void *data)
14132 {
14133 if (mwi_state && !ast_strlen_zero(mwi_state->uniqueid)) {
14134 imap_logout(mwi_state->uniqueid);
14135 }
14136
14137 return 0;
14138 }
14139
14140 #endif
14141
14142 static int mwi_handle_unsubscribe2(void *data)
14143 {
14144 struct ast_mwi_state *mwi_state = data;
14145
14146 /*
14147 * Go ahead and clear the implicit MWI publisher here to avoid a leak. If a backing
14148 * configuration is available it'll re-initialize (reset the cached state) on its
14149 * next publish.
14150 */
14151 ast_delete_mwi_state_full(mwi_state->uniqueid, NULL, NULL);
14152
14153 #ifdef IMAP_STORAGE
14154 imap_close_subscribed_mailbox(mwi_state, NULL);
14155 #endif
14156
14157 ao2_ref(mwi_state, -1);
14158 return 0;
14159 }
14160
14161 static void mwi_handle_unsubscribe(const char *id, struct ast_mwi_subscriber *sub)
14162 {
14163 void *data = ast_mwi_subscriber_data(sub);
14164
14165 /* Don't bump data's reference. We'll just use the one returned above */
14166 if (ast_taskprocessor_push(mwi_subscription_tps, mwi_handle_unsubscribe2, data) < 0) {
14167 /* A reference was returned for data when retrieving, so remove it on error */
14168 ao2_ref(data, -1);
14169 }
14170 }
14171
14172 static int mwi_handle_subscribe2(void *data)
14173 {
14174 poll_subscribed_mailbox(data, NULL);
14175 ao2_ref(data, -1);
14176 return 0;
14177 }
14178
14179 static void mwi_handle_subscribe(const char *id, struct ast_mwi_subscriber *sub)
14180 {
14181 void *data = ast_mwi_subscriber_data(sub);
14182
14183 /* Don't bump data's reference. We'll just use the one returned above */
14184 if (ast_taskprocessor_push(mwi_subscription_tps, mwi_handle_subscribe2, data) < 0) {
14185 /* A reference was returned for data when retrieving, so remove it on error */
14186 ao2_ref(data, -1);
14187 }
14188 }
14189
14190 struct ast_mwi_observer mwi_observer = {
14191 .on_subscribe = mwi_handle_subscribe,
14192 .on_unsubscribe = mwi_handle_unsubscribe,
14193 };
14194
14195 static void start_poll_thread(void)
14196 {
14197 int errcode;
14198 ast_mwi_add_observer(&mwi_observer);
14199
14200 poll_thread_run = 1;
14201
14202 if ((errcode = ast_pthread_create(&poll_thread, NULL, mb_poll_thread, NULL))) {
14203 ast_log(LOG_ERROR, "Could not create thread: %s\n", strerror(errcode));
14204 }
14205 }
14206
14207 static void stop_poll_thread(void)
14208 {
14209 poll_thread_run = 0;
14210
14211 ast_mutex_lock(&poll_lock);
14212 ast_cond_signal(&poll_cond);
14213 ast_mutex_unlock(&poll_lock);
14214
14215 pthread_join(poll_thread, NULL);
14216 poll_thread = AST_PTHREADT_NULL;
14217
14218 ast_mwi_remove_observer(&mwi_observer);
14219 }
14220
14221 /*!
14222 * \brief Append vmu info string into given astman with event_name.
14223 * \return 0 failed. 1 otherwise.
14224 */
14225 static int append_vmu_info_astman(
14226 struct mansession *s,
14227 struct ast_vm_user *vmu,
14228 const char* event_name,
14229 const char* actionid
14230 )
14231 {
14232 int new;
14233 int old;
14234 char *mailbox;
14235 int ret;
14236
14237 if((s == NULL) || (vmu == NULL) || (event_name == NULL) || (actionid == NULL)) {
14238 ast_log(LOG_ERROR, "Wrong input parameter.");
14239 return 0;
14240 }
14241
14242 /* create mailbox string */
14243 if (!ast_strlen_zero(vmu->context)) {
14244 ret = ast_asprintf(&mailbox, "%s@%s", vmu->mailbox, vmu->context);
14245 } else {
14246 ret = ast_asprintf(&mailbox, "%s", vmu->mailbox);
14247 }
14248 if (ret == -1) {
14249 ast_log(LOG_ERROR, "Could not create mailbox string. err[%s]\n", strerror(errno));
14250 return 0;
14251 }
14252
14253 /* get mailbox count */
14254 ret = inboxcount(mailbox, &new, &old);
14255 ast_free(mailbox);
14256 if (ret == -1) {
14257 ast_log(LOG_ERROR, "Could not get mailbox count. user[%s], context[%s]\n",
14258 vmu->mailbox ?: "", vmu->context ?: "");
14259 return 0;
14260 }
14261
14262 astman_append(s,
14263 "Event: %s\r\n"
14264 "%s"
14265 "VMContext: %s\r\n"
14266 "VoiceMailbox: %s\r\n"
14267 "Fullname: %s\r\n"
14268 "Email: %s\r\n"
14269 "Pager: %s\r\n"
14270 "ServerEmail: %s\r\n"
14271 "FromString: %s\r\n"
14272 "MailCommand: %s\r\n"
14273 "Language: %s\r\n"
14274 "TimeZone: %s\r\n"
14275 "Callback: %s\r\n"
14276 "Dialout: %s\r\n"
14277 "UniqueID: %s\r\n"
14278 "ExitContext: %s\r\n"
14279 "SayDurationMinimum: %d\r\n"
14280 "SayEnvelope: %s\r\n"
14281 "SayCID: %s\r\n"
14282 "AttachMessage: %s\r\n"
14283 "AttachmentFormat: %s\r\n"
14284 "DeleteMessage: %s\r\n"
14285 "VolumeGain: %.2f\r\n"
14286 "CanReview: %s\r\n"
14287 "CanMarkUrgent: %s\r\n"
14288 "CallOperator: %s\r\n"
14289 "MaxMessageCount: %d\r\n"
14290 "MaxMessageLength: %d\r\n"
14291 "NewMessageCount: %d\r\n"
14292 "OldMessageCount: %d\r\n"
14293 #ifdef IMAP_STORAGE
14294 "IMAPUser: %s\r\n"
14295 "IMAPServer: %s\r\n"
14296 "IMAPPort: %s\r\n"
14297 "IMAPFlags: %s\r\n"
14298 #endif
14299 "\r\n",
14300
14301 event_name,
14302 actionid,
14303 vmu->context,
14304 vmu->mailbox,
14305 vmu->fullname,
14306 vmu->email,
14307 vmu->pager,
14308 ast_strlen_zero(vmu->serveremail) ? serveremail : vmu->serveremail,
14309 ast_strlen_zero(vmu->fromstring) ? fromstring : vmu->fromstring,
14310 mailcmd,
14311 vmu->language,
14312 vmu->zonetag,
14313 vmu->callback,
14314 vmu->dialout,
14315 vmu->uniqueid,
14316 vmu->exit,
14317 vmu->saydurationm,
14318 ast_test_flag(vmu, VM_ENVELOPE) ? "Yes" : "No",
14319 ast_test_flag(vmu, VM_SAYCID) ? "Yes" : "No",
14320 ast_test_flag(vmu, VM_ATTACH) ? "Yes" : "No",
14321 vmu->attachfmt,
14322 ast_test_flag(vmu, VM_DELETE) ? "Yes" : "No",
14323 vmu->volgain,
14324 ast_test_flag(vmu, VM_REVIEW) ? "Yes" : "No",
14325 ast_test_flag(vmu, VM_MARK_URGENT) ? "Yes" : "No",
14326 ast_test_flag(vmu, VM_OPERATOR) ? "Yes" : "No",
14327 vmu->maxmsg,
14328 vmu->maxsecs,
14329 new,
14330 old
14331 #ifdef IMAP_STORAGE
14332 ,
14333 vmu->imapuser,
14334 vmu->imapserver,
14335 vmu->imapport,
14336 vmu->imapflags
14337 #endif
14338 );
14339
14340 return 1;
14341
14342 }
14343
14344
14345 /*!
14346 * \brief Append vmbox info string into given astman with event_name.
14347 * \return 0 if unable to append details, 1 otherwise.
14348 */
14349 static int append_vmbox_info_astman(
14350 struct mansession *s,
14351 const struct message *m,
14352 struct ast_vm_user *vmu,
14353 const char* event_name,
14354 const char* actionid)
14355 {
14356 struct ast_vm_mailbox_snapshot *mailbox_snapshot;
14357 struct ast_vm_msg_snapshot *msg;
14358 int nummessages = 0;
14359 int i;
14360
14361 /* Take a snapshot of the mailbox */
14362 mailbox_snapshot = ast_vm_mailbox_snapshot_create(vmu->mailbox, vmu->context, NULL, 0, AST_VM_SNAPSHOT_SORT_BY_ID, 0);
14363 if (!mailbox_snapshot) {
14364 ast_log(LOG_ERROR, "Could not append voicemail box info for box %s@%s.",
14365 vmu->mailbox, vmu->context);
14366 return 0;
14367 }
14368
14369 astman_send_listack(s, m, "Voicemail box detail will follow", "start");
14370 /* walk through each folder's contents and append info for each message */
14371 for (i = 0; i < mailbox_snapshot->folders; i++) {
14372 AST_LIST_TRAVERSE(&((mailbox_snapshot)->snapshots[i]), msg, msg) {
14373 astman_append(s,
14374 "Event: %s\r\n"
14375 "%s"
14376 "Folder: %s\r\n"
14377 "CallerID: %s\r\n"
14378 "Date: %s\r\n"
14379 "Duration: %s\r\n"
14380 "Flag: %s\r\n"
14381 "ID: %s\r\n"
14382 "\r\n",
14383 event_name,
14384 actionid,
14385 msg->folder_name,
14386 msg->callerid,
14387 msg->origdate,
14388 msg->duration,
14389 msg->flag,
14390 msg->msg_id
14391 );
14392 nummessages++;
14393 }
14394 }
14395
14396 /* done, destroy. */
14397 mailbox_snapshot = ast_vm_mailbox_snapshot_destroy(mailbox_snapshot);
14398 astman_send_list_complete_start(s, m, "VoicemailBoxDetailComplete", nummessages);
14399 astman_send_list_complete_end(s);
14400
14401 return 1;
14402 }
14403
14404 static int manager_match_mailbox(struct ast_mwi_state *mwi_state, void *data)
14405 {
14406 const char *context = astman_get_header(data, "Context");
14407 const char *mailbox = astman_get_header(data, "Mailbox");
14408 const char *at;
14409
14410 if (!ast_strlen_zero(mwi_state->uniqueid)) {
14411 if (
14412 /* First case: everything matches */
14413 (ast_strlen_zero(context) && ast_strlen_zero(mailbox)) ||
14414 /* Second case: match the mailbox only */
14415 (ast_strlen_zero(context) && !ast_strlen_zero(mailbox) &&
14416 (at = strchr(mwi_state->uniqueid, '@')) &&
14417 strncmp(mailbox, mwi_state->uniqueid, at - mwi_state->uniqueid) == 0) ||
14418 /* Third case: match the context only */
14419 (!ast_strlen_zero(context) && ast_strlen_zero(mailbox) &&
14420 (at = strchr(mwi_state->uniqueid, '@')) &&
14421 strcmp(context, at + 1) == 0) ||
14422 /* Final case: match an exact specified mailbox */
14423 (!ast_strlen_zero(context) && !ast_strlen_zero(mailbox) &&
14424 (at = strchr(mwi_state->uniqueid, '@')) &&
14425 strncmp(mailbox, mwi_state->uniqueid, at - mwi_state->uniqueid) == 0 &&
14426 strcmp(context, at + 1) == 0)
14427 ) {
14428 poll_subscribed_mailbox(mwi_state, NULL);
14429 }
14430 }
14431
14432 return 0;
14433 }
14434
14435 static int manager_voicemail_refresh(struct mansession *s, const struct message *m)
14436 {
14437 ast_mwi_state_callback_all(manager_match_mailbox, (void *)m);
14438 astman_send_ack(s, m, "Refresh sent");
14439 return RESULT_SUCCESS;
14440 }
14441
14442 static int manager_status_voicemail_user(struct mansession *s, const struct message *m)
14443 {
14444 struct ast_vm_user *vmu = NULL;
14445 const char *id = astman_get_header(m, "ActionID");
14446 char actionid[128];
14447 struct ast_vm_user svm;
14448 int ret;
14449
14450 const char *context = astman_get_header(m, "Context");
14451 const char *mailbox = astman_get_header(m, "Mailbox");
14452
14453 if ((ast_strlen_zero(context) || ast_strlen_zero(mailbox))) {
14454 astman_send_error(s, m, "Need 'Context' and 'Mailbox' parameters.");
14455 return RESULT_SUCCESS;
14456 }
14457
14458 actionid[0] = '\0';
14459 if (!ast_strlen_zero(id)) {
14460 snprintf(actionid, sizeof(actionid), "ActionID: %s\r\n", id);
14461 }
14462
14463 /* find user */
14464 memset(&svm, 0, sizeof(svm));
14465 vmu = find_user(&svm, context, mailbox);
14466 if (!vmu) {
14467 /* could not find it */
14468 astman_send_ack(s, m, "There is no voicemail user of the given info.");
14469 return RESULT_SUCCESS;
14470 }
14471
14472 astman_send_listack(s, m, "Voicemail user detail will follow", "start");
14473
14474 /* append vmu info event */
14475 ret = append_vmu_info_astman(s, vmu, "VoicemailUserDetail", actionid);
14476 free_user(vmu);
14477 if(ret == 0) {
14478 ast_log(LOG_ERROR, "Could not append voicemail user info.");
14479 }
14480
14481 astman_send_list_complete_start(s, m, "VoicemailUserDetailComplete", 1);
14482 astman_send_list_complete_end(s);
14483
14484 return RESULT_SUCCESS;
14485 }
14486
14487 /*! \brief Manager list voicemail users command */
14488 static int manager_list_voicemail_users(struct mansession *s, const struct message *m)
14489 {
14490 struct ast_vm_user *vmu = NULL;
14491 const char *id = astman_get_header(m, "ActionID");
14492 char actionid[128];
14493 int num_users = 0;
14494 int ret;
14495
14496 actionid[0] = '\0';
14497 if (!ast_strlen_zero(id)) {
14498 snprintf(actionid, sizeof(actionid), "ActionID: %s\r\n", id);
14499 }
14500
14501 AST_LIST_LOCK(&users);
14502
14503 if (AST_LIST_EMPTY(&users)) {
14504 astman_send_ack(s, m, "There are no voicemail users currently defined.");
14505 AST_LIST_UNLOCK(&users);
14506 return RESULT_SUCCESS;
14507 }
14508
14509 astman_send_listack(s, m, "Voicemail user list will follow", "start");
14510
14511 AST_LIST_TRAVERSE(&users, vmu, list) {
14512 /* append vmu info event */
14513 ret = append_vmu_info_astman(s, vmu, "VoicemailUserEntry", actionid);
14514 if(ret == 0) {
14515 ast_log(LOG_ERROR, "Could not append voicemail user info.");
14516 continue;
14517 }
14518 ++num_users;
14519 }
14520
14521 astman_send_list_complete_start(s, m, "VoicemailUserEntryComplete", num_users);
14522 astman_send_list_complete_end(s);
14523
14524 AST_LIST_UNLOCK(&users);
14525
14526 return RESULT_SUCCESS;
14527 }
14528
14529 static int manager_get_mailbox_summary(struct mansession *s, const struct message *m)
14530 {
14531 struct ast_vm_user *vmu = NULL;
14532 const char *id = astman_get_header(m, "ActionID");
14533 char actionid[128];
14534 struct ast_vm_user svm;
14535
14536 const char *context = astman_get_header(m, "Context");
14537 const char *mailbox = astman_get_header(m, "Mailbox");
14538
14539 if ((ast_strlen_zero(context) || ast_strlen_zero(mailbox))) {
14540 astman_send_error(s, m, "Need 'Context' and 'Mailbox' parameters.");
14541 return 0;
14542 }
14543
14544 actionid[0] = '\0';
14545 if (!ast_strlen_zero(id)) {
14546 snprintf(actionid, sizeof(actionid), "ActionID: %s\r\n", id);
14547 }
14548
14549 /* find user */
14550 memset(&svm, 0, sizeof(svm));
14551 vmu = find_user(&svm, context, mailbox);
14552 if (!vmu) {
14553 /* could not find it */
14554 astman_send_ack(s, m, "There is no voicemail user matching the given user.");
14555 return 0;
14556 }
14557
14558 /* Append the mailbox details */
14559 if (!append_vmbox_info_astman(s, m, vmu, "VoicemailBoxDetail", actionid)) {
14560 astman_send_error(s, m, "Unable to get mailbox info for the given user.");
14561 }
14562
14563 free_user(vmu);
14564 return 0;
14565 }
14566
14567 static int manager_voicemail_move(struct mansession *s, const struct message *m)
14568 {
14569 const char *mailbox = astman_get_header(m, "Mailbox");
14570 const char *context = astman_get_header(m, "Context");
14571 const char *from_folder = astman_get_header(m, "Folder");
14572 const char *id[] = { astman_get_header(m, "ID") };
14573 const char *to_folder = astman_get_header(m, "ToFolder");
14574
14575 if (ast_strlen_zero(mailbox)) {
14576 astman_send_error(s, m, "Mailbox not specified, required");
14577 return 0;
14578 }
14579 if (ast_strlen_zero(context)) {
14580 astman_send_error(s, m, "Context not specified, required");
14581 return 0;
14582 }
14583 if (ast_strlen_zero(from_folder)) {
14584 astman_send_error(s, m, "Folder not specified, required");
14585 return 0;
14586 }
14587 if (ast_strlen_zero(id[0])) {
14588 astman_send_error(s, m, "ID not specified, required");
14589 return 0;
14590 }
14591 if (ast_strlen_zero(to_folder)) {
14592 astman_send_error(s, m, "ToFolder not specified, required");
14593 return 0;
14594 }
14595
14596 if (vm_msg_move(mailbox, context, 1, from_folder, id, to_folder)) {
14597 astman_send_ack(s, m, "Message move failed\n");
14598 } else {
14599 astman_send_ack(s, m, "Message move successful\n");
14600 }
14601
14602 return 0;
14603 }
14604
14605 static int manager_voicemail_remove(struct mansession *s, const struct message *m)
14606 {
14607 const char *mailbox = astman_get_header(m, "Mailbox");
14608 const char *context = astman_get_header(m, "Context");
14609 const char *folder = astman_get_header(m, "Folder");
14610 const char *id[] = { astman_get_header(m, "ID") };
14611
14612 if (ast_strlen_zero(mailbox)) {
14613 astman_send_error(s, m, "Mailbox not specified, required");
14614 return 0;
14615 }
14616 if (ast_strlen_zero(context)) {
14617 astman_send_error(s, m, "Context not specified, required");
14618 return 0;
14619 }
14620 if (ast_strlen_zero(folder)) {
14621 astman_send_error(s, m, "Folder not specified, required");
14622 return 0;
14623 }
14624 if (ast_strlen_zero(id[0])) {
14625 astman_send_error(s, m, "ID not specified, required");
14626 return 0;
14627 }
14628
14629 if (vm_msg_remove(mailbox, context, 1, folder, id)) {
14630 astman_send_ack(s, m, "Message remove failed\n");
14631 } else {
14632 astman_send_ack(s, m, "Message remove successful\n");
14633 }
14634
14635 return 0;
14636 }
14637
14638 static int manager_voicemail_forward(struct mansession *s, const struct message *m)
14639 {
14640 const char *from_mailbox = astman_get_header(m, "Mailbox");
14641 const char *from_context = astman_get_header(m, "Context");
14642 const char *from_folder = astman_get_header(m, "Folder");
14643 const char *id[] = { astman_get_header(m, "ID") };
14644 const char *to_mailbox = astman_get_header(m, "ToMailbox");
14645 const char *to_context = astman_get_header(m, "ToContext");
14646 const char *to_folder = astman_get_header(m, "ToFolder");
14647
14648 if (ast_strlen_zero(from_mailbox)) {
14649 astman_send_error(s, m, "Mailbox not specified, required");
14650 return 0;
14651 }
14652 if (ast_strlen_zero(from_context)) {
14653 astman_send_error(s, m, "Context not specified, required");
14654 return 0;
14655 }
14656 if (ast_strlen_zero(from_folder)) {
14657 astman_send_error(s, m, "Folder not specified, required");
14658 return 0;
14659 }
14660 if (ast_strlen_zero(id[0])) {
14661 astman_send_error(s, m, "ID not specified, required");
14662 return 0;
14663 }
14664 if (ast_strlen_zero(to_mailbox)) {
14665 astman_send_error(s, m, "ToMailbox not specified, required");
14666 return 0;
14667 }
14668 if (ast_strlen_zero(to_context)) {
14669 astman_send_error(s, m, "ToContext not specified, required");
14670 return 0;
14671 }
14672 if (ast_strlen_zero(to_folder)) {
14673 astman_send_error(s, m, "ToFolder not specified, required");
14674 return 0;
14675 }
14676
14677 if (vm_msg_forward(from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder, 1, id, 0)) {
14678 astman_send_ack(s, m, "Message forward failed\n");
14679 } else {
14680 astman_send_ack(s, m, "Message forward successful\n");
14681 }
14682
14683 return 0;
14684 }
14685
14686 /*! \brief Free the users structure. */
14687 static void free_vm_users(void)
14688 {
14689 struct ast_vm_user *current;
14690 AST_LIST_LOCK(&users);
14691 while ((current = AST_LIST_REMOVE_HEAD(&users, list))) {
14692 ast_set_flag(current, VM_ALLOCED);
14693 free_user_final(current);
14694 }
14695 AST_LIST_UNLOCK(&users);
14696 }
14697
14698 /*! \brief Free the zones structure. */
14699 static void free_vm_zones(void)
14700 {
14701 struct vm_zone *zcur;
14702 AST_LIST_LOCK(&zones);
14703 while ((zcur = AST_LIST_REMOVE_HEAD(&zones, list)))
14704 free_zone(zcur);
14705 AST_LIST_UNLOCK(&zones);
14706 }
14707
14708 static const char *substitute_escapes(const char *value)
14709 {
14710 char *current;
14711
14712 /* Add 16 for fudge factor */
14713 struct ast_str *str = ast_str_thread_get(&ast_str_thread_global_buf, strlen(value) + 16);
14714
14715 ast_str_reset(str);
14716
14717 /* Substitute strings \r, \n, and \t into the appropriate characters */
14718 for (current = (char *) value; *current; current++) {
14719 if (*current == '\\') {
14720 current++;
14721 if (!*current) {
14722 ast_log(AST_LOG_NOTICE, "Incomplete escape at end of value.\n");
14723 break;
14724 }
14725 switch (*current) {
14726 case '\\':
14727 ast_str_append(&str, 0, "\\");
14728 break;
14729 case 'r':
14730 ast_str_append(&str, 0, "\r");
14731 break;
14732 case 'n':
14733 #ifdef IMAP_STORAGE
14734 if (!str->used || str->str[str->used - 1] != '\r') {
14735 ast_str_append(&str, 0, "\r");
14736 }
14737 #endif
14738 ast_str_append(&str, 0, "\n");
14739 break;
14740 case 't':
14741 ast_str_append(&str, 0, "\t");
14742 break;
14743 default:
14744 ast_log(AST_LOG_NOTICE, "Substitution routine does not support this character: \\%c\n", *current);
14745 break;
14746 }
14747 } else {
14748 ast_str_append(&str, 0, "%c", *current);
14749 }
14750 }
14751
14752 return ast_str_buffer(str);
14753 }
14754
14755 static int load_config_force(int reload, int force)
14756 {
14757 struct ast_config *cfg, *ucfg;
14758 struct ast_flags config_flags = { reload && !force ? CONFIG_FLAG_FILEUNCHANGED : 0 };
14759 int res;
14760
14761 ast_unload_realtime("voicemail");
14762 ast_unload_realtime("voicemail_data");
14763
14764 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
14765 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
14766 return 0;
14767 } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
14768 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Avoiding.\n");
14769 ucfg = NULL;
14770 }
14771 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
14772 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) == CONFIG_STATUS_FILEINVALID) {
14773 ast_config_destroy(ucfg);
14774 ast_log(LOG_ERROR, "Config file " VOICEMAIL_CONFIG " is in an invalid format. Aborting.\n");
14775 return 0;
14776 }
14777 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
14778 ast_log(LOG_ERROR, "Config file " VOICEMAIL_CONFIG " is in an invalid format. Aborting.\n");
14779 return 0;
14780 } else {
14781 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
14782 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
14783 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Avoiding.\n");
14784 ucfg = NULL;
14785 }
14786 }
14787
14788 res = actual_load_config(reload, cfg, ucfg);
14789
14790 ast_config_destroy(cfg);
14791 ast_config_destroy(ucfg);
14792
14793 return res;
14794 }
14795
14796 static int load_config(int reload)
14797 {
14798 return load_config_force(reload, 0);
14799 }
14800
14801 #ifdef TEST_FRAMEWORK
14802 static int load_config_from_memory(int reload, struct ast_config *cfg, struct ast_config *ucfg)
14803 {
14804 ast_unload_realtime("voicemail");
14805 ast_unload_realtime("voicemail_data");
14806 return actual_load_config(reload, cfg, ucfg);
14807 }
14808 #endif
14809
14810 static struct alias_mailbox_mapping *alias_mailbox_mapping_create(const char *alias, const char *mailbox)
14811 {
14812 struct alias_mailbox_mapping *mapping;
14813 size_t from_len = strlen(alias) + 1;
14814 size_t to_len = strlen(mailbox) + 1;
14815
14816 mapping = ao2_alloc(sizeof(*mapping) + from_len + to_len, NULL);
14817 if (!mapping) {
14818 return NULL;
14819 }
14820 mapping->alias = mapping->buf;
14821 mapping->mailbox = mapping->buf + from_len;
14822 ast_copy_string(mapping->alias, alias, from_len); /* Safe */
14823 ast_copy_string(mapping->mailbox, mailbox, to_len); /* Safe */
14824
14825 return mapping;
14826 }
14827
14828 static void load_aliases(struct ast_config *cfg)
14829 {
14830 struct ast_variable *var;
14831
14832 if (ast_strlen_zero(aliasescontext)) {
14833 return;
14834 }
14835 var = ast_variable_browse(cfg, aliasescontext);
14836 while (var) {
14837 struct alias_mailbox_mapping *mapping = alias_mailbox_mapping_create(var->name, var->value);
14838 if (mapping) {
14839 ao2_link(alias_mailbox_mappings, mapping);
14840 ao2_link(mailbox_alias_mappings, mapping);
14841 ao2_ref(mapping, -1);
14842 }
14843 var = var->next;
14844 }
14845 }
14846
14847 static void load_zonemessages(struct ast_config *cfg)
14848 {
14849 struct ast_variable *var;
14850
14851 var = ast_variable_browse(cfg, "zonemessages");
14852 while (var) {
14853 if (var->value) {
14854 struct vm_zone *z;
14855 char *msg_format, *tzone;
14856 char storage[strlen(var->value) + 1];
14857
14858 z = ast_malloc(sizeof(*z));
14859 if (!z) {
14860 return;
14861 }
14862
14863 strcpy(storage, var->value); /* safe */
14864 msg_format = storage;
14865 tzone = strsep(&msg_format, "|,");
14866 if (msg_format) {
14867 ast_copy_string(z->name, var->name, sizeof(z->name));
14868 ast_copy_string(z->timezone, tzone, sizeof(z->timezone));
14869 ast_copy_string(z->msg_format, msg_format, sizeof(z->msg_format));
14870 AST_LIST_LOCK(&zones);
14871 AST_LIST_INSERT_HEAD(&zones, z, list);
14872 AST_LIST_UNLOCK(&zones);
14873 } else {
14874 ast_log(AST_LOG_WARNING, "Invalid timezone definition at line %d\n", var->lineno);
14875 ast_free(z);
14876 }
14877 }
14878 var = var->next;
14879 }
14880 }
14881
14882 static void load_users(struct ast_config *cfg)
14883 {
14884 struct ast_variable *var;
14885 char *cat = NULL;
14886
14887 while ((cat = ast_category_browse(cfg, cat))) {
14888 if (strcasecmp(cat, "general") == 0
14889 || strcasecmp(cat, aliasescontext) == 0
14890 || strcasecmp(cat, "zonemessages") == 0) {
14891 continue;
14892 }
14893
14894 var = ast_variable_browse(cfg, cat);
14895 while (var) {
14896 append_mailbox(cat, var->name, var->value);
14897 var = var->next;
14898 }
14899 }
14900 }
14901
14902 static int actual_load_config(int reload, struct ast_config *cfg, struct ast_config *ucfg)
14903 {
14904 struct ast_vm_user *current;
14905 char *cat;
14906 const char *val;
14907 char *q, *stringp, *tmp;
14908 int x;
14909 unsigned int tmpadsi[4];
14910 char secretfn[PATH_MAX] = "";
14911 long tps_queue_low;
14912 long tps_queue_high;
14913
14914 #ifdef IMAP_STORAGE
14915 ast_copy_string(imapparentfolder, "\0", sizeof(imapparentfolder));
14916 #endif
14917 /* set audio control prompts */
14918 strcpy(listen_control_forward_key, DEFAULT_LISTEN_CONTROL_FORWARD_KEY);
14919 strcpy(listen_control_reverse_key, DEFAULT_LISTEN_CONTROL_REVERSE_KEY);
14920 strcpy(listen_control_pause_key, DEFAULT_LISTEN_CONTROL_PAUSE_KEY);
14921 strcpy(listen_control_restart_key, DEFAULT_LISTEN_CONTROL_RESTART_KEY);
14922 strcpy(listen_control_stop_key, DEFAULT_LISTEN_CONTROL_STOP_KEY);
14923
14924 #ifdef IMAP_STORAGE
14925 ast_mwi_state_callback_all(imap_close_subscribed_mailbox, NULL);
14926 #endif
14927
14928 /* Free all the users structure */
14929 free_vm_users();
14930
14931 /* Free all the zones structure */
14932 free_vm_zones();
14933
14934 /* Remove all aliases */
14935 ao2_callback(alias_mailbox_mappings, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
14936 ao2_callback(mailbox_alias_mappings, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
14937
14938 AST_LIST_LOCK(&users);
14939
14940 memset(ext_pass_cmd, 0, sizeof(ext_pass_cmd));
14941 memset(ext_pass_check_cmd, 0, sizeof(ext_pass_check_cmd));
14942
14943 if (cfg) {
14944 /* General settings */
14945
14946 if (!(val = ast_variable_retrieve(cfg, "general", "userscontext")))
14947 val = "default";
14948 ast_copy_string(userscontext, val, sizeof(userscontext));
14949
14950 aliasescontext[0] = '\0';
14951 val = ast_variable_retrieve(cfg, "general", "aliasescontext");
14952 ast_copy_string(aliasescontext, S_OR(val, ""), sizeof(aliasescontext));
14953
14954 /* Attach voice message to mail message ? */
14955 if (!(val = ast_variable_retrieve(cfg, "general", "attach")))
14956 val = "yes";
14957 ast_set2_flag((&globalflags), ast_true(val), VM_ATTACH);
14958
14959 if (!(val = ast_variable_retrieve(cfg, "general", "searchcontexts")))
14960 val = "no";
14961 ast_set2_flag((&globalflags), ast_true(val), VM_SEARCH);
14962
14963 volgain = 0.0;
14964 if ((val = ast_variable_retrieve(cfg, "general", "volgain")))
14965 sscanf(val, "%30lf", &volgain);
14966
14967 #ifdef ODBC_STORAGE
14968 strcpy(odbc_database, "asterisk");
14969 if ((val = ast_variable_retrieve(cfg, "general", "odbcstorage"))) {
14970 ast_copy_string(odbc_database, val, sizeof(odbc_database));
14971 }
14972
14973 strcpy(odbc_table, "voicemessages");
14974 if ((val = ast_variable_retrieve(cfg, "general", "odbctable"))) {
14975 ast_copy_string(odbc_table, val, sizeof(odbc_table));
14976 }
14977 odbc_table_len = strlen(odbc_table);
14978
14979 ast_set2_flag((&globalflags), 0, VM_ODBC_AUDIO_ON_DISK);
14980 if (!(val = ast_variable_retrieve(cfg, "general", "odbc_audio_on_disk")))
14981 val = "no";
14982 ast_set2_flag((&globalflags), ast_true(val), VM_ODBC_AUDIO_ON_DISK);
14983
14984 #endif
14985 /* Mail command */
14986 strcpy(mailcmd, SENDMAIL);
14987 if ((val = ast_variable_retrieve(cfg, "general", "mailcmd")))
14988 ast_copy_string(mailcmd, val, sizeof(mailcmd)); /* User setting */
14989
14990 maxsilence = 0;
14991 if ((val = ast_variable_retrieve(cfg, "general", "maxsilence"))) {
14992 maxsilence = atoi(val);
14993 if (maxsilence > 0)
14994 maxsilence *= 1000;
14995 }
14996
14997 if (!(val = ast_variable_retrieve(cfg, "general", "maxmsg"))) {
14998 maxmsg = MAXMSG;
14999 } else {
15000 maxmsg = atoi(val);
15001 if (maxmsg < 0) {
15002 ast_log(AST_LOG_WARNING, "Invalid number of messages per folder '%s'. Using default value %i\n", val, MAXMSG);
15003 maxmsg = MAXMSG;
15004 } else if (maxmsg > MAXMSGLIMIT) {
15005 ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %i. Cannot accept value '%s'\n", MAXMSGLIMIT, val);
15006 maxmsg = MAXMSGLIMIT;
15007 }
15008 }
15009
15010 if (!(val = ast_variable_retrieve(cfg, "general", "backupdeleted"))) {
15011 maxdeletedmsg = 0;
15012 } else {
15013 if (sscanf(val, "%30d", &x) == 1)
15014 maxdeletedmsg = x;
15015 else if (ast_true(val))
15016 maxdeletedmsg = MAXMSG;
15017 else
15018 maxdeletedmsg = 0;
15019
15020 if (maxdeletedmsg < 0) {
15021 ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox '%s'. Using default value %i\n", val, MAXMSG);
15022 maxdeletedmsg = MAXMSG;
15023 } else if (maxdeletedmsg > MAXMSGLIMIT) {
15024 ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %i. Cannot accept value '%s'\n", MAXMSGLIMIT, val);
15025 maxdeletedmsg = MAXMSGLIMIT;
15026 }
15027 }
15028
15029 /* Load date format config for voicemail mail */
15030 if ((val = ast_variable_retrieve(cfg, "general", "emaildateformat"))) {
15031 ast_copy_string(emaildateformat, val, sizeof(emaildateformat));
15032 }
15033
15034 /* Load date format config for voicemail pager mail */
15035 if ((val = ast_variable_retrieve(cfg, "general", "pagerdateformat"))) {
15036 ast_copy_string(pagerdateformat, val, sizeof(pagerdateformat));
15037 }
15038
15039 /* External password changing command */
15040 if ((val = ast_variable_retrieve(cfg, "general", "externpass"))) {
15041 ast_copy_string(ext_pass_cmd, val, sizeof(ext_pass_cmd));
15042 pwdchange = PWDCHANGE_EXTERNAL;
15043 } else if ((val = ast_variable_retrieve(cfg, "general", "externpassnotify"))) {
15044 ast_copy_string(ext_pass_cmd, val, sizeof(ext_pass_cmd));
15045 pwdchange = PWDCHANGE_EXTERNAL | PWDCHANGE_INTERNAL;
15046 }
15047
15048 /* External password validation command */
15049 if ((val = ast_variable_retrieve(cfg, "general", "externpasscheck"))) {
15050 ast_copy_string(ext_pass_check_cmd, val, sizeof(ext_pass_check_cmd));
15051 ast_debug(1, "found externpasscheck: %s\n", ext_pass_check_cmd);
15052 }
15053
15054 #ifdef IMAP_STORAGE
15055 /* IMAP server address */
15056 if ((val = ast_variable_retrieve(cfg, "general", "imapserver"))) {
15057 ast_copy_string(imapserver, val, sizeof(imapserver));
15058 } else {
15059 ast_copy_string(imapserver, "localhost", sizeof(imapserver));
15060 }
15061 /* IMAP server port */
15062 if ((val = ast_variable_retrieve(cfg, "general", "imapport"))) {
15063 ast_copy_string(imapport, val, sizeof(imapport));
15064 } else {
15065 ast_copy_string(imapport, "143", sizeof(imapport));
15066 }
15067 /* IMAP server flags */
15068 if ((val = ast_variable_retrieve(cfg, "general", "imapflags"))) {
15069 ast_copy_string(imapflags, val, sizeof(imapflags));
15070 }
15071 /* IMAP server master username */
15072 if ((val = ast_variable_retrieve(cfg, "general", "authuser"))) {
15073 ast_copy_string(authuser, val, sizeof(authuser));
15074 }
15075 /* IMAP server master password */
15076 if ((val = ast_variable_retrieve(cfg, "general", "authpassword"))) {
15077 ast_copy_string(authpassword, val, sizeof(authpassword));
15078 }
15079 /* Expunge on exit */
15080 if ((val = ast_variable_retrieve(cfg, "general", "expungeonhangup"))) {
15081 if (ast_false(val))
15082 expungeonhangup = 0;
15083 else
15084 expungeonhangup = 1;
15085 } else {
15086 expungeonhangup = 1;
15087 }
15088 /* IMAP voicemail folder */
15089 if ((val = ast_variable_retrieve(cfg, "general", "imapfolder"))) {
15090 ast_copy_string(imapfolder, val, sizeof(imapfolder));
15091 } else {
15092 ast_copy_string(imapfolder, "INBOX", sizeof(imapfolder));
15093 }
15094 if ((val = ast_variable_retrieve(cfg, "general", "imapparentfolder"))) {
15095 ast_copy_string(imapparentfolder, val, sizeof(imapparentfolder));
15096 }
15097 if ((val = ast_variable_retrieve(cfg, "general", "imapgreetings"))) {
15098 imapgreetings = ast_true(val);
15099 } else {
15100 imapgreetings = 0;
15101 }
15102 if ((val = ast_variable_retrieve(cfg, "general", "greetingfolder"))) {
15103 ast_copy_string(greetingfolder, val, sizeof(greetingfolder));
15104 } else if ((val = ast_variable_retrieve(cfg, "general", "greetingsfolder"))) {
15105 /* Also support greetingsfolder as documented in voicemail.conf.sample */
15106 ast_copy_string(greetingfolder, val, sizeof(greetingfolder));
15107 } else {
15108 ast_copy_string(greetingfolder, imapfolder, sizeof(greetingfolder));
15109 }
15110 if ((val = ast_variable_retrieve(cfg, "general", "imap_poll_logout"))) {
15111 imap_poll_logout = ast_true(val);
15112 } else {
15113 imap_poll_logout = 0;
15114 }
15115
15116 /* There is some very unorthodox casting done here. This is due
15117 * to the way c-client handles the argument passed in. It expects a
15118 * void pointer and casts the pointer directly to a long without
15119 * first dereferencing it. */
15120 if ((val = ast_variable_retrieve(cfg, "general", "imapreadtimeout"))) {
15121 mail_parameters(NIL, SET_READTIMEOUT, (void *) (atol(val)));
15122 } else {
15123 mail_parameters(NIL, SET_READTIMEOUT, (void *) 60L);
15124 }
15125
15126 if ((val = ast_variable_retrieve(cfg, "general", "imapwritetimeout"))) {
15127 mail_parameters(NIL, SET_WRITETIMEOUT, (void *) (atol(val)));
15128 } else {
15129 mail_parameters(NIL, SET_WRITETIMEOUT, (void *) 60L);
15130 }
15131
15132 if ((val = ast_variable_retrieve(cfg, "general", "imapopentimeout"))) {
15133 mail_parameters(NIL, SET_OPENTIMEOUT, (void *) (atol(val)));
15134 } else {
15135 mail_parameters(NIL, SET_OPENTIMEOUT, (void *) 60L);
15136 }
15137
15138 if ((val = ast_variable_retrieve(cfg, "general", "imapclosetimeout"))) {
15139 mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) (atol(val)));
15140 } else {
15141 mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) 60L);
15142 }
15143
15144 /* Increment configuration version */
15145 imapversion++;
15146 #endif
15147 /* External voicemail notify application */
15148 if ((val = ast_variable_retrieve(cfg, "general", "externnotify"))) {
15149 ast_copy_string(externnotify, val, sizeof(externnotify));
15150 ast_debug(1, "found externnotify: %s\n", externnotify);
15151 } else {
15152 externnotify[0] = '\0';
15153 }
15154
15155 /* SMDI voicemail notification */
15156 if ((val = ast_variable_retrieve(cfg, "general", "smdienable")) && ast_true(val)) {
15157 ast_debug(1, "Enabled SMDI voicemail notification\n");
15158 if ((val = ast_variable_retrieve(cfg, "general", "smdiport"))) {
15159 smdi_iface = ast_smdi_interface_find(val);
15160 } else {
15161 ast_debug(1, "No SMDI interface set, trying default (/dev/ttyS0)\n");
15162 smdi_iface = ast_smdi_interface_find("/dev/ttyS0");
15163 }
15164 if (!smdi_iface) {
15165 ast_log(AST_LOG_ERROR, "No valid SMDI interface specified, disabling SMDI voicemail notification\n");
15166 }
15167 }
15168
15169 /* Silence treshold */
15170 silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
15171 if ((val = ast_variable_retrieve(cfg, "general", "silencethreshold")))
15172 silencethreshold = atoi(val);
15173
15174 if (!(val = ast_variable_retrieve(cfg, "general", "serveremail")))
15175 val = ASTERISK_USERNAME;
15176 ast_copy_string(serveremail, val, sizeof(serveremail));
15177
15178 vmmaxsecs = 0;
15179 if ((val = ast_variable_retrieve(cfg, "general", "maxsecs"))) {
15180 if (sscanf(val, "%30d", &x) == 1) {
15181 vmmaxsecs = x;
15182 } else {
15183 ast_log(AST_LOG_WARNING, "Invalid max message time length\n");
15184 }
15185 } else if ((val = ast_variable_retrieve(cfg, "general", "maxmessage"))) {
15186 static int maxmessage_deprecate = 0;
15187 if (maxmessage_deprecate == 0) {
15188 maxmessage_deprecate = 1;
15189 ast_log(AST_LOG_WARNING, "Setting 'maxmessage' has been deprecated in favor of 'maxsecs'.\n");
15190 }
15191 if (sscanf(val, "%30d", &x) == 1) {
15192 vmmaxsecs = x;
15193 } else {
15194 ast_log(AST_LOG_WARNING, "Invalid max message time length\n");
15195 }
15196 }
15197
15198 vmminsecs = 0;
15199 if ((val = ast_variable_retrieve(cfg, "general", "minsecs"))) {
15200 if (sscanf(val, "%30d", &x) == 1) {
15201 vmminsecs = x;
15202 if (maxsilence / 1000 >= vmminsecs) {
15203 ast_log(AST_LOG_WARNING, "maxsilence should be less than minsecs or you may get empty messages\n");
15204 }
15205 } else {
15206 ast_log(AST_LOG_WARNING, "Invalid min message time length\n");
15207 }
15208 } else if ((val = ast_variable_retrieve(cfg, "general", "minmessage"))) {
15209 static int maxmessage_deprecate = 0;
15210 if (maxmessage_deprecate == 0) {
15211 maxmessage_deprecate = 1;
15212 ast_log(AST_LOG_WARNING, "Setting 'minmessage' has been deprecated in favor of 'minsecs'.\n");
15213 }
15214 if (sscanf(val, "%30d", &x) == 1) {
15215 vmminsecs = x;
15216 if (maxsilence / 1000 >= vmminsecs) {
15217 ast_log(AST_LOG_WARNING, "maxsilence should be less than minmessage or you may get empty messages\n");
15218 }
15219 } else {
15220 ast_log(AST_LOG_WARNING, "Invalid min message time length\n");
15221 }
15222 }
15223
15224 val = ast_variable_retrieve(cfg, "general", "format");
15225 if (!val) {
15226 val = "wav";
15227 } else {
15228 tmp = ast_strdupa(val);
15229 val = ast_format_str_reduce(tmp);
15230 if (!val) {
15231 ast_log(LOG_ERROR, "Error processing format string, defaulting to format 'wav'\n");
15232 val = "wav";
15233 }
15234 }
15235 ast_copy_string(vmfmts, val, sizeof(vmfmts));
15236
15237 skipms = 3000;
15238 if ((val = ast_variable_retrieve(cfg, "general", "maxgreet"))) {
15239 if (sscanf(val, "%30d", &x) == 1) {
15240 maxgreet = x;
15241 } else {
15242 ast_log(AST_LOG_WARNING, "Invalid max message greeting length\n");
15243 }
15244 }
15245
15246 if ((val = ast_variable_retrieve(cfg, "general", "skipms"))) {
15247 if (sscanf(val, "%30d", &x) == 1) {
15248 skipms = x;
15249 } else {
15250 ast_log(AST_LOG_WARNING, "Invalid skipms value\n");
15251 }
15252 }
15253
15254 maxlogins = 3;
15255 if ((val = ast_variable_retrieve(cfg, "general", "maxlogins"))) {
15256 if (sscanf(val, "%30d", &x) == 1) {
15257 maxlogins = x;
15258 } else {
15259 ast_log(AST_LOG_WARNING, "Invalid max failed login attempts\n");
15260 }
15261 }
15262
15263 minpassword = MINPASSWORD;
15264 if ((val = ast_variable_retrieve(cfg, "general", "minpassword"))) {
15265 if (sscanf(val, "%30d", &x) == 1) {
15266 minpassword = x;
15267 } else {
15268 ast_log(AST_LOG_WARNING, "Invalid minimum password length. Default to %d\n", minpassword);
15269 }
15270 }
15271
15272 /* Force new user to record name ? */
15273 if (!(val = ast_variable_retrieve(cfg, "general", "forcename")))
15274 val = "no";
15275 ast_set2_flag((&globalflags), ast_true(val), VM_FORCENAME);
15276
15277 /* Force new user to record greetings ? */
15278 if (!(val = ast_variable_retrieve(cfg, "general", "forcegreetings")))
15279 val = "no";
15280 ast_set2_flag((&globalflags), ast_true(val), VM_FORCEGREET);
15281
15282 if ((val = ast_variable_retrieve(cfg, "general", "cidinternalcontexts"))) {
15283 ast_debug(1, "VM_CID Internal context string: %s\n", val);
15284 stringp = ast_strdupa(val);
15285 for (x = 0 ; x < MAX_NUM_CID_CONTEXTS ; x++){
15286 if (!ast_strlen_zero(stringp)) {
15287 q = strsep(&stringp, ",");
15288 while ((*q == ' ')||(*q == '\t')) /* Eat white space between contexts */
15289 q++;
15290 ast_copy_string(cidinternalcontexts[x], q, sizeof(cidinternalcontexts[x]));
15291 ast_debug(1, "VM_CID Internal context %d: %s\n", x, cidinternalcontexts[x]);
15292 } else {
15293 cidinternalcontexts[x][0] = '\0';
15294 }
15295 }
15296 }
15297 if (!(val = ast_variable_retrieve(cfg, "general", "review"))){
15298 ast_debug(1, "VM Review Option disabled globally\n");
15299 val = "no";
15300 }
15301 ast_set2_flag((&globalflags), ast_true(val), VM_REVIEW);
15302
15303 if (!(val = ast_variable_retrieve(cfg, "general", "leaveurgent"))){
15304 val = "yes";
15305 } else if (ast_false(val)) {
15306 ast_debug(1, "VM leave urgent messages disabled globally\n");
15307 val = "no";
15308 }
15309 ast_set2_flag((&globalflags), ast_true(val), VM_MARK_URGENT);
15310
15311 /* Temporary greeting reminder */
15312 if (!(val = ast_variable_retrieve(cfg, "general", "tempgreetwarn"))) {
15313 ast_debug(1, "VM Temporary Greeting Reminder Option disabled globally\n");
15314 val = "no";
15315 } else {
15316 ast_debug(1, "VM Temporary Greeting Reminder Option enabled globally\n");
15317 }
15318 ast_set2_flag((&globalflags), ast_true(val), VM_TEMPGREETWARN);
15319 if (!(val = ast_variable_retrieve(cfg, "general", "messagewrap"))){
15320 ast_debug(1, "VM next message wrap disabled globally\n");
15321 val = "no";
15322 }
15323 ast_set2_flag((&globalflags), ast_true(val), VM_MESSAGEWRAP);
15324
15325 if (!(val = ast_variable_retrieve(cfg, "general", "operator"))){
15326 ast_debug(1, "VM Operator break disabled globally\n");
15327 val = "no";
15328 }
15329 ast_set2_flag((&globalflags), ast_true(val), VM_OPERATOR);
15330
15331 if (!(val = ast_variable_retrieve(cfg, "general", "saycid"))) {
15332 ast_debug(1, "VM CID Info before msg disabled globally\n");
15333 val = "no";
15334 }
15335 ast_set2_flag((&globalflags), ast_true(val), VM_SAYCID);
15336
15337 if (!(val = ast_variable_retrieve(cfg, "general", "sendvoicemail"))){
15338 ast_debug(1, "Send Voicemail msg disabled globally\n");
15339 val = "no";
15340 }
15341 ast_set2_flag((&globalflags), ast_true(val), VM_SVMAIL);
15342
15343 if (!(val = ast_variable_retrieve(cfg, "general", "envelope"))) {
15344 ast_debug(1, "ENVELOPE before msg enabled globally\n");
15345 val = "yes";
15346 }
15347 ast_set2_flag((&globalflags), ast_true(val), VM_ENVELOPE);
15348
15349 if (!(val = ast_variable_retrieve(cfg, "general", "moveheard"))) {
15350 ast_debug(1, "Move Heard enabled globally\n");
15351 val = "yes";
15352 }
15353 ast_set2_flag((&globalflags), ast_true(val), VM_MOVEHEARD);
15354
15355 if (!(val = ast_variable_retrieve(cfg, "general", "forward_urgent_auto"))) {
15356 ast_debug(1, "Autoset of Urgent flag on forwarded Urgent messages disabled globally\n");
15357 val = "no";
15358 }
15359 ast_set2_flag((&globalflags), ast_true(val), VM_FWDURGAUTO);
15360
15361 if (!(val = ast_variable_retrieve(cfg, "general", "sayduration"))) {
15362 ast_debug(1, "Duration info before msg enabled globally\n");
15363 val = "yes";
15364 }
15365 ast_set2_flag((&globalflags), ast_true(val), VM_SAYDURATION);
15366
15367 saydurationminfo = 2;
15368 if ((val = ast_variable_retrieve(cfg, "general", "saydurationm"))) {
15369 if (sscanf(val, "%30d", &x) == 1) {
15370 saydurationminfo = x;
15371 } else {
15372 ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
15373 }
15374 }
15375
15376 if (!(val = ast_variable_retrieve(cfg, "general", "nextaftercmd"))) {
15377 ast_debug(1, "We are not going to skip to the next msg after save/delete\n");
15378 val = "no";
15379 }
15380 ast_set2_flag((&globalflags), ast_true(val), VM_SKIPAFTERCMD);
15381
15382 if ((val = ast_variable_retrieve(cfg, "general", "dialout"))) {
15383 ast_copy_string(dialcontext, val, sizeof(dialcontext));
15384 ast_debug(1, "found dialout context: %s\n", dialcontext);
15385 } else {
15386 dialcontext[0] = '\0';
15387 }
15388
15389 if ((val = ast_variable_retrieve(cfg, "general", "callback"))) {
15390 ast_copy_string(callcontext, val, sizeof(callcontext));
15391 ast_debug(1, "found callback context: %s\n", callcontext);
15392 } else {
15393 callcontext[0] = '\0';
15394 }
15395
15396 if ((val = ast_variable_retrieve(cfg, "general", "exitcontext"))) {
15397 ast_copy_string(exitcontext, val, sizeof(exitcontext));
15398 ast_debug(1, "found operator context: %s\n", exitcontext);
15399 } else {
15400 exitcontext[0] = '\0';
15401 }
15402
15403 /* load password sounds configuration */
15404 if ((val = ast_variable_retrieve(cfg, "general", "vm-login")))
15405 ast_copy_string(vm_login, val, sizeof(vm_login));
15406 if ((val = ast_variable_retrieve(cfg, "general", "vm-newuser")))
15407 ast_copy_string(vm_newuser, val, sizeof(vm_newuser));
15408 if ((val = ast_variable_retrieve(cfg, "general", "vm-password")))
15409 ast_copy_string(vm_password, val, sizeof(vm_password));
15410 if ((val = ast_variable_retrieve(cfg, "general", "vm-newpassword")))
15411 ast_copy_string(vm_newpassword, val, sizeof(vm_newpassword));
15412 if ((val = ast_variable_retrieve(cfg, "general", "vm-invalid-password")))
15413 ast_copy_string(vm_invalid_password, val, sizeof(vm_invalid_password));
15414 if ((val = ast_variable_retrieve(cfg, "general", "vm-passchanged")))
15415 ast_copy_string(vm_passchanged, val, sizeof(vm_passchanged));
15416 if ((val = ast_variable_retrieve(cfg, "general", "vm-reenterpassword")))
15417 ast_copy_string(vm_reenterpassword, val, sizeof(vm_reenterpassword));
15418 if ((val = ast_variable_retrieve(cfg, "general", "vm-mismatch")))
15419 ast_copy_string(vm_mismatch, val, sizeof(vm_mismatch));
15420 if ((val = ast_variable_retrieve(cfg, "general", "vm-pls-try-again"))) {
15421 ast_copy_string(vm_pls_try_again, val, sizeof(vm_pls_try_again));
15422 }
15423 if ((val = ast_variable_retrieve(cfg, "general", "vm-prepend-timeout"))) {
15424 ast_copy_string(vm_prepend_timeout, val, sizeof(vm_prepend_timeout));
15425 }
15426 /* load configurable audio prompts */
15427 if ((val = ast_variable_retrieve(cfg, "general", "listen-control-forward-key")) && is_valid_dtmf(val))
15428 ast_copy_string(listen_control_forward_key, val, sizeof(listen_control_forward_key));
15429 if ((val = ast_variable_retrieve(cfg, "general", "listen-control-reverse-key")) && is_valid_dtmf(val))
15430 ast_copy_string(listen_control_reverse_key, val, sizeof(listen_control_reverse_key));
15431 if ((val = ast_variable_retrieve(cfg, "general", "listen-control-pause-key")) && is_valid_dtmf(val))
15432 ast_copy_string(listen_control_pause_key, val, sizeof(listen_control_pause_key));
15433 if ((val = ast_variable_retrieve(cfg, "general", "listen-control-restart-key")) && is_valid_dtmf(val))
15434 ast_copy_string(listen_control_restart_key, val, sizeof(listen_control_restart_key));
15435 if ((val = ast_variable_retrieve(cfg, "general", "listen-control-stop-key")) && is_valid_dtmf(val))
15436 ast_copy_string(listen_control_stop_key, val, sizeof(listen_control_stop_key));
15437
15438 if (!(val = ast_variable_retrieve(cfg, "general", "usedirectory")))
15439 val = "no";
15440 ast_set2_flag((&globalflags), ast_true(val), VM_DIRECTFORWARD);
15441
15442 if (!(val = ast_variable_retrieve(cfg, "general", "passwordlocation"))) {
15443 val = "voicemail.conf";
15444 }
15445 if (!(strcmp(val, "spooldir"))) {
15446 passwordlocation = OPT_PWLOC_SPOOLDIR;
15447 } else {
15448 passwordlocation = OPT_PWLOC_VOICEMAILCONF;
15449 }
15450
15451 poll_freq = DEFAULT_POLL_FREQ;
15452 if ((val = ast_variable_retrieve(cfg, "general", "pollfreq"))) {
15453 if (sscanf(val, "%30u", &poll_freq) != 1) {
15454 poll_freq = DEFAULT_POLL_FREQ;
15455 ast_log(AST_LOG_ERROR, "'%s' is not a valid value for the pollfreq option!\n", val);
15456 }
15457 }
15458
15459 poll_mailboxes = 0;
15460 if ((val = ast_variable_retrieve(cfg, "general", "pollmailboxes")))
15461 poll_mailboxes = ast_true(val);
15462
15463 memset(fromstring, 0, sizeof(fromstring));
15464 memset(pagerfromstring, 0, sizeof(pagerfromstring));
15465 strcpy(charset, "ISO-8859-1");
15466 if (emailbody) {
15467 ast_free(emailbody);
15468 emailbody = NULL;
15469 }
15470 if (emailsubject) {
15471 ast_free(emailsubject);
15472 emailsubject = NULL;
15473 }
15474 if (pagerbody) {
15475 ast_free(pagerbody);
15476 pagerbody = NULL;
15477 }
15478 if (pagersubject) {
15479 ast_free(pagersubject);
15480 pagersubject = NULL;
15481 }
15482 if ((val = ast_variable_retrieve(cfg, "general", "pbxskip")))
15483 ast_set2_flag((&globalflags), ast_true(val), VM_PBXSKIP);
15484 if ((val = ast_variable_retrieve(cfg, "general", "fromstring")))
15485 ast_copy_string(fromstring, val, sizeof(fromstring));
15486 if ((val = ast_variable_retrieve(cfg, "general", "pagerfromstring")))
15487 ast_copy_string(pagerfromstring, val, sizeof(pagerfromstring));
15488 if ((val = ast_variable_retrieve(cfg, "general", "charset")))
15489 ast_copy_string(charset, val, sizeof(charset));
15490 if ((val = ast_variable_retrieve(cfg, "general", "adsifdn"))) {
15491 sscanf(val, "%2x%2x%2x%2x", &tmpadsi[0], &tmpadsi[1], &tmpadsi[2], &tmpadsi[3]);
15492 for (x = 0; x < 4; x++) {
15493 memcpy(&adsifdn[x], &tmpadsi[x], 1);
15494 }
15495 }
15496 if ((val = ast_variable_retrieve(cfg, "general", "adsisec"))) {
15497 sscanf(val, "%2x%2x%2x%2x", &tmpadsi[0], &tmpadsi[1], &tmpadsi[2], &tmpadsi[3]);
15498 for (x = 0; x < 4; x++) {
15499 memcpy(&adsisec[x], &tmpadsi[x], 1);
15500 }
15501 }
15502 if ((val = ast_variable_retrieve(cfg, "general", "adsiver"))) {
15503 if (atoi(val)) {
15504 adsiver = atoi(val);
15505 }
15506 }
15507 if ((val = ast_variable_retrieve(cfg, "general", "tz"))) {
15508 ast_copy_string(zonetag, val, sizeof(zonetag));
15509 }
15510 if ((val = ast_variable_retrieve(cfg, "general", "locale"))) {
15511 ast_copy_string(locale, val, sizeof(locale));
15512 }
15513 if ((val = ast_variable_retrieve(cfg, "general", "emailsubject"))) {
15514 emailsubject = ast_strdup(substitute_escapes(val));
15515 }
15516 if ((val = ast_variable_retrieve(cfg, "general", "emailbody"))) {
15517 emailbody = ast_strdup(substitute_escapes(val));
15518 }
15519 if ((val = ast_variable_retrieve(cfg, "general", "pagersubject"))) {
15520 pagersubject = ast_strdup(substitute_escapes(val));
15521 }
15522 if ((val = ast_variable_retrieve(cfg, "general", "pagerbody"))) {
15523 pagerbody = ast_strdup(substitute_escapes(val));
15524 }
15525
15526 tps_queue_high = AST_TASKPROCESSOR_HIGH_WATER_LEVEL;
15527 if ((val = ast_variable_retrieve(cfg, "general", "tps_queue_high"))) {
15528 if (sscanf(val, "%30ld", &tps_queue_high) != 1 || tps_queue_high <= 0) {
15529 ast_log(AST_LOG_WARNING, "Invalid the taskprocessor high water alert trigger level '%s'\n", val);
15530 tps_queue_high = AST_TASKPROCESSOR_HIGH_WATER_LEVEL;
15531 }
15532 }
15533 tps_queue_low = -1;
15534 if ((val = ast_variable_retrieve(cfg, "general", "tps_queue_low"))) {
15535 if (sscanf(val, "%30ld", &tps_queue_low) != 1 ||
15536 tps_queue_low < -1 || tps_queue_high < tps_queue_low) {
15537 ast_log(AST_LOG_WARNING, "Invalid the taskprocessor low water clear alert level '%s'\n", val);
15538 tps_queue_low = -1;
15539 }
15540 }
15541 if (ast_taskprocessor_alert_set_levels(mwi_subscription_tps, tps_queue_low, tps_queue_high)) {
15542 ast_log(AST_LOG_WARNING, "Failed to set alert levels for voicemail taskprocessor.\n");
15543 }
15544
15545 /* load mailboxes from users.conf */
15546 if (ucfg) {
15547 for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
15548 if (!strcasecmp(cat, "general")) {
15549 continue;
15550 }
15551 if (!ast_true(ast_config_option(ucfg, cat, "hasvoicemail")))
15552 continue;
15553 if ((current = find_or_create(userscontext, cat))) {
15554 populate_defaults(current);
15555 apply_options_full(current, ast_variable_browse(ucfg, cat));
15556 ast_copy_string(current->context, userscontext, sizeof(current->context));
15557 if (!ast_strlen_zero(current->password) && current->passwordlocation == OPT_PWLOC_VOICEMAILCONF) {
15558 current->passwordlocation = OPT_PWLOC_USERSCONF;
15559 }
15560
15561 switch (current->passwordlocation) {
15562 case OPT_PWLOC_SPOOLDIR:
15563 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, current->context, current->mailbox);
15564 read_password_from_file(secretfn, current->password, sizeof(current->password));
15565 }
15566 }
15567 }
15568 }
15569
15570 /* load mailboxes from voicemail.conf */
15571
15572 /*
15573 * Aliases must be loaded before users or the aliases won't be notified
15574 * if there's existing voicemail in the user mailbox.
15575 */
15576 load_aliases(cfg);
15577
15578 load_zonemessages(cfg);
15579
15580 load_users(cfg);
15581
15582 AST_LIST_UNLOCK(&users);
15583
15584 if (poll_mailboxes && poll_thread == AST_PTHREADT_NULL)
15585 start_poll_thread();
15586 if (!poll_mailboxes && poll_thread != AST_PTHREADT_NULL)
15587 stop_poll_thread();;
15588
15589 return 0;
15590 } else {
15591 AST_LIST_UNLOCK(&users);
15592 ast_log(AST_LOG_WARNING, "Failed to load configuration file.\n");
15593 return 0;
15594 }
15595 }
15596
15597 static int sayname(struct ast_channel *chan, const char *mailbox, const char *context)
15598 {
15599 int res = -1;
15600 char dir[PATH_MAX];
15601 snprintf(dir, sizeof(dir), "%s%s/%s/greet", VM_SPOOL_DIR, context, mailbox);
15602 ast_debug(2, "About to try retrieving name file %s\n", dir);
15603 RETRIEVE(dir, -1, mailbox, context);
15604 if (ast_fileexists(dir, NULL, NULL)) {
15605 res = ast_stream_and_wait(chan, dir, AST_DIGIT_ANY);
15606 }
15607 DISPOSE(dir, -1);
15608 return res;
15609 }
15610
15611 /*!
15612 * \internal
15613 * \brief Play a recorded user name for the mailbox to the specified channel.
15614 *
15615 * \param chan Where to play the recorded name file.
15616 * \param mailbox_id The mailbox name.
15617 *
15618 * \retval 0 Name played without interruption
15619 * \retval dtmf ASCII value of the DTMF which interrupted playback.
15620 * \retval -1 Unable to locate mailbox or hangup occurred.
15621 */
15622 static int vm_sayname(struct ast_channel *chan, const char *mailbox_id)
15623 {
15624 char *context;
15625 char *mailbox;
15626
15627 if (ast_strlen_zero(mailbox_id)
15628 || separate_mailbox(ast_strdupa(mailbox_id), &mailbox, &context)) {
15629 return -1;
15630 }
15631 return sayname(chan, mailbox, context);
15632 }
15633
15634 static void read_password_from_file(const char *secretfn, char *password, int passwordlen) {
15635 struct ast_config *pwconf;
15636 struct ast_flags config_flags = { 0 };
15637
15638 pwconf = ast_config_load(secretfn, config_flags);
15639 if (valid_config(pwconf)) {
15640 const char *val = ast_variable_retrieve(pwconf, "general", "password");
15641 if (val) {
15642 ast_copy_string(password, val, passwordlen);
15643 ast_config_destroy(pwconf);
15644 return;
15645 }
15646 ast_config_destroy(pwconf);
15647 }
15648 ast_log(LOG_NOTICE, "Failed reading voicemail password from %s, using secret from config file\n", secretfn);
15649 }
15650
15651 static int write_password_to_file(const char *secretfn, const char *password) {
15652 struct ast_config *conf;
15653 struct ast_category *cat;
15654 struct ast_variable *var;
15655 int res = -1;
15656
15657 if (!(conf = ast_config_new())) {
15658 ast_log(LOG_ERROR, "Error creating new config structure\n");
15659 return res;
15660 }
15661 if (!(cat = ast_category_new("general", "", 1))) {
15662 ast_log(LOG_ERROR, "Error creating new category structure\n");
15663 ast_config_destroy(conf);
15664 return res;
15665 }
15666 if (!(var = ast_variable_new("password", password, ""))) {
15667 ast_log(LOG_ERROR, "Error creating new variable structure\n");
15668 ast_config_destroy(conf);
15669 ast_category_destroy(cat);
15670 return res;
15671 }
15672 ast_category_append(conf, cat);
15673 ast_variable_append(cat, var);
15674 if (!ast_config_text_file_save(secretfn, conf, "app_voicemail")) {
15675 res = 0;
15676 } else {
15677 ast_log(LOG_ERROR, "Error writing voicemail password to %s\n", secretfn);
15678 }
15679
15680 ast_config_destroy(conf);
15681 return res;
15682 }
15683
15684 static int vmsayname_exec(struct ast_channel *chan, const char *data)
15685 {
15686 char *context;
15687 char *mailbox;
15688 int res;
15689
15690 if (ast_strlen_zero(data)
15691 || separate_mailbox(ast_strdupa(data), &mailbox, &context)) {
15692 ast_log(LOG_WARNING, "VMSayName requires argument mailbox@context\n");
15693 return -1;
15694 }
15695
15696 if ((res = sayname(chan, mailbox, context)) < 0) {
15697 ast_debug(3, "Greeting not found for '%s@%s', falling back to mailbox number.\n", mailbox, context);
15698 res = ast_stream_and_wait(chan, "vm-extension", AST_DIGIT_ANY);
15699 if (!res) {
15700 res = ast_say_character_str(chan, mailbox, AST_DIGIT_ANY, ast_channel_language(chan), AST_SAY_CASE_NONE);
15701 }
15702 }
15703
15704 return res;
15705 }
15706
15707 #ifdef TEST_FRAMEWORK
15708 static int fake_write(struct ast_channel *ast, struct ast_frame *frame)
15709 {
15710 return 0;
15711 }
15712
15713 static struct ast_frame *fake_read(struct ast_channel *ast)
15714 {
15715 return &ast_null_frame;
15716 }
15717
15718 AST_TEST_DEFINE(test_voicemail_vmsayname)
15719 {
15720 char dir[PATH_MAX];
15721 char dir2[PATH_MAX];
15722 static const char TEST_CONTEXT[] = "very_long_unique_context_so_that_nobody_will_ever_have_the_same_one_configured_3141592653";
15723 static const char TEST_EXTENSION[] = "1234";
15724
15725 struct ast_channel *test_channel1 = NULL;
15726 int res = -1;
15727 struct ast_format_cap *capabilities;
15728
15729 static const struct ast_channel_tech fake_tech = {
15730 .write = fake_write,
15731 .read = fake_read,
15732 };
15733
15734 switch (cmd) {
15735 case TEST_INIT:
15736 info->name = "vmsayname_exec";
15737 info->category = "/apps/app_voicemail/";
15738 info->summary = "Vmsayname unit test";
15739 info->description =
15740 "This tests passing various parameters to vmsayname";
15741 return AST_TEST_NOT_RUN;
15742 case TEST_EXECUTE:
15743 break;
15744 }
15745
15746 if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, NULL,
15747 NULL, NULL, 0, 0, "TestChannel1"))) {
15748 goto exit_vmsayname_test;
15749 }
15750
15751 /* normally this is done in the channel driver */
15752 capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
15753 if (!capabilities) {
15754 goto exit_vmsayname_test;
15755 }
15756 ast_format_cap_append(capabilities, ast_format_gsm, 0);
15757 ast_channel_nativeformats_set(test_channel1, capabilities);
15758 ao2_ref(capabilities, -1);
15759 ast_channel_set_writeformat(test_channel1, ast_format_gsm);
15760 ast_channel_set_rawwriteformat(test_channel1, ast_format_gsm);
15761 ast_channel_set_readformat(test_channel1, ast_format_gsm);
15762 ast_channel_set_rawreadformat(test_channel1, ast_format_gsm);
15763 ast_channel_tech_set(test_channel1, &fake_tech);
15764
15765 ast_channel_unlock(test_channel1);
15766
15767 ast_test_status_update(test, "Test playing of extension when greeting is not available...\n");
15768 snprintf(dir, sizeof(dir), "%s@%s", TEST_EXTENSION, TEST_CONTEXT); /* not a dir, don't get confused */
15769 if (!(res = vmsayname_exec(test_channel1, dir))) {
15770 snprintf(dir, sizeof(dir), "%s%s/%s/greet", VM_SPOOL_DIR, TEST_CONTEXT, TEST_EXTENSION);
15771 if (ast_fileexists(dir, NULL, NULL)) {
15772 ast_test_status_update(test, "This should not happen, most likely means clean up from previous test failed\n");
15773 res = -1;
15774 goto exit_vmsayname_test;
15775 } else {
15776 /* no greeting already exists as expected, let's create one to fully test sayname */
15777 if ((res = create_dirpath(dir, sizeof(dir), TEST_CONTEXT, TEST_EXTENSION, ""))) {
15778 ast_log(AST_LOG_WARNING, "Failed to make test directory\n");
15779 goto exit_vmsayname_test;
15780 }
15781 snprintf(dir, sizeof(dir), "%s/sounds/beep.gsm", ast_config_AST_DATA_DIR);
15782 snprintf(dir2, sizeof(dir2), "%s%s/%s/greet.gsm", VM_SPOOL_DIR, TEST_CONTEXT, TEST_EXTENSION);
15783 /* we're not going to hear the sound anyway, just use a valid gsm audio file */
15784 if ((res = symlink(dir, dir2))) {
15785 ast_log(LOG_WARNING, "Symlink reported %s\n", strerror(errno));
15786 goto exit_vmsayname_test;
15787 }
15788 ast_test_status_update(test, "Test playing created mailbox greeting...\n");
15789 snprintf(dir, sizeof(dir), "%s@%s", TEST_EXTENSION, TEST_CONTEXT); /* not a dir, don't get confused */
15790 res = vmsayname_exec(test_channel1, dir);
15791
15792 /* TODO: there may be a better way to do this */
15793 unlink(dir2);
15794 snprintf(dir2, sizeof(dir2), "%s%s/%s", VM_SPOOL_DIR, TEST_CONTEXT, TEST_EXTENSION);
15795 rmdir(dir2);
15796 snprintf(dir2, sizeof(dir2), "%s%s", VM_SPOOL_DIR, TEST_CONTEXT);
15797 rmdir(dir2);
15798 }
15799 }
15800
15801 exit_vmsayname_test:
15802
15803 ast_hangup(test_channel1);
15804
15805 return res ? AST_TEST_FAIL : AST_TEST_PASS;
15806 }
15807
15808 struct test_files {
15809 char dir[256];
15810 char file[256];
15811 char txtfile[256];
15812 };
15813
15814 AST_TEST_DEFINE(test_voicemail_msgcount)
15815 {
15816 int i, j, res = AST_TEST_PASS, syserr;
15817 struct ast_vm_user *vmu;
15818 struct ast_vm_user svm;
15819 struct vm_state vms;
15820 #ifdef IMAP_STORAGE
15821 struct ast_channel *chan = NULL;
15822 #endif
15823 /* Using ast_alloca instead of just declaring tmp as an array is a workaround for a GCC 10 issue with -Wrestrict */
15824 struct test_files *tmp = ast_alloca(sizeof(struct test_files) * 3);
15825 char syscmd[256];
15826 const char origweasels[] = "tt-weasels";
15827 const char testcontext[] = "test";
15828 const char testmailbox[] = "00000000";
15829 const char testspec[] = "00000000@test";
15830 FILE *txt;
15831 int new, old, urgent;
15832 const char *folders[3] = { "Old", "Urgent", "INBOX" };
15833 const int folder2mbox[3] = { 1, 11, 0 };
15834 const int expected_results[3][12] = {
15835 /* hasvm-old, hasvm-urgent, hasvm-new, ic-old, ic-urgent, ic-new, ic2-old, ic2-urgent, ic2-new, mc-old, mc-urgent, mc-new */
15836 { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 },
15837 { 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 },
15838 { 1, 1, 1, 1, 0, 2, 1, 1, 1, 1, 1, 2 },
15839 };
15840
15841 switch (cmd) {
15842 case TEST_INIT:
15843 info->name = "test_voicemail_msgcount";
15844 info->category = "/apps/app_voicemail/";
15845 info->summary = "Test Voicemail status checks";
15846 info->description =
15847 "Verify that message counts are correct when retrieved through the public API";
15848 return AST_TEST_NOT_RUN;
15849 case TEST_EXECUTE:
15850 break;
15851 }
15852
15853 /* Make sure the original path was completely empty */
15854 snprintf(syscmd, sizeof(syscmd), "rm -rf \"%s%s/%s\"", VM_SPOOL_DIR, testcontext, testmailbox);
15855 if ((syserr = ast_safe_system(syscmd))) {
15856 ast_test_status_update(test, "Unable to clear test directory: %s\n",
15857 syserr > 0 ? strerror(syserr) : "unable to fork()");
15858 return AST_TEST_FAIL;
15859 }
15860
15861 #ifdef IMAP_STORAGE
15862 if (!(chan = ast_dummy_channel_alloc())) {
15863 ast_test_status_update(test, "Unable to create dummy channel\n");
15864 return AST_TEST_FAIL;
15865 }
15866 #endif
15867
15868 memset(&svm, 0, sizeof(svm));
15869 if (!(vmu = find_user(&svm, testcontext, testmailbox)) &&
15870 !(vmu = find_or_create(testcontext, testmailbox))) {
15871 ast_test_status_update(test, "Cannot create vmu structure\n");
15872 #ifdef IMAP_STORAGE
15873 chan = ast_channel_unref(chan);
15874 #endif
15875 return AST_TEST_FAIL;
15876 }
15877
15878 populate_defaults(vmu);
15879 memset(&vms, 0, sizeof(vms));
15880
15881 /* Create temporary voicemail */
15882 for (i = 0; i < 3; i++) {
15883 create_dirpath(tmp[i].dir, sizeof(tmp[i].dir), testcontext, testmailbox, folders[i]);
15884 make_file(tmp[i].file, sizeof(tmp[i].file), tmp[i].dir, 0);
15885 snprintf(tmp[i].txtfile, sizeof(tmp[i].txtfile), "%s.txt", tmp[i].file);
15886
15887 if (ast_fileexists(origweasels, "gsm", "en") > 0) {
15888 snprintf(syscmd, sizeof(syscmd), "cp \"%s/sounds/en/%s.gsm\" \"%s/%s/%s/%s/msg0000.gsm\"", ast_config_AST_DATA_DIR, origweasels,
15889 VM_SPOOL_DIR, testcontext, testmailbox, folders[i]);
15890 if ((syserr = ast_safe_system(syscmd))) {
15891 ast_test_status_update(test, "Unable to create test voicemail: %s\n",
15892 syserr > 0 ? strerror(syserr) : "unable to fork()");
15893 #ifdef IMAP_STORAGE
15894 chan = ast_channel_unref(chan);
15895 #endif
15896 free_user(vmu);
15897 return AST_TEST_FAIL;
15898 }
15899 }
15900
15901 if ((txt = fopen(tmp[i].txtfile, "w+"))) {
15902 fprintf(txt, "; just a stub\n[message]\nflag=%s\n", strcmp(folders[i], "Urgent") ? "" : "Urgent");
15903 fclose(txt);
15904 } else {
15905 ast_test_status_update(test, "Unable to write message file '%s'\n", tmp[i].txtfile);
15906 res = AST_TEST_FAIL;
15907 break;
15908 }
15909 open_mailbox(&vms, vmu, folder2mbox[i]);
15910 STORE(tmp[i].dir, testmailbox, testcontext, 0, chan, vmu, "gsm", 600, &vms, strcmp(folders[i], "Urgent") ? "" : "Urgent", NULL);
15911
15912 /* hasvm-old, hasvm-urgent, hasvm-new, ic-old, ic-urgent, ic-new, ic2-old, ic2-urgent, ic2-new, mc-old, mc-urgent, mc-new */
15913 for (j = 0; j < 3; j++) {
15914 /* folder[2] is INBOX, __has_voicemail will default back to INBOX */
15915 if (ast_app_has_voicemail(testspec, (j==2 ? NULL : folders[j])) != expected_results[i][0 + j]) {
15916 ast_test_status_update(test, "has_voicemail(%s, %s) returned %d and we expected %d\n",
15917 testspec, folders[j], ast_app_has_voicemail(testspec, folders[j]), expected_results[i][0 + j]);
15918 res = AST_TEST_FAIL;
15919 }
15920 }
15921
15922 new = old = urgent = 0;
15923 if (ast_app_inboxcount(testspec, &new, &old)) {
15924 ast_test_status_update(test, "inboxcount returned failure\n");
15925 res = AST_TEST_FAIL;
15926 } else if (old != expected_results[i][3 + 0] || new != expected_results[i][3 + 2]) {
15927 ast_test_status_update(test, "inboxcount(%s) returned old=%d (expected %d) and new=%d (expected %d)\n",
15928 testspec, old, expected_results[i][3 + 0], new, expected_results[i][3 + 2]);
15929 res = AST_TEST_FAIL;
15930 }
15931
15932 new = old = urgent = 0;
15933 if (ast_app_inboxcount2(testspec, &urgent, &new, &old)) {
15934 ast_test_status_update(test, "inboxcount2 returned failure\n");
15935 res = AST_TEST_FAIL;
15936 } else if (old != expected_results[i][6 + 0] ||
15937 urgent != expected_results[i][6 + 1] ||
15938 new != expected_results[i][6 + 2] ) {
15939 ast_test_status_update(test, "inboxcount2(%s) returned old=%d (expected %d), urgent=%d (expected %d), and new=%d (expected %d)\n",
15940 testspec, old, expected_results[i][6 + 0], urgent, expected_results[i][6 + 1], new, expected_results[i][6 + 2]);
15941 res = AST_TEST_FAIL;
15942 }
15943
15944 new = old = urgent = 0;
15945 for (j = 0; j < 3; j++) {
15946 if (ast_app_messagecount(testspec, folders[j]) != expected_results[i][9 + j]) {
15947 ast_test_status_update(test, "messagecount(%s, %s) returned %d and we expected %d\n",
15948 testspec, folders[j], ast_app_messagecount(testspec, folders[j]), expected_results[i][9 + j]);
15949 res = AST_TEST_FAIL;
15950 }
15951 }
15952 }
15953
15954 for (i = 0; i < 3; i++) {
15955 /* This is necessary if the voicemails are stored on an ODBC/IMAP
15956 * server, in which case, the rm below will not affect the
15957 * voicemails. */
15958 DELETE(tmp[i].dir, 0, tmp[i].file, vmu);
15959 DISPOSE(tmp[i].dir, 0);
15960 }
15961
15962 if (vms.deleted) {
15963 ast_free(vms.deleted);
15964 }
15965 if (vms.heard) {
15966 ast_free(vms.heard);
15967 }
15968
15969 #ifdef IMAP_STORAGE
15970 chan = ast_channel_unref(chan);
15971 #endif
15972
15973 /* And remove test directory */
15974 snprintf(syscmd, sizeof(syscmd), "rm -rf \"%s%s/%s\"", VM_SPOOL_DIR, testcontext, testmailbox);
15975 if ((syserr = ast_safe_system(syscmd))) {
15976 ast_test_status_update(test, "Unable to clear test directory: %s\n",
15977 syserr > 0 ? strerror(syserr) : "unable to fork()");
15978 }
15979
15980 free_user(vmu);
15981 force_reload_config(); /* Restore original config */
15982 return res;
15983 }
15984
15985 AST_TEST_DEFINE(test_voicemail_notify_endl)
15986 {
15987 int res = AST_TEST_PASS;
15988 char testcontext[] = "test";
15989 char testmailbox[] = "00000000";
15990 char from[] = "[email protected]", cidnum[] = "1234", cidname[] = "Mark Spencer", format[] = "gsm";
15991 char attach[256], attach2[256];
15992 char buf[256] = ""; /* No line should actually be longer than 80 */
15993 struct ast_channel *chan = NULL;
15994 struct ast_vm_user *vmu, vmus = {
15995 .flags = 0,
15996 };
15997 FILE *file;
15998 struct {
15999 char *name;
16000 enum { INT, FLAGVAL, STATIC, STRPTR } type;
16001 void *location;
16002 union {
16003 int intval;
16004 char *strval;
16005 } u;
16006 } test_items[] = {
16007 { "plain jane config", STATIC, vmus.password, .u.strval = "1234" }, /* No, this doesn't change this test any. */
16008 { "emailsubject", STRPTR, vmus.emailsubject, .u.strval = "Oogly boogly\xf8koogly with what appears to be UTF-8" },
16009 { "emailbody", STRPTR, vmus.emailbody, .u.strval = "This is a test\n\twith multiple\nlines\nwithin\n" },
16010 { "serveremail", STATIC, vmus.serveremail, .u.strval = "\"\xf8Something\xe8that\xd8seems to have UTF-8 chars\" <[email protected]>" },
16011 { "attachment flag", FLAGVAL, &vmus.flags, .u.intval = VM_ATTACH },
16012 { "attach2", STRPTR, attach2, .u.strval = "" },
16013 { "attach", STRPTR, attach, .u.strval = "" },
16014 };
16015 int which;
16016
16017 switch (cmd) {
16018 case TEST_INIT:
16019 info->name = "test_voicemail_notify_endl";
16020 info->category = "/apps/app_voicemail/";
16021 info->summary = "Test Voicemail notification end-of-line";
16022 info->description =
16023 "Verify that notification emails use a consistent end-of-line character";
16024 return AST_TEST_NOT_RUN;
16025 case TEST_EXECUTE:
16026 break;
16027 }
16028
16029 snprintf(attach, sizeof(attach), "%s/sounds/en/tt-weasels", ast_config_AST_DATA_DIR);
16030 snprintf(attach2, sizeof(attach2), "%s/sounds/en/tt-somethingwrong", ast_config_AST_DATA_DIR);
16031
16032 if (!(vmu = find_user(&vmus, testcontext, testmailbox)) &&
16033 !(vmu = find_or_create(testcontext, testmailbox))) {
16034 ast_test_status_update(test, "Cannot create vmu structure\n");
16035 return AST_TEST_NOT_RUN;
16036 }
16037
16038 if (vmu != &vmus && !(vmu = find_user(&vmus, testcontext, testmailbox))) {
16039 ast_test_status_update(test, "Cannot find vmu structure?!!\n");
16040 return AST_TEST_NOT_RUN;
16041 }
16042
16043 populate_defaults(vmu);
16044 vmu->email = ast_strdup("[email protected]");
16045 #ifdef IMAP_STORAGE
16046 /* TODO When we set up the IMAP server test, we'll need to have credentials for the VMU structure added here */
16047 #endif
16048
16049 file = tmpfile();
16050 for (which = 0; which < ARRAY_LEN(test_items); which++) {
16051 /* Kill previous test, if any */
16052 rewind(file);
16053 if (ftruncate(fileno(file), 0)) {
16054 ast_test_status_update(test, "Cannot truncate test output file: %s\n", strerror(errno));
16055 res = AST_TEST_FAIL;
16056 break;
16057 }
16058
16059 /* Make each change, in order, to the test mailbox */
16060 if (test_items[which].type == INT) {
16061 *((int *) test_items[which].location) = test_items[which].u.intval;
16062 } else if (test_items[which].type == FLAGVAL) {
16063 if (ast_test_flag(vmu, test_items[which].u.intval)) {
16064 ast_clear_flag(vmu, test_items[which].u.intval);
16065 } else {
16066 ast_set_flag(vmu, test_items[which].u.intval);
16067 }
16068 } else if (test_items[which].type == STATIC) {
16069 strcpy(test_items[which].location, test_items[which].u.strval);
16070 } else if (test_items[which].type == STRPTR) {
16071 test_items[which].location = test_items[which].u.strval;
16072 }
16073
16074 make_email_file(file, from, vmu, 0, testcontext, testmailbox, "INBOX", cidnum, cidname, attach, attach2, format, 999, 1, chan, NULL, 0, NULL, NULL);
16075 rewind(file);
16076 while (fgets(buf, sizeof(buf), file)) {
16077 if (
16078 (strlen(buf) > 1 &&
16079 #ifdef IMAP_STORAGE
16080 buf[strlen(buf) - 2] != '\r'
16081 #else
16082 buf[strlen(buf) - 2] == '\r'
16083 #endif
16084 )
16085 || buf[strlen(buf) - 1] != '\n') {
16086 res = AST_TEST_FAIL;
16087 }
16088 }
16089 }
16090 fclose(file);
16091 free_user(vmu);
16092 force_reload_config(); /* Restore original config */
16093 return res;
16094 }
16095
16096 AST_TEST_DEFINE(test_voicemail_load_config)
16097 {
16098 int res = AST_TEST_PASS;
16099 struct ast_vm_user *vmu;
16100 struct ast_config *cfg;
16101 char config_filename[32] = "/tmp/voicemail.conf.XXXXXX";
16102 int fd;
16103 FILE *file;
16104 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
16105
16106 switch (cmd) {
16107 case TEST_INIT:
16108 info->name = "test_voicemail_load_config";
16109 info->category = "/apps/app_voicemail/";
16110 info->summary = "Test loading Voicemail config";
16111 info->description =
16112 "Verify that configuration is loaded consistently. "
16113 "This is to test regressions of ASTERISK-18838 where it was noticed that "
16114 "some options were loaded after the mailboxes were instantiated, causing "
16115 "those options not to be set correctly.";
16116 return AST_TEST_NOT_RUN;
16117 case TEST_EXECUTE:
16118 break;
16119 }
16120
16121 /* build a config file by hand... */
16122 if ((fd = mkstemp(config_filename)) < 0) {
16123 return AST_TEST_FAIL;
16124 }
16125 if (!(file = fdopen(fd, "w"))) {
16126 close(fd);
16127 unlink(config_filename);
16128 return AST_TEST_FAIL;
16129 }
16130 fputs("[general]\ncallback=somecontext\nlocale=de_DE.UTF-8\ntz=european\n[test]", file);
16131 fputs("00000001 => 9999,Mr. Test,,,callback=othercontext|locale=nl_NL.UTF-8|tz=central\n", file);
16132 fputs("00000002 => 9999,Mrs. Test\n", file);
16133 fclose(file);
16134
16135 if (!(cfg = ast_config_load(config_filename, config_flags)) || !valid_config(cfg)) {
16136 res = AST_TEST_FAIL;
16137 goto cleanup;
16138 }
16139
16140 load_config_from_memory(1, cfg, NULL);
16141 ast_config_destroy(cfg);
16142
16143 #define CHECK(u, attr, value) else if (strcmp(u->attr, value)) { \
16144 ast_test_status_update(test, "mailbox %s should have %s '%s', but has '%s'\n", \
16145 u->mailbox, #attr, value, u->attr); res = AST_TEST_FAIL; break; }
16146
16147 AST_LIST_LOCK(&users);
16148 AST_LIST_TRAVERSE(&users, vmu, list) {
16149 if (!strcmp(vmu->mailbox, "00000001")) {
16150 if (0); /* trick to get CHECK to work */
16151 CHECK(vmu, callback, "othercontext")
16152 CHECK(vmu, locale, "nl_NL.UTF-8")
16153 CHECK(vmu, zonetag, "central")
16154 } else if (!strcmp(vmu->mailbox, "00000002")) {
16155 if (0); /* trick to get CHECK to work */
16156 CHECK(vmu, callback, "somecontext")
16157 CHECK(vmu, locale, "de_DE.UTF-8")
16158 CHECK(vmu, zonetag, "european")
16159 }
16160 }
16161 AST_LIST_UNLOCK(&users);
16162
16163 #undef CHECK
16164
16165 /* Forcibly restore the original config, to reinitialize after test */
16166 force_reload_config(); /* this might say "Failed to load configuration file." */
16167
16168 cleanup:
16169 unlink(config_filename);
16170 return res;
16171 }
16172
16173 AST_TEST_DEFINE(test_voicemail_vm_info)
16174 {
16175 struct ast_vm_user *vmu;
16176 struct ast_channel *chan = NULL;
16177 const char testcontext[] = "test";
16178 const char testmailbox[] = "00000000";
16179 const char vminfo_cmd[] = "VM_INFO";
16180 char vminfo_buf[256], vminfo_args[256];
16181 int res = AST_TEST_PASS;
16182 int test_ret = 0;
16183 int test_counter = 0;
16184
16185 struct {
16186 char *vminfo_test_args;
16187 char *vminfo_expected;
16188 int vminfo_ret;
16189 } test_items[] = {
16190 { "", "", -1 }, /* Missing argument */
16191 { "00000000@test,badparam", "", -1 }, /* Wrong argument */
16192 { "00000000@test", "", -1 }, /* Missing argument */
16193 { "00000000@test,exists", "1", 0 },
16194 { "11111111@test,exists", "0", 0 }, /* Invalid mailbox */
16195 { "00000000@test,email", "[email protected]", 0 },
16196 { "11111111@test,email", "", 0 }, /* Invalid mailbox */
16197 { "00000000@test,fullname", "Test Framework Mailbox", 0 },
16198 { "00000000@test,pager", "[email protected]", 0 },
16199 { "00000000@test,locale", "en_US", 0 },
16200 { "00000000@test,tz", "central", 0 },
16201 { "00000000@test,language", "en", 0 },
16202 { "00000000@test,password", "9876", 0 },
16203 };
16204
16205 switch (cmd) {
16206 case TEST_INIT:
16207 info->name = "test_voicemail_vm_info";
16208 info->category = "/apps/app_voicemail/";
16209 info->summary = "VM_INFO unit test";
16210 info->description =
16211 "This tests passing various parameters to VM_INFO";
16212 return AST_TEST_NOT_RUN;
16213 case TEST_EXECUTE:
16214 break;
16215 }
16216
16217 if (!(chan = ast_dummy_channel_alloc())) {
16218 ast_test_status_update(test, "Unable to create dummy channel\n");
16219 return AST_TEST_FAIL;
16220 }
16221
16222 if (!(vmu = find_user(NULL, testcontext, testmailbox)) &&
16223 !(vmu = find_or_create(testcontext, testmailbox))) {
16224 ast_test_status_update(test, "Cannot create vmu structure\n");
16225 chan = ast_channel_unref(chan);
16226 return AST_TEST_FAIL;
16227 }
16228
16229 populate_defaults(vmu);
16230
16231 vmu->email = ast_strdup("[email protected]");
16232 if (!vmu->email) {
16233 ast_test_status_update(test, "Cannot create vmu email\n");
16234 chan = ast_channel_unref(chan);
16235 return AST_TEST_FAIL;
16236 }
16237 ast_copy_string(vmu->fullname, "Test Framework Mailbox", sizeof(vmu->fullname));
16238 ast_copy_string(vmu->pager, "[email protected]", sizeof(vmu->pager));
16239 ast_copy_string(vmu->language, "en", sizeof(vmu->language));
16240 ast_copy_string(vmu->zonetag, "central", sizeof(vmu->zonetag));
16241 ast_copy_string(vmu->locale, "en_US", sizeof(vmu->zonetag));
16242 ast_copy_string(vmu->password, "9876", sizeof(vmu->password));
16243
16244 for (test_counter = 0; test_counter < ARRAY_LEN(test_items); test_counter++) {
16245 ast_copy_string(vminfo_args, test_items[test_counter].vminfo_test_args, sizeof(vminfo_args));
16246 test_ret = acf_vm_info(chan, vminfo_cmd, vminfo_args, vminfo_buf, sizeof(vminfo_buf));
16247 if (strcmp(vminfo_buf, test_items[test_counter].vminfo_expected)) {
16248 ast_test_status_update(test, "VM_INFO response was: '%s', but expected: '%s'\n", vminfo_buf, test_items[test_counter].vminfo_expected);
16249 res = AST_TEST_FAIL;
16250 }
16251 if (!(test_ret == test_items[test_counter].vminfo_ret)) {
16252 ast_test_status_update(test, "VM_INFO return code was: '%i', but expected '%i'\n", test_ret, test_items[test_counter].vminfo_ret);
16253 res = AST_TEST_FAIL;
16254 }
16255 }
16256
16257 chan = ast_channel_unref(chan);
16258 free_user(vmu);
16259 return res;
16260 }
16261 #endif /* defined(TEST_FRAMEWORK) */
16262
16263 static const struct ast_vm_functions vm_table = {
16264 .module_version = VM_MODULE_VERSION,
16265 .module_name = AST_MODULE,
16266
16267 .has_voicemail = has_voicemail,
16268 .inboxcount = inboxcount,
16269 .inboxcount2 = inboxcount2,
16270 .messagecount = messagecount,
16271 .copy_recording_to_vm = msg_create_from_file,
16272 .index_to_foldername = vm_index_to_foldername,
16273 .mailbox_snapshot_create = vm_mailbox_snapshot_create,
16274 .mailbox_snapshot_destroy = vm_mailbox_snapshot_destroy,
16275 .msg_move = vm_msg_move,
16276 .msg_remove = vm_msg_remove,
16277 .msg_forward = vm_msg_forward,
16278 .msg_play = vm_msg_play,
16279 };
16280
16281 static const struct ast_vm_greeter_functions vm_greeter_table = {
16282 .module_version = VM_GREETER_MODULE_VERSION,
16283 .module_name = AST_MODULE,
16284
16285 .sayname = vm_sayname,
16286 };
16287
16288 static int reload(void)
16289 {
16290 return load_config(1);
16291 }
16292
16293 static int unload_module(void)
16294 {
16295 int res;
16296
16297 res = ast_unregister_application(voicemail_app);
16298 res |= ast_unregister_application(voicemailmain_app);
16299 res |= ast_unregister_application(vmauthenticate_app);
16300 res |= ast_unregister_application(playmsg_app);
16301 res |= ast_unregister_application(sayname_app);
16302 res |= ast_custom_function_unregister(&vm_info_acf);
16303 res |= ast_manager_unregister("VoicemailUsersList");
16304 res |= ast_manager_unregister("VoicemailUserStatus");
16305 res |= ast_manager_unregister("VoicemailRefresh");
16306 res |= ast_manager_unregister("VoicemailBoxSummary");
16307 res |= ast_manager_unregister("VoicemailMove");
16308 res |= ast_manager_unregister("VoicemailRemove");
16309 res |= ast_manager_unregister("VoicemailForward");
16310 #ifdef TEST_FRAMEWORK
16311 res |= AST_TEST_UNREGISTER(test_voicemail_vmsayname);
16312 res |= AST_TEST_UNREGISTER(test_voicemail_msgcount);
16313 res |= AST_TEST_UNREGISTER(test_voicemail_vmuser);
16314 res |= AST_TEST_UNREGISTER(test_voicemail_notify_endl);
16315 res |= AST_TEST_UNREGISTER(test_voicemail_load_config);
16316 res |= AST_TEST_UNREGISTER(test_voicemail_vm_info);
16317 #endif
16318 ast_cli_unregister_multiple(cli_voicemail, ARRAY_LEN(cli_voicemail));
16319 ast_vm_unregister(vm_table.module_name);
16320 ast_vm_greeter_unregister(vm_greeter_table.module_name);
16321 #ifdef TEST_FRAMEWORK
16322 ast_uninstall_vm_test_functions();
16323 #endif
16324 ao2_ref(inprocess_container, -1);
16325
16326 ao2_container_unregister("voicemail_alias_mailbox_mappings");
16327 ao2_cleanup(alias_mailbox_mappings);
16328 ao2_container_unregister("voicemail_mailbox_alias_mappings");
16329 ao2_cleanup(mailbox_alias_mappings);
16330
16331 if (poll_thread != AST_PTHREADT_NULL)
16332 stop_poll_thread();
16333
16334 mwi_subscription_tps = ast_taskprocessor_unreference(mwi_subscription_tps);
16335 ast_unload_realtime("voicemail");
16336 ast_unload_realtime("voicemail_data");
16337
16338 #ifdef IMAP_STORAGE
16339 ast_mwi_state_callback_all(imap_close_subscribed_mailbox, NULL);
16340 #endif
16341 free_vm_users();
16342 free_vm_zones();
16343 return res;
16344 }
16345
16346 static void print_mappings(void *v_obj, void *where, ao2_prnt_fn *prnt)
16347 {
16348 struct alias_mailbox_mapping *mapping = v_obj;
16349
16350 if (!mapping) {
16351 return;
16352 }
16353 prnt(where, "Alias: %s Mailbox: %s", mapping->alias, mapping->mailbox);
16354 }
16355
16356 /*!
16357 * \brief Load the module
16358 *
16359 * Module loading including tests for configuration or dependencies.
16360 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
16361 * or AST_MODULE_LOAD_SUCCESS.
16362 *
16363 * If a dependency, allocation or environment variable fails tests, return AST_MODULE_LOAD_FAILURE.
16364 *
16365 * If the module can't load the configuration file, can't register as a provider or
16366 * has another issue not fatal to Asterisk itself, return AST_MODULE_LOAD_DECLINE.
16367 *
16368 * On success return AST_MODULE_LOAD_SUCCESS.
16369 */
16370 static int load_module(void)
16371 {
16372 int res;
16373 my_umask = umask(0);
16374 umask(my_umask);
16375
16376 inprocess_container = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 573,
16377 inprocess_hash_fn, NULL, inprocess_cmp_fn);
16378 if (!inprocess_container) {
16379 return AST_MODULE_LOAD_DECLINE;
16380 }
16381
16382 alias_mailbox_mappings = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, MAPPING_BUCKETS,
16383 alias_mailbox_mapping_hash_fn, NULL, alias_mailbox_mapping_cmp_fn);
16384 if (!alias_mailbox_mappings) {
16385 ast_log(LOG_ERROR, "Unable to create alias_mailbox_mappings container\n");
16386 ao2_cleanup(inprocess_container);
16387 return AST_MODULE_LOAD_DECLINE;
16388 }
16389 res = ao2_container_register("voicemail_alias_mailbox_mappings", alias_mailbox_mappings, print_mappings);
16390 if (res) {
16391 ast_log(LOG_ERROR, "Unable to register alias_mailbox_mappings container\n");
16392 ao2_cleanup(inprocess_container);
16393 ao2_cleanup(alias_mailbox_mappings);
16394 return AST_MODULE_LOAD_DECLINE;
16395 }
16396
16397 mailbox_alias_mappings = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, MAPPING_BUCKETS,
16398 mailbox_alias_mapping_hash_fn, NULL, mailbox_alias_mapping_cmp_fn);
16399 if (!mailbox_alias_mappings) {
16400 ast_log(LOG_ERROR, "Unable to create mailbox_alias_mappings container\n");
16401 ao2_cleanup(inprocess_container);
16402 ao2_container_unregister("voicemail_alias_mailbox_mappings");
16403 ao2_cleanup(alias_mailbox_mappings);
16404 return AST_MODULE_LOAD_DECLINE;
16405 }
16406 res = ao2_container_register("voicemail_mailbox_alias_mappings", mailbox_alias_mappings, print_mappings);
16407 if (res) {
16408 ast_log(LOG_ERROR, "Unable to register mailbox_alias_mappings container\n");
16409 ao2_cleanup(inprocess_container);
16410 ao2_container_unregister("voicemail_alias_mailbox_mappings");
16411 ao2_cleanup(alias_mailbox_mappings);
16412 ao2_cleanup(mailbox_alias_mappings);
16413 return AST_MODULE_LOAD_DECLINE;
16414 }
16415
16416 /* compute the location of the voicemail spool directory */
16417 snprintf(VM_SPOOL_DIR, sizeof(VM_SPOOL_DIR), "%s/voicemail/", ast_config_AST_SPOOL_DIR);
16418
16419 if (!(mwi_subscription_tps = ast_taskprocessor_get("app_voicemail", 0))) {
16420 ast_log(AST_LOG_WARNING, "failed to reference mwi subscription taskprocessor. MWI will not work\n");
16421 }
16422
16423 if ((res = load_config(0))) {
16424 unload_module();
16425 return AST_MODULE_LOAD_DECLINE;
16426 }
16427
16428 res = ast_register_application_xml(voicemail_app, vm_exec);
16429 res |= ast_register_application_xml(voicemailmain_app, vm_execmain);
16430 res |= ast_register_application_xml(vmauthenticate_app, vmauthenticate);
16431 res |= ast_register_application_xml(playmsg_app, vm_playmsgexec);
16432 res |= ast_register_application_xml(sayname_app, vmsayname_exec);
16433 res |= ast_custom_function_register(&vm_info_acf);
16434 res |= ast_manager_register_xml("VoicemailUsersList", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, manager_list_voicemail_users);
16435 res |= ast_manager_register_xml("VoicemailUserStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, manager_status_voicemail_user);
16436 res |= ast_manager_register_xml("VoicemailRefresh", EVENT_FLAG_USER, manager_voicemail_refresh);
16437 res |= ast_manager_register_xml("VoicemailBoxSummary", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, manager_get_mailbox_summary);
16438 res |= ast_manager_register_xml("VoicemailMove", EVENT_FLAG_USER, manager_voicemail_move);
16439 res |= ast_manager_register_xml("VoicemailRemove", EVENT_FLAG_USER, manager_voicemail_remove);
16440 res |= ast_manager_register_xml("VoicemailForward", EVENT_FLAG_USER, manager_voicemail_forward);
16441 #ifdef TEST_FRAMEWORK
16442 res |= AST_TEST_REGISTER(test_voicemail_vmsayname);
16443 res |= AST_TEST_REGISTER(test_voicemail_msgcount);
16444 res |= AST_TEST_REGISTER(test_voicemail_vmuser);
16445 res |= AST_TEST_REGISTER(test_voicemail_notify_endl);
16446 res |= AST_TEST_REGISTER(test_voicemail_load_config);
16447 res |= AST_TEST_REGISTER(test_voicemail_vm_info);
16448 #endif
16449
16450 if (res) {
16451 ast_log(LOG_ERROR, "Failure registering applications, functions or tests\n");
16452 unload_module();
16453 return AST_MODULE_LOAD_DECLINE;
16454 }
16455
16456 /* ast_vm_register may return DECLINE if another module registered for vm */
16457 res = ast_vm_register(&vm_table);
16458 if (res) {
16459 ast_log(LOG_ERROR, "Failure registering as a voicemail provider\n");
16460 unload_module();
16461 return AST_MODULE_LOAD_DECLINE;
16462 }
16463
16464 /* ast_vm_greeter_register may return DECLINE if another module registered as a greeter */
16465 res = ast_vm_greeter_register(&vm_greeter_table);
16466 if (res) {
16467 ast_log(LOG_ERROR, "Failure registering as a greeter provider\n");
16468 unload_module();
16469 return AST_MODULE_LOAD_DECLINE;
16470 }
16471
16472 ast_cli_register_multiple(cli_voicemail, ARRAY_LEN(cli_voicemail));
16473
16474 #ifdef TEST_FRAMEWORK
16475 ast_install_vm_test_functions(vm_test_create_user, vm_test_destroy_user);
16476 #endif
16477
16478 ast_realtime_require_field("voicemail", "uniqueid", RQ_UINTEGER3, 11, "password", RQ_CHAR, 10, SENTINEL);
16479 ast_realtime_require_field("voicemail_data", "filename", RQ_CHAR, 30, "duration", RQ_UINTEGER3, 5, SENTINEL);
16480
16481 return AST_MODULE_LOAD_SUCCESS;
16482 }
16483
16484 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context)
16485 {
16486 int cmd = 0;
16487 char destination[80] = "";
16488 int retries = 0;
16489
16490 if (!num) {
16491 ast_verb(3, "Destination number will be entered manually\n");
16492 while (retries < 3 && cmd != 't') {
16493 destination[1] = '\0';
16494 destination[0] = cmd = ast_play_and_wait(chan, "vm-enter-num-to-call");
16495 if (!cmd)
16496 destination[0] = cmd = ast_play_and_wait(chan, "vm-then-pound");
16497 if (!cmd)
16498 destination[0] = cmd = ast_play_and_wait(chan, "vm-star-cancel");
16499 if (!cmd) {
16500 cmd = ast_waitfordigit(chan, 6000);
16501 if (cmd)
16502 destination[0] = cmd;
16503 }
16504 if (!cmd) {
16505 retries++;
16506 } else {
16507
16508 if (cmd < 0)
16509 return 0;
16510 if (cmd == '*') {
16511 ast_verb(3, "User hit '*' to cancel outgoing call\n");
16512 return 0;
16513 }
16514 if ((cmd = ast_readstring(chan, destination + strlen(destination), sizeof(destination) - 1, 6000, 10000, "#")) < 0)
16515 retries++;
16516 else
16517 cmd = 't';
16518 }
16519 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
16520 isprint(cmd) ? cmd : '?', isprint(cmd) ? cmd : '?');
16521 }
16522 if (retries >= 3) {
16523 return 0;
16524 }
16525
16526 } else {
16527 ast_verb(3, "Destination number is CID number '%s'\n", num);
16528 ast_copy_string(destination, num, sizeof(destination));
16529 }
16530
16531 if (!ast_strlen_zero(destination)) {
16532 if (destination[strlen(destination) -1 ] == '*')
16533 return 0;
16534 ast_verb(3, "Placing outgoing call to extension '%s' in context '%s' from context '%s'\n", destination, outgoing_context, ast_channel_context(chan));
16535 ast_channel_exten_set(chan, destination);
16536 ast_channel_context_set(chan, outgoing_context);
16537 ast_channel_priority_set(chan, 0);
16538 return 9;
16539 }
16540 return 0;
16541 }
16542
16543 /*!
16544 * \brief The advanced options within a message.
16545 * \param chan
16546 * \param vmu
16547 * \param vms
16548 * \param msg
16549 * \param option
16550 * \param record_gain
16551 *
16552 * Provides handling for the play message envelope, call the person back, or reply to message.
16553 *
16554 * \return zero on success, -1 on error.
16555 */
16556 static int advanced_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int msg, int option, signed char record_gain)
16557 {
16558 int res = 0;
16559 char filename[PATH_MAX];
16560 struct ast_config *msg_cfg = NULL;
16561 const char *origtime, *context;
16562 char *name, *num;
16563 int retries = 0;
16564 char *cid;
16565 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE, };
16566
16567 vms->starting = 0;
16568
16569 make_file(vms->fn, sizeof(vms->fn), vms->curdir, msg);
16570
16571 /* Retrieve info from VM attribute file */
16572 snprintf(filename, sizeof(filename), "%s.txt", vms->fn);
16573 RETRIEVE(vms->curdir, vms->curmsg, vmu->mailbox, vmu->context);
16574 msg_cfg = ast_config_load(filename, config_flags);
16575 DISPOSE(vms->curdir, vms->curmsg);
16576 if (!valid_config(msg_cfg)) {
16577 ast_log(AST_LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
16578 return 0;
16579 }
16580
16581 if (!(origtime = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
16582 ast_config_destroy(msg_cfg);
16583 return 0;
16584 }
16585
16586 cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
16587
16588 context = ast_variable_retrieve(msg_cfg, "message", "context");
16589 switch (option) {
16590 case 3: /* Play message envelope */
16591 if (!res) {
16592 res = play_message_datetime(chan, vmu, origtime, filename);
16593 }
16594 if (!res) {
16595 res = play_message_callerid(chan, vms, cid, context, 0, 1);
16596 }
16597
16598 res = 't';
16599 break;
16600
16601 case 2: /* Call back */
16602
16603 if (ast_strlen_zero(cid))
16604 break;
16605
16606 ast_callerid_parse(cid, &name, &num);
16607 while ((res > -1) && (res != 't')) {
16608 switch (res) {
16609 case '1':
16610 if (num) {
16611 /* Dial the CID number */
16612 res = dialout(chan, vmu, num, vmu->callback);
16613 if (res) {
16614 ast_config_destroy(msg_cfg);
16615 return 9;
16616 }
16617 } else {
16618 res = '2';
16619 }
16620 break;
16621
16622 case '2':
16623 /* Want to enter a different number, can only do this if there's a dialout context for this user */
16624 if (!ast_strlen_zero(vmu->dialout)) {
16625 res = dialout(chan, vmu, NULL, vmu->dialout);
16626 if (res) {
16627 ast_config_destroy(msg_cfg);
16628 return 9;
16629 }
16630 } else {
16631 ast_verb(3, "Caller can not specify callback number - no dialout context available\n");
16632 res = ast_play_and_wait(chan, "vm-sorry");
16633 }
16634 ast_config_destroy(msg_cfg);
16635 return res;
16636 case '*':
16637 res = 't';
16638 break;
16639 case '3':
16640 case '4':
16641 case '5':
16642 case '6':
16643 case '7':
16644 case '8':
16645 case '9':
16646 case '0':
16647
16648 res = ast_play_and_wait(chan, "vm-sorry");
16649 retries++;
16650 break;
16651 default:
16652 if (num) {
16653 ast_verb(3, "Confirm CID number '%s' is number to use for callback\n", num);
16654 res = ast_play_and_wait(chan, "vm-num-i-have");
16655 if (!res)
16656 res = play_message_callerid(chan, vms, num, vmu->context, 1, 1);
16657 if (!res)
16658 res = ast_play_and_wait(chan, "vm-tocallnum");
16659 /* Only prompt for a caller-specified number if there is a dialout context specified */
16660 if (!ast_strlen_zero(vmu->dialout)) {
16661 if (!res)
16662 res = ast_play_and_wait(chan, "vm-calldiffnum");
16663 }
16664 } else {
16665 res = ast_play_and_wait(chan, "vm-nonumber");
16666 if (!ast_strlen_zero(vmu->dialout)) {
16667 if (!res)
16668 res = ast_play_and_wait(chan, "vm-toenternumber");
16669 }
16670 }
16671 if (!res) {
16672 res = ast_play_and_wait(chan, "vm-star-cancel");
16673 }
16674 if (!res) {
16675 res = ast_waitfordigit(chan, 6000);
16676 }
16677 if (!res) {
16678 retries++;
16679 if (retries > 3) {
16680 res = 't';
16681 }
16682 }
16683 ast_test_suite_event_notify("USERPRESS", "Message: User pressed %c\r\nDTMF: %c",
16684 isprint(res) ? res : '?', isprint(res) ? res : '?');
16685 break;
16686
16687 }
16688 if (res == 't')
16689 res = 0;
16690 else if (res == '*')
16691 res = -1;
16692 }
16693 break;
16694
16695 case 1: /* Reply */
16696 /* Send reply directly to sender */
16697 if (ast_strlen_zero(cid))
16698 break;
16699
16700 ast_callerid_parse(cid, &name, &num);
16701 if (!num) {
16702 ast_verb(3, "No CID number available, no reply sent\n");
16703 if (!res)
16704 res = ast_play_and_wait(chan, "vm-nonumber");
16705 ast_config_destroy(msg_cfg);
16706 return res;
16707 } else {
16708 struct ast_vm_user vmu2, *vmu3;
16709 memset(&vmu2, 0, sizeof(vmu2));
16710 vmu3 = find_user(&vmu2, vmu->context, num);
16711 if (vmu3) {
16712 struct leave_vm_options leave_options;
16713 char mailbox[AST_MAX_EXTENSION * 2 + 2];
16714 snprintf(mailbox, sizeof(mailbox), "%s@%s", num, vmu->context);
16715
16716 ast_verb(3, "Leaving voicemail for '%s' in context '%s'\n", num, vmu->context);
16717
16718 memset(&leave_options, 0, sizeof(leave_options));
16719 leave_options.record_gain = record_gain;
16720 leave_options.beeptone = "beep";
16721 res = leave_voicemail(chan, mailbox, &leave_options);
16722 if (!res)
16723 res = 't';
16724 ast_config_destroy(msg_cfg);
16725 free_user(vmu3);
16726 return res;
16727 } else {
16728 /* Sender has no mailbox, can't reply */
16729 ast_verb(3, "No mailbox number '%s' in context '%s', no reply sent\n", num, vmu->context);
16730 ast_play_and_wait(chan, "vm-nobox");
16731 res = 't';
16732 ast_config_destroy(msg_cfg);
16733 return res;
16734 }
16735 }
16736 res = 0;
16737
16738 break;
16739 }
16740
16741 ast_config_destroy(msg_cfg);
16742
16743 #ifndef IMAP_STORAGE
16744 if (!res) {
16745 make_file(vms->fn, sizeof(vms->fn), vms->curdir, msg);
16746 vms->heard[msg] = 1;
16747 res = wait_file(chan, vms, vms->fn);
16748 }
16749 #endif
16750 return res;
16751 }
16752
16753 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt,
16754 int outsidecaller, struct ast_vm_user *vmu, int *duration, int *sound_duration, const char *unlockdir,
16755 signed char record_gain, struct vm_state *vms, char *flag, const char *msg_id, int forwardintro)
16756 {
16757 /* Record message & let caller review or re-record it, or set options if applicable */
16758 int res = 0;
16759 int cmd = 0;
16760 int max_attempts = 3;
16761 int attempts = 0;
16762 int recorded = 0;
16763 int msg_exists = 0;
16764 signed char zero_gain = 0;
16765 char tempfile[PATH_MAX];
16766 char *acceptdtmf = "#";
16767 char *canceldtmf = "";
16768 int canceleddtmf = 0;
16769 SCOPE_ENTER(3, "%s: rf: %s fmt: %s type: %s vmu: %s\n",
16770 ast_channel_name(chan), recordfile, fmt, outsidecaller ? "msg" : "greeting",
16771 vmu->mailbox);
16772 /* Note that urgent and private are for flagging messages as such in the future */
16773
16774 /* barf if no pointer passed to store duration in */
16775 if (duration == NULL) {
16776 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s\n", "Error play_record_review called without duration pointer\n");
16777 }
16778
16779 if (!outsidecaller)
16780 snprintf(tempfile, sizeof(tempfile), "%s.tmp", recordfile);
16781 else
16782 ast_copy_string(tempfile, recordfile, sizeof(tempfile));
16783
16784 cmd = '3'; /* Want to start by recording */
16785
16786 while ((cmd >= 0) && (cmd != 't')) {
16787 switch (cmd) {
16788 case '1':
16789 if (!msg_exists) {
16790 /* In this case, 1 is to record a message */
16791 cmd = '3';
16792 break;
16793 } else {
16794 /* Otherwise 1 is to save the existing message */
16795 ast_verb(3, "Saving message as is\n");
16796 if (!outsidecaller) {
16797 ast_trace(-1, "Renaming greeting '%s' to '%s'\n", tempfile, recordfile);
16798 ast_filerename(tempfile, recordfile, NULL);
16799 }
16800 if (!forwardintro) {
16801 ast_stream_and_wait(chan, "vm-msgsaved", "");
16802 }
16803 if (!outsidecaller) {
16804 /* Saves to IMAP server only if imapgreeting=yes */
16805 ast_trace(-1, "Saving greeting '%s'\n", recordfile);
16806 SCOPE_CALL(-1, STORE, recordfile, vmu->mailbox, vmu->context, -1, chan, vmu, fmt, *duration, vms, flag, msg_id);
16807 SCOPE_CALL(-1, DISPOSE, recordfile, -1);
16808 }
16809 cmd = 't';
16810 SCOPE_EXIT_RTN_VALUE(res, "Message saved to %s\n", recordfile);
16811 }
16812 case '2':
16813 /* Review */
16814 ast_verb(3, "Reviewing the message\n");
16815 ast_trace(-1, "Reviewing '%s'\n", tempfile);
16816 cmd = ast_stream_and_wait(chan, tempfile, AST_DIGIT_ANY);
16817 break;
16818 case '3':
16819 msg_exists = 0;
16820 /* Record */
16821 if (recorded == 1)
16822 ast_verb(3, "Re-recording the message\n");
16823 else
16824 ast_verb(3, "Recording the message\n");
16825
16826 if (recorded && outsidecaller) {
16827 if (forwardintro) {
16828 cmd = ast_play_and_wait(chan, "vm-record-prepend");
16829 } else {
16830 cmd = ast_play_and_wait(chan, INTRO);
16831 }
16832 cmd = ast_play_and_wait(chan, "beep");
16833 }
16834 if (cmd == -1) {
16835 /* User has hung up, no options to give */
16836 ast_filedelete(tempfile, NULL);
16837 SCOPE_EXIT_RTN_VALUE(cmd, "User hung up before message could be rerecorded. Deleted '%s'\n", tempfile);
16838 }
16839 recorded = 1;
16840 /* After an attempt has been made to record message, we have to take care of INTRO and beep for incoming messages, but not for greetings */
16841 if (record_gain)
16842 ast_channel_setoption(chan, AST_OPTION_RXGAIN, &record_gain, sizeof(record_gain), 0);
16843 if (ast_test_flag(vmu, VM_OPERATOR))
16844 canceldtmf = "0";
16845 ast_trace(-1, "Recording '%s'\n", tempfile);
16846 cmd = ast_play_and_record_full(chan, playfile, tempfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, unlockdir, acceptdtmf, canceldtmf, 0, AST_RECORD_IF_EXISTS_OVERWRITE);
16847 if (strchr(canceldtmf, cmd)) {
16848 /* need this flag here to distinguish between pressing '0' during message recording or after */
16849 canceleddtmf = 1;
16850 }
16851 if (record_gain)
16852 ast_channel_setoption(chan, AST_OPTION_RXGAIN, &zero_gain, sizeof(zero_gain), 0);
16853 if (cmd == -1) {
16854 /* User has hung up, no options to give */
16855 if (!outsidecaller) {
16856 /* user was recording a greeting and they hung up, so let's delete the recording. */
16857 ast_filedelete(tempfile, NULL);
16858 }
16859 SCOPE_EXIT_RTN_VALUE(cmd, "User hung up after recording. %s %s\n",
16860 outsidecaller ? "Saved message " : "Deleted greeting \n", tempfile);
16861 }
16862 if (cmd == '0') {
16863 break;
16864 } else if (cmd == '*') {
16865 break;
16866 #if 0
16867 } else if (vmu->review && sound_duration && (*sound_duration < 5)) {
16868 /* Message is too short */
16869 ast_verb(3, "Message too short\n");
16870 cmd = ast_play_and_wait(chan, "vm-tooshort");
16871 cmd = ast_filedelete(tempfile, NULL);
16872 break;
16873 } else if (vmu->review && (cmd == 2 && sound_duration && *sound_duration < (maxsilence + 3))) {
16874 /* Message is all silence */
16875 ast_verb(3, "Nothing recorded\n");
16876 cmd = ast_filedelete(tempfile, NULL);
16877 cmd = ast_play_and_wait(chan, "vm-nothingrecorded");
16878 if (!cmd)
16879 cmd = ast_play_and_wait(chan, "vm-speakup");
16880 break;
16881 #endif
16882 } else {
16883 /* If all is well, a message exists */
16884 msg_exists = 1;
16885 cmd = 0;
16886 }
16887 break;
16888 case '4':
16889 if (outsidecaller && ast_test_flag(vmu, VM_MARK_URGENT)) { /* only mark vm messages */
16890 /* Mark Urgent */
16891 if ((flag && ast_strlen_zero(flag)) || (!ast_strlen_zero(flag) && strcmp(flag, "Urgent"))) {
16892 ast_verb(3, "marking message as Urgent\n");
16893 res = ast_play_and_wait(chan, "vm-marked-urgent");
16894 strcpy(flag, "Urgent");
16895 } else if (flag) {
16896 ast_verb(3, "UNmarking message as Urgent\n");
16897 res = ast_play_and_wait(chan, "vm-marked-nonurgent");
16898 strcpy(flag, "");
16899 } else {
16900 ast_play_and_wait(chan, "vm-sorry");
16901 }
16902 cmd = 0;
16903 } else {
16904 cmd = ast_play_and_wait(chan, "vm-sorry");
16905 }
16906 break;
16907 case '5':
16908 case '6':
16909 case '7':
16910 case '8':
16911 case '9':
16912 case '*':
16913 case '#':
16914 cmd = ast_play_and_wait(chan, "vm-sorry");
16915 break;
16916 #if 0
16917 /* XXX Commented out for the moment because of the dangers of deleting
16918 a message while recording (can put the message numbers out of sync) */
16919 case '*':
16920 /* Cancel recording, delete message, offer to take another message*/
16921 cmd = ast_play_and_wait(chan, "vm-deleted");
16922 cmd = ast_filedelete(tempfile, NULL);
16923 if (outsidecaller) {
16924 res = vm_exec(chan, NULL);
16925 return res;
16926 }
16927 else
16928 return 1;
16929 #endif
16930 case '0':
16931 if (!ast_test_flag(vmu, VM_OPERATOR) || (!canceleddtmf && !outsidecaller)) {
16932 cmd = ast_play_and_wait(chan, "vm-sorry");
16933 break;
16934 }
16935 if (msg_exists || recorded) {
16936 ast_trace(-1, "Reviewing '%s'\n", tempfile);
16937 cmd = ast_play_and_wait(chan, "vm-saveoper");
16938 if (!cmd)
16939 cmd = ast_waitfordigit(chan, 3000);
16940 if (cmd == '1') {
16941 ast_trace(-1, "Saving '%s' to '%s'\n", tempfile, recordfile);
16942 ast_filerename(tempfile, recordfile, NULL);
16943 ast_play_and_wait(chan, "vm-msgsaved");
16944 cmd = '0';
16945 } else if (cmd == '4') {
16946 if (flag) {
16947 ast_play_and_wait(chan, "vm-marked-urgent");
16948 strcpy(flag, "Urgent");
16949 }
16950 ast_play_and_wait(chan, "vm-msgsaved");
16951 cmd = '0';
16952 } else {
16953 ast_trace(-1, "Deleting '%s'\n", tempfile);
16954 ast_play_and_wait(chan, "vm-deleted");
16955 SCOPE_CALL(-1, DELETE, tempfile, -1, tempfile, vmu);
16956 SCOPE_CALL(-1, DISPOSE, tempfile, -1);
16957 cmd = '0';
16958 }
16959 }
16960 return cmd;
16961 default:
16962 /* If the caller is an outside caller and the review option is enabled or it's forward intro
16963 allow them to review the message, but let the owner of the box review
16964 their OGM's */
16965 if (outsidecaller && !ast_test_flag(vmu, VM_REVIEW) && !forwardintro) {
16966 SCOPE_EXIT_RTN_VALUE(cmd, "Done. Outside caller, review not set, no forwardintro\n");
16967 }
16968 if (msg_exists) {
16969 cmd = ast_play_and_wait(chan, "vm-review");
16970 if (!cmd && outsidecaller && ast_test_flag(vmu, VM_MARK_URGENT)) {
16971 if ((flag && ast_strlen_zero(flag)) || (!ast_strlen_zero(flag) && strcmp(flag, "Urgent"))) {
16972 cmd = ast_play_and_wait(chan, "vm-review-urgent");
16973 } else if (flag) {
16974 cmd = ast_play_and_wait(chan, "vm-review-nonurgent");
16975 }
16976 }
16977 } else {
16978 cmd = ast_play_and_wait(chan, "vm-torerecord");
16979 if (!cmd)
16980 cmd = ast_waitfordigit(chan, 600);
16981 }
16982
16983 if (!cmd && outsidecaller && ast_test_flag(vmu, VM_OPERATOR)) {
16984 cmd = ast_play_and_wait(chan, "vm-reachoper");
16985 if (!cmd)
16986 cmd = ast_waitfordigit(chan, 600);
16987 }
16988 #if 0
16989 if (!cmd)
16990 cmd = ast_play_and_wait(chan, "vm-tocancelmsg");
16991 #endif
16992 if (!cmd)
16993 cmd = ast_waitfordigit(chan, 6000);
16994 if (!cmd) {
16995 attempts++;
16996 }
16997 if (attempts > max_attempts) {
16998 cmd = 't';
16999 }
17000 }
17001 }
17002 if (!outsidecaller && (cmd == -1 || cmd == 't')) {
17003 /* Hang up or timeout, so delete the recording. */
17004 ast_trace(-1, "Deleting '%s' on hangup or timeout\n", tempfile);
17005 ast_filedelete(tempfile, NULL);
17006 }
17007
17008 if (cmd != 't' && outsidecaller)
17009 ast_play_and_wait(chan, "vm-goodbye");
17010
17011 SCOPE_EXIT_RTN_VALUE(cmd, "Done\n");
17012 }
17013
17014 static struct ast_vm_msg_snapshot *vm_msg_snapshot_alloc(void)
17015 {
17016 struct ast_vm_msg_snapshot *msg_snapshot;
17017
17018 if (!(msg_snapshot = ast_calloc(1, sizeof(*msg_snapshot)))) {
17019 return NULL;
17020 }
17021
17022 if (ast_string_field_init(msg_snapshot, 512)) {
17023 ast_free(msg_snapshot);
17024 return NULL;
17025 }
17026
17027 return msg_snapshot;
17028 }
17029
17030 static struct ast_vm_msg_snapshot *vm_msg_snapshot_destroy(struct ast_vm_msg_snapshot *msg_snapshot)
17031 {
17032 ast_string_field_free_memory(msg_snapshot);
17033 ast_free(msg_snapshot);
17034
17035 return NULL;
17036 }
17037
17038 #ifdef TEST_FRAMEWORK
17039
17040 static int vm_test_destroy_user(const char *context, const char *mailbox)
17041 {
17042 struct ast_vm_user *vmu;
17043
17044 AST_LIST_LOCK(&users);
17045 AST_LIST_TRAVERSE_SAFE_BEGIN(&users, vmu, list) {
17046 if (!strcmp(context, vmu->context)
17047 && !strcmp(mailbox, vmu->mailbox)) {
17048 AST_LIST_REMOVE_CURRENT(list);
17049 ast_free(vmu);
17050 break;
17051 }
17052 }
17053 AST_LIST_TRAVERSE_SAFE_END
17054 AST_LIST_UNLOCK(&users);
17055 return 0;
17056 }
17057
17058 static int vm_test_create_user(const char *context, const char *mailbox)
17059 {
17060 struct ast_vm_user *vmu;
17061
17062 if (!(vmu = find_or_create(context, mailbox))) {
17063 return -1;
17064 }
17065 populate_defaults(vmu);
17066 return 0;
17067 }
17068
17069 #endif
17070
17071 /*!
17072 * \brief Create and store off all the msgs in an open mailbox
17073 *
17074 * \note TODO XXX This function should work properly for all
17075 * voicemail storage options, but is far more expensive for
17076 * ODBC at the moment. This is because the RETRIEVE macro
17077 * not only pulls out the message's meta data file from the
17078 * database, but also the actual audio for each message, temporarily
17079 * writing it to the file system. This is an area that needs
17080 * to be made more efficient.
17081 */
17082 static int vm_msg_snapshot_create(struct ast_vm_user *vmu,
17083 struct vm_state *vms,
17084 struct ast_vm_mailbox_snapshot *mailbox_snapshot,
17085 int snapshot_index,
17086 int mailbox_index,
17087 int descending,
17088 enum ast_vm_snapshot_sort_val sort_val)
17089 {
17090 struct ast_vm_msg_snapshot *msg_snapshot;
17091 struct ast_vm_msg_snapshot *msg_snapshot_tmp;
17092 struct ast_config *msg_cfg;
17093 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
17094 char filename[PATH_MAX];
17095 const char *value;
17096
17097 for (vms->curmsg = 0; vms->curmsg <= vms->lastmsg; vms->curmsg++) {
17098 int inserted = 0;
17099 /* Find the msg */
17100 make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
17101 snprintf(filename, sizeof(filename), "%s.txt", vms->fn);
17102 RETRIEVE(vms->curdir, vms->curmsg, vmu->mailbox, vmu->context);
17103 msg_cfg = ast_config_load(filename, config_flags);
17104 if (!msg_cfg || msg_cfg == CONFIG_STATUS_FILEINVALID) {
17105 DISPOSE(vms->curdir, vms->curmsg);
17106 continue;
17107 }
17108
17109 /* Create the snapshot object */
17110 if (!(msg_snapshot = vm_msg_snapshot_alloc())) {
17111 ast_config_destroy(msg_cfg);
17112 return -1;
17113 }
17114
17115 /* Fill in the snapshot object */
17116 if ((value = ast_variable_retrieve(msg_cfg, "message", "msg_id"))) {
17117 ast_string_field_set(msg_snapshot, msg_id, value);
17118 } else {
17119 /* Message snapshots *really* should have a
17120 * message ID. Add one to the message config
17121 * if it does not already exist
17122 */
17123 char id[MSG_ID_LEN];
17124 if (!(add_message_id(msg_cfg, vms->curdir, vms->curmsg,
17125 filename, id, sizeof(id), vmu, mailbox_index))) {
17126 ast_string_field_set(msg_snapshot, msg_id, id);
17127 } else {
17128 ast_log(LOG_WARNING, "Unable to create a message ID for message %s/%d\n", vms->curdir, vms->curmsg);
17129 }
17130 }
17131 if ((value = ast_variable_retrieve(msg_cfg, "message", "callerid"))) {
17132 ast_string_field_set(msg_snapshot, callerid, value);
17133 }
17134 if ((value = ast_variable_retrieve(msg_cfg, "message", "callerchan"))) {
17135 ast_string_field_set(msg_snapshot, callerchan, value);
17136 }
17137 if ((value = ast_variable_retrieve(msg_cfg, "message", "exten"))) {
17138 ast_string_field_set(msg_snapshot, exten, value);
17139 }
17140 if ((value = ast_variable_retrieve(msg_cfg, "message", "origdate"))) {
17141 ast_string_field_set(msg_snapshot, origdate, value);
17142 }
17143 if ((value = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
17144 ast_string_field_set(msg_snapshot, origtime, value);
17145 }
17146 if ((value = ast_variable_retrieve(msg_cfg, "message", "duration"))) {
17147 ast_string_field_set(msg_snapshot, duration, value);
17148 }
17149 if ((value = ast_variable_retrieve(msg_cfg, "message", "flag"))) {
17150 ast_string_field_set(msg_snapshot, flag, value);
17151 }
17152 msg_snapshot->msg_number = vms->curmsg;
17153 ast_string_field_set(msg_snapshot, folder_name, mailbox_folders[mailbox_index]);
17154
17155 /* store msg snapshot in mailbox snapshot */
17156 switch (sort_val) {
17157 default:
17158 case AST_VM_SNAPSHOT_SORT_BY_ID:
17159 if (descending) {
17160 AST_LIST_INSERT_HEAD(&mailbox_snapshot->snapshots[snapshot_index], msg_snapshot, msg);
17161 } else {
17162 AST_LIST_INSERT_TAIL(&mailbox_snapshot->snapshots[snapshot_index], msg_snapshot, msg);
17163 }
17164 inserted = 1;
17165 break;
17166 case AST_VM_SNAPSHOT_SORT_BY_TIME:
17167 AST_LIST_TRAVERSE_SAFE_BEGIN(&mailbox_snapshot->snapshots[snapshot_index], msg_snapshot_tmp, msg) {
17168 int val = strcmp(msg_snapshot->origtime, msg_snapshot_tmp->origtime);
17169 if (descending && val >= 0) {
17170 AST_LIST_INSERT_BEFORE_CURRENT(msg_snapshot, msg);
17171 inserted = 1;
17172 break;
17173 } else if (!descending && val <= 0) {
17174 AST_LIST_INSERT_BEFORE_CURRENT(msg_snapshot, msg);
17175 inserted = 1;
17176 break;
17177 }
17178 }
17179 AST_LIST_TRAVERSE_SAFE_END;
17180 break;
17181 }
17182
17183 if (!inserted) {
17184 AST_LIST_INSERT_TAIL(&mailbox_snapshot->snapshots[snapshot_index], msg_snapshot, msg);
17185 }
17186
17187 mailbox_snapshot->total_msg_num++;
17188
17189 /* cleanup configs and msg */
17190 ast_config_destroy(msg_cfg);
17191 DISPOSE(vms->curdir, vms->curmsg);
17192 }
17193
17194 return 0;
17195 }
17196
17197 static struct ast_vm_mailbox_snapshot *vm_mailbox_snapshot_create(const char *mailbox,
17198 const char *context,
17199 const char *folder,
17200 int descending,
17201 enum ast_vm_snapshot_sort_val sort_val,
17202 int combine_INBOX_and_OLD)
17203 {
17204 struct ast_vm_mailbox_snapshot *mailbox_snapshot;
17205 struct vm_state vms;
17206 struct ast_vm_user *vmu = NULL, vmus;
17207 int res;
17208 int i;
17209 int this_index_only = -1;
17210 int open = 0;
17211 int inbox_index = get_folder_by_name("INBOX");
17212 int old_index = get_folder_by_name("Old");
17213 int urgent_index = get_folder_by_name("Urgent");
17214
17215 if (ast_strlen_zero(mailbox)) {
17216 ast_log(LOG_WARNING, "Cannot create a mailbox snapshot since no mailbox was specified\n");
17217 return NULL;
17218 }
17219
17220 memset(&vmus, 0, sizeof(vmus));
17221
17222 if (!(ast_strlen_zero(folder))) {
17223 /* find the folder index */
17224 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
17225 if (!strcasecmp(mailbox_folders[i], folder)) {
17226 this_index_only = i;
17227 break;
17228 }
17229 }
17230 if (this_index_only == -1) {
17231 /* Folder was specified and it did not match any folder in our list */
17232 return NULL;
17233 }
17234 }
17235
17236 if (!(vmu = find_user(&vmus, context, mailbox))) {
17237 ast_log(AST_LOG_WARNING, "Failed to create mailbox snapshot for unknown voicemail user %s@%s\n", mailbox, context);
17238 return NULL;
17239 }
17240
17241 if (!(mailbox_snapshot = ast_calloc(1, sizeof(*mailbox_snapshot)))) {
17242 ast_log(AST_LOG_ERROR, "Failed to allocate memory for mailbox snapshot\n");
17243 free_user(vmu);
17244 return NULL;
17245 }
17246
17247 if (!(mailbox_snapshot->snapshots = ast_calloc(ARRAY_LEN(mailbox_folders), sizeof(*mailbox_snapshot->snapshots)))) {
17248 ast_free(mailbox_snapshot);
17249 free_user(vmu);
17250 return NULL;
17251 }
17252
17253 mailbox_snapshot->folders = ARRAY_LEN(mailbox_folders);
17254
17255 for (i = 0; i < mailbox_snapshot->folders; i++) {
17256 int msg_folder_index = i;
17257
17258 /* We want this message in the snapshot if any of the following:
17259 * No folder was specified.
17260 * The specified folder matches the current folder.
17261 * The specified folder is INBOX AND we were asked to combine messages AND the current folder is either Old or Urgent.
17262 */
17263 if (!(this_index_only == -1 || this_index_only == i || (this_index_only == inbox_index && combine_INBOX_and_OLD && (i == old_index || i == urgent_index)))) {
17264 continue;
17265 }
17266
17267 /* Make sure that Old or Urgent messages are marked as being in INBOX. */
17268 if (combine_INBOX_and_OLD && (i == old_index || i == urgent_index)) {
17269 msg_folder_index = inbox_index;
17270 }
17271
17272 memset(&vms, 0, sizeof(vms));
17273 ast_copy_string(vms.username, mailbox, sizeof(vms.username));
17274 vms.lastmsg = -1;
17275 open = 0;
17276
17277 /* open the mailbox state */
17278 if ((res = open_mailbox(&vms, vmu, i)) < 0) {
17279 ast_log(LOG_WARNING, "Could not open mailbox %s\n", mailbox);
17280 goto snapshot_cleanup;
17281 }
17282 open = 1;
17283
17284 /* Iterate through each msg, storing off info */
17285 if (vms.lastmsg != -1) {
17286 if ((vm_msg_snapshot_create(vmu, &vms, mailbox_snapshot, msg_folder_index, i, descending, sort_val))) {
17287 ast_log(LOG_WARNING, "Failed to create msg snapshots for %s@%s\n", mailbox, context);
17288 goto snapshot_cleanup;
17289 }
17290 }
17291
17292 /* close mailbox */
17293 if ((res = close_mailbox(&vms, vmu) == ERROR_LOCK_PATH)) {
17294 goto snapshot_cleanup;
17295 }
17296 open = 0;
17297 }
17298
17299 snapshot_cleanup:
17300 if (vmu && open) {
17301 close_mailbox(&vms, vmu);
17302 }
17303
17304 #ifdef IMAP_STORAGE
17305 if (vmu) {
17306 vmstate_delete(&vms);
17307 }
17308 #endif
17309
17310 free_user(vmu);
17311 return mailbox_snapshot;
17312 }
17313
17314 static struct ast_vm_mailbox_snapshot *vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
17315 {
17316 int i;
17317 struct ast_vm_msg_snapshot *msg_snapshot;
17318
17319 for (i = 0; i < mailbox_snapshot->folders; i++) {
17320 while ((msg_snapshot = AST_LIST_REMOVE_HEAD(&mailbox_snapshot->snapshots[i], msg))) {
17321 msg_snapshot = vm_msg_snapshot_destroy(msg_snapshot);
17322 }
17323 }
17324 ast_free(mailbox_snapshot->snapshots);
17325 ast_free(mailbox_snapshot);
17326 return NULL;
17327 }
17328
17329 /*!
17330 * \brief common bounds checking and existence check for Voicemail API functions.
17331 *
17332 * \details
17333 * This is called by vm_msg_move, vm_msg_remove, and vm_msg_forward to
17334 * ensure that data passed in are valid. This ensures that given the
17335 * desired message IDs, they can be found.
17336 *
17337 * \param vms The voicemail state corresponding to an open mailbox
17338 * \param msg_ids An array of message identifiers
17339 * \param num_msgs The number of identifiers in msg_ids
17340 * \param[out] msg_nums The message indexes corresponding to the given
17341 * \param vmu
17342 * message IDs
17343 * \pre vms must have open_mailbox() called on it prior to this function.
17344 *
17345 * \retval -1 Failure
17346 * \retval 0 Success
17347 */
17348 static int message_range_and_existence_check(struct vm_state *vms, const char *msg_ids [], size_t num_msgs, int *msg_nums, struct ast_vm_user *vmu)
17349 {
17350 int i;
17351 int res = 0;
17352 for (i = 0; i < num_msgs; ++i) {
17353 const char *msg_id = msg_ids[i];
17354 int found = 0;
17355 for (vms->curmsg = 0; vms->curmsg <= vms->lastmsg; vms->curmsg++) {
17356 const char *other_msg_id;
17357 char filename[PATH_MAX];
17358 struct ast_config *msg_cfg;
17359 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
17360
17361 make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
17362 snprintf(filename, sizeof(filename), "%s.txt", vms->fn);
17363 RETRIEVE(vms->curdir, vms->curmsg, vmu->mailbox, vmu->context);
17364 msg_cfg = ast_config_load(filename, config_flags);
17365 if (!msg_cfg || msg_cfg == CONFIG_STATUS_FILEINVALID) {
17366 DISPOSE(vms->curdir, vms->curmsg);
17367 res = -1;
17368 goto done;
17369 }
17370
17371 other_msg_id = ast_variable_retrieve(msg_cfg, "message", "msg_id");
17372
17373 if (!ast_strlen_zero(other_msg_id) && !strcmp(other_msg_id, msg_id)) {
17374 /* Message found. We can get out of this inner loop
17375 * and move on to the next message to find
17376 */
17377 found = 1;
17378 msg_nums[i] = vms->curmsg;
17379 ast_config_destroy(msg_cfg);
17380 DISPOSE(vms->curdir, vms->curmsg);
17381 break;
17382 }
17383 ast_config_destroy(msg_cfg);
17384 DISPOSE(vms->curdir, vms->curmsg);
17385 }
17386 if (!found) {
17387 /* If we can't find one of the message IDs requested, then OH NO! */
17388 res = -1;
17389 goto done;
17390 }
17391 }
17392
17393 done:
17394 return res;
17395 }
17396
17397 static void notify_new_state(struct ast_vm_user *vmu)
17398 {
17399 int new = 0, old = 0, urgent = 0;
17400 char ext_context[1024];
17401
17402 snprintf(ext_context, sizeof(ext_context), "%s@%s", vmu->mailbox, vmu->context);
17403 run_externnotify(vmu->context, vmu->mailbox, NULL);
17404 ast_app_inboxcount2(ext_context, &urgent, &new, &old);
17405 queue_mwi_event(NULL, ext_context, urgent, new, old);
17406 }
17407
17408 static int vm_msg_forward(const char *from_mailbox,
17409 const char *from_context,
17410 const char *from_folder,
17411 const char *to_mailbox,
17412 const char *to_context,
17413 const char *to_folder,
17414 size_t num_msgs,
17415 const char *msg_ids [],
17416 int delete_old)
17417 {
17418 struct vm_state from_vms;
17419 struct ast_vm_user *vmu = NULL, vmus;
17420 struct ast_vm_user *to_vmu = NULL, to_vmus;
17421 struct ast_config *msg_cfg;
17422 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
17423 char filename[PATH_MAX];
17424 int from_folder_index;
17425 int open = 0;
17426 int res = 0;
17427 int i;
17428 int *msg_nums;
17429
17430 if (ast_strlen_zero(from_mailbox) || ast_strlen_zero(to_mailbox)) {
17431 ast_log(LOG_WARNING, "Cannot forward message because either the from or to mailbox was not specified\n");
17432 return -1;
17433 }
17434
17435 if (!num_msgs) {
17436 ast_log(LOG_WARNING, "Invalid number of messages specified to forward: %zu\n", num_msgs);
17437 return -1;
17438 }
17439
17440 if (ast_strlen_zero(from_folder) || ast_strlen_zero(to_folder)) {
17441 ast_log(LOG_WARNING, "Cannot forward message because the from_folder or to_folder was not specified\n");
17442 return -1;
17443 }
17444
17445 memset(&vmus, 0, sizeof(vmus));
17446 memset(&to_vmus, 0, sizeof(to_vmus));
17447 memset(&from_vms, 0, sizeof(from_vms));
17448
17449 from_folder_index = get_folder_by_name(from_folder);
17450 if (from_folder_index == -1) {
17451 return -1;
17452 }
17453
17454 if (get_folder_by_name(to_folder) == -1) {
17455 return -1;
17456 }
17457
17458 if (!(vmu = find_user(&vmus, from_context, from_mailbox))) {
17459 ast_log(LOG_WARNING, "Can't find voicemail user to forward from (%s@%s)\n", from_mailbox, from_context);
17460 return -1;
17461 }
17462
17463 if (!(to_vmu = find_user(&to_vmus, to_context, to_mailbox))) {
17464 ast_log(LOG_WARNING, "Can't find voicemail user to forward to (%s@%s)\n", to_mailbox, to_context);
17465 free_user(vmu);
17466 return -1;
17467 }
17468
17469 ast_copy_string(from_vms.username, from_mailbox, sizeof(from_vms.username));
17470 from_vms.lastmsg = -1;
17471 open = 0;
17472
17473 /* open the mailbox state */
17474 if ((res = open_mailbox(&from_vms, vmu, from_folder_index)) < 0) {
17475 ast_log(LOG_WARNING, "Could not open mailbox %s\n", from_mailbox);
17476 res = -1;
17477 goto vm_forward_cleanup;
17478 }
17479
17480 open = 1;
17481
17482 if ((from_vms.lastmsg + 1) < num_msgs) {
17483 ast_log(LOG_WARNING, "Folder %s has less than %zu messages\n", from_folder, num_msgs);
17484 res = -1;
17485 goto vm_forward_cleanup;
17486 }
17487
17488 msg_nums = ast_alloca(sizeof(int) * num_msgs);
17489
17490 if ((res = message_range_and_existence_check(&from_vms, msg_ids, num_msgs, msg_nums, vmu) < 0)) {
17491 goto vm_forward_cleanup;
17492 }
17493
17494 /* Now we actually forward the messages */
17495 for (i = 0; i < num_msgs; i++) {
17496 int cur_msg = msg_nums[i];
17497 int duration = 0;
17498 const char *value;
17499
17500 make_file(from_vms.fn, sizeof(from_vms.fn), from_vms.curdir, cur_msg);
17501 snprintf(filename, sizeof(filename), "%s.txt", from_vms.fn);
17502 RETRIEVE(from_vms.curdir, cur_msg, vmu->mailbox, vmu->context);
17503 msg_cfg = ast_config_load(filename, config_flags);
17504 /* XXX This likely will not fail since we previously ensured that the
17505 * message we are looking for exists. However, there still could be some
17506 * circumstance where this fails, so atomicity is not guaranteed.
17507 */
17508 if (!msg_cfg || msg_cfg == CONFIG_STATUS_FILEINVALID) {
17509 DISPOSE(from_vms.curdir, cur_msg);
17510 continue;
17511 }
17512 if ((value = ast_variable_retrieve(msg_cfg, "message", "duration"))) {
17513 duration = atoi(value);
17514 }
17515
17516 copy_message(NULL, vmu, from_folder_index, cur_msg, duration, to_vmu, vmfmts, from_vms.curdir, "", to_folder);
17517
17518 if (delete_old) {
17519 from_vms.deleted[cur_msg] = 1;
17520 }
17521 ast_config_destroy(msg_cfg);
17522 DISPOSE(from_vms.curdir, cur_msg);
17523 }
17524
17525 /* close mailbox */
17526 if ((res = close_mailbox(&from_vms, vmu) == ERROR_LOCK_PATH)) {
17527 res = -1;
17528 goto vm_forward_cleanup;
17529 }
17530 open = 0;
17531
17532 vm_forward_cleanup:
17533 if (vmu && open) {
17534 close_mailbox(&from_vms, vmu);
17535 }
17536 #ifdef IMAP_STORAGE
17537 if (vmu) {
17538 vmstate_delete(&from_vms);
17539 }
17540 #endif
17541
17542 if (!res) {
17543 notify_new_state(to_vmu);
17544 }
17545
17546 free_user(vmu);
17547 free_user(to_vmu);
17548 return res;
17549 }
17550
17551 static int vm_msg_move(const char *mailbox,
17552 const char *context,
17553 size_t num_msgs,
17554 const char *oldfolder,
17555 const char *old_msg_ids [],
17556 const char *newfolder)
17557 {
17558 struct vm_state vms;
17559 struct ast_vm_user *vmu = NULL, vmus;
17560 int old_folder_index;
17561 int new_folder_index;
17562 int open = 0;
17563 int res = 0;
17564 int i;
17565 int *old_msg_nums;
17566
17567 if (ast_strlen_zero(mailbox)) {
17568 ast_log(LOG_WARNING, "Cannot move message because no mailbox was specified\n");
17569 return -1;
17570 }
17571
17572 if (!num_msgs) {
17573 ast_log(LOG_WARNING, "Invalid number of messages specified to move: %zu\n", num_msgs);
17574 return -1;
17575 }
17576
17577 if (ast_strlen_zero(oldfolder) || ast_strlen_zero(newfolder)) {
17578 ast_log(LOG_WARNING, "Cannot move message because either oldfolder or newfolder was not specified\n");
17579 return -1;
17580 }
17581
17582 old_folder_index = get_folder_by_name(oldfolder);
17583 new_folder_index = get_folder_by_name(newfolder);
17584
17585 memset(&vmus, 0, sizeof(vmus));
17586 memset(&vms, 0, sizeof(vms));
17587
17588 if (old_folder_index == -1 || new_folder_index == -1) {
17589 return -1;
17590 }
17591
17592 if (!(vmu = find_user(&vmus, context, mailbox))) {
17593 return -1;
17594 }
17595
17596 ast_copy_string(vms.username, mailbox, sizeof(vms.username));
17597 vms.lastmsg = -1;
17598 open = 0;
17599
17600 /* open the mailbox state */
17601 if ((res = open_mailbox(&vms, vmu, old_folder_index)) < 0) {
17602 ast_log(LOG_WARNING, "Could not open mailbox %s\n", mailbox);
17603 res = -1;
17604 goto vm_move_cleanup;
17605 }
17606
17607 open = 1;
17608
17609 if ((vms.lastmsg + 1) < num_msgs) {
17610 ast_log(LOG_WARNING, "Folder %s has less than %zu messages\n", oldfolder, num_msgs);
17611 res = -1;
17612 goto vm_move_cleanup;
17613 }
17614
17615 old_msg_nums = ast_alloca(sizeof(int) * num_msgs);
17616
17617 if ((res = message_range_and_existence_check(&vms, old_msg_ids, num_msgs, old_msg_nums, vmu)) < 0) {
17618 goto vm_move_cleanup;
17619 }
17620
17621 /* Now actually move the message */
17622 for (i = 0; i < num_msgs; ++i) {
17623 if (save_to_folder(vmu, &vms, old_msg_nums[i], new_folder_index, NULL, 0)) {
17624 res = -1;
17625 goto vm_move_cleanup;
17626 }
17627 vms.deleted[old_msg_nums[i]] = 1;
17628 }
17629
17630 /* close mailbox */
17631 if ((res = close_mailbox(&vms, vmu) == ERROR_LOCK_PATH)) {
17632 res = -1;
17633 goto vm_move_cleanup;
17634 }
17635 open = 0;
17636
17637 vm_move_cleanup:
17638 if (vmu && open) {
17639 close_mailbox(&vms, vmu);
17640 }
17641 #ifdef IMAP_STORAGE
17642 if (vmu) {
17643 vmstate_delete(&vms);
17644 }
17645 #endif
17646
17647 if (!res) {
17648 notify_new_state(vmu);
17649 }
17650
17651 free_user(vmu);
17652 return res;
17653 }
17654
17655 static int vm_msg_remove(const char *mailbox,
17656 const char *context,
17657 size_t num_msgs,
17658 const char *folder,
17659 const char *msgs[])
17660 {
17661 struct vm_state vms;
17662 struct ast_vm_user *vmu = NULL, vmus;
17663 int folder_index;
17664 int open = 0;
17665 int res = 0;
17666 int i;
17667 int *msg_nums;
17668
17669 if (ast_strlen_zero(mailbox)) {
17670 ast_log(LOG_WARNING, "Cannot remove message because no mailbox was specified\n");
17671 return -1;
17672 }
17673
17674 if (!num_msgs) {
17675 ast_log(LOG_WARNING, "Invalid number of messages specified to remove: %zu\n", num_msgs);
17676 return -1;
17677 }
17678
17679 if (ast_strlen_zero(folder)) {
17680 ast_log(LOG_WARNING, "Cannot remove message because no folder was specified\n");
17681 return -1;
17682 }
17683
17684 memset(&vmus, 0, sizeof(vmus));
17685 memset(&vms, 0, sizeof(vms));
17686
17687 folder_index = get_folder_by_name(folder);
17688 if (folder_index == -1) {
17689 ast_log(LOG_WARNING, "Could not remove msgs from unknown folder %s\n", folder);
17690 return -1;
17691 }
17692
17693 if (!(vmu = find_user(&vmus, context, mailbox))) {
17694 ast_log(LOG_WARNING, "Can't find voicemail user to remove msg from (%s@%s)\n", mailbox, context);
17695 return -1;
17696 }
17697
17698 ast_copy_string(vms.username, mailbox, sizeof(vms.username));
17699 vms.lastmsg = -1;
17700 open = 0;
17701
17702 /* open the mailbox state */
17703 if ((res = open_mailbox(&vms, vmu, folder_index)) < 0) {
17704 ast_log(LOG_WARNING, "Could not open mailbox %s\n", mailbox);
17705 res = -1;
17706 goto vm_remove_cleanup;
17707 }
17708
17709 open = 1;
17710
17711 if ((vms.lastmsg + 1) < num_msgs) {
17712 ast_log(LOG_WARNING, "Folder %s has less than %zu messages\n", folder, num_msgs);
17713 res = -1;
17714 goto vm_remove_cleanup;
17715 }
17716
17717 msg_nums = ast_alloca(sizeof(int) * num_msgs);
17718
17719 if ((res = message_range_and_existence_check(&vms, msgs, num_msgs, msg_nums, vmu)) < 0) {
17720 goto vm_remove_cleanup;
17721 }
17722
17723 for (i = 0; i < num_msgs; i++) {
17724 vms.deleted[msg_nums[i]] = 1;
17725 }
17726
17727 /* close mailbox */
17728 if ((res = close_mailbox(&vms, vmu) == ERROR_LOCK_PATH)) {
17729 res = -1;
17730 ast_log(AST_LOG_ERROR, "Failed to close mailbox folder %s while removing msgs\n", folder);
17731 goto vm_remove_cleanup;
17732 }
17733 open = 0;
17734
17735 vm_remove_cleanup:
17736 if (vmu && open) {
17737 close_mailbox(&vms, vmu);
17738 }
17739 #ifdef IMAP_STORAGE
17740 if (vmu) {
17741 vmstate_delete(&vms);
17742 }
17743 #endif
17744
17745 if (!res) {
17746 notify_new_state(vmu);
17747 }
17748
17749 free_user(vmu);
17750 return res;
17751 }
17752
17753 static int vm_msg_play(struct ast_channel *chan,
17754 const char *mailbox,
17755 const char *context,
17756 const char *folder,
17757 const char *msg_id,
17758 ast_vm_msg_play_cb cb)
17759 {
17760 struct vm_state vms;
17761 struct ast_vm_user *vmu = NULL, vmus;
17762 int res = 0;
17763 int open = 0;
17764 int i;
17765 char filename[PATH_MAX];
17766 struct ast_config *msg_cfg;
17767 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
17768 int duration = 0;
17769 const char *value;
17770
17771 if (ast_strlen_zero(mailbox)) {
17772 ast_log(LOG_WARNING, "Cannot play message because no mailbox was specified\n");
17773 return -1;
17774 }
17775
17776 if (ast_strlen_zero(folder)) {
17777 ast_log(LOG_WARNING, "Cannot play message because no folder was specified\n");
17778 return -1;
17779 }
17780
17781 if (ast_strlen_zero(msg_id)) {
17782 ast_log(LOG_WARNING, "Cannot play message because no message number was specified\n");
17783 return -1;
17784 }
17785
17786 memset(&vmus, 0, sizeof(vmus));
17787 memset(&vms, 0, sizeof(vms));
17788
17789 if (ast_strlen_zero(context)) {
17790 context = "default";
17791 }
17792
17793 if (!(vmu = find_user(&vmus, context, mailbox))) {
17794 return -1;
17795 }
17796
17797 i = get_folder_by_name(folder);
17798 ast_copy_string(vms.username, mailbox, sizeof(vms.username));
17799 vms.lastmsg = -1;
17800 if ((res = open_mailbox(&vms, vmu, i)) < 0) {
17801 ast_log(LOG_WARNING, "Could not open mailbox %s\n", mailbox);
17802 goto play2_msg_cleanup;
17803 }
17804 open = 1;
17805
17806 if (message_range_and_existence_check(&vms, &msg_id, 1, &vms.curmsg, vmu)) {
17807 res = -1;
17808 goto play2_msg_cleanup;
17809 }
17810
17811 /* Find the msg */
17812 make_file(vms.fn, sizeof(vms.fn), vms.curdir, vms.curmsg);
17813 snprintf(filename, sizeof(filename), "%s.txt", vms.fn);
17814 RETRIEVE(vms.curdir, vms.curmsg, vmu->mailbox, vmu->context);
17815
17816 msg_cfg = ast_config_load(filename, config_flags);
17817 if (!msg_cfg || msg_cfg == CONFIG_STATUS_FILEINVALID) {
17818 DISPOSE(vms.curdir, vms.curmsg);
17819 res = -1;
17820 goto play2_msg_cleanup;
17821 }
17822 if ((value = ast_variable_retrieve(msg_cfg, "message", "duration"))) {
17823 duration = atoi(value);
17824 }
17825 ast_config_destroy(msg_cfg);
17826
17827 #ifdef IMAP_STORAGE
17828 /*IMAP storage stores any prepended message from a forward
17829 * as a separate file from the rest of the message
17830 */
17831 if (!ast_strlen_zero(vms.introfn) && ast_fileexists(vms.introfn, NULL, NULL) > 0) {
17832 wait_file(chan, &vms, vms.introfn);
17833 }
17834 #endif
17835 if (cb) {
17836 cb(chan, vms.fn, duration);
17837 } else if ((wait_file(chan, &vms, vms.fn)) < 0) {
17838 ast_log(AST_LOG_WARNING, "Playback of message %s failed\n", vms.fn);
17839 } else {
17840 res = 0;
17841 }
17842
17843 vms.heard[vms.curmsg] = 1;
17844
17845 /* cleanup configs and msg */
17846 DISPOSE(vms.curdir, vms.curmsg);
17847
17848 play2_msg_cleanup:
17849 if (vmu && open) {
17850 close_mailbox(&vms, vmu);
17851 }
17852
17853 #ifdef IMAP_STORAGE
17854 if (vmu) {
17855 vmstate_delete(&vms);
17856 }
17857 #endif
17858
17859 if (!res) {
17860 notify_new_state(vmu);
17861 }
17862
17863 free_user(vmu);
17864 return res;
17865 }
17866
17867 /* This is a workaround so that menuselect displays a proper description
17868 * AST_MODULE_INFO(, , "Comedian Mail (Voicemail System)"
17869 */
17870
17871 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
17872 .support_level = AST_MODULE_SUPPORT_CORE,
17873 .load = load_module,
17874 .unload = unload_module,
17875 .reload = reload,
17876 .optional_modules = "res_adsi,res_smdi",
17877 );