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