BuildSystem: Remove unused dependency on libltdl.
[asterisk/asterisk.git] / apps / app_voicemail.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \author Mark Spencer <markster@digium.com>
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 Config_vm
30  * \note For information about voicemail IMAP storage, https://wiki.asterisk.org/wiki/display/AST/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 /*** MODULEINFO
50         <defaultenabled>yes</defaultenabled>
51         <use type="module">res_adsi</use>
52         <use type="module">res_smdi</use>
53         <support_level>core</support_level>
54  ***/
55
56 /*** MAKEOPTS
57 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" touch_on_change="apps/app_voicemail.c apps/app_directory.c">
58         <member name="FILE_STORAGE" displayname="Storage of Voicemail using filesystem">
59                 <conflict>ODBC_STORAGE</conflict>
60                 <conflict>IMAP_STORAGE</conflict>
61                 <defaultenabled>yes</defaultenabled>
62                 <support_level>core</support_level>
63         </member>
64         <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
65                 <depend>generic_odbc</depend>
66                 <conflict>IMAP_STORAGE</conflict>
67                 <conflict>FILE_STORAGE</conflict>
68                 <defaultenabled>no</defaultenabled>
69                 <support_level>core</support_level>
70         </member>
71         <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
72                 <depend>imap_tk</depend>
73                 <conflict>ODBC_STORAGE</conflict>
74                 <conflict>FILE_STORAGE</conflict>
75                 <use type="external">openssl</use>
76                 <defaultenabled>no</defaultenabled>
77                 <support_level>core</support_level>
78         </member>
79 </category>
80 ***/
81
82 #include "asterisk.h"
83
84 #ifdef IMAP_STORAGE
85 #include <ctype.h>
86 #include <signal.h>
87 #include <pwd.h>
88 #ifdef USE_SYSTEM_IMAP
89 #include <imap/c-client.h>
90 #include <imap/imap4r1.h>
91 #include <imap/linkage.h>
92 #elif defined (USE_SYSTEM_CCLIENT)
93 #include <c-client/c-client.h>
94 #include <c-client/imap4r1.h>
95 #include <c-client/linkage.h>
96 #else
97 #include "c-client.h"
98 #include "imap4r1.h"
99 #include "linkage.h"
100 #endif
101 #endif
102
103 #include "asterisk/paths.h"     /* use ast_config_AST_SPOOL_DIR */
104 #include <sys/time.h>
105 #include <sys/stat.h>
106 #include <sys/mman.h>
107 #include <time.h>
108 #include <dirent.h>
109 #if defined(__FreeBSD__) || defined(__OpenBSD__)
110 #include <sys/wait.h>
111 #endif
112
113 #include "asterisk/logger.h"
114 #include "asterisk/lock.h"
115 #include "asterisk/file.h"
116 #include "asterisk/channel.h"
117 #include "asterisk/pbx.h"
118 #include "asterisk/config.h"
119 #include "asterisk/say.h"
120 #include "asterisk/module.h"
121 #include "asterisk/adsi.h"
122 #include "asterisk/app.h"
123 #include "asterisk/manager.h"
124 #include "asterisk/dsp.h"
125 #include "asterisk/localtime.h"
126 #include "asterisk/cli.h"
127 #include "asterisk/utils.h"
128 #include "asterisk/stringfields.h"
129 #include "asterisk/strings.h"
130 #include "asterisk/smdi.h"
131 #include "asterisk/astobj2.h"
132 #include "asterisk/taskprocessor.h"
133 #include "asterisk/test.h"
134 #include "asterisk/format_cache.h"
135
136 #ifdef ODBC_STORAGE
137 #include "asterisk/res_odbc.h"
138 #endif
139
140 #ifdef IMAP_STORAGE
141 #include "asterisk/threadstorage.h"
142 #endif
143
144 /*** DOCUMENTATION
145         <application name="VoiceMail" language="en_US">
146                 <synopsis>
147                         Leave a Voicemail message.
148                 </synopsis>
149                 <syntax>
150                         <parameter name="mailboxs" argsep="&amp;" required="true">
151                                 <argument name="mailbox1" argsep="@" required="true">
152                                         <argument name="mailbox" required="true" />
153                                         <argument name="context" />
154                                 </argument>
155                                 <argument name="mailbox2" argsep="@" multiple="true">
156                                         <argument name="mailbox" required="true" />
157                                         <argument name="context" />
158                                 </argument>
159                         </parameter>
160                         <parameter name="options">
161                                 <optionlist>
162                                         <option name="b">
163                                                 <para>Play the <literal>busy</literal> greeting to the calling party.</para>
164                                         </option>
165                                         <option name="d">
166                                                 <argument name="c" />
167                                                 <para>Accept digits for a new extension in context <replaceable>c</replaceable>,
168                                                 if played during the greeting. Context defaults to the current context.</para>
169                                         </option>
170                                         <option name="g">
171                                                 <argument name="#" required="true" />
172                                                 <para>Use the specified amount of gain when recording the voicemail
173                                                 message. The units are whole-number decibels (dB). Only works on supported
174                                                 technologies, which is DAHDI only.</para>
175                                         </option>
176                                         <option name="s">
177                                                 <para>Skip the playback of instructions for leaving a message to the
178                                                 calling party.</para>
179                                         </option>
180                                         <option name="u">
181                                                 <para>Play the <literal>unavailable</literal> greeting.</para>
182                                         </option>
183                                         <option name="U">
184                                                 <para>Mark message as <literal>URGENT</literal>.</para>
185                                         </option>
186                                         <option name="P">
187                                                 <para>Mark message as <literal>PRIORITY</literal>.</para>
188                                         </option>
189                                 </optionlist>
190                         </parameter>
191                 </syntax>
192                 <description>
193                         <para>This application allows the calling party to leave a message for the specified
194                         list of mailboxes. When multiple mailboxes are specified, the greeting will be taken from
195                         the first mailbox specified. Dialplan execution will stop if the specified mailbox does not
196                         exist.</para>
197                         <para>The Voicemail application will exit if any of the following DTMF digits are received:</para>
198                         <enumlist>
199                                 <enum name="0">
200                                         <para>Jump to the <literal>o</literal> extension in the current dialplan context.</para>
201                                 </enum>
202                                 <enum name="*">
203                                         <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
204                                 </enum>
205                         </enumlist>
206                         <para>This application will set the following channel variable upon completion:</para>
207                         <variablelist>
208                                 <variable name="VMSTATUS">
209                                         <para>This indicates the status of the execution of the VoiceMail application.</para>
210                                         <value name="SUCCESS" />
211                                         <value name="USEREXIT" />
212                                         <value name="FAILED" />
213                                 </variable>
214                         </variablelist>
215                 </description>
216                 <see-also>
217                         <ref type="application">VoiceMailMain</ref>
218                 </see-also>
219         </application>
220         <application name="VoiceMailMain" language="en_US">
221                 <synopsis>
222                         Check Voicemail messages.
223                 </synopsis>
224                 <syntax>
225                         <parameter name="mailbox" required="true" argsep="@">
226                                 <argument name="mailbox" />
227                                 <argument name="context" />
228                         </parameter>
229                         <parameter name="options">
230                                 <optionlist>
231                                         <option name="p">
232                                                 <para>Consider the <replaceable>mailbox</replaceable> parameter as a prefix to
233                                                 the mailbox that is entered by the caller.</para>
234                                         </option>
235                                         <option name="g">
236                                                 <argument name="#" required="true" />
237                                                 <para>Use the specified amount of gain when recording a voicemail message.
238                                                 The units are whole-number decibels (dB).</para>
239                                         </option>
240                                         <option name="s">
241                                                 <para>Skip checking the passcode for the mailbox.</para>
242                                         </option>
243                                         <option name="a">
244                                                 <argument name="folder" required="true" />
245                                                 <para>Skip folder prompt and go directly to <replaceable>folder</replaceable> specified.
246                                                 Defaults to <literal>INBOX</literal> (or <literal>0</literal>).</para>
247                                                 <enumlist>
248                                                         <enum name="0"><para>INBOX</para></enum>
249                                                         <enum name="1"><para>Old</para></enum>
250                                                         <enum name="2"><para>Work</para></enum>
251                                                         <enum name="3"><para>Family</para></enum>
252                                                         <enum name="4"><para>Friends</para></enum>
253                                                         <enum name="5"><para>Cust1</para></enum>
254                                                         <enum name="6"><para>Cust2</para></enum>
255                                                         <enum name="7"><para>Cust3</para></enum>
256                                                         <enum name="8"><para>Cust4</para></enum>
257                                                         <enum name="9"><para>Cust5</para></enum>
258                                                 </enumlist>
259                                         </option>
260                                 </optionlist>
261                         </parameter>
262                 </syntax>
263                 <description>
264                         <para>This application allows the calling party to check voicemail messages. A specific
265                         <replaceable>mailbox</replaceable>, and optional corresponding <replaceable>context</replaceable>,
266                         may be specified. If a <replaceable>mailbox</replaceable> is not provided, the calling party will
267                         be prompted to enter one. If a <replaceable>context</replaceable> is not specified, the
268                         <literal>default</literal> context will be used.</para>
269                         <para>The VoiceMailMain application will exit if the following DTMF digit is entered as Mailbox
270                         or Password, and the extension exists:</para>
271                         <enumlist>
272                                 <enum name="*">
273                                         <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
274                                 </enum>
275                         </enumlist>
276                 </description>
277                 <see-also>
278                         <ref type="application">VoiceMail</ref>
279                 </see-also>
280         </application>
281         <application name="MailboxExists" language="en_US">
282                 <synopsis>
283                         Check to see if Voicemail mailbox exists.
284                 </synopsis>
285                 <syntax>
286                         <parameter name="mailbox" required="true" argsep="@">
287                                 <argument name="mailbox" required="true" />
288                                 <argument name="context" />
289                         </parameter>
290                         <parameter name="options">
291                                 <para>None options.</para>
292                         </parameter>
293                 </syntax>
294                 <description>
295                         <note><para>DEPRECATED. Use VM_INFO(mailbox[@context],exists) instead.</para></note>
296                         <para>Check to see if the specified <replaceable>mailbox</replaceable> exists. If no voicemail
297                         <replaceable>context</replaceable> is specified, the <literal>default</literal> context
298                         will be used.</para>
299                         <para>This application will set the following channel variable upon completion:</para>
300                         <variablelist>
301                                 <variable name="VMBOXEXISTSSTATUS">
302                                         <para>This will contain the status of the execution of the MailboxExists application.
303                                         Possible values include:</para>
304                                         <value name="SUCCESS" />
305                                         <value name="FAILED" />
306                                 </variable>
307                         </variablelist>
308                 </description>
309                 <see-also>
310                         <ref type="function">VM_INFO</ref>
311                 </see-also>
312         </application>
313         <application name="VMAuthenticate" language="en_US">
314                 <synopsis>
315                         Authenticate with Voicemail passwords.
316                 </synopsis>
317                 <syntax>
318                         <parameter name="mailbox" required="true" argsep="@">
319                                 <argument name="mailbox" />
320                                 <argument name="context" />
321                         </parameter>
322                         <parameter name="options">
323                                 <optionlist>
324                                         <option name="s">
325                                                 <para>Skip playing the initial prompts.</para>
326                                         </option>
327                                 </optionlist>
328                         </parameter>
329                 </syntax>
330                 <description>
331                         <para>This application behaves the same way as the Authenticate application, but the passwords
332                         are taken from <filename>voicemail.conf</filename>. If the <replaceable>mailbox</replaceable> is
333                         specified, only that mailbox's password will be considered valid. If the <replaceable>mailbox</replaceable>
334                         is not specified, the channel variable <variable>AUTH_MAILBOX</variable> will be set with the authenticated
335                         mailbox.</para>
336                         <para>The VMAuthenticate application will exit if the following DTMF digit is entered as Mailbox
337                         or Password, and the extension exists:</para>
338                         <enumlist>
339                                 <enum name="*">
340                                         <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
341                                 </enum>
342                         </enumlist>
343                 </description>
344         </application>
345         <application name="VoiceMailPlayMsg" language="en_US">
346                 <synopsis>
347                         Play a single voice mail msg from a mailbox by msg id.
348                 </synopsis>
349                 <syntax>
350                         <parameter name="mailbox" required="true" argsep="@">
351                                 <argument name="mailbox" />
352                                 <argument name="context" />
353                         </parameter>
354                         <parameter name="msg_id" required="true">
355                                 <para>The msg id of the msg to play back. </para>
356                         </parameter>
357                 </syntax>
358                 <description>
359                         <para>This application sets the following channel variable upon completion:</para>
360                         <variablelist>
361                                 <variable name="VOICEMAIL_PLAYBACKSTATUS">
362                                         <para>The status of the playback attempt as a text string.</para>
363                                         <value name="SUCCESS"/>
364                                         <value name="FAILED"/>
365                                 </variable>
366                         </variablelist>
367                 </description>
368         </application>
369         <application name="VMSayName" language="en_US">
370                 <synopsis>
371                         Play the name of a voicemail user
372                 </synopsis>
373                 <syntax>
374                         <parameter name="mailbox" required="true" argsep="@">
375                                 <argument name="mailbox" />
376                                 <argument name="context" />
377                         </parameter>
378                 </syntax>
379                 <description>
380                         <para>This application will say the recorded name of the voicemail user specified as the
381                         argument to this application. If no context is provided, <literal>default</literal> is assumed.</para>
382                 </description>
383         </application>
384         <function name="MAILBOX_EXISTS" language="en_US">
385                 <synopsis>
386                         Tell if a mailbox is configured.
387                 </synopsis>
388                 <syntax argsep="@">
389                         <parameter name="mailbox" required="true" />
390                         <parameter name="context" />
391                 </syntax>
392                 <description>
393                         <note><para>DEPRECATED. Use VM_INFO(mailbox[@context],exists) instead.</para></note>
394                         <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.
395                         If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
396                         context.</para>
397                 </description>
398                 <see-also>
399                         <ref type="function">VM_INFO</ref>
400                 </see-also>
401         </function>
402         <function name="VM_INFO" language="en_US">
403                 <synopsis>
404                         Returns the selected attribute from a mailbox.
405                 </synopsis>
406                 <syntax argsep=",">
407                         <parameter name="mailbox" argsep="@" required="true">
408                                 <argument name="mailbox" required="true" />
409                                 <argument name="context" />
410                         </parameter>
411                         <parameter name="attribute" required="true">
412                                 <optionlist>
413                                         <option name="count">
414                                                 <para>Count of messages in specified <replaceable>folder</replaceable>.
415                                                 If <replaceable>folder</replaceable> is not specified, defaults to <literal>INBOX</literal>.</para>
416                                         </option>
417                                         <option name="email">
418                                                 <para>E-mail address associated with the mailbox.</para>
419                                         </option>
420                                         <option name="exists">
421                                                 <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.</para>
422                                         </option>
423                                         <option name="fullname">
424                                                 <para>Full name associated with the mailbox.</para>
425                                         </option>
426                                         <option name="language">
427                                                 <para>Mailbox language if overridden, otherwise the language of the channel.</para>
428                                         </option>
429                                         <option name="locale">
430                                                 <para>Mailbox locale if overridden, otherwise global locale.</para>
431                                         </option>
432                                         <option name="pager">
433                                                 <para>Pager e-mail address associated with the mailbox.</para>
434                                         </option>
435                                         <option name="password">
436                                                 <para>Mailbox access password.</para>
437                                         </option>
438                                         <option name="tz">
439                                                 <para>Mailbox timezone if overridden, otherwise global timezone</para>
440                                         </option>
441                                 </optionlist>
442                         </parameter>
443                         <parameter name="folder" required="false">
444                                 <para>If not specified, <literal>INBOX</literal> is assumed.</para>
445                         </parameter>
446                 </syntax>
447                 <description>
448                         <para>Returns the selected attribute from the specified <replaceable>mailbox</replaceable>.
449                         If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
450                         context. Where the <replaceable>folder</replaceable> can be specified, common folders
451                         include <literal>INBOX</literal>, <literal>Old</literal>, <literal>Work</literal>,
452                         <literal>Family</literal> and <literal>Friends</literal>.</para>
453                 </description>
454         </function>
455         <manager name="VoicemailUsersList" language="en_US">
456                 <synopsis>
457                         List All Voicemail User Information.
458                 </synopsis>
459                 <syntax>
460                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
461                 </syntax>
462                 <description>
463                 </description>
464         </manager>
465         <manager name="VoicemailUserStatus" language="en_US">
466                 <synopsis>
467                         Show the status of given voicemail user's info.
468                 </synopsis>
469                 <syntax>
470                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
471                         <parameter name="Context" required="true">
472                                 <para>The context you want to check.</para>
473                         </parameter>
474                         <parameter name="Mailbox" required="true">
475                                 <para>The mailbox you want to check.</para>
476                         </parameter>
477                 </syntax>
478                 <description>
479                         <para>Retrieves the status of the given voicemail user.</para>
480                 </description>
481         </manager>
482         <manager name="VoicemailRefresh" language="en_US">
483                 <synopsis>
484                         Tell Asterisk to poll mailboxes for a change
485                 </synopsis>
486                 <syntax>
487                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
488                         <parameter name="Context" />
489                         <parameter name="Mailbox" />
490                 </syntax>
491                 <description>
492                         <para>Normally, MWI indicators are only sent when Asterisk itself
493                         changes a mailbox.  With external programs that modify the content
494                         of a mailbox from outside the application, an option exists called
495                         <literal>pollmailboxes</literal> that will cause voicemail to
496                         continually scan all mailboxes on a system for changes.  This can
497                         cause a large amount of load on a system.  This command allows
498                         external applications to signal when a particular mailbox has
499                         changed, thus permitting external applications to modify mailboxes
500                         and MWI to work without introducing considerable CPU load.</para>
501                         <para>If <replaceable>Context</replaceable> is not specified, all
502                         mailboxes on the system will be polled for changes.  If
503                         <replaceable>Context</replaceable> is specified, but
504                         <replaceable>Mailbox</replaceable> is omitted, then all mailboxes
505                         within <replaceable>Context</replaceable> will be polled.
506                         Otherwise, only a single mailbox will be polled for changes.</para>
507                 </description>
508         </manager>
509  ***/
510
511 #ifdef IMAP_STORAGE
512 static char imapserver[48];
513 static char imapport[8];
514 static char imapflags[128];
515 static char imapfolder[64];
516 static char imapparentfolder[64] = "\0";
517 static char greetingfolder[64];
518 static char authuser[32];
519 static char authpassword[42];
520 static int imapversion = 1;
521
522 static int expungeonhangup = 1;
523 static int imapgreetings = 0;
524 static int imap_poll_logout = 0;
525 static char delimiter = '\0';
526
527 /* mail_open cannot be protected on a stream basis */
528 ast_mutex_t mail_open_lock;
529
530 struct vm_state;
531 struct ast_vm_user;
532
533 AST_THREADSTORAGE(ts_vmstate);
534
535 /* Forward declarations for IMAP */
536 static int init_mailstream(struct vm_state *vms, int box);
537 static void write_file(char *filename, char *buffer, unsigned long len);
538 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
539 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu);
540 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
541 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive);
542 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
543 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
544 static void vmstate_insert(struct vm_state *vms);
545 static void vmstate_delete(struct vm_state *vms);
546 static void set_update(MAILSTREAM * stream);
547 static void init_vm_state(struct vm_state *vms);
548 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
549 static void get_mailbox_delimiter(struct vm_state *vms, MAILSTREAM *stream);
550 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
551 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
552 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);
553 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);
554 static void update_messages_by_imapuser(const char *user, unsigned long number);
555 static int vm_delete(char *file);
556
557 static int imap_remove_file (char *dir, int msgnum);
558 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
559 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
560 static void check_quota(struct vm_state *vms, char *mailbox);
561 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
562 static void imap_logout(const char *mailbox_id);
563
564 struct vmstate {
565         struct vm_state *vms;
566         AST_LIST_ENTRY(vmstate) list;
567 };
568
569 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
570
571 #endif
572
573 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
574
575 #define COMMAND_TIMEOUT 5000
576 /* Don't modify these here; set your umask at runtime instead */
577 #define VOICEMAIL_DIR_MODE      0777
578 #define VOICEMAIL_FILE_MODE     0666
579 #define CHUNKSIZE       65536
580
581 #define VOICEMAIL_CONFIG "voicemail.conf"
582 #define ASTERISK_USERNAME "asterisk"
583
584 /* Define fast-forward, pause, restart, and reverse keys
585  * while listening to a voicemail message - these are
586  * strings, not characters */
587 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
588 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
589 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
590 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
591 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
592 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
593
594 /* Default mail command to mail voicemail. Change it with the
595  * mailcmd= command in voicemail.conf */
596 #define SENDMAIL "/usr/sbin/sendmail -t"
597
598 #define INTRO "vm-intro"
599
600 #define MAX_MAIL_BODY_CONTENT_SIZE 134217728L // 128 Mbyte
601
602 #define MAXMSG 100
603 #define MAXMSGLIMIT 9999
604
605 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
606
607 #define BASELINELEN 72
608 #define BASEMAXINLINE 256
609 #ifdef IMAP_STORAGE
610 #define ENDL "\r\n"
611 #else
612 #define ENDL "\n"
613 #endif
614
615 #define MAX_DATETIME_FORMAT     512
616 #define MAX_NUM_CID_CONTEXTS 10
617
618 #define VM_REVIEW        (1 << 0)   /*!< After recording, permit the caller to review the recording before saving */
619 #define VM_OPERATOR      (1 << 1)   /*!< Allow 0 to be pressed to go to 'o' extension */
620 #define VM_SAYCID        (1 << 2)   /*!< Repeat the CallerID info during envelope playback */
621 #define VM_SVMAIL        (1 << 3)   /*!< Allow the user to compose a new VM from within VoicemailMain */
622 #define VM_ENVELOPE      (1 << 4)   /*!< Play the envelope information (who-from, time received, etc.) */
623 #define VM_SAYDURATION   (1 << 5)   /*!< Play the length of the message during envelope playback */
624 #define VM_SKIPAFTERCMD  (1 << 6)   /*!< After deletion, assume caller wants to go to the next message */
625 #define VM_FORCENAME     (1 << 7)   /*!< Have new users record their name */
626 #define VM_FORCEGREET    (1 << 8)   /*!< Have new users record their greetings */
627 #define VM_PBXSKIP       (1 << 9)   /*!< Skip the [PBX] preamble in the Subject line of emails */
628 #define VM_DIRECFORWARD  (1 << 10)  /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
629 #define VM_ATTACH        (1 << 11)  /*!< Attach message to voicemail notifications? */
630 #define VM_DELETE        (1 << 12)  /*!< Delete message after sending notification */
631 #define VM_ALLOCED       (1 << 13)  /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
632 #define VM_SEARCH        (1 << 14)  /*!< Search all contexts for a matching mailbox */
633 #define VM_TEMPGREETWARN (1 << 15)  /*!< Remind user tempgreeting is set */
634 #define VM_MOVEHEARD     (1 << 16)  /*!< Move a "heard" message to Old after listening to it */
635 #define VM_MESSAGEWRAP   (1 << 17)  /*!< Wrap around from the last message to the first, and vice-versa */
636 #define VM_FWDURGAUTO    (1 << 18)  /*!< Autoset of Urgent flag on forwarded Urgent messages set globally */
637 #define ERROR_LOCK_PATH  -100
638 #define ERROR_MAX_MSGS   -101
639 #define OPERATOR_EXIT     300
640
641 enum vm_box {
642         NEW_FOLDER =            0,
643         OLD_FOLDER =            1,
644         WORK_FOLDER =           2,
645         FAMILY_FOLDER =         3,
646         FRIENDS_FOLDER =        4,
647         GREETINGS_FOLDER =      -1
648 };
649
650 enum vm_option_flags {
651         OPT_SILENT =           (1 << 0),
652         OPT_BUSY_GREETING =    (1 << 1),
653         OPT_UNAVAIL_GREETING = (1 << 2),
654         OPT_RECORDGAIN =       (1 << 3),
655         OPT_PREPEND_MAILBOX =  (1 << 4),
656         OPT_AUTOPLAY =         (1 << 6),
657         OPT_DTMFEXIT =         (1 << 7),
658         OPT_MESSAGE_Urgent =   (1 << 8),
659         OPT_MESSAGE_PRIORITY = (1 << 9)
660 };
661
662 enum vm_option_args {
663         OPT_ARG_RECORDGAIN = 0,
664         OPT_ARG_PLAYFOLDER = 1,
665         OPT_ARG_DTMFEXIT   = 2,
666         /* This *must* be the last value in this enum! */
667         OPT_ARG_ARRAY_SIZE = 3,
668 };
669
670 enum vm_passwordlocation {
671         OPT_PWLOC_VOICEMAILCONF = 0,
672         OPT_PWLOC_SPOOLDIR      = 1,
673         OPT_PWLOC_USERSCONF     = 2,
674 };
675
676 AST_APP_OPTIONS(vm_app_options, {
677         AST_APP_OPTION('s', OPT_SILENT),
678         AST_APP_OPTION('b', OPT_BUSY_GREETING),
679         AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
680         AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
681         AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
682         AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
683         AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
684         AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
685         AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY)
686 });
687
688 static const char * const mailbox_folders[] = {
689 #ifdef IMAP_STORAGE
690         imapfolder,
691 #else
692         "INBOX",
693 #endif
694         "Old",
695         "Work",
696         "Family",
697         "Friends",
698         "Cust1",
699         "Cust2",
700         "Cust3",
701         "Cust4",
702         "Cust5",
703         "Deleted",
704         "Urgent",
705 };
706
707 static int load_config(int reload);
708 #ifdef TEST_FRAMEWORK
709 static int load_config_from_memory(int reload, struct ast_config *cfg, struct ast_config *ucfg);
710 #endif
711 static int actual_load_config(int reload, struct ast_config *cfg, struct ast_config *ucfg);
712
713 /*! \page vmlang Voicemail Language Syntaxes Supported
714
715         \par Syntaxes supported, not really language codes.
716         \arg \b en    - English
717         \arg \b de    - German
718         \arg \b es    - Spanish
719         \arg \b fr    - French
720         \arg \b it    - Italian
721         \arg \b nl    - Dutch
722         \arg \b pt    - Portuguese
723         \arg \b pt_BR - Portuguese (Brazil)
724         \arg \b gr    - Greek
725         \arg \b no    - Norwegian
726         \arg \b se    - Swedish
727         \arg \b tw    - Chinese (Taiwan)
728         \arg \b ua - Ukrainian
729
730 German requires the following additional soundfile:
731 \arg \b 1F      einE (feminine)
732
733 Spanish requires the following additional soundfile:
734 \arg \b 1M      un (masculine)
735
736 Dutch, Portuguese & Spanish require the following additional soundfiles:
737 \arg \b vm-INBOXs       singular of 'new'
738 \arg \b vm-Olds         singular of 'old/heard/read'
739
740 NB these are plural:
741 \arg \b vm-INBOX        nieuwe (nl)
742 \arg \b vm-Old          oude (nl)
743
744 Polish uses:
745 \arg \b vm-new-a        'new', feminine singular accusative
746 \arg \b vm-new-e        'new', feminine plural accusative
747 \arg \b vm-new-ych      'new', feminine plural genitive
748 \arg \b vm-old-a        'old', feminine singular accusative
749 \arg \b vm-old-e        'old', feminine plural accusative
750 \arg \b vm-old-ych      'old', feminine plural genitive
751 \arg \b digits/1-a      'one', not always same as 'digits/1'
752 \arg \b digits/2-ie     'two', not always same as 'digits/2'
753
754 Swedish uses:
755 \arg \b vm-nytt         singular of 'new'
756 \arg \b vm-nya          plural of 'new'
757 \arg \b vm-gammalt      singular of 'old'
758 \arg \b vm-gamla        plural of 'old'
759 \arg \b digits/ett      'one', not always same as 'digits/1'
760
761 Norwegian uses:
762 \arg \b vm-ny           singular of 'new'
763 \arg \b vm-nye          plural of 'new'
764 \arg \b vm-gammel       singular of 'old'
765 \arg \b vm-gamle        plural of 'old'
766
767 Dutch also uses:
768 \arg \b nl-om           'at'?
769
770 Spanish also uses:
771 \arg \b vm-youhaveno
772
773 Italian requires the following additional soundfile:
774
775 For vm_intro_it:
776 \arg \b vm-nuovo        new
777 \arg \b vm-nuovi        new plural
778 \arg \b vm-vecchio      old
779 \arg \b vm-vecchi       old plural
780
781 Japanese requires the following additional soundfile:
782 \arg \b jp-arimasu          there is
783 \arg \b jp-arimasen         there is not
784 \arg \b jp-oshitekudasai    please press
785 \arg \b jp-ni               article ni
786 \arg \b jp-ga               article ga
787 \arg \b jp-wa               article wa
788 \arg \b jp-wo               article wo
789
790 Chinese (Taiwan) requires the following additional soundfile:
791 \arg \b vm-tong         A class-word for call (tong1)
792 \arg \b vm-ri           A class-word for day (ri4)
793 \arg \b vm-you          You (ni3)
794 \arg \b vm-haveno   Have no (mei2 you3)
795 \arg \b vm-have     Have (you3)
796 \arg \b vm-listen   To listen (yao4 ting1)
797
798
799 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
800 spelled among others when you have to change folder. For the above reasons, vm-INBOX
801 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
802
803 */
804
805 struct baseio {
806         int iocp;
807         int iolen;
808         int linelength;
809         int ateof;
810         unsigned char iobuf[BASEMAXINLINE];
811 };
812
813 /*! Structure for linked list of users
814  * Use ast_vm_user_destroy() to free one of these structures. */
815 struct ast_vm_user {
816         char context[AST_MAX_CONTEXT];   /*!< Voicemail context */
817         char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
818         char password[80];               /*!< Secret pin code, numbers only */
819         char fullname[80];               /*!< Full name, for directory app */
820         char *email;                     /*!< E-mail address */
821         char *emailsubject;              /*!< E-mail subject */
822         char *emailbody;                 /*!< E-mail body */
823         char pager[80];                  /*!< E-mail address to pager (no attachment) */
824         char serveremail[80];            /*!< From: Mail address */
825         char fromstring[100];            /*!< From: Username */
826         char language[MAX_LANGUAGE];     /*!< Config: Language setting */
827         char zonetag[80];                /*!< Time zone */
828         char locale[20];                 /*!< The locale (for presentation of date/time) */
829         char callback[80];
830         char dialout[80];
831         char uniqueid[80];               /*!< Unique integer identifier */
832         char exit[80];
833         char attachfmt[20];              /*!< Attachment format */
834         unsigned int flags;              /*!< VM_ flags */
835         int saydurationm;
836         int minsecs;                     /*!< Minimum number of seconds per message for this mailbox */
837         int maxmsg;                      /*!< Maximum number of msgs per folder for this mailbox */
838         int maxdeletedmsg;               /*!< Maximum number of deleted msgs saved for this mailbox */
839         int maxsecs;                     /*!< Maximum number of seconds per message for this mailbox */
840         int passwordlocation;            /*!< Storage location of the password */
841 #ifdef IMAP_STORAGE
842         char imapserver[48];             /*!< IMAP server address */
843         char imapport[8];                /*!< IMAP server port */
844         char imapflags[128];             /*!< IMAP optional flags */
845         char imapuser[80];               /*!< IMAP server login */
846         char imappassword[80];           /*!< IMAP server password if authpassword not defined */
847         char imapfolder[64];             /*!< IMAP voicemail folder */
848         char imapvmshareid[80];          /*!< Shared mailbox ID to use rather than the dialed one */
849         int imapversion;                 /*!< If configuration changes, use the new values */
850 #endif
851         double volgain;                  /*!< Volume gain for voicemails sent via email */
852         AST_LIST_ENTRY(ast_vm_user) list;
853 };
854
855 /*! Voicemail time zones */
856 struct vm_zone {
857         AST_LIST_ENTRY(vm_zone) list;
858         char name[80];
859         char timezone[80];
860         char msg_format[512];
861 };
862
863 #define VMSTATE_MAX_MSG_ARRAY 256
864
865 /*! Voicemail mailbox state */
866 struct vm_state {
867         char curbox[80];
868         char username[80];
869         char context[80];
870         char curdir[PATH_MAX];
871         char vmbox[PATH_MAX];
872         char fn[PATH_MAX];
873         char intro[PATH_MAX];
874         int *deleted;
875         int *heard;
876         int dh_arraysize; /* used for deleted / heard allocation */
877         int curmsg;
878         int lastmsg;
879         int newmessages;
880         int oldmessages;
881         int urgentmessages;
882         int starting;
883         int repeats;
884 #ifdef IMAP_STORAGE
885         ast_mutex_t lock;
886         int updated;                         /*!< decremented on each mail check until 1 -allows delay */
887         long *msgArray;
888         unsigned msg_array_max;
889         MAILSTREAM *mailstream;
890         int vmArrayIndex;
891         char imapuser[80];                   /*!< IMAP server login */
892         char imapfolder[64];                 /*!< IMAP voicemail folder */
893         char imapserver[48];                 /*!< IMAP server address */
894         char imapport[8];                    /*!< IMAP server port */
895         char imapflags[128];                 /*!< IMAP optional flags */
896         int imapversion;
897         int interactive;
898         char introfn[PATH_MAX];              /*!< Name of prepended file */
899         unsigned int quota_limit;
900         unsigned int quota_usage;
901         struct vm_state *persist_vms;
902 #endif
903 };
904
905 #ifdef ODBC_STORAGE
906 static char odbc_database[80];
907 static char odbc_table[80];
908 #define RETRIEVE(a,b,c,d) retrieve_file(a,b)
909 #define DISPOSE(a,b) remove_file(a,b)
910 #define STORE(a,b,c,d,e,f,g,h,i,j,k) store_file(a,b,c,d)
911 #define EXISTS(a,b,c,d) (message_exists(a,b))
912 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
913 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
914 #define DELETE(a,b,c,d) (delete_file(a,b))
915 #define UPDATE_MSG_ID(a, b, c, d, e, f) (odbc_update_msg_id((a), (b), (c)))
916 #else
917 #ifdef IMAP_STORAGE
918 #define DISPOSE(a,b) (imap_remove_file(a,b))
919 #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))
920 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
921 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
922 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
923 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
924 #define DELETE(a,b,c,d) (vm_imap_delete(a,b,d))
925 #define UPDATE_MSG_ID(a, b, c, d, e, f) (vm_imap_update_msg_id((a), (b), (c), (d), (e), (f)))
926 #else
927 #define RETRIEVE(a,b,c,d)
928 #define DISPOSE(a,b)
929 #define STORE(a,b,c,d,e,f,g,h,i,j,k)
930 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
931 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
932 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
933 #define DELETE(a,b,c,d) (vm_delete(c))
934 #define UPDATE_MSG_ID(a, b, c, d, e, f)
935 #endif
936 #endif
937
938 static char VM_SPOOL_DIR[PATH_MAX];
939
940 static char ext_pass_cmd[128];
941 static char ext_pass_check_cmd[128];
942
943 static int my_umask;
944
945 #define PWDCHANGE_INTERNAL (1 << 1)
946 #define PWDCHANGE_EXTERNAL (1 << 2)
947 static int pwdchange = PWDCHANGE_INTERNAL;
948
949 #ifdef ODBC_STORAGE
950 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
951 #else
952 # ifdef IMAP_STORAGE
953 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
954 # else
955 # define tdesc "Comedian Mail (Voicemail System)"
956 # endif
957 #endif
958
959 static char userscontext[AST_MAX_EXTENSION] = "default";
960
961 static char *addesc = "Comedian Mail";
962
963 /* Leave a message */
964 static char *app = "VoiceMail";
965
966 /* Check mail, control, etc */
967 static char *app2 = "VoiceMailMain";
968
969 static char *app3 = "MailboxExists";
970 static char *app4 = "VMAuthenticate";
971
972 static char *playmsg_app = "VoiceMailPlayMsg";
973
974 static char *sayname_app = "VMSayName";
975
976 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
977 static AST_LIST_HEAD_STATIC(zones, vm_zone);
978 static char zonetag[80];
979 static char locale[20];
980 static int maxsilence;
981 static int maxmsg;
982 static int maxdeletedmsg;
983 static int silencethreshold = 128;
984 static char serveremail[80];
985 static char mailcmd[160];       /* Configurable mail cmd */
986 static char externnotify[160];
987 static struct ast_smdi_interface *smdi_iface = NULL;
988 static char vmfmts[80];
989 static double volgain;
990 static int vmminsecs;
991 static int vmmaxsecs;
992 static int maxgreet;
993 static int skipms;
994 static int maxlogins;
995 static int minpassword;
996 static int passwordlocation;
997
998 /*! Poll mailboxes for changes since there is something external to
999  *  app_voicemail that may change them. */
1000 static unsigned int poll_mailboxes;
1001
1002 /*! Polling frequency */
1003 static unsigned int poll_freq;
1004 /*! By default, poll every 30 seconds */
1005 #define DEFAULT_POLL_FREQ 30
1006
1007 AST_MUTEX_DEFINE_STATIC(poll_lock);
1008 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
1009 static pthread_t poll_thread = AST_PTHREADT_NULL;
1010 static unsigned char poll_thread_run;
1011
1012 /*! Subscription to MWI event subscription changes */
1013 static struct stasis_subscription *mwi_sub_sub;
1014
1015 /*!
1016  * \brief An MWI subscription
1017  *
1018  * This is so we can keep track of which mailboxes are subscribed to.
1019  * This way, we know which mailboxes to poll when the pollmailboxes
1020  * option is being used.
1021  */
1022 struct mwi_sub {
1023         AST_RWLIST_ENTRY(mwi_sub) entry;
1024         int old_urgent;
1025         int old_new;
1026         int old_old;
1027         char *uniqueid;
1028         char mailbox[1];
1029 };
1030
1031 struct mwi_sub_task {
1032         const char *mailbox;
1033         const char *context;
1034         const char *uniqueid;
1035 };
1036
1037 static void mwi_sub_task_dtor(struct mwi_sub_task *mwist)
1038 {
1039         ast_free((void *) mwist->mailbox);
1040         ast_free((void *) mwist->context);
1041         ast_free((void *) mwist->uniqueid);
1042         ast_free(mwist);
1043 }
1044
1045 static struct ast_taskprocessor *mwi_subscription_tps;
1046
1047 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
1048
1049 /* custom audio control prompts for voicemail playback */
1050 static char listen_control_forward_key[12];
1051 static char listen_control_reverse_key[12];
1052 static char listen_control_pause_key[12];
1053 static char listen_control_restart_key[12];
1054 static char listen_control_stop_key[12];
1055
1056 /* custom password sounds */
1057 static char vm_login[80] = "vm-login";
1058 static char vm_newuser[80] = "vm-newuser";
1059 static char vm_password[80] = "vm-password";
1060 static char vm_newpassword[80] = "vm-newpassword";
1061 static char vm_passchanged[80] = "vm-passchanged";
1062 static char vm_reenterpassword[80] = "vm-reenterpassword";
1063 static char vm_mismatch[80] = "vm-mismatch";
1064 static char vm_invalid_password[80] = "vm-invalid-password";
1065 static char vm_pls_try_again[80] = "vm-pls-try-again";
1066
1067 /*
1068  * XXX If we have the time, motivation, etc. to fix up this prompt, one of the following would be appropriate:
1069  * 1. create a sound along the lines of "Please try again.  When done, press the pound key" which could be spliced
1070  * from existing sound clips.  This would require some programming changes in the area of vm_forward options and also
1071  * app.c's __ast_play_and_record function
1072  * 2. create a sound prompt saying "Please try again.  When done recording, press any key to stop and send the prepended
1073  * message."  At the time of this comment, I think this would require new voice work to be commissioned.
1074  * 3. Something way different like providing instructions before a time out or a post-recording menu.  This would require
1075  * more effort than either of the other two.
1076  */
1077 static char vm_prepend_timeout[80] = "vm-then-pound";
1078
1079 static struct ast_flags globalflags = {0};
1080
1081 static int saydurationminfo;
1082
1083 static char dialcontext[AST_MAX_CONTEXT] = "";
1084 static char callcontext[AST_MAX_CONTEXT] = "";
1085 static char exitcontext[AST_MAX_CONTEXT] = "";
1086
1087 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
1088
1089
1090 static char *emailbody = NULL;
1091 static char *emailsubject = NULL;
1092 static char *pagerbody = NULL;
1093 static char *pagersubject = NULL;
1094 static char fromstring[100];
1095 static char pagerfromstring[100];
1096 static char charset[32] = "ISO-8859-1";
1097
1098 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
1099 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
1100 static int adsiver = 1;
1101 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
1102 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
1103
1104 /* Forward declarations - generic */
1105 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
1106 static int close_mailbox(struct vm_state *vms, struct ast_vm_user *vmu);
1107 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);
1108 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
1109 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
1110                         char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, int *sound_duration, const char *unlockdir,
1111                         signed char record_gain, struct vm_state *vms, char *flag, const char *msg_id, int forwardintro);
1112 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
1113 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
1114 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);
1115 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);
1116 static void apply_options(struct ast_vm_user *vmu, const char *options);
1117 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);
1118 static int is_valid_dtmf(const char *key);
1119 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
1120 static int write_password_to_file(const char *secretfn, const char *password);
1121 static const char *substitute_escapes(const char *value);
1122 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);
1123 static void notify_new_state(struct ast_vm_user *vmu);
1124 static int append_vmu_info_astman(struct mansession *s, struct ast_vm_user *vmu, const char* event_name, const char* actionid);
1125
1126
1127 /*!
1128  * Place a message in the indicated folder
1129  *
1130  * \param vmu Voicemail user
1131  * \param vms Current voicemail state for the user
1132  * \param msg The message number to save
1133  * \param box The folder into which the message should be saved
1134  * \param[out] newmsg The new message number of the saved message
1135  * \param move Tells whether to copy or to move the message
1136  *
1137  * \note the "move" parameter is only honored for IMAP voicemail presently
1138  * \retval 0 Success
1139  * \retval other Failure
1140  */
1141 static int save_to_folder(struct ast_vm_user *vmu, struct vm_state *vms, int msg, int box, int *newmsg, int move);
1142
1143 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);
1144 static struct ast_vm_mailbox_snapshot *vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot);
1145
1146 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);
1147 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);
1148 static int vm_msg_remove(const char *mailbox, const char *context, size_t num_msgs, const char *folder, const char *msgs[]);
1149 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);
1150
1151 #ifdef TEST_FRAMEWORK
1152 static int vm_test_destroy_user(const char *context, const char *mailbox);
1153 static int vm_test_create_user(const char *context, const char *mailbox);
1154 #endif
1155
1156 /*!
1157  * \internal
1158  * \brief Parse the given mailbox_id into mailbox and context.
1159  * \since 12.0.0
1160  *
1161  * \param mailbox_id The mailbox@context string to separate.
1162  * \param mailbox Where the mailbox part will start.
1163  * \param context Where the context part will start.  ("default" if not present)
1164  *
1165  * \retval 0 on success.
1166  * \retval -1 on error.
1167  */
1168 static int separate_mailbox(char *mailbox_id, char **mailbox, char **context)
1169 {
1170         if (ast_strlen_zero(mailbox_id) || !mailbox || !context) {
1171                 return -1;
1172         }
1173         *context = mailbox_id;
1174         *mailbox = strsep(context, "@");
1175         if (ast_strlen_zero(*mailbox)) {
1176                 return -1;
1177         }
1178         if (ast_strlen_zero(*context)) {
1179                 *context = "default";
1180         }
1181         return 0;
1182 }
1183
1184 struct ao2_container *inprocess_container;
1185
1186 struct inprocess {
1187         int count;
1188         char *context;
1189         char mailbox[0];
1190 };
1191
1192 static int inprocess_hash_fn(const void *obj, const int flags)
1193 {
1194         const struct inprocess *i = obj;
1195         return atoi(i->mailbox);
1196 }
1197
1198 static int inprocess_cmp_fn(void *obj, void *arg, int flags)
1199 {
1200         struct inprocess *i = obj, *j = arg;
1201         if (strcmp(i->mailbox, j->mailbox)) {
1202                 return 0;
1203         }
1204         return !strcmp(i->context, j->context) ? CMP_MATCH : 0;
1205 }
1206
1207 static int inprocess_count(const char *context, const char *mailbox, int delta)
1208 {
1209         struct inprocess *i, *arg = ast_alloca(sizeof(*arg) + strlen(context) + strlen(mailbox) + 2);
1210         arg->context = arg->mailbox + strlen(mailbox) + 1;
1211         strcpy(arg->mailbox, mailbox); /* SAFE */
1212         strcpy(arg->context, context); /* SAFE */
1213         ao2_lock(inprocess_container);
1214         if ((i = ao2_find(inprocess_container, arg, 0))) {
1215                 int ret = ast_atomic_fetchadd_int(&i->count, delta);
1216                 ao2_unlock(inprocess_container);
1217                 ao2_ref(i, -1);
1218                 return ret;
1219         }
1220         if (delta < 0) {
1221                 ast_log(LOG_WARNING, "BUG: ref count decrement on non-existing object???\n");
1222         }
1223         if (!(i = ao2_alloc(sizeof(*i) + strlen(context) + strlen(mailbox) + 2, NULL))) {
1224                 ao2_unlock(inprocess_container);
1225                 return 0;
1226         }
1227         i->context = i->mailbox + strlen(mailbox) + 1;
1228         strcpy(i->mailbox, mailbox); /* SAFE */
1229         strcpy(i->context, context); /* SAFE */
1230         i->count = delta;
1231         ao2_link(inprocess_container, i);
1232         ao2_unlock(inprocess_container);
1233         ao2_ref(i, -1);
1234         return 0;
1235 }
1236
1237 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
1238 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
1239 #endif
1240
1241 /*!
1242  * \brief Strips control and non 7-bit clean characters from input string.
1243  *
1244  * \note To map control and none 7-bit characters to a 7-bit clean characters
1245  *  please use ast_str_encode_mine().
1246  */
1247 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
1248 {
1249         char *bufptr = buf;
1250         for (; *input; input++) {
1251                 if (*input < 32) {
1252                         continue;
1253                 }
1254                 *bufptr++ = *input;
1255                 if (bufptr == buf + buflen - 1) {
1256                         break;
1257                 }
1258         }
1259         *bufptr = '\0';
1260         return buf;
1261 }
1262
1263
1264 /*!
1265  * \brief Sets default voicemail system options to a voicemail user.
1266  *
1267  * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
1268  * - all the globalflags
1269  * - the saydurationminfo
1270  * - the callcontext
1271  * - the dialcontext
1272  * - the exitcontext
1273  * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
1274  * - volume gain.
1275  * - emailsubject, emailbody set to NULL
1276  */
1277 static void populate_defaults(struct ast_vm_user *vmu)
1278 {
1279         ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);
1280         vmu->passwordlocation = passwordlocation;
1281         if (saydurationminfo) {
1282                 vmu->saydurationm = saydurationminfo;
1283         }
1284         ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
1285         ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
1286         ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
1287         ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
1288         ast_copy_string(vmu->locale, locale, sizeof(vmu->locale));
1289         if (vmminsecs) {
1290                 vmu->minsecs = vmminsecs;
1291         }
1292         if (vmmaxsecs) {
1293                 vmu->maxsecs = vmmaxsecs;
1294         }
1295         if (maxmsg) {
1296                 vmu->maxmsg = maxmsg;
1297         }
1298         if (maxdeletedmsg) {
1299                 vmu->maxdeletedmsg = maxdeletedmsg;
1300         }
1301         vmu->volgain = volgain;
1302         ast_free(vmu->email);
1303         vmu->email = NULL;
1304         ast_free(vmu->emailsubject);
1305         vmu->emailsubject = NULL;
1306         ast_free(vmu->emailbody);
1307         vmu->emailbody = NULL;
1308 #ifdef IMAP_STORAGE
1309         ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
1310         ast_copy_string(vmu->imapserver, imapserver, sizeof(vmu->imapserver));
1311         ast_copy_string(vmu->imapport, imapport, sizeof(vmu->imapport));
1312         ast_copy_string(vmu->imapflags, imapflags, sizeof(vmu->imapflags));
1313 #endif
1314 }
1315
1316 /*!
1317  * \brief Sets a specific property value.
1318  * \param vmu The voicemail user object to work with.
1319  * \param var The name of the property to be set.
1320  * \param value The value to be set to the property.
1321  *
1322  * The property name must be one of the understood properties. See the source for details.
1323  */
1324 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
1325 {
1326         int x;
1327         if (!strcasecmp(var, "attach")) {
1328                 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
1329         } else if (!strcasecmp(var, "attachfmt")) {
1330                 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
1331         } else if (!strcasecmp(var, "serveremail")) {
1332                 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
1333         } else if (!strcasecmp(var, "fromstring")) {
1334                 ast_copy_string(vmu->fromstring, value, sizeof(vmu->fromstring));
1335         } else if (!strcasecmp(var, "emailbody")) {
1336                 ast_free(vmu->emailbody);
1337                 vmu->emailbody = ast_strdup(substitute_escapes(value));
1338         } else if (!strcasecmp(var, "emailsubject")) {
1339                 ast_free(vmu->emailsubject);
1340                 vmu->emailsubject = ast_strdup(substitute_escapes(value));
1341         } else if (!strcasecmp(var, "language")) {
1342                 ast_copy_string(vmu->language, value, sizeof(vmu->language));
1343         } else if (!strcasecmp(var, "tz")) {
1344                 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
1345         } else if (!strcasecmp(var, "locale")) {
1346                 ast_copy_string(vmu->locale, value, sizeof(vmu->locale));
1347 #ifdef IMAP_STORAGE
1348         } else if (!strcasecmp(var, "imapuser")) {
1349                 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
1350                 vmu->imapversion = imapversion;
1351         } else if (!strcasecmp(var, "imapserver")) {
1352                 ast_copy_string(vmu->imapserver, value, sizeof(vmu->imapserver));
1353                 vmu->imapversion = imapversion;
1354         } else if (!strcasecmp(var, "imapport")) {
1355                 ast_copy_string(vmu->imapport, value, sizeof(vmu->imapport));
1356                 vmu->imapversion = imapversion;
1357         } else if (!strcasecmp(var, "imapflags")) {
1358                 ast_copy_string(vmu->imapflags, value, sizeof(vmu->imapflags));
1359                 vmu->imapversion = imapversion;
1360         } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
1361                 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
1362                 vmu->imapversion = imapversion;
1363         } else if (!strcasecmp(var, "imapfolder")) {
1364                 ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
1365                 vmu->imapversion = imapversion;
1366         } else if (!strcasecmp(var, "imapvmshareid")) {
1367                 ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
1368                 vmu->imapversion = imapversion;
1369 #endif
1370         } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
1371                 ast_set2_flag(vmu, ast_true(value), VM_DELETE);
1372         } else if (!strcasecmp(var, "saycid")){
1373                 ast_set2_flag(vmu, ast_true(value), VM_SAYCID);
1374         } else if (!strcasecmp(var, "sendvoicemail")){
1375                 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);
1376         } else if (!strcasecmp(var, "review")){
1377                 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
1378         } else if (!strcasecmp(var, "tempgreetwarn")){
1379                 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);
1380         } else if (!strcasecmp(var, "messagewrap")){
1381                 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);
1382         } else if (!strcasecmp(var, "operator")) {
1383                 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);
1384         } else if (!strcasecmp(var, "envelope")){
1385                 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);
1386         } else if (!strcasecmp(var, "moveheard")){
1387                 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
1388         } else if (!strcasecmp(var, "sayduration")){
1389                 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);
1390         } else if (!strcasecmp(var, "saydurationm")){
1391                 if (sscanf(value, "%30d", &x) == 1) {
1392                         vmu->saydurationm = x;
1393                 } else {
1394                         ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
1395                 }
1396         } else if (!strcasecmp(var, "forcename")){
1397                 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);
1398         } else if (!strcasecmp(var, "forcegreetings")){
1399                 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);
1400         } else if (!strcasecmp(var, "callback")) {
1401                 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
1402         } else if (!strcasecmp(var, "dialout")) {
1403                 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
1404         } else if (!strcasecmp(var, "exitcontext")) {
1405                 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
1406         } else if (!strcasecmp(var, "minsecs")) {
1407                 if (sscanf(value, "%30d", &x) == 1 && x >= 0) {
1408                         vmu->minsecs = x;
1409                 } else {
1410                         ast_log(LOG_WARNING, "Invalid min message length of %s. Using global value %d\n", value, vmminsecs);
1411                         vmu->minsecs = vmminsecs;
1412                 }
1413         } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
1414                 vmu->maxsecs = atoi(value);
1415                 if (vmu->maxsecs <= 0) {
1416                         ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
1417                         vmu->maxsecs = vmmaxsecs;
1418                 } else {
1419                         vmu->maxsecs = atoi(value);
1420                 }
1421                 if (!strcasecmp(var, "maxmessage"))
1422                         ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'.  Please make that change in your voicemail config.\n");
1423         } else if (!strcasecmp(var, "maxmsg")) {
1424                 vmu->maxmsg = atoi(value);
1425                 /* Accept maxmsg=0 (Greetings only voicemail) */
1426                 if (vmu->maxmsg < 0) {
1427                         ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
1428                         vmu->maxmsg = MAXMSG;
1429                 } else if (vmu->maxmsg > MAXMSGLIMIT) {
1430                         ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
1431                         vmu->maxmsg = MAXMSGLIMIT;
1432                 }
1433         } else if (!strcasecmp(var, "nextaftercmd")) {
1434                 ast_set2_flag(vmu, ast_true(value), VM_SKIPAFTERCMD);
1435         } else if (!strcasecmp(var, "backupdeleted")) {
1436                 if (sscanf(value, "%30d", &x) == 1)
1437                         vmu->maxdeletedmsg = x;
1438                 else if (ast_true(value))
1439                         vmu->maxdeletedmsg = MAXMSG;
1440                 else
1441                         vmu->maxdeletedmsg = 0;
1442
1443                 if (vmu->maxdeletedmsg < 0) {
1444                         ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
1445                         vmu->maxdeletedmsg = MAXMSG;
1446                 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
1447                         ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
1448                         vmu->maxdeletedmsg = MAXMSGLIMIT;
1449                 }
1450         } else if (!strcasecmp(var, "volgain")) {
1451                 sscanf(value, "%30lf", &vmu->volgain);
1452         } else if (!strcasecmp(var, "passwordlocation")) {
1453                 if (!strcasecmp(value, "spooldir")) {
1454                         vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
1455                 } else {
1456                         vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
1457                 }
1458         } else if (!strcasecmp(var, "options")) {
1459                 apply_options(vmu, value);
1460         }
1461 }
1462
1463 static char *vm_check_password_shell(char *command, char *buf, size_t len)
1464 {
1465         int fds[2], pid = 0;
1466
1467         memset(buf, 0, len);
1468
1469         if (pipe(fds)) {
1470                 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
1471         } else {
1472                 /* good to go*/
1473                 pid = ast_safe_fork(0);
1474
1475                 if (pid < 0) {
1476                         /* ok maybe not */
1477                         close(fds[0]);
1478                         close(fds[1]);
1479                         snprintf(buf, len, "FAILURE: Fork failed");
1480                 } else if (pid) {
1481                         /* parent */
1482                         close(fds[1]);
1483                         if (read(fds[0], buf, len) < 0) {
1484                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
1485                         }
1486                         close(fds[0]);
1487                 } else {
1488                         /*  child */
1489                         AST_DECLARE_APP_ARGS(arg,
1490                                 AST_APP_ARG(v)[20];
1491                         );
1492                         char *mycmd = ast_strdupa(command);
1493
1494                         close(fds[0]);
1495                         dup2(fds[1], STDOUT_FILENO);
1496                         close(fds[1]);
1497                         ast_close_fds_above_n(STDOUT_FILENO);
1498
1499                         AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
1500
1501                         execv(arg.v[0], arg.v);
1502                         printf("FAILURE: %s", strerror(errno));
1503                         _exit(0);
1504                 }
1505         }
1506         return buf;
1507 }
1508
1509 /*!
1510  * \brief Check that password meets minimum required length
1511  * \param vmu The voicemail user to change the password for.
1512  * \param password The password string to check
1513  *
1514  * \return zero on ok, 1 on not ok.
1515  */
1516 static int check_password(struct ast_vm_user *vmu, char *password)
1517 {
1518         /* check minimum length */
1519         if (strlen(password) < minpassword)
1520                 return 1;
1521         /* check that password does not contain '*' character */
1522         if (!ast_strlen_zero(password) && password[0] == '*')
1523                 return 1;
1524         if (!ast_strlen_zero(ext_pass_check_cmd)) {
1525                 char cmd[255], buf[255];
1526
1527                 ast_debug(1, "Verify password policies for %s\n", password);
1528
1529                 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
1530                 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
1531                         ast_debug(5, "Result: %s\n", buf);
1532                         if (!strncasecmp(buf, "VALID", 5)) {
1533                                 ast_debug(3, "Passed password check: '%s'\n", buf);
1534                                 return 0;
1535                         } else if (!strncasecmp(buf, "FAILURE", 7)) {
1536                                 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
1537                                 return 0;
1538                         } else {
1539                                 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
1540                                 return 1;
1541                         }
1542                 }
1543         }
1544         return 0;
1545 }
1546
1547 /*!
1548  * \brief Performs a change of the voicemail passowrd in the realtime engine.
1549  * \param vmu The voicemail user to change the password for.
1550  * \param password The new value to be set to the password for this user.
1551  *
1552  * This only works if there is a realtime engine configured.
1553  * This is called from the (top level) vm_change_password.
1554  *
1555  * \return zero on success, -1 on error.
1556  */
1557 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
1558 {
1559         int res = -1;
1560         if (!strcmp(vmu->password, password)) {
1561                 /* No change (but an update would return 0 rows updated, so we opt out here) */
1562                 return 0;
1563         }
1564
1565         if (strlen(password) > 10) {
1566                 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
1567         }
1568         if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
1569                 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: realtime engine updated with new password\r\nPasswordSource: realtime");
1570                 ast_copy_string(vmu->password, password, sizeof(vmu->password));
1571                 res = 0;
1572         }
1573         return res;
1574 }
1575
1576 /*!
1577  * \brief Destructively Parse options and apply.
1578  */
1579 static void apply_options(struct ast_vm_user *vmu, const char *options)
1580 {
1581         char *stringp;
1582         char *s;
1583         char *var, *value;
1584         stringp = ast_strdupa(options);
1585         while ((s = strsep(&stringp, "|"))) {
1586                 value = s;
1587                 if ((var = strsep(&value, "=")) && value) {
1588                         apply_option(vmu, var, value);
1589                 }
1590         }
1591 }
1592
1593 /*!
1594  * \brief Loads the options specific to a voicemail user.
1595  *
1596  * This is called when a vm_user structure is being set up, such as from load_options.
1597  */
1598 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
1599 {
1600         for (; var; var = var->next) {
1601                 if (!strcasecmp(var->name, "vmsecret")) {
1602                         ast_copy_string(retval->password, var->value, sizeof(retval->password));
1603                 } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
1604                         if (ast_strlen_zero(retval->password)) {
1605                                 if (!ast_strlen_zero(var->value) && var->value[0] == '*') {
1606                                         ast_log(LOG_WARNING, "Invalid password detected for mailbox %s.  The password"
1607                                                 "\n\tmust be reset in voicemail.conf.\n", retval->mailbox);
1608                                 } else {
1609                                         ast_copy_string(retval->password, var->value, sizeof(retval->password));
1610                                 }
1611                         }
1612                 } else if (!strcasecmp(var->name, "uniqueid")) {
1613                         ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
1614                 } else if (!strcasecmp(var->name, "pager")) {
1615                         ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
1616                 } else if (!strcasecmp(var->name, "email")) {
1617                         ast_free(retval->email);
1618                         retval->email = ast_strdup(var->value);
1619                 } else if (!strcasecmp(var->name, "fullname")) {
1620                         ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
1621                 } else if (!strcasecmp(var->name, "context")) {
1622                         ast_copy_string(retval->context, var->value, sizeof(retval->context));
1623                 } else if (!strcasecmp(var->name, "emailsubject")) {
1624                         ast_free(retval->emailsubject);
1625                         retval->emailsubject = ast_strdup(substitute_escapes(var->value));
1626                 } else if (!strcasecmp(var->name, "emailbody")) {
1627                         ast_free(retval->emailbody);
1628                         retval->emailbody = ast_strdup(substitute_escapes(var->value));
1629 #ifdef IMAP_STORAGE
1630                 } else if (!strcasecmp(var->name, "imapuser")) {
1631                         ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
1632                         retval->imapversion = imapversion;
1633                 } else if (!strcasecmp(var->name, "imapserver")) {
1634                         ast_copy_string(retval->imapserver, var->value, sizeof(retval->imapserver));
1635                         retval->imapversion = imapversion;
1636                 } else if (!strcasecmp(var->name, "imapport")) {
1637                         ast_copy_string(retval->imapport, var->value, sizeof(retval->imapport));
1638                         retval->imapversion = imapversion;
1639                 } else if (!strcasecmp(var->name, "imapflags")) {
1640                         ast_copy_string(retval->imapflags, var->value, sizeof(retval->imapflags));
1641                         retval->imapversion = imapversion;
1642                 } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
1643                         ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
1644                         retval->imapversion = imapversion;
1645                 } else if (!strcasecmp(var->name, "imapfolder")) {
1646                         ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
1647                         retval->imapversion = imapversion;
1648                 } else if (!strcasecmp(var->name, "imapvmshareid")) {
1649                         ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
1650                         retval->imapversion = imapversion;
1651 #endif
1652                 } else
1653                         apply_option(retval, var->name, var->value);
1654         }
1655 }
1656
1657 /*!
1658  * \brief Determines if a DTMF key entered is valid.
1659  * \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.
1660  *
1661  * Tests the character entered against the set of valid DTMF characters.
1662  * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1663  */
1664 static int is_valid_dtmf(const char *key)
1665 {
1666         int i;
1667         char *local_key = ast_strdupa(key);
1668
1669         for (i = 0; i < strlen(key); ++i) {
1670                 if (!strchr(VALID_DTMF, *local_key)) {
1671                         ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1672                         return 0;
1673                 }
1674                 local_key++;
1675         }
1676         return 1;
1677 }
1678
1679 /*!
1680  * \brief Finds a voicemail user from the realtime engine.
1681  * \param ivm
1682  * \param context
1683  * \param mailbox
1684  *
1685  * 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.
1686  *
1687  * \return The ast_vm_user structure for the user that was found.
1688  */
1689 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1690 {
1691         struct ast_variable *var;
1692         struct ast_vm_user *retval;
1693
1694         if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1695                 if (ivm) {
1696                         memset(retval, 0, sizeof(*retval));
1697                 }
1698                 populate_defaults(retval);
1699                 if (!ivm) {
1700                         ast_set_flag(retval, VM_ALLOCED);
1701                 }
1702                 if (mailbox) {
1703                         ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1704                 }
1705                 if (!context && ast_test_flag((&globalflags), VM_SEARCH)) {
1706                         var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1707                 } else {
1708                         var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1709                 }
1710                 if (var) {
1711                         apply_options_full(retval, var);
1712                         ast_variables_destroy(var);
1713                 } else {
1714                         if (!ivm)
1715                                 ast_free(retval);
1716                         retval = NULL;
1717                 }
1718         }
1719         return retval;
1720 }
1721
1722 /*!
1723  * \brief Finds a voicemail user from the users file or the realtime engine.
1724  * \param ivm
1725  * \param context
1726  * \param mailbox
1727  *
1728  * \return The ast_vm_user structure for the user that was found.
1729  */
1730 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1731 {
1732         /* This function could be made to generate one from a database, too */
1733         struct ast_vm_user *vmu = NULL, *cur;
1734         AST_LIST_LOCK(&users);
1735
1736         if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1737                 context = "default";
1738
1739         AST_LIST_TRAVERSE(&users, cur, list) {
1740 #ifdef IMAP_STORAGE
1741                 if (cur->imapversion != imapversion) {
1742                         continue;
1743                 }
1744 #endif
1745                 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1746                         break;
1747                 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
1748                         break;
1749         }
1750         if (cur) {
1751                 /* Make a copy, so that on a reload, we have no race */
1752                 if ((vmu = (ivm ? ivm : ast_calloc(1, sizeof(*vmu))))) {
1753                         ast_free(vmu->email);
1754                         ast_free(vmu->emailbody);
1755                         ast_free(vmu->emailsubject);
1756                         *vmu = *cur;
1757                         vmu->email = ast_strdup(cur->email);
1758                         vmu->emailbody = ast_strdup(cur->emailbody);
1759                         vmu->emailsubject = ast_strdup(cur->emailsubject);
1760                         ast_set2_flag(vmu, !ivm, VM_ALLOCED);
1761                         AST_LIST_NEXT(vmu, list) = NULL;
1762                 }
1763         } else
1764                 vmu = find_user_realtime(ivm, context, mailbox);
1765         AST_LIST_UNLOCK(&users);
1766         return vmu;
1767 }
1768
1769 /*!
1770  * \brief Resets a user password to a specified password.
1771  * \param context
1772  * \param mailbox
1773  * \param newpass
1774  *
1775  * This does the actual change password work, called by the vm_change_password() function.
1776  *
1777  * \return zero on success, -1 on error.
1778  */
1779 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
1780 {
1781         /* This function could be made to generate one from a database, too */
1782         struct ast_vm_user *cur;
1783         int res = -1;
1784         AST_LIST_LOCK(&users);
1785         AST_LIST_TRAVERSE(&users, cur, list) {
1786                 if ((!context || !strcasecmp(context, cur->context)) &&
1787                         (!strcasecmp(mailbox, cur->mailbox)))
1788                                 break;
1789         }
1790         if (cur) {
1791                 ast_copy_string(cur->password, newpass, sizeof(cur->password));
1792                 res = 0;
1793         }
1794         AST_LIST_UNLOCK(&users);
1795         return res;
1796 }
1797
1798 /*!
1799  * \brief Check if configuration file is valid
1800  */
1801 static inline int valid_config(const struct ast_config *cfg)
1802 {
1803         return cfg && cfg != CONFIG_STATUS_FILEINVALID;
1804 }
1805
1806 /*!
1807  * \brief The handler for the change password option.
1808  * \param vmu The voicemail user to work with.
1809  * \param newpassword The new password (that has been gathered from the appropriate prompting).
1810  * 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.
1811  * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
1812  */
1813 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
1814 {
1815         struct ast_config   *cfg = NULL;
1816         struct ast_variable *var = NULL;
1817         struct ast_category *cat = NULL;
1818         char *category = NULL, *value = NULL, *new = NULL;
1819         const char *tmp = NULL;
1820         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
1821         char secretfn[PATH_MAX] = "";
1822         int found = 0;
1823
1824         if (!change_password_realtime(vmu, newpassword))
1825                 return;
1826
1827         /* check if we should store the secret in the spool directory next to the messages */
1828         switch (vmu->passwordlocation) {
1829         case OPT_PWLOC_SPOOLDIR:
1830                 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
1831                 if (write_password_to_file(secretfn, newpassword) == 0) {
1832                         ast_test_suite_event_notify("PASSWORDCHANGED", "Message: secret.conf updated with new password\r\nPasswordSource: secret.conf");
1833                         ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
1834                         reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1835                         ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1836                         break;
1837                 } else {
1838                         ast_verb(4, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
1839                 }
1840                 /* Fall-through */
1841         case OPT_PWLOC_VOICEMAILCONF:
1842                 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && valid_config(cfg)) {
1843                         while ((category = ast_category_browse(cfg, category))) {
1844                                 if (!strcasecmp(category, vmu->context)) {
1845                                         if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
1846                                                 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
1847                                                 break;
1848                                         }
1849                                         value = strstr(tmp, ",");
1850                                         if (!value) {
1851                                                 new = ast_alloca(strlen(newpassword)+1);
1852                                                 sprintf(new, "%s", newpassword);
1853                                         } else {
1854                                                 new = ast_alloca((strlen(value) + strlen(newpassword) + 1));
1855                                                 sprintf(new, "%s%s", newpassword, value);
1856                                         }
1857                                         if (!(cat = ast_category_get(cfg, category, NULL))) {
1858                                                 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
1859                                                 break;
1860                                         }
1861                                         ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
1862                                         found = 1;
1863                                 }
1864                         }
1865                         /* save the results */
1866                         if (found) {
1867                                 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: voicemail.conf updated with new password\r\nPasswordSource: voicemail.conf");
1868                                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1869                                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1870                                 ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "app_voicemail");
1871                                 ast_config_destroy(cfg);
1872                                 break;
1873                         }
1874
1875                         ast_config_destroy(cfg);
1876                 }
1877                 /* Fall-through */
1878         case OPT_PWLOC_USERSCONF:
1879                 /* check users.conf and update the password stored for the mailbox */
1880                 /* if no vmsecret entry exists create one. */
1881                 if ((cfg = ast_config_load("users.conf", config_flags)) && valid_config(cfg)) {
1882                         ast_debug(4, "we are looking for %s\n", vmu->mailbox);
1883                         for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
1884                                 ast_debug(4, "users.conf: %s\n", category);
1885                                 if (!strcasecmp(category, vmu->mailbox)) {
1886                                         if (!ast_variable_retrieve(cfg, category, "vmsecret")) {
1887                                                 ast_debug(3, "looks like we need to make vmsecret!\n");
1888                                                 var = ast_variable_new("vmsecret", newpassword, "");
1889                                         } else {
1890                                                 var = NULL;
1891                                         }
1892                                         new = ast_alloca(strlen(newpassword) + 1);
1893                                         sprintf(new, "%s", newpassword);
1894                                         if (!(cat = ast_category_get(cfg, category, NULL))) {
1895                                                 ast_debug(4, "failed to get category!\n");
1896                                                 ast_free(var);
1897                                                 break;
1898                                         }
1899                                         if (!var) {
1900                                                 ast_variable_update(cat, "vmsecret", new, NULL, 0);
1901                                         } else {
1902                                                 ast_variable_append(cat, var);
1903                                         }
1904                                         found = 1;
1905                                         break;
1906                                 }
1907                         }
1908                         /* save the results and clean things up */
1909                         if (found) {
1910                                 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: users.conf updated with new password\r\nPasswordSource: users.conf");
1911                                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1912                                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1913                                 ast_config_text_file_save("users.conf", cfg, "app_voicemail");
1914                         }
1915
1916                         ast_config_destroy(cfg);
1917                 }
1918         }
1919 }
1920
1921 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
1922 {
1923         char buf[255];
1924         snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
1925         ast_debug(1, "External password: %s\n",buf);
1926         if (!ast_safe_system(buf)) {
1927                 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: external script updated with new password\r\nPasswordSource: external");
1928                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1929                 /* Reset the password in memory, too */
1930                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1931         }
1932 }
1933
1934 /*!
1935  * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1936  * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1937  * \param len The length of the path string that was written out.
1938  * \param context
1939  * \param ext
1940  * \param folder
1941  *
1942  * The path is constructed as
1943  *      VM_SPOOL_DIRcontext/ext/folder
1944  *
1945  * \return zero on success, -1 on error.
1946  */
1947 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
1948 {
1949         return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
1950 }
1951
1952 /*!
1953  * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1954  * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1955  * \param len The length of the path string that was written out.
1956  * \param dir
1957  * \param num
1958  *
1959  * The path is constructed as
1960  *      VM_SPOOL_DIRcontext/ext/folder
1961  *
1962  * \return zero on success, -1 on error.
1963  */
1964 static int make_file(char *dest, const int len, const char *dir, const int num)
1965 {
1966         return snprintf(dest, len, "%s/msg%04d", dir, num);
1967 }
1968
1969 /* same as mkstemp, but return a FILE * */
1970 static FILE *vm_mkftemp(char *template)
1971 {
1972         FILE *p = NULL;
1973         int pfd = mkstemp(template);
1974         chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
1975         if (pfd > -1) {
1976                 p = fdopen(pfd, "w+");
1977                 if (!p) {
1978                         close(pfd);
1979                         pfd = -1;
1980                 }
1981         }
1982         return p;
1983 }
1984
1985 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
1986  * \param dest    String. base directory.
1987  * \param len     Length of dest.
1988  * \param context String. Ignored if is null or empty string.
1989  * \param ext     String. Ignored if is null or empty string.
1990  * \param folder  String. Ignored if is null or empty string.
1991  * \return -1 on failure, 0 on success.
1992  */
1993 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
1994 {
1995         mode_t  mode = VOICEMAIL_DIR_MODE;
1996         int res;
1997
1998         make_dir(dest, len, context, ext, folder);
1999         if ((res = ast_mkdir(dest, mode))) {
2000                 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
2001                 return -1;
2002         }
2003         return 0;
2004 }
2005
2006 static const char *mbox(struct ast_vm_user *vmu, int id)
2007 {
2008 #ifdef IMAP_STORAGE
2009         if (vmu && id == 0) {
2010                 return vmu->imapfolder;
2011         }
2012 #endif
2013         return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
2014 }
2015
2016 static const char *vm_index_to_foldername(int id)
2017 {
2018         return mbox(NULL, id);
2019 }
2020
2021
2022 static int get_folder_by_name(const char *name)
2023 {
2024         size_t i;
2025
2026         for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
2027                 if (strcasecmp(name, mailbox_folders[i]) == 0) {
2028                         return i;
2029                 }
2030         }
2031
2032         return -1;
2033 }
2034
2035 static void free_user(struct ast_vm_user *vmu)
2036 {
2037         if (!vmu) {
2038                 return;
2039         }
2040
2041         ast_free(vmu->email);
2042         vmu->email = NULL;
2043         ast_free(vmu->emailbody);
2044         vmu->emailbody = NULL;
2045         ast_free(vmu->emailsubject);
2046         vmu->emailsubject = NULL;
2047
2048         if (ast_test_flag(vmu, VM_ALLOCED)) {
2049                 ast_free(vmu);
2050         }
2051 }
2052
2053 static int vm_allocate_dh(struct vm_state *vms, struct ast_vm_user *vmu, int count_msg) {
2054
2055         int arraysize = (vmu->maxmsg > count_msg ? vmu->maxmsg : count_msg);
2056
2057         /* remove old allocation */
2058         if (vms->deleted) {
2059                 ast_free(vms->deleted);
2060                 vms->deleted = NULL;
2061         }
2062         if (vms->heard) {
2063                 ast_free(vms->heard);
2064                 vms->heard = NULL;
2065         }
2066         vms->dh_arraysize = 0;
2067
2068         if (arraysize > 0) {
2069                 if (!(vms->deleted = ast_calloc(arraysize, sizeof(int)))) {
2070                         return -1;
2071                 }
2072                 if (!(vms->heard = ast_calloc(arraysize, sizeof(int)))) {
2073                         ast_free(vms->deleted);
2074                         vms->deleted = NULL;
2075                         return -1;
2076                 }
2077                 vms->dh_arraysize = arraysize;
2078         }
2079
2080         return 0;
2081 }
2082
2083 /* All IMAP-specific functions should go in this block. This
2084  * keeps them from being spread out all over the code */
2085 #ifdef IMAP_STORAGE
2086 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
2087 {
2088         char arg[10];
2089         struct vm_state *vms;
2090         unsigned long messageNum;
2091
2092         /* If greetings aren't stored in IMAP, just delete the file */
2093         if (msgnum < 0 && !imapgreetings) {
2094                 ast_filedelete(file, NULL);
2095                 return;
2096         }
2097
2098         if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2099                 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);
2100                 return;
2101         }
2102
2103         if (msgnum < 0) {
2104                 imap_delete_old_greeting(file, vms);
2105                 return;
2106         }
2107
2108         /* find real message number based on msgnum */
2109         /* this may be an index into vms->msgArray based on the msgnum. */
2110         messageNum = vms->msgArray[msgnum];
2111         if (messageNum == 0) {
2112                 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
2113                 return;
2114         }
2115         ast_debug(3, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
2116         /* delete message */
2117         snprintf (arg, sizeof(arg), "%lu", messageNum);
2118         ast_mutex_lock(&vms->lock);
2119         mail_setflag (vms->mailstream, arg, "\\DELETED");
2120         mail_expunge(vms->mailstream);
2121         ast_mutex_unlock(&vms->lock);
2122 }
2123
2124 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)
2125 {
2126         struct ast_channel *chan;
2127         char *cid;
2128         char *cid_name;
2129         char *cid_num;
2130         struct vm_state *vms;
2131         const char *duration_str;
2132         int duration = 0;
2133
2134         /*
2135          * First, get things initially set up. If any of this fails, then
2136          * back out before doing anything substantial
2137          */
2138         vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0);
2139         if (!vms) {
2140                 return;
2141         }
2142
2143         if (open_mailbox(vms, vmu, folder)) {
2144                 return;
2145         }
2146
2147         chan = ast_dummy_channel_alloc();
2148         if (!chan) {
2149                 close_mailbox(vms, vmu);
2150                 return;
2151         }
2152
2153         /*
2154          * We need to make sure the new message we save has the same
2155          * callerid, flag, and duration as the original message
2156          */
2157         cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
2158
2159         if (!ast_strlen_zero(cid)) {
2160                 ast_callerid_parse(cid, &cid_name, &cid_num);
2161                 ast_party_caller_init(ast_channel_caller(chan));
2162                 if (!ast_strlen_zero(cid_name)) {
2163                         ast_channel_caller(chan)->id.name.valid = 1;
2164                         ast_channel_caller(chan)->id.name.str = ast_strdup(cid_name);
2165                 }
2166                 if (!ast_strlen_zero(cid_num)) {
2167                         ast_channel_caller(chan)->id.number.valid = 1;
2168                         ast_channel_caller(chan)->id.number.str = ast_strdup(cid_num);
2169                 }
2170         }
2171
2172         duration_str = ast_variable_retrieve(msg_cfg, "message", "duration");
2173
2174         if (!ast_strlen_zero(duration_str)) {
2175                 sscanf(duration_str, "%30d", &duration);
2176         }
2177
2178         /*
2179          * IMAP messages cannot be altered once delivered. So we have to delete the
2180          * current message and then re-add it with the updated message ID.
2181          *
2182          * Furthermore, there currently is no atomic way to create a new message and to
2183          * store it in an arbitrary folder. So we have to save it to the INBOX and then
2184          * move to the appropriate folder.
2185          */
2186         if (!imap_store_file(dir, vmu->mailbox, vmu->context, msgnum, chan, vmu, vmfmts,
2187                         duration, vms, ast_variable_retrieve(msg_cfg, "message", "flag"), msg_id)) {
2188                 if (folder != NEW_FOLDER) {
2189                         save_to_folder(vmu, vms, msgnum, folder, NULL, 1);
2190                 }
2191                 vm_imap_delete(dir, msgnum, vmu);
2192         }
2193         close_mailbox(vms, vmu);
2194         ast_channel_unref(chan);
2195 }
2196
2197 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
2198 {
2199         struct vm_state *vms_p;
2200         char *file, *filename;
2201         char dest[PATH_MAX];
2202         char *attachment;
2203         int i;
2204         BODY *body;
2205         int ret = 0;
2206         int curr_mbox;
2207
2208         /* This function is only used for retrieval of IMAP greetings
2209          * regular messages are not retrieved this way, nor are greetings
2210          * if they are stored locally*/
2211         if (msgnum > -1 || !imapgreetings) {
2212                 return 0;
2213         } else {
2214                 file = strrchr(ast_strdupa(dir), '/');
2215                 if (file)
2216                         *file++ = '\0';
2217                 else {
2218                         ast_debug(1, "Failed to procure file name from directory passed.\n");
2219                         return -1;
2220                 }
2221         }
2222
2223         /* check if someone is accessing this box right now... */
2224         if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) &&
2225                 !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2226                 /* Unlike when retrieving a message, it is reasonable not to be able to find a
2227                 * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
2228                 * that's all we need to do.
2229                 */
2230                 if (!(vms_p = create_vm_state_from_user(vmu))) {
2231                         ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
2232                         return -1;
2233                 }
2234         }
2235
2236         /* Greetings will never have a prepended message */
2237         *vms_p->introfn = '\0';
2238
2239         ast_mutex_lock(&vms_p->lock);
2240
2241         /* get the current mailbox so that we can point the mailstream back to it later */
2242         curr_mbox = get_folder_by_name(vms_p->curbox);
2243
2244         if (init_mailstream(vms_p, GREETINGS_FOLDER) || !vms_p->mailstream) {
2245                 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
2246                 ast_mutex_unlock(&vms_p->lock);
2247                 return -1;
2248         }
2249
2250         /*XXX Yuck, this could probably be done a lot better */
2251         for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
2252                 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
2253                 /* We have the body, now we extract the file name of the first attachment. */
2254                 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
2255                         attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
2256                 } else {
2257                         ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
2258                         ret = -1;
2259                         break;
2260                 }
2261                 filename = strsep(&attachment, ".");
2262                 if (!strcmp(filename, file)) {
2263                         ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
2264                         vms_p->msgArray[vms_p->curmsg] = i + 1;
2265                         create_dirpath(dest, sizeof(dest), vmu->context, vms_p->username, "");
2266                         save_body(body, vms_p, "2", attachment, 0);
2267                         ret = 0;
2268                         break;
2269                 }
2270         }
2271
2272         if (curr_mbox != -1) {
2273                 /* restore previous mbox stream */
2274                 if (init_mailstream(vms_p, curr_mbox) || !vms_p->mailstream) {
2275                         ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
2276                         ret = -1;
2277                 }
2278         }
2279         ast_mutex_unlock(&vms_p->lock);
2280         return ret;
2281 }
2282
2283 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
2284 {
2285         BODY *body;
2286         char *header_content;
2287         char *attachedfilefmt;
2288         char buf[80];
2289         struct vm_state *vms;
2290         char text_file[PATH_MAX];
2291         FILE *text_file_ptr;
2292         int res = 0;
2293         struct ast_vm_user *vmu;
2294         int curr_mbox;
2295
2296         if (!(vmu = find_user(NULL, context, mailbox))) {
2297                 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
2298                 return -1;
2299         }
2300
2301         if (msgnum < 0) {
2302                 if (imapgreetings) {
2303                         res = imap_retrieve_greeting(dir, msgnum, vmu);
2304                         goto exit;
2305                 } else {
2306                         res = 0;
2307                         goto exit;
2308                 }
2309         }
2310
2311         /* Before anything can happen, we need a vm_state so that we can
2312          * actually access the imap server through the vms->mailstream
2313          */
2314         if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2315                 /* This should not happen. If it does, then I guess we'd
2316                  * need to create the vm_state, extract which mailbox to
2317                  * open, and then set up the msgArray so that the correct
2318                  * IMAP message could be accessed. If I have seen correctly
2319                  * though, the vms should be obtainable from the vmstates list
2320                  * and should have its msgArray properly set up.
2321                  */
2322                 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
2323                 res = -1;
2324                 goto exit;
2325         }
2326
2327         /* Ensure we have the correct mailbox open and have a valid mailstream for it */
2328         curr_mbox = get_folder_by_name(vms->curbox);
2329         if (curr_mbox < 0) {
2330                 ast_debug(3, "Mailbox folder curbox not set, defaulting to Inbox\n");
2331                 curr_mbox = 0;
2332         }
2333         init_mailstream(vms, curr_mbox);
2334         if (!vms->mailstream) {
2335                 ast_log(AST_LOG_ERROR, "IMAP mailstream for %s is NULL\n", vmu->mailbox);
2336                 res = -1;
2337                 goto exit;
2338         }
2339
2340         make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
2341         snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
2342
2343         /* Don't try to retrieve a message from IMAP if it already is on the file system */
2344         if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
2345                 res = 0;
2346                 goto exit;
2347         }
2348
2349         ast_debug(3, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
2350         if (vms->msgArray[msgnum] == 0) {
2351                 ast_log(LOG_WARNING, "Trying to access unknown message\n");
2352                 res = -1;
2353                 goto exit;
2354         }
2355
2356         /* This will only work for new messages... */
2357         ast_mutex_lock(&vms->lock);
2358         header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
2359         ast_mutex_unlock(&vms->lock);
2360         /* empty string means no valid header */
2361         if (ast_strlen_zero(header_content)) {
2362                 ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
2363                 res = -1;
2364                 goto exit;
2365         }
2366
2367         ast_mutex_lock(&vms->lock);
2368         mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
2369         ast_mutex_unlock(&vms->lock);
2370
2371         /* We have the body, now we extract the file name of the first attachment. */
2372         if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
2373                 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
2374         } else {
2375                 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
2376                 res = -1;
2377                 goto exit;
2378         }
2379
2380         /* Find the format of the attached file */
2381
2382         strsep(&attachedfilefmt, ".");
2383         if (!attachedfilefmt) {
2384                 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
2385                 res = -1;
2386                 goto exit;
2387         }
2388
2389         save_body(body, vms, "2", attachedfilefmt, 0);
2390         if (save_body(body, vms, "3", attachedfilefmt, 1)) {
2391                 *vms->introfn = '\0';
2392         }
2393
2394         /* Get info from headers!! */
2395         snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
2396
2397         if (!(text_file_ptr = fopen(text_file, "w"))) {
2398                 ast_log(LOG_ERROR, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
2399                 goto exit;
2400         }
2401
2402         fprintf(text_file_ptr, "%s\n", "[message]");
2403
2404         if (get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf))) {
2405                 fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
2406         }
2407         if (get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf))) {
2408                 fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
2409         }
2410         if (get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf))) {
2411                 fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
2412         }
2413         if (get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf))) {
2414                 fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
2415         }
2416         if (get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf))) {
2417                 fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
2418         }
2419         if (get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf))) {
2420                 fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
2421         }
2422         if (get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf))) {
2423                 fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
2424         }
2425         if (get_header_by_tag(header_content, "X-Asterisk-VM-Message-ID:", buf, sizeof(buf))) {
2426                 fprintf(text_file_ptr, "msg_id=%s\n", S_OR(buf, ""));
2427         }
2428         fclose(text_file_ptr);
2429
2430 exit:
2431         free_user(vmu);
2432         return res;
2433 }
2434
2435 static int folder_int(const char *folder)
2436 {
2437         /*assume a NULL folder means INBOX*/
2438         if (!folder) {
2439                 return 0;
2440         }
2441         if (!strcasecmp(folder, imapfolder)) {
2442                 return 0;
2443         } else if (!strcasecmp(folder, "Old")) {
2444                 return 1;
2445         } else if (!strcasecmp(folder, "Work")) {
2446                 return 2;
2447         } else if (!strcasecmp(folder, "Family")) {
2448                 return 3;
2449         } else if (!strcasecmp(folder, "Friends")) {
2450                 return 4;
2451         } else if (!strcasecmp(folder, "Cust1")) {
2452                 return 5;
2453         } else if (!strcasecmp(folder, "Cust2")) {
2454                 return 6;
2455         } else if (!strcasecmp(folder, "Cust3")) {
2456                 return 7;
2457         } else if (!strcasecmp(folder, "Cust4")) {
2458                 return 8;
2459         } else if (!strcasecmp(folder, "Cust5")) {
2460                 return 9;
2461         } else if (!strcasecmp(folder, "Urgent")) {
2462                 return 11;
2463         } else { /*assume they meant INBOX if folder is not found otherwise*/
2464                 return 0;
2465         }
2466 }
2467
2468 static int __messagecount(const char *context, const char *mailbox, const char *folder)
2469 {
2470         SEARCHPGM *pgm;
2471         SEARCHHEADER *hdr;
2472
2473         struct ast_vm_user *vmu, vmus;
2474         struct vm_state *vms_p;
2475         int ret = 0;
2476         int fold = folder_int(folder);
2477         int urgent = 0;
2478
2479         /* If URGENT, then look at INBOX */
2480         if (fold == 11) {
2481                 fold = NEW_FOLDER;
2482                 urgent = 1;
2483         }
2484
2485         if (ast_strlen_zero(mailbox))
2486                 return 0;
2487
2488         /* We have to get the user before we can open the stream! */
2489         memset(&vmus, 0, sizeof(vmus));
2490         vmu = find_user(&vmus, context, mailbox);
2491         if (!vmu) {
2492                 ast_log(AST_LOG_WARNING, "Couldn't find mailbox %s in context %s\n", mailbox, context);
2493                 free_user(vmu);
2494                 return -1;
2495         } else {
2496                 /* No IMAP account available */
2497                 if (vmu->imapuser[0] == '\0') {
2498                         ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2499                         free_user(vmu);
2500                         return -1;
2501                 }
2502         }
2503
2504         /* No IMAP account available */
2505         if (vmu->imapuser[0] == '\0') {
2506                 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2507                 free_user(vmu);
2508                 return -1;
2509         }
2510
2511         /* check if someone is accessing this box right now... */
2512         vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
2513         if (!vms_p) {
2514                 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
2515         }
2516         if (vms_p) {
2517                 ast_debug(3, "Returning before search - user is logged in\n");
2518                 if (fold == 0) { /* INBOX */
2519                         free_user(vmu);
2520                         return urgent ? vms_p->urgentmessages : vms_p->newmessages;
2521                 }
2522                 if (fold == 1) { /* Old messages */
2523                         free_user(vmu);
2524                         return vms_p->oldmessages;
2525                 }
2526         }
2527
2528         /* add one if not there... */
2529         vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
2530         if (!vms_p) {
2531                 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
2532         }
2533
2534         if (!vms_p) {
2535                 vms_p = create_vm_state_from_user(vmu);
2536         }
2537         ret = init_mailstream(vms_p, fold);
2538         if (!vms_p->mailstream) {
2539                 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
2540                 free_user(vmu);
2541                 return -1;
2542         }
2543         if (ret == 0) {
2544                 ast_mutex_lock(&vms_p->lock);
2545                 pgm = mail_newsearchpgm ();
2546                 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
2547                 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
2548                 pgm->header = hdr;
2549                 if (fold != OLD_FOLDER) {
2550                         pgm->unseen = 1;
2551                         pgm->seen = 0;
2552                 }
2553                 /* In the special case where fold is 1 (old messages) we have to do things a bit
2554                  * differently. Old messages are stored in the INBOX but are marked as "seen"
2555                  */
2556                 else {
2557                         pgm->unseen = 0;
2558                         pgm->seen = 1;
2559                 }
2560                 /* look for urgent messages */
2561                 if (fold == NEW_FOLDER) {
2562                         if (urgent) {
2563                                 pgm->flagged = 1;
2564                                 pgm->unflagged = 0;
2565                         } else {
2566                                 pgm->flagged = 0;
2567                                 pgm->unflagged = 1;
2568                         }
2569                 }
2570                 pgm->undeleted = 1;
2571                 pgm->deleted = 0;
2572
2573                 vms_p->vmArrayIndex = 0;
2574                 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
2575                 if (fold == 0 && urgent == 0)
2576                         vms_p->newmessages = vms_p->vmArrayIndex;
2577                 if (fold == 1)
2578                         vms_p->oldmessages = vms_p->vmArrayIndex;
2579                 if (fold == 0 && urgent == 1)
2580                         vms_p->urgentmessages = vms_p->vmArrayIndex;
2581                 /*Freeing the searchpgm also frees the searchhdr*/
2582                 mail_free_searchpgm(&pgm);
2583                 ast_mutex_unlock(&vms_p->lock);
2584                 free_user(vmu);
2585                 vms_p->updated = 0;
2586                 return vms_p->vmArrayIndex;
2587         } else {
2588                 ast_mutex_lock(&vms_p->lock);
2589                 mail_ping(vms_p->mailstream);
2590                 ast_mutex_unlock(&vms_p->lock);
2591         }
2592         free_user(vmu);
2593         return 0;
2594 }
2595
2596 static int imap_check_limits(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu, int msgnum)
2597 {
2598         /* Check if mailbox is full */
2599         check_quota(vms, vmu->imapfolder);
2600         if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
2601                 ast_debug(1, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
2602                 if (chan) {
2603                         ast_play_and_wait(chan, "vm-mailboxfull");
2604                 }
2605                 return -1;
2606         }
2607
2608         /* Check if we have exceeded maxmsg */
2609         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));
2610         if (msgnum >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
2611                 ast_log(LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u >= %u)\n", msgnum, vmu->maxmsg);
2612                 if (chan) {
2613                         ast_play_and_wait(chan, "vm-mailboxfull");
2614                         pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
2615                 }
2616                 return -1;
2617         }
2618
2619         return 0;
2620 }
2621
2622 /*!
2623  * \brief Gets the number of messages that exist in a mailbox folder.
2624  * \param mailbox_id
2625  * \param folder
2626  *
2627  * This method is used when IMAP backend is used.
2628  * \return The number of messages in this mailbox folder (zero or more).
2629  */
2630 static int messagecount(const char *mailbox_id, const char *folder)
2631 {
2632         char *context;
2633         char *mailbox;
2634
2635         if (ast_strlen_zero(mailbox_id)
2636                 || separate_mailbox(ast_strdupa(mailbox_id), &mailbox, &context)) {
2637                 return 0;
2638         }
2639
2640         if (ast_strlen_zero(folder) || !strcmp(folder, "INBOX")) {
2641                 return __messagecount(context, mailbox, "INBOX") + __messagecount(context, mailbox, "Urgent");
2642         } else {
2643                 return __messagecount(context, mailbox, folder);
2644         }
2645 }
2646
2647 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)
2648 {
2649         char *myserveremail = serveremail;
2650         char fn[PATH_MAX];
2651         char introfn[PATH_MAX];
2652         char mailbox[256];
2653         char *stringp;
2654         FILE *p = NULL;
2655         char tmp[80] = "/tmp/astmail-XXXXXX";
2656         long len;
2657         void *buf;
2658         int tempcopy = 0;
2659         STRING str;
2660         int ret; /* for better error checking */
2661         char *imap_flags = NIL;
2662         int msgcount;
2663         int box = NEW_FOLDER;
2664
2665         snprintf(mailbox, sizeof(mailbox), "%s@%s", vmu->mailbox, vmu->context);
2666         msgcount = messagecount(mailbox, "INBOX") + messagecount(mailbox, "Old");
2667
2668         /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
2669         if (msgnum < 0) {
2670                 if(!imapgreetings) {
2671                         return 0;
2672                 } else {
2673                         box = GREETINGS_FOLDER;
2674                 }
2675         }
2676
2677         if (imap_check_limits(chan, vms, vmu, msgcount)) {
2678                 return -1;
2679         }
2680
2681         /* Set urgent flag for IMAP message */
2682         if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
2683                 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
2684                 imap_flags = "\\FLAGGED";
2685         }
2686
2687         /* Attach only the first format */
2688         fmt = ast_strdupa(fmt);
2689         stringp = fmt;
2690         strsep(&stringp, "|");
2691
2692         if (!ast_strlen_zero(vmu->serveremail))
2693                 myserveremail = vmu->serveremail;
2694
2695         if (msgnum > -1)
2696                 make_file(fn, sizeof(fn), dir, msgnum);
2697         else
2698                 ast_copy_string (fn, dir, sizeof(fn));
2699
2700         snprintf(introfn, sizeof(introfn), "%sintro", fn);
2701         if (ast_fileexists(introfn, NULL, NULL) <= 0) {
2702                 *introfn = '\0';
2703         }
2704
2705         if (ast_strlen_zero(vmu->email)) {
2706                 /* We need the vmu->email to be set when we call make_email_file, but
2707                  * if we keep it set, a duplicate e-mail will be created. So at the end
2708                  * of this function, we will revert back to an empty string if tempcopy
2709                  * is 1.
2710                  */
2711                 vmu->email = ast_strdup(vmu->imapuser);
2712                 tempcopy = 1;
2713         }
2714
2715         if (!strcmp(fmt, "wav49"))
2716                 fmt = "WAV";
2717         ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
2718
2719         /* Make a temporary file instead of piping directly to sendmail, in case the mail
2720            command hangs. */
2721         if (!(p = vm_mkftemp(tmp))) {
2722                 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
2723                 if (tempcopy) {
2724                         ast_free(vmu->email);
2725                         vmu->email = NULL;
2726                 }
2727                 return -1;
2728         }
2729
2730         if (msgnum < 0 && imapgreetings) {
2731                 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
2732                         ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
2733                         return -1;
2734                 }
2735                 imap_delete_old_greeting(fn, vms);
2736         }
2737
2738         make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, "INBOX",
2739                 chan ? S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL) : NULL,
2740                 chan ? S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL) : NULL,
2741                 fn, introfn, fmt, duration, 1, chan, NULL, 1, flag, msg_id);
2742         /* read mail file to memory */
2743         len = ftell(p);
2744         rewind(p);
2745         if (!(buf = ast_malloc(len + 1))) {
2746                 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
2747                 fclose(p);
2748                 if (tempcopy)
2749                         *(vmu->email) = '\0';
2750                 return -1;
2751         }
2752         if (fread(buf, 1, len, p) != len) {
2753                 if (ferror(p)) {
2754                         ast_log(LOG_ERROR, "Error while reading mail file: %s\n", tmp);
2755                         return -1;
2756                 }
2757         }
2758         ((char *) buf)[len] = '\0';
2759         INIT(&str, mail_string, buf, len);
2760         ret = init_mailstream(vms, box);
2761         if (ret == 0) {
2762                 imap_mailbox_name(mailbox, sizeof(mailbox), vms, box, 1);
2763                 ast_mutex_lock(&vms->lock);
2764                 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
2765                         ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
2766                 ast_mutex_unlock(&vms->lock);
2767                 fclose(p);
2768                 unlink(tmp);
2769                 ast_free(buf);
2770         } else {
2771                 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
2772                 fclose(p);
2773                 unlink(tmp);
2774                 ast_free(buf);
2775                 return -1;
2776         }
2777         ast_debug(3, "%s stored\n", fn);
2778
2779         if (tempcopy)
2780                 *(vmu->email) = '\0';
2781         inprocess_count(vmu->mailbox, vmu->context, -1);
2782         return 0;
2783
2784 }
2785
2786 /*!
2787  * \brief Gets the number of messages that exist in the inbox folder.
2788  * \param mailbox_context
2789  * \param newmsgs The variable that is updated with the count of new messages within this inbox.
2790  * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
2791  * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
2792  *
2793  * This method is used when IMAP backend is used.
2794  * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
2795  *
2796  * \return zero on success, -1 on error.
2797  */
2798
2799 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
2800 {
2801         char tmp[PATH_MAX] = "";
2802         char *mailboxnc;
2803         char *context;
2804         char *mb;
2805         char *cur;
2806         if (newmsgs)
2807                 *newmsgs = 0;
2808         if (oldmsgs)
2809                 *oldmsgs = 0;
2810         if (urgentmsgs)
2811                 *urgentmsgs = 0;
2812
2813         ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
2814         /* If no mailbox, return immediately */
2815         if (ast_strlen_zero(mailbox_context))
2816                 return 0;
2817
2818         ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2819         context = strchr(tmp, '@');
2820         if (strchr(mailbox_context, ',')) {
2821                 int tmpnew, tmpold, tmpurgent;
2822                 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2823                 mb = tmp;
2824                 while ((cur = strsep(&mb, ", "))) {
2825                         if (!ast_strlen_zero(cur)) {
2826                                 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2827                                         return -1;
2828                                 else {
2829                                         if (newmsgs)
2830                                                 *newmsgs += tmpnew;
2831                                         if (oldmsgs)
2832                                                 *oldmsgs += tmpold;
2833                                         if (urgentmsgs)
2834                                                 *urgentmsgs += tmpurgent;
2835                                 }
2836                         }
2837                 }
2838                 return 0;
2839         }
2840         if (context) {
2841                 *context = '\0';
2842                 mailboxnc = tmp;
2843                 context++;
2844         } else {
2845                 context = "default";
2846                 mailboxnc = (char *) mailbox_context;
2847         }
2848
2849         if (newmsgs) {
2850                 struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
2851                 if (!vmu) {
2852                         ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
2853                         return -1;
2854                 }
2855                 if ((*newmsgs = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
2856                         free_user(vmu);
2857                         return -1;
2858                 }
2859                 free_user(vmu);
2860         }
2861         if (oldmsgs) {
2862                 if ((*oldmsgs = __messagecount(context, mailboxnc, "Old")) < 0) {
2863                         return -1;
2864                 }
2865         }
2866         if (urgentmsgs) {
2867                 if ((*urgentmsgs = __messagecount(context, mailboxnc, "Urgent")) < 0) {
2868                         return -1;
2869                 }
2870         }
2871         return 0;
2872 }
2873
2874 /**
2875  * \brief Determines if the given folder has messages.
2876  * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
2877  * \param folder the folder to look in
2878  *
2879  * This function is used when the mailbox is stored in an IMAP back end.
2880  * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
2881  * \return 1 if the folder has one or more messages. zero otherwise.
2882  */
2883
2884 static int has_voicemail(const char *mailbox, const char *folder)
2885 {
2886         char tmp[256], *tmp2, *box, *context;
2887         ast_copy_string(tmp, mailbox, sizeof(tmp));
2888         tmp2 = tmp;
2889         if (strchr(tmp2, ',') || strchr(tmp2, '&')) {
2890                 while ((box = strsep(&tmp2, ",&"))) {
2891                         if (!ast_strlen_zero(box)) {
2892                                 if (has_voicemail(box, folder)) {
2893                                         return 1;
2894                                 }
2895                         }
2896                 }
2897         }
2898         if ((context = strchr(tmp, '@'))) {
2899                 *context++ = '\0';
2900         } else {
2901                 context = "default";
2902         }
2903         return __messagecount(context, tmp, folder) ? 1 : 0;
2904 }
2905
2906 /*!
2907  * \brief Copies a message from one mailbox to another.
2908  * \param chan
2909  * \param vmu
2910  * \param imbox
2911  * \param msgnum
2912  * \param duration
2913  * \param recip
2914  * \param fmt
2915  * \param dir
2916  *
2917  * This works with IMAP storage based mailboxes.
2918  *
2919  * \return zero on success, -1 on error.
2920  */
2921 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)
2922 {
2923         struct vm_state *sendvms = NULL;
2924         char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
2925         if (msgnum >= recip->maxmsg) {
2926                 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
2927                 return -1;
2928         }
2929         if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
2930                 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
2931                 return -1;
2932         }
2933         if (!get_vm_state_by_imapuser(recip->imapuser, 0)) {
2934                 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
2935                 return -1;
2936         }
2937         snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
2938         ast_mutex_lock(&sendvms->lock);
2939         if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
2940                 ast_mutex_unlock(&sendvms->lock);
2941                 return 0;
2942         }
2943         ast_mutex_unlock(&sendvms->lock);
2944         ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
2945         return -1;
2946 }
2947
2948 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
2949 {
2950         char tmp[256], *t = tmp;
2951         size_t left = sizeof(tmp);
2952
2953         if (box == OLD_FOLDER) {
2954                 ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
2955         } else {
2956                 ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
2957         }
2958
2959         if (box == NEW_FOLDER) {
2960                 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
2961         } else {
2962                 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
2963         }
2964
2965         /* Build up server information */
2966         ast_build_string(&t, &left, "{%s:%s/imap", S_OR(vms->imapserver, imapserver), S_OR(vms->imapport, imapport));
2967
2968         /* Add authentication user if present */
2969         if (!ast_strlen_zero(authuser))
2970                 ast_build_string(&t, &left, "/authuser=%s", authuser);
2971
2972         /* Add flags if present */
2973         if (!ast_strlen_zero(imapflags) || !(ast_strlen_zero(vms->imapflags))) {
2974                 ast_build_string(&t, &left, "/%s", S_OR(vms->imapflags, imapflags));
2975         }
2976
2977         /* End with username */
2978 #if 1
2979         ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
2980 #else
2981         ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
2982 #endif
2983         if (box == NEW_FOLDER || box == OLD_FOLDER)
2984                 snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
2985         else if (box == GREETINGS_FOLDER)
2986                 snprintf(spec, len, "%s%s", tmp, greetingfolder);
2987         else {  /* Other folders such as Friends, Family, etc... */
2988                 if (!ast_strlen_zero(imapparentfolder)) {
2989                         /* imapparentfolder would typically be set to INBOX */
2990                         snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
2991                 } else {
2992                         snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
2993                 }
2994         }
2995 }
2996
2997 static int init_mailstream(struct vm_state *vms, int box)
2998 {
2999         MAILSTREAM *stream = NIL;
3000         long debug;
3001         char tmp[256];
3002
3003         if (!vms) {
3004                 ast_log(LOG_ERROR, "vm_state is NULL!\n");
3005                 return -1;
3006         }
3007         ast_debug(3, "vm_state user is:%s\n", vms->imapuser);
3008         if (vms->mailstream == NIL || !vms->mailstream) {
3009                 ast_debug(1, "mailstream not set.\n");
3010         } else {
3011                 stream = vms->mailstream;
3012         }
3013         /* debug = T;  user wants protocol telemetry? */
3014         debug = NIL;  /* NO protocol telemetry? */
3015
3016         if (delimiter == '\0') {                /* did not probe the server yet */
3017                 char *cp;
3018 #ifdef USE_SYSTEM_IMAP
3019 #include <imap/linkage.c>
3020 #elif defined(USE_SYSTEM_CCLIENT)
3021 #include <c-client/linkage.c>
3022 #else
3023 #include "linkage.c"
3024 #endif
3025                 /* Connect to INBOX first to get folders delimiter */
3026                 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
3027                 ast_mutex_lock(&vms->lock);
3028                 ast_mutex_lock(&mail_open_lock);
3029                 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
3030                 ast_mutex_unlock(&mail_open_lock);
3031                 ast_mutex_unlock(&vms->lock);
3032                 if (stream == NIL) {
3033                         ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
3034                         return -1;
3035                 }
3036                 get_mailbox_delimiter(vms, stream);
3037                 /* update delimiter in imapfolder */
3038                 for (cp = vms->imapfolder; *cp; cp++)
3039                         if (*cp == '/')
3040                                 *cp = delimiter;
3041         }
3042         /* Now connect to the target folder */
3043         imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
3044         ast_debug(3, "Before mail_open, server: %s, box:%d\n", tmp, box);
3045         ast_mutex_lock(&vms->lock);
3046         ast_mutex_lock(&mail_open_lock);
3047         vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
3048         /* Create the folder if it dosn't exist */
3049         if (vms->mailstream && !mail_status(vms->mailstream, tmp, SA_UIDNEXT)) {
3050                 mail_create(vms->mailstream, tmp);
3051         }