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