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