1c6666fd9ecf2bb74a2053d6bc824783c80e281c
[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 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
837
838 /* Forward declarations - generic */
839 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
840 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);
841 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
842 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
843                         char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
844                         signed char record_gain, struct vm_state *vms, char *flag);
845 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
846 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
847 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);
848 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);
849 static void apply_options(struct ast_vm_user *vmu, const char *options);
850 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);
851 static int is_valid_dtmf(const char *key);
852 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
853 static int write_password_to_file(const char *secretfn, const char *password);
854
855 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
856 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
857 #endif
858
859 /*!
860  * \brief Strips control and non 7-bit clean characters from input string.
861  *
862  * \note To map control and none 7-bit characters to a 7-bit clean characters
863  *  please use ast_str_encode_mine().
864  */
865 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
866 {
867         char *bufptr = buf;
868         for (; *input; input++) {
869                 if (*input < 32) {
870                         continue;
871                 }
872                 *bufptr++ = *input;
873                 if (bufptr == buf + buflen - 1) {
874                         break;
875                 }
876         }
877         *bufptr = '\0';
878         return buf;
879 }
880
881
882 /*!
883  * \brief Sets default voicemail system options to a voicemail user.
884  *
885  * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
886  * - all the globalflags
887  * - the saydurationminfo
888  * - the callcontext
889  * - the dialcontext
890  * - the exitcontext
891  * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
892  * - volume gain.
893  */
894 static void populate_defaults(struct ast_vm_user *vmu)
895 {
896         ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);     
897         vmu->passwordlocation = passwordlocation;
898         if (saydurationminfo)
899                 vmu->saydurationm = saydurationminfo;
900         ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
901         ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
902         ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
903         ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
904         if (vmmaxsecs)
905                 vmu->maxsecs = vmmaxsecs;
906         if (maxmsg)
907                 vmu->maxmsg = maxmsg;
908         if (maxdeletedmsg)
909                 vmu->maxdeletedmsg = maxdeletedmsg;
910         vmu->volgain = volgain;
911         vmu->emailsubject = NULL;
912         vmu->emailbody = NULL;
913 #ifdef IMAP_STORAGE
914         ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
915 #endif
916 }
917
918 /*!
919  * \brief Sets a a specific property value.
920  * \param vmu The voicemail user object to work with.
921  * \param var The name of the property to be set.
922  * \param value The value to be set to the property.
923  * 
924  * The property name must be one of the understood properties. See the source for details.
925  */
926 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
927 {
928         int x;
929         if (!strcasecmp(var, "attach")) {
930                 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
931         } else if (!strcasecmp(var, "attachfmt")) {
932                 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
933         } else if (!strcasecmp(var, "serveremail")) {
934                 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
935         } else if (!strcasecmp(var, "language")) {
936                 ast_copy_string(vmu->language, value, sizeof(vmu->language));
937         } else if (!strcasecmp(var, "tz")) {
938                 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
939 #ifdef IMAP_STORAGE
940         } else if (!strcasecmp(var, "imapuser")) {
941                 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
942                 vmu->imapversion = imapversion;
943         } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
944                 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
945                 vmu->imapversion = imapversion;
946         } else if (!strcasecmp(var, "imapfolder")) {
947                 ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
948         } else if (!strcasecmp(var, "imapvmshareid")) {
949                 ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
950                 vmu->imapversion = imapversion;
951 #endif
952         } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
953                 ast_set2_flag(vmu, ast_true(value), VM_DELETE); 
954         } else if (!strcasecmp(var, "saycid")){
955                 ast_set2_flag(vmu, ast_true(value), VM_SAYCID); 
956         } else if (!strcasecmp(var, "sendvoicemail")){
957                 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL); 
958         } else if (!strcasecmp(var, "review")){
959                 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
960         } else if (!strcasecmp(var, "tempgreetwarn")){
961                 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);  
962         } else if (!strcasecmp(var, "messagewrap")){
963                 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);    
964         } else if (!strcasecmp(var, "operator")) {
965                 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);       
966         } else if (!strcasecmp(var, "envelope")){
967                 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);       
968         } else if (!strcasecmp(var, "moveheard")){
969                 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
970         } else if (!strcasecmp(var, "sayduration")){
971                 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);    
972         } else if (!strcasecmp(var, "saydurationm")){
973                 if (sscanf(value, "%30d", &x) == 1) {
974                         vmu->saydurationm = x;
975                 } else {
976                         ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
977                 }
978         } else if (!strcasecmp(var, "forcename")){
979                 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);      
980         } else if (!strcasecmp(var, "forcegreetings")){
981                 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);     
982         } else if (!strcasecmp(var, "callback")) {
983                 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
984         } else if (!strcasecmp(var, "dialout")) {
985                 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
986         } else if (!strcasecmp(var, "exitcontext")) {
987                 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
988         } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
989                 vmu->maxsecs = atoi(value);
990                 if (vmu->maxsecs <= 0) {
991                         ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
992                         vmu->maxsecs = vmmaxsecs;
993                 } else {
994                         vmu->maxsecs = atoi(value);
995                 }
996                 if (!strcasecmp(var, "maxmessage"))
997                         ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'.  Please make that change in your voicemail config.\n");
998         } else if (!strcasecmp(var, "maxmsg")) {
999                 vmu->maxmsg = atoi(value);
1000                 if (vmu->maxmsg <= 0) {
1001                         ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
1002                         vmu->maxmsg = MAXMSG;
1003                 } else if (vmu->maxmsg > MAXMSGLIMIT) {
1004                         ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
1005                         vmu->maxmsg = MAXMSGLIMIT;
1006                 }
1007         } else if (!strcasecmp(var, "backupdeleted")) {
1008                 if (sscanf(value, "%30d", &x) == 1)
1009                         vmu->maxdeletedmsg = x;
1010                 else if (ast_true(value))
1011                         vmu->maxdeletedmsg = MAXMSG;
1012                 else
1013                         vmu->maxdeletedmsg = 0;
1014
1015                 if (vmu->maxdeletedmsg < 0) {
1016                         ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
1017                         vmu->maxdeletedmsg = MAXMSG;
1018                 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
1019                         ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
1020                         vmu->maxdeletedmsg = MAXMSGLIMIT;
1021                 }
1022         } else if (!strcasecmp(var, "volgain")) {
1023                 sscanf(value, "%30lf", &vmu->volgain);
1024         } else if (!strcasecmp(var, "passwordlocation")) {
1025                 if (!strcasecmp(value, "spooldir")) {
1026                         vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
1027                 } else {
1028                         vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
1029                 }
1030         } else if (!strcasecmp(var, "options")) {
1031                 apply_options(vmu, value);
1032         }
1033 }
1034
1035 static char *vm_check_password_shell(char *command, char *buf, size_t len) 
1036 {
1037         int fds[2], pid = 0;
1038
1039         memset(buf, 0, len);
1040
1041         if (pipe(fds)) {
1042                 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
1043         } else {
1044                 /* good to go*/
1045                 pid = ast_safe_fork(0);
1046
1047                 if (pid < 0) {
1048                         /* ok maybe not */
1049                         close(fds[0]);
1050                         close(fds[1]);
1051                         snprintf(buf, len, "FAILURE: Fork failed");
1052                 } else if (pid) {
1053                         /* parent */
1054                         close(fds[1]);
1055                         if (read(fds[0], buf, len) < 0) {
1056                                 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
1057                         }
1058                         close(fds[0]);
1059                 } else {
1060                         /*  child */
1061                         AST_DECLARE_APP_ARGS(arg,
1062                                 AST_APP_ARG(v)[20];
1063                         );
1064                         char *mycmd = ast_strdupa(command);
1065
1066                         close(fds[0]);
1067                         dup2(fds[1], STDOUT_FILENO);
1068                         close(fds[1]);
1069                         ast_close_fds_above_n(STDOUT_FILENO);
1070
1071                         AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
1072
1073                         execv(arg.v[0], arg.v); 
1074                         printf("FAILURE: %s", strerror(errno));
1075                         _exit(0);
1076                 }
1077         }
1078         return buf;
1079 }
1080
1081 /*!
1082  * \brief Check that password meets minimum required length
1083  * \param vmu The voicemail user to change the password for.
1084  * \param password The password string to check
1085  *
1086  * \return zero on ok, 1 on not ok.
1087  */
1088 static int check_password(struct ast_vm_user *vmu, char *password)
1089 {
1090         /* check minimum length */
1091         if (strlen(password) < minpassword)
1092                 return 1;
1093         if (!ast_strlen_zero(ext_pass_check_cmd)) {
1094                 char cmd[255], buf[255];
1095
1096                 ast_log(AST_LOG_DEBUG, "Verify password policies for %s\n", password);
1097
1098                 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
1099                 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
1100                         ast_debug(5, "Result: %s\n", buf);
1101                         if (!strncasecmp(buf, "VALID", 5)) {
1102                                 ast_debug(3, "Passed password check: '%s'\n", buf);
1103                                 return 0;
1104                         } else if (!strncasecmp(buf, "FAILURE", 7)) {
1105                                 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
1106                                 return 0;
1107                         } else {
1108                                 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
1109                                 return 1;
1110                         }
1111                 }
1112         }
1113         return 0;
1114 }
1115
1116 /*! 
1117  * \brief Performs a change of the voicemail passowrd in the realtime engine.
1118  * \param vmu The voicemail user to change the password for.
1119  * \param password The new value to be set to the password for this user.
1120  * 
1121  * This only works if there is a realtime engine configured.
1122  * This is called from the (top level) vm_change_password.
1123  *
1124  * \return zero on success, -1 on error.
1125  */
1126 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
1127 {
1128         int res = -1;
1129         if (!strcmp(vmu->password, password)) {
1130                 /* No change (but an update would return 0 rows updated, so we opt out here) */
1131                 return 0;
1132         }
1133
1134         if (strlen(password) > 10) {
1135                 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
1136         }
1137         if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
1138                 ast_copy_string(vmu->password, password, sizeof(vmu->password));
1139                 res = 0;
1140         }
1141         return res;
1142 }
1143
1144 /*!
1145  * \brief Destructively Parse options and apply.
1146  */
1147 static void apply_options(struct ast_vm_user *vmu, const char *options)
1148 {       
1149         char *stringp;
1150         char *s;
1151         char *var, *value;
1152         stringp = ast_strdupa(options);
1153         while ((s = strsep(&stringp, "|"))) {
1154                 value = s;
1155                 if ((var = strsep(&value, "=")) && value) {
1156                         apply_option(vmu, var, value);
1157                 }
1158         }       
1159 }
1160
1161 /*!
1162  * \brief Loads the options specific to a voicemail user.
1163  * 
1164  * This is called when a vm_user structure is being set up, such as from load_options.
1165  */
1166 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
1167 {
1168         for (; var; var = var->next) {
1169                 if (!strcasecmp(var->name, "vmsecret")) {
1170                         ast_copy_string(retval->password, var->value, sizeof(retval->password));
1171                 } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
1172                         if (ast_strlen_zero(retval->password))
1173                                 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1174                 } else if (!strcasecmp(var->name, "uniqueid")) {
1175                         ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
1176                 } else if (!strcasecmp(var->name, "pager")) {
1177                         ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
1178                 } else if (!strcasecmp(var->name, "email")) {
1179                         ast_copy_string(retval->email, var->value, sizeof(retval->email));
1180                 } else if (!strcasecmp(var->name, "fullname")) {
1181                         ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
1182                 } else if (!strcasecmp(var->name, "context")) {
1183                         ast_copy_string(retval->context, var->value, sizeof(retval->context));
1184                 } else if (!strcasecmp(var->name, "emailsubject")) {
1185                         retval->emailsubject = ast_strdup(var->value);
1186                 } else if (!strcasecmp(var->name, "emailbody")) {
1187                         retval->emailbody = ast_strdup(var->value);
1188 #ifdef IMAP_STORAGE
1189                 } else if (!strcasecmp(var->name, "imapuser")) {
1190                         ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
1191                         retval->imapversion = imapversion;
1192                 } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
1193                         ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
1194                         retval->imapversion = imapversion;
1195                 } else if (!strcasecmp(var->name, "imapfolder")) {
1196                         ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
1197                 } else if (!strcasecmp(var->name, "imapvmshareid")) {
1198                         ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
1199                         retval->imapversion = imapversion;
1200 #endif
1201                 } else
1202                         apply_option(retval, var->name, var->value);
1203         }
1204 }
1205
1206 /*!
1207  * \brief Determines if a DTMF key entered is valid.
1208  * \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.
1209  *
1210  * Tests the character entered against the set of valid DTMF characters. 
1211  * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1212  */
1213 static int is_valid_dtmf(const char *key)
1214 {
1215         int i;
1216         char *local_key = ast_strdupa(key);
1217
1218         for (i = 0; i < strlen(key); ++i) {
1219                 if (!strchr(VALID_DTMF, *local_key)) {
1220                         ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1221                         return 0;
1222                 }
1223                 local_key++;
1224         }
1225         return 1;
1226 }
1227
1228 /*!
1229  * \brief Finds a voicemail user from the realtime engine.
1230  * \param ivm
1231  * \param context
1232  * \param mailbox
1233  *
1234  * 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.
1235  *
1236  * \return The ast_vm_user structure for the user that was found.
1237  */
1238 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1239 {
1240         struct ast_variable *var;
1241         struct ast_vm_user *retval;
1242
1243         if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1244                 if (!ivm)
1245                         ast_set_flag(retval, VM_ALLOCED);       
1246                 else
1247                         memset(retval, 0, sizeof(*retval));
1248                 if (mailbox) 
1249                         ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1250                 populate_defaults(retval);
1251                 if (!context && ast_test_flag((&globalflags), VM_SEARCH))
1252                         var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1253                 else
1254                         var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1255                 if (var) {
1256                         apply_options_full(retval, var);
1257                         ast_variables_destroy(var);
1258                 } else { 
1259                         if (!ivm) 
1260                                 ast_free(retval);
1261                         retval = NULL;
1262                 }       
1263         } 
1264         return retval;
1265 }
1266
1267 /*!
1268  * \brief Finds a voicemail user from the users file or the realtime engine.
1269  * \param ivm
1270  * \param context
1271  * \param mailbox
1272  * 
1273  * \return The ast_vm_user structure for the user that was found.
1274  */
1275 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1276 {
1277         /* This function could be made to generate one from a database, too */
1278         struct ast_vm_user *vmu = NULL, *cur;
1279         AST_LIST_LOCK(&users);
1280
1281         if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1282                 context = "default";
1283
1284         AST_LIST_TRAVERSE(&users, cur, list) {
1285 #ifdef IMAP_STORAGE
1286                 if (cur->imapversion != imapversion) {
1287                         continue;
1288                 }
1289 #endif
1290                 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1291                         break;
1292                 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
1293                         break;
1294         }
1295         if (cur) {
1296                 /* Make a copy, so that on a reload, we have no race */
1297                 if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
1298                         memcpy(vmu, cur, sizeof(*vmu));
1299                         ast_set2_flag(vmu, !ivm, VM_ALLOCED);
1300                         AST_LIST_NEXT(vmu, list) = NULL;
1301                 }
1302         } else
1303                 vmu = find_user_realtime(ivm, context, mailbox);
1304         AST_LIST_UNLOCK(&users);
1305         return vmu;
1306 }
1307
1308 /*!
1309  * \brief Resets a user password to a specified password.
1310  * \param context
1311  * \param mailbox
1312  * \param newpass
1313  *
1314  * This does the actual change password work, called by the vm_change_password() function.
1315  *
1316  * \return zero on success, -1 on error.
1317  */
1318 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
1319 {
1320         /* This function could be made to generate one from a database, too */
1321         struct ast_vm_user *cur;
1322         int res = -1;
1323         AST_LIST_LOCK(&users);
1324         AST_LIST_TRAVERSE(&users, cur, list) {
1325                 if ((!context || !strcasecmp(context, cur->context)) &&
1326                         (!strcasecmp(mailbox, cur->mailbox)))
1327                                 break;
1328         }
1329         if (cur) {
1330                 ast_copy_string(cur->password, newpass, sizeof(cur->password));
1331                 res = 0;
1332         }
1333         AST_LIST_UNLOCK(&users);
1334         return res;
1335 }
1336
1337 /*! 
1338  * \brief The handler for the change password option.
1339  * \param vmu The voicemail user to work with.
1340  * \param newpassword The new password (that has been gathered from the appropriate prompting).
1341  * 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.
1342  * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
1343  */
1344 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
1345 {
1346         struct ast_config   *cfg = NULL;
1347         struct ast_variable *var = NULL;
1348         struct ast_category *cat = NULL;
1349         char *category = NULL, *value = NULL, *new = NULL;
1350         const char *tmp = NULL;
1351         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
1352         char secretfn[PATH_MAX] = "";
1353         int found = 0;
1354
1355         if (!change_password_realtime(vmu, newpassword))
1356                 return;
1357
1358         /* check if we should store the secret in the spool directory next to the messages */
1359         switch (vmu->passwordlocation) {
1360         case OPT_PWLOC_SPOOLDIR:
1361                 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
1362                 if (write_password_to_file(secretfn, newpassword) == 0) {
1363                         ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
1364                         reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1365                         ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1366                         break;
1367                 } else {
1368                         ast_verb(4, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
1369                 }
1370                 /* Fall-through */
1371         case OPT_PWLOC_VOICEMAILCONF:
1372                 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1373                         while ((category = ast_category_browse(cfg, category))) {
1374                                 if (!strcasecmp(category, vmu->context)) {
1375                                         if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
1376                                                 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
1377                                                 break;
1378                                         }
1379                                         value = strstr(tmp, ",");
1380                                         if (!value) {
1381                                                 ast_log(AST_LOG_WARNING, "variable has bad format.\n");
1382                                                 break;
1383                                         }
1384                                         new = alloca((strlen(value) + strlen(newpassword) + 1));
1385                                         sprintf(new, "%s%s", newpassword, value);
1386                                         if (!(cat = ast_category_get(cfg, category))) {
1387                                                 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
1388                                                 break;
1389                                         }
1390                                         ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
1391                                         found = 1;
1392                                 }
1393                         }
1394                         /* save the results */
1395                         if (found) {
1396                                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1397                                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1398                                 ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
1399                                 break;
1400                         }
1401                 }
1402                 /* Fall-through */
1403         case OPT_PWLOC_USERSCONF:
1404                 /* check users.conf and update the password stored for the mailbox */
1405                 /* if no vmsecret entry exists create one. */
1406                 if ((cfg = ast_config_load("users.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1407                         ast_debug(4, "we are looking for %s\n", vmu->mailbox);
1408                         for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
1409                                 ast_debug(4, "users.conf: %s\n", category);
1410                                 if (!strcasecmp(category, vmu->mailbox)) {
1411                                         if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
1412                                                 ast_debug(3, "looks like we need to make vmsecret!\n");
1413                                                 var = ast_variable_new("vmsecret", newpassword, "");
1414                                         } else {
1415                                                 var = NULL;
1416                                         }
1417                                         new = alloca(strlen(newpassword) + 1);
1418                                         sprintf(new, "%s", newpassword);
1419                                         if (!(cat = ast_category_get(cfg, category))) {
1420                                                 ast_debug(4, "failed to get category!\n");
1421                                                 ast_free(var);
1422                                                 break;
1423                                         }
1424                                         if (!var) {
1425                                                 ast_variable_update(cat, "vmsecret", new, NULL, 0);
1426                                         } else {
1427                                                 ast_variable_append(cat, var);
1428                                         }
1429                                         found = 1;
1430                                         break;
1431                                 }
1432                         }
1433                         /* save the results and clean things up */
1434                         if (found) {
1435                                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1436                                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1437                                 ast_config_text_file_save("users.conf", cfg, "AppVoicemail");
1438                         }
1439                 }
1440         }
1441 }
1442
1443 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
1444 {
1445         char buf[255];
1446         snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
1447         if (!ast_safe_system(buf)) {
1448                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1449                 /* Reset the password in memory, too */
1450                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1451         }
1452 }
1453
1454 /*! 
1455  * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1456  * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1457  * \param len The length of the path string that was written out.
1458  * 
1459  * The path is constructed as 
1460  *      VM_SPOOL_DIRcontext/ext/folder
1461  *
1462  * \return zero on success, -1 on error.
1463  */
1464 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
1465 {
1466         return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
1467 }
1468
1469 /*! 
1470  * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1471  * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1472  * \param len The length of the path string that was written out.
1473  * 
1474  * The path is constructed as 
1475  *      VM_SPOOL_DIRcontext/ext/folder
1476  *
1477  * \return zero on success, -1 on error.
1478  */
1479 static int make_file(char *dest, const int len, const char *dir, const int num)
1480 {
1481         return snprintf(dest, len, "%s/msg%04d", dir, num);
1482 }
1483
1484 /* same as mkstemp, but return a FILE * */
1485 static FILE *vm_mkftemp(char *template)
1486 {
1487         FILE *p = NULL;
1488         int pfd = mkstemp(template);
1489         chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
1490         if (pfd > -1) {
1491                 p = fdopen(pfd, "w+");
1492                 if (!p) {
1493                         close(pfd);
1494                         pfd = -1;
1495                 }
1496         }
1497         return p;
1498 }
1499
1500 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
1501  * \param dest    String. base directory.
1502  * \param len     Length of dest.
1503  * \param context String. Ignored if is null or empty string.
1504  * \param ext     String. Ignored if is null or empty string.
1505  * \param folder  String. Ignored if is null or empty string. 
1506  * \return -1 on failure, 0 on success.
1507  */
1508 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
1509 {
1510         mode_t  mode = VOICEMAIL_DIR_MODE;
1511         int res;
1512
1513         make_dir(dest, len, context, ext, folder);
1514         if ((res = ast_mkdir(dest, mode))) {
1515                 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
1516                 return -1;
1517         }
1518         return 0;
1519 }
1520
1521 static const char * const mailbox_folders[] = {
1522 #ifdef IMAP_STORAGE
1523         imapfolder,
1524 #else
1525         "INBOX",
1526 #endif
1527         "Old",
1528         "Work",
1529         "Family",
1530         "Friends",
1531         "Cust1",
1532         "Cust2",
1533         "Cust3",
1534         "Cust4",
1535         "Cust5",
1536         "Deleted",
1537         "Urgent",
1538 };
1539
1540 static const char *mbox(struct ast_vm_user *vmu, int id)
1541 {
1542 #ifdef IMAP_STORAGE
1543         if (vmu && id == 0) {
1544                 return vmu->imapfolder;
1545         }
1546 #endif
1547         return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
1548 }
1549
1550 static int get_folder_by_name(const char *name)
1551 {
1552         size_t i;
1553
1554         for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
1555                 if (strcasecmp(name, mailbox_folders[i]) == 0) {
1556                         return i;
1557                 }
1558         }
1559
1560         return -1;
1561 }
1562
1563 static void free_user(struct ast_vm_user *vmu)
1564 {
1565         if (ast_test_flag(vmu, VM_ALLOCED)) {
1566                 if (vmu->emailbody != NULL) {
1567                         ast_free(vmu->emailbody);
1568                         vmu->emailbody = NULL;
1569                 }
1570                 if (vmu->emailsubject != NULL) {
1571                         ast_free(vmu->emailsubject);
1572                         vmu->emailsubject = NULL;
1573                 }
1574                 ast_free(vmu);
1575         }
1576 }
1577
1578 /* All IMAP-specific functions should go in this block. This
1579  * keeps them from being spread out all over the code */
1580 #ifdef IMAP_STORAGE
1581 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
1582 {
1583         char arg[10];
1584         struct vm_state *vms;
1585         unsigned long messageNum;
1586
1587         /* If greetings aren't stored in IMAP, just delete the file */
1588         if (msgnum < 0 && !imapgreetings) {
1589                 ast_filedelete(file, NULL);
1590                 return;
1591         }
1592
1593         if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1594                 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);
1595                 return;
1596         }
1597
1598         /* find real message number based on msgnum */
1599         /* this may be an index into vms->msgArray based on the msgnum. */
1600         messageNum = vms->msgArray[msgnum];
1601         if (messageNum == 0) {
1602                 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
1603                 return;
1604         }
1605         if (option_debug > 2)
1606                 ast_log(LOG_DEBUG, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
1607         /* delete message */
1608         snprintf (arg, sizeof(arg), "%lu", messageNum);
1609         ast_mutex_lock(&vms->lock);
1610         mail_setflag (vms->mailstream, arg, "\\DELETED");
1611         mail_expunge(vms->mailstream);
1612         ast_mutex_unlock(&vms->lock);
1613 }
1614
1615 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
1616 {
1617         struct vm_state *vms_p;
1618         char *file, *filename;
1619         char *attachment;
1620         int ret = 0, i;
1621         BODY *body;
1622
1623         /* This function is only used for retrieval of IMAP greetings
1624          * regular messages are not retrieved this way, nor are greetings
1625          * if they are stored locally*/
1626         if (msgnum > -1 || !imapgreetings) {
1627                 return 0;
1628         } else {
1629                 file = strrchr(ast_strdupa(dir), '/');
1630                 if (file)
1631                         *file++ = '\0';
1632                 else {
1633                         ast_debug (1, "Failed to procure file name from directory passed.\n");
1634                         return -1;
1635                 }
1636         }
1637
1638         /* check if someone is accessing this box right now... */
1639         if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && 
1640                 !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1641                 /* Unlike when retrieving a message, it is reasonable not to be able to find a 
1642                 * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
1643                 * that's all we need to do.
1644                 */
1645                 if (!(vms_p = create_vm_state_from_user(vmu))) {
1646                         ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
1647                         return -1;
1648                 }
1649         }
1650         
1651         /* Greetings will never have a prepended message */
1652         *vms_p->introfn = '\0';
1653
1654         ast_mutex_lock(&vms_p->lock);
1655         ret = init_mailstream(vms_p, GREETINGS_FOLDER);
1656         if (!vms_p->mailstream) {
1657                 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL\n");
1658                 ast_mutex_unlock(&vms_p->lock);
1659                 return -1;
1660         }
1661
1662         /*XXX Yuck, this could probably be done a lot better */
1663         for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
1664                 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
1665                 /* We have the body, now we extract the file name of the first attachment. */
1666                 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1667                         attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
1668                 } else {
1669                         ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
1670                         ast_mutex_unlock(&vms_p->lock);
1671                         return -1;
1672                 }
1673                 filename = strsep(&attachment, ".");
1674                 if (!strcmp(filename, file)) {
1675                         ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
1676                         vms_p->msgArray[vms_p->curmsg] = i + 1;
1677                         save_body(body, vms_p, "2", attachment, 0);
1678                         ast_mutex_unlock(&vms_p->lock);
1679                         return 0;
1680                 }
1681         }
1682         ast_mutex_unlock(&vms_p->lock);
1683
1684         return -1;
1685 }
1686
1687 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
1688 {
1689         BODY *body;
1690         char *header_content;
1691         char *attachedfilefmt;
1692         char buf[80];
1693         struct vm_state *vms;
1694         char text_file[PATH_MAX];
1695         FILE *text_file_ptr;
1696         int res = 0;
1697         struct ast_vm_user *vmu;
1698
1699         if (!(vmu = find_user(NULL, context, mailbox))) {
1700                 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
1701                 return -1;
1702         }
1703         
1704         if (msgnum < 0) {
1705                 if (imapgreetings) {
1706                         res = imap_retrieve_greeting(dir, msgnum, vmu);
1707                         goto exit;
1708                 } else {
1709                         res = 0;
1710                         goto exit;
1711                 }
1712         }
1713
1714         /* Before anything can happen, we need a vm_state so that we can
1715          * actually access the imap server through the vms->mailstream
1716          */
1717         if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1718                 /* This should not happen. If it does, then I guess we'd
1719                  * need to create the vm_state, extract which mailbox to
1720                  * open, and then set up the msgArray so that the correct
1721                  * IMAP message could be accessed. If I have seen correctly
1722                  * though, the vms should be obtainable from the vmstates list
1723                  * and should have its msgArray properly set up.
1724                  */
1725                 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
1726                 res = -1;
1727                 goto exit;
1728         }
1729         
1730         make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
1731         snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
1732
1733         /* Don't try to retrieve a message from IMAP if it already is on the file system */
1734         if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
1735                 res = 0;
1736                 goto exit;
1737         }
1738
1739         if (option_debug > 2)
1740                 ast_log(LOG_DEBUG, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
1741         if (vms->msgArray[msgnum] == 0) {
1742                 ast_log(LOG_WARNING, "Trying to access unknown message\n");
1743                 res = -1;
1744                 goto exit;
1745         }
1746
1747         /* This will only work for new messages... */
1748         ast_mutex_lock(&vms->lock);
1749         header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
1750         ast_mutex_unlock(&vms->lock);
1751         /* empty string means no valid header */
1752         if (ast_strlen_zero(header_content)) {
1753                 ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
1754                 res = -1;
1755                 goto exit;
1756         }
1757
1758         ast_mutex_lock(&vms->lock);
1759         mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
1760         ast_mutex_unlock(&vms->lock);
1761
1762         /* We have the body, now we extract the file name of the first attachment. */
1763         if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1764                 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
1765         } else {
1766                 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
1767                 res = -1;
1768                 goto exit;
1769         }
1770         
1771         /* Find the format of the attached file */
1772
1773         strsep(&attachedfilefmt, ".");
1774         if (!attachedfilefmt) {
1775                 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
1776                 res = -1;
1777                 goto exit;
1778         }
1779         
1780         save_body(body, vms, "2", attachedfilefmt, 0);
1781         if (save_body(body, vms, "3", attachedfilefmt, 1)) {
1782                 *vms->introfn = '\0';
1783         }
1784
1785         /* Get info from headers!! */
1786         snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
1787
1788         if (!(text_file_ptr = fopen(text_file, "w"))) {
1789                 ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
1790         }
1791
1792         fprintf(text_file_ptr, "%s\n", "[message]");
1793
1794         get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf));
1795         fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
1796         get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf));
1797         fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
1798         get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf));
1799         fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
1800         get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf));
1801         fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
1802         get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf));
1803         fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
1804         get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf));
1805         fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
1806         get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf));
1807         fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
1808         fclose(text_file_ptr);
1809
1810 exit:
1811         free_user(vmu);
1812         return res;
1813 }
1814
1815 static int folder_int(const char *folder)
1816 {
1817         /*assume a NULL folder means INBOX*/
1818         if (!folder)
1819                 return 0;
1820         if (!strcasecmp(folder, imapfolder))
1821                 return 0;
1822         else if (!strcasecmp(folder, "Old"))
1823                 return 1;
1824         else if (!strcasecmp(folder, "Work"))
1825                 return 2;
1826         else if (!strcasecmp(folder, "Family"))
1827                 return 3;
1828         else if (!strcasecmp(folder, "Friends"))
1829                 return 4;
1830         else if (!strcasecmp(folder, "Cust1"))
1831                 return 5;
1832         else if (!strcasecmp(folder, "Cust2"))
1833                 return 6;
1834         else if (!strcasecmp(folder, "Cust3"))
1835                 return 7;
1836         else if (!strcasecmp(folder, "Cust4"))
1837                 return 8;
1838         else if (!strcasecmp(folder, "Cust5"))
1839                 return 9;
1840         else /*assume they meant INBOX if folder is not found otherwise*/
1841                 return 0;
1842 }
1843
1844 /*!
1845  * \brief Gets the number of messages that exist in a mailbox folder.
1846  * \param context
1847  * \param mailbox
1848  * \param folder
1849  * 
1850  * This method is used when IMAP backend is used.
1851  * \return The number of messages in this mailbox folder (zero or more).
1852  */
1853 static int messagecount(const char *context, const char *mailbox, const char *folder)
1854 {
1855         SEARCHPGM *pgm;
1856         SEARCHHEADER *hdr;
1857
1858         struct ast_vm_user *vmu, vmus;
1859         struct vm_state *vms_p;
1860         int ret = 0;
1861         int fold = folder_int(folder);
1862         int urgent = 0;
1863         
1864         /* If URGENT, then look at INBOX */
1865         if (fold == 11) {
1866                 fold = NEW_FOLDER;
1867                 urgent = 1;
1868         }
1869
1870         if (ast_strlen_zero(mailbox))
1871                 return 0;
1872
1873         /* We have to get the user before we can open the stream! */
1874         vmu = find_user(&vmus, context, mailbox);
1875         if (!vmu) {
1876                 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailbox, context);
1877                 return -1;
1878         } else {
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                         return -1;
1883                 }
1884         }
1885         
1886         /* No IMAP account available */
1887         if (vmu->imapuser[0] == '\0') {
1888                 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
1889                 free_user(vmu);
1890                 return -1;
1891         }
1892
1893         /* check if someone is accessing this box right now... */
1894         vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
1895         if (!vms_p) {
1896                 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
1897         }
1898         if (vms_p) {
1899                 ast_debug(3, "Returning before search - user is logged in\n");
1900                 if (fold == 0) { /* INBOX */
1901                         return vms_p->newmessages;
1902                 }
1903                 if (fold == 1) { /* Old messages */
1904                         return vms_p->oldmessages;
1905                 }
1906                 if (fold == 11) {/*Urgent messages*/
1907                         return vms_p->urgentmessages;
1908                 }
1909         }
1910
1911         /* add one if not there... */
1912         vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
1913         if (!vms_p) {
1914                 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
1915         }
1916
1917         if (!vms_p) {
1918                 vms_p = create_vm_state_from_user(vmu);
1919         }
1920         ret = init_mailstream(vms_p, fold);
1921         if (!vms_p->mailstream) {
1922                 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
1923                 return -1;
1924         }
1925         if (ret == 0) {
1926                 ast_mutex_lock(&vms_p->lock);
1927                 pgm = mail_newsearchpgm ();
1928                 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
1929                 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
1930                 pgm->header = hdr;
1931                 if (fold != 1) {
1932                         pgm->unseen = 1;
1933                         pgm->seen = 0;
1934                 }
1935                 /* In the special case where fold is 1 (old messages) we have to do things a bit
1936                  * differently. Old messages are stored in the INBOX but are marked as "seen"
1937                  */
1938                 else {
1939                         pgm->unseen = 0;
1940                         pgm->seen = 1;
1941                 }
1942                 /* look for urgent messages */
1943                 if (urgent) {
1944                         pgm->flagged = 1;
1945                         pgm->unflagged = 0;
1946                 }
1947                 pgm->undeleted = 1;
1948                 pgm->deleted = 0;
1949
1950                 vms_p->vmArrayIndex = 0;
1951                 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
1952                 if (fold == 0 && urgent == 0)
1953                         vms_p->newmessages = vms_p->vmArrayIndex;
1954                 if (fold == 1)
1955                         vms_p->oldmessages = vms_p->vmArrayIndex;
1956                 if (fold == 0 && urgent == 1)
1957                         vms_p->urgentmessages = vms_p->vmArrayIndex;
1958                 /*Freeing the searchpgm also frees the searchhdr*/
1959                 mail_free_searchpgm(&pgm);
1960                 ast_mutex_unlock(&vms_p->lock);
1961                 vms_p->updated = 0;
1962                 return vms_p->vmArrayIndex;
1963         } else {
1964                 ast_mutex_lock(&vms_p->lock);
1965                 mail_ping(vms_p->mailstream);
1966                 ast_mutex_unlock(&vms_p->lock);
1967         }
1968         return 0;
1969 }
1970
1971 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)
1972 {
1973         char *myserveremail = serveremail;
1974         char fn[PATH_MAX];
1975         char introfn[PATH_MAX];
1976         char mailbox[256];
1977         char *stringp;
1978         FILE *p = NULL;
1979         char tmp[80] = "/tmp/astmail-XXXXXX";
1980         long len;
1981         void *buf;
1982         int tempcopy = 0;
1983         STRING str;
1984         int ret; /* for better error checking */
1985         char *imap_flags = NIL;
1986
1987     /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
1988     if (msgnum < 0 && !imapgreetings) {
1989         return 0;
1990     }
1991
1992         /* Set urgent flag for IMAP message */
1993         if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
1994                 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
1995                 imap_flags = "\\FLAGGED";
1996         }
1997         
1998         /* Attach only the first format */
1999         fmt = ast_strdupa(fmt);
2000         stringp = fmt;
2001         strsep(&stringp, "|");
2002
2003         if (!ast_strlen_zero(vmu->serveremail))
2004                 myserveremail = vmu->serveremail;
2005
2006         if (msgnum > -1)
2007                 make_file(fn, sizeof(fn), dir, msgnum);
2008         else
2009                 ast_copy_string (fn, dir, sizeof(fn));
2010
2011         snprintf(introfn, sizeof(introfn), "%sintro", fn);
2012         if (ast_fileexists(introfn, NULL, NULL) <= 0) {
2013                 *introfn = '\0';
2014         }
2015         
2016         if (ast_strlen_zero(vmu->email)) {
2017                 /* We need the vmu->email to be set when we call make_email_file, but
2018                  * if we keep it set, a duplicate e-mail will be created. So at the end
2019                  * of this function, we will revert back to an empty string if tempcopy
2020                  * is 1.
2021                  */
2022                 ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
2023                 tempcopy = 1;
2024         }
2025
2026         if (!strcmp(fmt, "wav49"))
2027                 fmt = "WAV";
2028         ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
2029
2030         /* Make a temporary file instead of piping directly to sendmail, in case the mail
2031            command hangs. */
2032         if (!(p = vm_mkftemp(tmp))) {
2033                 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
2034                 if (tempcopy)
2035                         *(vmu->email) = '\0';
2036                 return -1;
2037         }
2038
2039         if (msgnum < 0 && imapgreetings) {
2040                 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
2041                         ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
2042                         return -1;
2043                 }
2044                 imap_delete_old_greeting(fn, vms);
2045         }
2046
2047         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);
2048         /* read mail file to memory */
2049         len = ftell(p);
2050         rewind(p);
2051         if (!(buf = ast_malloc(len + 1))) {
2052                 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
2053                 fclose(p);
2054                 if (tempcopy)
2055                         *(vmu->email) = '\0';
2056                 return -1;
2057         }
2058         if (fread(buf, len, 1, p) < len) {
2059                 if (ferror(p)) {
2060                         ast_log(LOG_ERROR, "Short read while reading in mail file.\n");
2061                         return -1;
2062                 }
2063         }
2064         ((char *) buf)[len] = '\0';
2065         INIT(&str, mail_string, buf, len);
2066         ret = init_mailstream(vms, NEW_FOLDER);
2067         if (ret == 0) {
2068                 imap_mailbox_name(mailbox, sizeof(mailbox), vms, NEW_FOLDER, 1);
2069                 ast_mutex_lock(&vms->lock);
2070                 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
2071                         ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
2072                 ast_mutex_unlock(&vms->lock);
2073                 fclose(p);
2074                 unlink(tmp);
2075                 ast_free(buf);
2076         } else {
2077                 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
2078                 fclose(p);
2079                 unlink(tmp);
2080                 ast_free(buf);
2081                 return -1;
2082         }
2083         ast_debug(3, "%s stored\n", fn);
2084         
2085         if (tempcopy)
2086                 *(vmu->email) = '\0';
2087         
2088         return 0;
2089
2090 }
2091
2092 /*!
2093  * \brief Gets the number of messages that exist in the inbox folder.
2094  * \param mailbox_context
2095  * \param newmsgs The variable that is updated with the count of new messages within this inbox.
2096  * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
2097  * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
2098  * 
2099  * This method is used when IMAP backend is used.
2100  * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
2101  *
2102  * \return zero on success, -1 on error.
2103  */
2104
2105 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
2106 {
2107         char tmp[PATH_MAX] = "";
2108         char *mailboxnc;
2109         char *context;
2110         char *mb;
2111         char *cur;
2112         if (newmsgs)
2113                 *newmsgs = 0;
2114         if (oldmsgs)
2115                 *oldmsgs = 0;
2116         if (urgentmsgs)
2117                 *urgentmsgs = 0;
2118
2119         ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
2120         /* If no mailbox, return immediately */
2121         if (ast_strlen_zero(mailbox_context))
2122                 return 0;
2123         
2124         ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2125         context = strchr(tmp, '@');
2126         if (strchr(mailbox_context, ',')) {
2127                 int tmpnew, tmpold, tmpurgent;
2128                 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2129                 mb = tmp;
2130                 while ((cur = strsep(&mb, ", "))) {
2131                         if (!ast_strlen_zero(cur)) {
2132                                 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2133                                         return -1;
2134                                 else {
2135                                         if (newmsgs)
2136                                                 *newmsgs += tmpnew; 
2137                                         if (oldmsgs)
2138                                                 *oldmsgs += tmpold;
2139                                         if (urgentmsgs)
2140                                                 *urgentmsgs += tmpurgent;
2141                                 }
2142                         }
2143                 }
2144                 return 0;
2145         }
2146         if (context) {
2147                 *context = '\0';
2148                 mailboxnc = tmp;
2149                 context++;
2150         } else {
2151                 context = "default";
2152                 mailboxnc = (char *) mailbox_context;
2153         }
2154
2155         if (newmsgs) {
2156                 struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
2157                 if (!vmu) {
2158                         ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
2159                         return -1;
2160                 }
2161                 if ((*newmsgs = messagecount(context, mailboxnc, vmu->imapfolder)) < 0)
2162                         return -1;
2163         }
2164         if (oldmsgs) {
2165                 if ((*oldmsgs = messagecount(context, mailboxnc, "Old")) < 0)
2166                         return -1;
2167         }
2168         if (urgentmsgs) {
2169                 if((*urgentmsgs = messagecount(context, mailboxnc, "Urgent")) < 0)
2170                         return -1;
2171         }
2172         return 0;
2173 }
2174
2175 static int inboxcount(const char *mailbox_context, int *newmsgs, int *oldmsgs)
2176 {
2177         return inboxcount2(mailbox_context, NULL, newmsgs, oldmsgs);
2178 }
2179
2180 /** 
2181  * \brief Determines if the given folder has messages.
2182  * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
2183  * \param folder the folder to look in
2184  *
2185  * This function is used when the mailbox is stored in an IMAP back end.
2186  * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
2187  * \return 1 if the folder has one or more messages. zero otherwise.
2188  */
2189
2190 static int has_voicemail(const char *mailbox, const char *folder)
2191 {
2192         char tmp[256], *tmp2, *box, *context;
2193         ast_copy_string(tmp, mailbox, sizeof(tmp));
2194         tmp2 = tmp;
2195         if (strchr(tmp2, ',')) {
2196                 while ((box = strsep(&tmp2, ","))) {
2197                         if (!ast_strlen_zero(box)) {
2198                                 if (has_voicemail(box, folder))
2199                                         return 1;
2200                         }
2201                 }
2202         }
2203         if ((context = strchr(tmp, '@')))
2204                 *context++ = '\0';
2205         else
2206                 context = "default";
2207         return messagecount(context, tmp, folder) ? 1 : 0;
2208 }
2209
2210 /*!
2211  * \brief Copies a message from one mailbox to another.
2212  * \param chan
2213  * \param vmu
2214  * \param imbox
2215  * \param msgnum
2216  * \param duration
2217  * \param recip
2218  * \param fmt
2219  * \param dir
2220  *
2221  * This works with IMAP storage based mailboxes.
2222  *
2223  * \return zero on success, -1 on error.
2224  */
2225 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)
2226 {
2227         struct vm_state *sendvms = NULL, *destvms = NULL;
2228         char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
2229         if (msgnum >= recip->maxmsg) {
2230                 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
2231                 return -1;
2232         }
2233         if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
2234                 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
2235                 return -1;
2236         }
2237         if (!(destvms = get_vm_state_by_imapuser(recip->imapuser, 0))) {
2238                 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
2239                 return -1;
2240         }
2241         snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
2242         ast_mutex_lock(&sendvms->lock);
2243         if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
2244                 ast_mutex_unlock(&sendvms->lock);
2245                 return 0;
2246         }
2247         ast_mutex_unlock(&sendvms->lock);
2248         ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
2249         return -1;
2250 }
2251
2252 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
2253 {
2254         char tmp[256], *t = tmp;
2255         size_t left = sizeof(tmp);
2256         
2257         if (box == OLD_FOLDER) {
2258                 ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
2259         } else {
2260                 ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
2261         }
2262
2263         if (box == NEW_FOLDER) {
2264                 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
2265         } else {
2266                 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
2267         }
2268
2269         /* Build up server information */
2270         ast_build_string(&t, &left, "{%s:%s/imap", imapserver, imapport);
2271
2272         /* Add authentication user if present */
2273         if (!ast_strlen_zero(authuser))
2274                 ast_build_string(&t, &left, "/authuser=%s", authuser);
2275
2276         /* Add flags if present */
2277         if (!ast_strlen_zero(imapflags))
2278                 ast_build_string(&t, &left, "/%s", imapflags);
2279
2280         /* End with username */
2281 #if 1
2282         ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
2283 #else
2284         ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
2285 #endif
2286         if (box == NEW_FOLDER || box == OLD_FOLDER)
2287                 snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
2288         else if (box == GREETINGS_FOLDER)
2289                 snprintf(spec, len, "%s%s", tmp, greetingfolder);
2290         else {  /* Other folders such as Friends, Family, etc... */
2291                 if (!ast_strlen_zero(imapparentfolder)) {
2292                         /* imapparentfolder would typically be set to INBOX */
2293                         snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
2294                 } else {
2295                         snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
2296                 }
2297         }
2298 }
2299
2300 static int init_mailstream(struct vm_state *vms, int box)
2301 {
2302         MAILSTREAM *stream = NIL;
2303         long debug;
2304         char tmp[256];
2305         
2306         if (!vms) {
2307                 ast_log(LOG_ERROR, "vm_state is NULL!\n");
2308                 return -1;
2309         }
2310         if (option_debug > 2)
2311                 ast_log(LOG_DEBUG, "vm_state user is:%s\n", vms->imapuser);
2312         if (vms->mailstream == NIL || !vms->mailstream) {
2313                 if (option_debug)
2314                         ast_log(LOG_DEBUG, "mailstream not set.\n");
2315         } else {
2316                 stream = vms->mailstream;
2317         }
2318         /* debug = T;  user wants protocol telemetry? */
2319         debug = NIL;  /* NO protocol telemetry? */
2320
2321         if (delimiter == '\0') {                /* did not probe the server yet */
2322                 char *cp;
2323 #ifdef USE_SYSTEM_IMAP
2324 #include <imap/linkage.c>
2325 #elif defined(USE_SYSTEM_CCLIENT)
2326 #include <c-client/linkage.c>
2327 #else
2328 #include "linkage.c"
2329 #endif
2330                 /* Connect to INBOX first to get folders delimiter */
2331                 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
2332                 ast_mutex_lock(&vms->lock);
2333                 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2334                 ast_mutex_unlock(&vms->lock);
2335                 if (stream == NIL) {
2336                         ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
2337                         return -1;
2338                 }
2339                 get_mailbox_delimiter(stream);
2340                 /* update delimiter in imapfolder */
2341                 for (cp = vms->imapfolder; *cp; cp++)
2342                         if (*cp == '/')
2343                                 *cp = delimiter;
2344         }
2345         /* Now connect to the target folder */
2346         imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
2347         if (option_debug > 2)
2348                 ast_log(LOG_DEBUG, "Before mail_open, server: %s, box:%d\n", tmp, box);
2349         ast_mutex_lock(&vms->lock);
2350         vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2351         ast_mutex_unlock(&vms->lock);
2352         if (vms->mailstream == NIL) {
2353                 return -1;
2354         } else {
2355                 return 0;
2356         }
2357 }
2358
2359 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
2360 {
2361         SEARCHPGM *pgm;
2362         SEARCHHEADER *hdr;
2363         int ret, urgent = 0;
2364
2365         /* If Urgent, then look at INBOX */
2366         if (box == 11) {
2367                 box = NEW_FOLDER;
2368                 urgent = 1;
2369         }
2370
2371         ast_copy_string(vms->imapuser, vmu->imapuser, sizeof(vms->imapuser));
2372         ast_copy_string(vms->imapfolder, vmu->imapfolder, sizeof(vms->imapfolder));
2373         vms->imapversion = vmu->imapversion;
2374         ast_debug(3, "Before init_mailstream, user is %s\n", vmu->imapuser);
2375
2376         if ((ret = init_mailstream(vms, box)) || !vms->mailstream) {
2377                 ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
2378                 return -1;
2379         }
2380         
2381         create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
2382         
2383         /* Check Quota */
2384         if  (box == 0)  {
2385                 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(vmu, box));
2386                 check_quota(vms, (char *) mbox(vmu, box));
2387         }
2388
2389         ast_mutex_lock(&vms->lock);
2390         pgm = mail_newsearchpgm();
2391
2392         /* Check IMAP folder for Asterisk messages only... */
2393         hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : vmu->mailbox));
2394         hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", vmu->context);
2395         pgm->header = hdr;
2396         pgm->deleted = 0;
2397         pgm->undeleted = 1;
2398
2399         /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
2400         if (box == NEW_FOLDER && urgent == 1) {
2401                 pgm->unseen = 1;
2402                 pgm->seen = 0;
2403                 pgm->flagged = 1;
2404                 pgm->unflagged = 0;
2405         } else if (box == NEW_FOLDER && urgent == 0) {
2406                 pgm->unseen = 1;
2407                 pgm->seen = 0;
2408                 pgm->flagged = 0;
2409                 pgm->unflagged = 1;
2410         } else if (box == OLD_FOLDER) {
2411                 pgm->seen = 1;
2412                 pgm->unseen = 0;
2413         }
2414
2415         ast_debug(3, "Before mail_search_full, user is %s\n", vmu->imapuser);
2416
2417         vms->vmArrayIndex = 0;
2418         mail_search_full (vms->mailstream, NULL, pgm, NIL);
2419         vms->lastmsg = vms->vmArrayIndex - 1;
2420         mail_free_searchpgm(&pgm);
2421
2422         ast_mutex_unlock(&vms->lock);
2423         return 0;
2424 }
2425
2426 static void write_file(char *filename, char *buffer, unsigned long len)
2427 {
2428         FILE *output;
2429
2430         output = fopen (filename, "w");
2431         if (fwrite(buffer, len, 1, output) != 1) {
2432                 if (ferror(output)) {
2433                         ast_log(LOG_ERROR, "Short write while writing e-mail body: %s.\n", strerror(errno));
2434                 }
2435         }
2436         fclose (output);
2437 }
2438
2439 static void update_messages_by_imapuser(const char *user, unsigned long number)
2440 {
2441         struct vm_state *vms = get_vm_state_by_imapuser(user, 1);
2442
2443         if (!vms && !(vms = get_vm_state_by_imapuser(user, 0))) {
2444                 return;
2445         }
2446
2447         ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vms->vmArrayIndex, vms->interactive);
2448         vms->msgArray[vms->vmArrayIndex++] = number;
2449 }
2450
2451 void mm_searched(MAILSTREAM *stream, unsigned long number)
2452 {
2453         char *mailbox = stream->mailbox, buf[1024] = "", *user;
2454
2455         if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
2456                 return;
2457
2458         update_messages_by_imapuser(user, number);
2459 }
2460
2461 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
2462 {
2463         struct ast_variable *var;
2464         struct ast_vm_user *vmu;
2465
2466         vmu = ast_calloc(1, sizeof *vmu);
2467         if (!vmu)
2468                 return NULL;
2469         ast_set_flag(vmu, VM_ALLOCED);
2470         populate_defaults(vmu);
2471
2472         var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
2473         if (var) {
2474                 apply_options_full(vmu, var);
2475                 ast_variables_destroy(var);
2476                 return vmu;
2477         } else {
2478                 ast_free(vmu);
2479                 return NULL;
2480         }
2481 }
2482
2483 /* Interfaces to C-client */
2484
2485 void mm_exists(MAILSTREAM * stream, unsigned long number)
2486 {
2487         /* mail_ping will callback here if new mail! */
2488         ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
2489         if (number == 0) return;
2490         set_update(stream);
2491 }
2492
2493
2494 void mm_expunged(MAILSTREAM * stream, unsigned long number)
2495 {
2496         /* mail_ping will callback here if expunged mail! */
2497         ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
2498         if (number == 0) return;
2499         set_update(stream);
2500 }
2501
2502
2503 void mm_flags(MAILSTREAM * stream, unsigned long number)
2504 {
2505         /* mail_ping will callback here if read mail! */
2506         ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
2507         if (number == 0) return;
2508         set_update(stream);
2509 }
2510
2511
2512 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
2513 {
2514         ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
2515         mm_log (string, errflg);
2516 }
2517
2518
2519 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2520 {
2521         if (delimiter == '\0') {
2522                 delimiter = delim;
2523         }
2524
2525         ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
2526         if (attributes & LATT_NOINFERIORS)
2527                 ast_debug(5, "no inferiors\n");
2528         if (attributes & LATT_NOSELECT)
2529                 ast_debug(5, "no select\n");
2530         if (attributes & LATT_MARKED)
2531                 ast_debug(5, "marked\n");
2532         if (attributes & LATT_UNMARKED)
2533                 ast_debug(5, "unmarked\n");
2534 }
2535
2536
2537 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2538 {
2539         ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
2540         if (attributes & LATT_NOINFERIORS)
2541                 ast_debug(5, "no inferiors\n");
2542         if (attributes & LATT_NOSELECT)
2543                 ast_debug(5, "no select\n");
2544         if (attributes & LATT_MARKED)
2545                 ast_debug(5, "marked\n");
2546         if (attributes & LATT_UNMARKED)
2547                 ast_debug(5, "unmarked\n");
2548 }
2549
2550
2551 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
2552 {
2553         ast_log(AST_LOG_NOTICE, " Mailbox %s", mailbox);
2554         if (status->flags & SA_MESSAGES)
2555                 ast_log(AST_LOG_NOTICE, ", %lu messages", status->messages);
2556         if (status->flags & SA_RECENT)
2557                 ast_log(AST_LOG_NOTICE, ", %lu recent", status->recent);
2558         if (status->flags & SA_UNSEEN)
2559                 ast_log(AST_LOG_NOTICE, ", %lu unseen", status->unseen);
2560         if (status->flags & SA_UIDVALIDITY)
2561                 ast_log(AST_LOG_NOTICE, ", %lu UID validity", status->uidvalidity);
2562         if (status->flags & SA_UIDNEXT)
2563                 ast_log(AST_LOG_NOTICE, ", %lu next UID", status->uidnext);
2564         ast_log(AST_LOG_NOTICE, "\n");
2565 }
2566
2567
2568 void mm_log(char *string, long errflg)
2569 {
2570         switch ((short) errflg) {
2571                 case NIL:
2572                         ast_debug(1, "IMAP Info: %s\n", string);
2573                         break;
2574                 case PARSE:
2575                 case WARN:
2576                         ast_log(AST_LOG_WARNING, "IMAP Warning: %s\n", string);
2577                         break;
2578                 case ERROR:
2579                         ast_log(AST_LOG_ERROR, "IMAP Error: %s\n", string);
2580                         break;
2581         }
2582 }
2583
2584
2585 void mm_dlog(char *string)
2586 {
2587         ast_log(AST_LOG_NOTICE, "%s\n", string);
2588 }
2589
2590
2591 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
2592 {
2593         struct ast_vm_user *vmu;
2594
2595         ast_debug(4, "Entering callback mm_login\n");
2596
2597         ast_copy_string(user, mb->user, MAILTMPLEN);
2598
2599         /* We should only do this when necessary */
2600         if (!ast_strlen_zero(authpassword)) {
2601                 ast_copy_string(pwd, authpassword, MAILTMPLEN);
2602         } else {
2603                 AST_LIST_TRAVERSE(&users, vmu, list) {
2604                         if (!strcasecmp(mb->user, vmu->imapuser)) {
2605                                 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2606                                 break;
2607                         }
2608                 }
2609                 if (!vmu) {
2610                         if ((vmu = find_user_realtime_imapuser(mb->user))) {
2611                                 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2612                                 free_user(vmu);
2613                         }
2614                 }
2615         }
2616 }
2617
2618
2619 void mm_critical(MAILSTREAM * stream)
2620 {
2621 }
2622
2623
2624 void mm_nocritical(MAILSTREAM * stream)
2625 {
2626 }
2627
2628
2629 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
2630 {
2631         kill (getpid (), SIGSTOP);
2632         return NIL;
2633 }
2634
2635
2636 void mm_fatal(char *string)
2637 {
2638         ast_log(AST_LOG_ERROR, "IMAP access FATAL error: %s\n", string);
2639 }
2640
2641 /* C-client callback to handle quota */
2642 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
2643 {
2644         struct vm_state *vms;
2645         char *mailbox = stream->mailbox, *user;
2646         char buf[1024] = "";
2647         unsigned long usage = 0, limit = 0;
2648         
2649         while (pquota) {
2650                 usage = pquota->usage;
2651                 limit = pquota->limit;
2652                 pquota = pquota->next;
2653         }
2654         
2655         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)))) {
2656                 ast_log(AST_LOG_ERROR, "No state found.\n");
2657                 return;
2658         }
2659
2660         ast_debug(3, "User %s usage is %lu, limit is %lu\n", user, usage, limit);
2661
2662         vms->quota_usage = usage;
2663         vms->quota_limit = limit;
2664 }
2665
2666 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len)
2667 {
2668         char *start, *eol_pnt;
2669         int taglen;
2670
2671         if (ast_strlen_zero(header) || ast_strlen_zero(tag))
2672                 return NULL;
2673
2674         taglen = strlen(tag) + 1;
2675         if (taglen < 1)
2676                 return NULL;
2677
2678         if (!(start = strstr(header, tag)))
2679                 return NULL;
2680
2681         /* Since we can be called multiple times we should clear our buffer */
2682         memset(buf, 0, len);
2683
2684         ast_copy_string(buf, start+taglen, len);
2685         if ((eol_pnt = strchr(buf,'\r')) || (eol_pnt = strchr(buf,'\n')))
2686                 *eol_pnt = '\0';
2687         return buf;
2688 }
2689
2690 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len)
2691 {
2692         char *start, *quote, *eol_pnt;
2693
2694         if (ast_strlen_zero(mailbox))
2695                 return NULL;
2696
2697         if (!(start = strstr(mailbox, "/user=")))
2698                 return NULL;
2699
2700         ast_copy_string(buf, start+6, len);
2701
2702         if (!(quote = strchr(buf, '\"'))) {
2703                 if (!(eol_pnt = strchr(buf, '/')))
2704                         eol_pnt = strchr(buf,'}');
2705                 *eol_pnt = '\0';
2706                 return buf;
2707         } else {
2708                 eol_pnt = strchr(buf+1,'\"');
2709                 *eol_pnt = '\0';
2710                 return buf+1;
2711         }
2712 }
2713
2714 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
2715 {
2716         struct vm_state *vms_p;
2717
2718         pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2719         if ((vms_p = pthread_getspecific(ts_vmstate.key)) && !strcmp(vms_p->imapuser, vmu->imapuser) && !strcmp(vms_p->username, vmu->mailbox)) {
2720                 return vms_p;
2721         }
2722         if (option_debug > 4)
2723                 ast_log(AST_LOG_DEBUG, "Adding new vmstate for %s\n", vmu->imapuser);
2724         if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
2725                 return NULL;
2726         ast_copy_string(vms_p->imapuser, vmu->imapuser, sizeof(vms_p->imapuser));
2727         ast_copy_string(vms_p->imapfolder, vmu->imapfolder, sizeof(vms_p->imapfolder));
2728         ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
2729         ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
2730         vms_p->mailstream = NIL; /* save for access from interactive entry point */
2731         vms_p->imapversion = vmu->imapversion;
2732         if (option_debug > 4)
2733                 ast_log(AST_LOG_DEBUG, "Copied %s to %s\n", vmu->imapuser, vms_p->imapuser);
2734         vms_p->updated = 1;
2735         /* set mailbox to INBOX! */
2736         ast_copy_string(vms_p->curbox, mbox(vmu, 0), sizeof(vms_p->curbox));
2737         init_vm_state(vms_p);
2738         vmstate_insert(vms_p);
2739         return vms_p;
2740 }
2741
2742 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive)
2743 {
2744         struct vmstate *vlist = NULL;
2745
2746         if (interactive) {
2747                 struct vm_state *vms;
2748                 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2749                 vms = pthread_getspecific(ts_vmstate.key);
2750                 return vms;
2751         }
2752
2753         AST_LIST_LOCK(&vmstates);
2754         AST_LIST_TRAVERSE(&vmstates, vlist, list) {
2755                 if (!vlist->vms) {
2756                         ast_debug(3, "error: vms is NULL for %s\n", user);
2757                         continue;
2758                 }
2759                 if (vlist->vms->imapversion != imapversion) {
2760                         continue;
2761                 }
2762                 if (!vlist->vms->imapuser) {
2763                         ast_debug(3, "error: imapuser is NULL for %s\n", user);
2764                         continue;
2765                 }
2766
2767                 if (!strcmp(vlist->vms->imapuser, user) && (interactive == 2 || vlist->vms->interactive == interactive)) {
2768                         AST_LIST_UNLOCK(&vmstates);
2769                         return vlist->vms;
2770                 }
2771         }
2772         AST_LIST_UNLOCK(&vmstates);
2773
2774         ast_debug(3, "%s not found in vmstates\n", user);
2775
2776         return NULL;
2777 }
2778
2779 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
2780 {
2781
2782         struct vmstate *vlist = NULL;
2783         const char *local_context = S_OR(context, "default");
2784
2785         if (interactive) {
2786                 struct vm_state *vms;
2787                 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2788                 vms = pthread_getspecific(ts_vmstate.key);
2789                 return vms;
2790         }
2791
2792         AST_LIST_LOCK(&vmstates);
2793         AST_LIST_TRAVERSE(&vmstates, vlist, list) {
2794                 if (!vlist->vms) {
2795                         ast_debug(3, "error: vms is NULL for %s\n", mailbox);
2796                         continue;
2797                 }
2798                 if (vlist->vms->imapversion != imapversion) {
2799                         continue;
2800                 }
2801                 if (!vlist->vms->username || !vlist->vms->context) {
2802                         ast_debug(3, "error: username is NULL for %s\n", mailbox);
2803                         continue;
2804                 }
2805
2806                 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);
2807                 
2808                 if (!strcmp(vlist->vms->username, mailbox) && !strcmp(vlist->vms->context, local_context) && vlist->vms->interactive == interactive) {
2809                         ast_debug(3, "Found it!\n");
2810                         AST_LIST_UNLOCK(&vmstates);
2811                         return vlist->vms;
2812                 }
2813         }
2814         AST_LIST_UNLOCK(&vmstates);
2815
2816         ast_debug(3, "%s not found in vmstates\n", mailbox);
2817
2818         return NULL;
2819 }
2820
2821 static void vmstate_insert(struct vm_state *vms) 
2822 {
2823         struct vmstate *v;
2824         struct vm_state *altvms;
2825
2826         /* If interactive, it probably already exists, and we should
2827            use the one we already have since it is more up to date.
2828            We can compare the username to find the duplicate */
2829         if (vms->interactive == 1) {
2830                 altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
2831                 if (altvms) {   
2832                         ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
2833                         vms->newmessages = altvms->newmessages;
2834                         vms->oldmessages = altvms->oldmessages;
2835                         vms->vmArrayIndex = altvms->vmArrayIndex;
2836                         vms->lastmsg = altvms->lastmsg;
2837                         vms->curmsg = altvms->curmsg;
2838                         /* get a pointer to the persistent store */
2839                         vms->persist_vms = altvms;
2840                         /* Reuse the mailstream? */
2841 #ifdef REALLY_FAST_EVEN_IF_IT_MEANS_RESOURCE_LEAKS
2842                         vms->mailstream = altvms->mailstream;
2843 #else
2844                         vms->mailstream = NIL;
2845 #endif
2846                 }
2847                 return;
2848         }
2849
2850         if (!(v = ast_calloc(1, sizeof(*v))))
2851                 return;
2852         
2853         v->vms = vms;
2854
2855         ast_debug(3, "Inserting vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
2856
2857         AST_LIST_LOCK(&vmstates);
2858         AST_LIST_INSERT_TAIL(&vmstates, v, list);
2859         AST_LIST_UNLOCK(&vmstates);
2860 }
2861
2862 static void vmstate_delete(struct vm_state *vms) 
2863 {
2864         struct vmstate *vc = NULL;
2865         struct vm_state *altvms = NULL;
2866
2867         /* If interactive, we should copy pertinent info
2868            back to the persistent state (to make update immediate) */
2869         if (vms->interactive == 1 && (altvms = vms->persist_vms)) {
2870                 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
2871                 altvms->newmessages = vms->newmessages;
2872                 altvms->oldmessages = vms->oldmessages;
2873                 altvms->updated = 1;
2874                 vms->mailstream = mail_close(vms->mailstream);
2875
2876                 /* Interactive states are not stored within the persistent list */
2877                 return;
2878         }
2879         
2880         ast_debug(3, "Removing vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
2881         
2882         AST_LIST_LOCK(&vmstates);
2883         AST_LIST_TRAVERSE_SAFE_BEGIN(&vmstates, vc, list) {
2884                 if (vc->vms == vms) {
2885                         AST_LIST_REMOVE_CURRENT(list);
2886                         break;
2887                 }
2888         }
2889         AST_LIST_TRAVERSE_SAFE_END
2890         AST_LIST_UNLOCK(&vmstates);
2891         
2892         if (vc) {
2893                 ast_mutex_destroy(&vc->vms->lock);
2894                 ast_free(vc);
2895         }
2896         else
2897                 ast_log(AST_LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n", vms->imapuser, vms->username);
2898 }
2899
2900 static void set_update(MAILSTREAM * stream) 
2901 {
2902         struct vm_state *vms;
2903         char *mailbox = stream->mailbox, *user;
2904         char buf[1024] = "";
2905
2906         if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || !(vms = get_vm_state_by_imapuser(user, 0))) {
2907                 if (user && option_debug > 2)
2908                         ast_log(AST_LOG_WARNING, "User %s mailbox not found for update.\n", user);
2909                 return;
2910         }
2911
2912         ast_debug(3, "User %s mailbox set for update.\n", user);
2913
2914         vms->updated = 1; /* Set updated flag since mailbox changed */
2915 }
2916
2917 static void init_vm_state(struct vm_state *vms) 
2918 {
2919         int x;
2920         vms->vmArrayIndex = 0;
2921         for (x = 0; x < VMSTATE_MAX_MSG_ARRAY; x++) {
2922                 vms->msgArray[x] = 0;
2923         }
2924         ast_mutex_init(&vms->lock);
2925 }
2926
2927 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro) 
2928 {
2929         char *body_content;
2930         char *body_decoded;
2931         char *fn = is_intro ? vms->introfn : vms->fn;
2932         unsigned long len;
2933         unsigned long newlen;
2934         char filename[256];
2935         
2936         if (!body || body == NIL)
2937                 return -1;
2938
2939         ast_mutex_lock(&vms->lock);
2940         body_content = mail_fetchbody(vms->mailstream, vms->msgArray[vms->curmsg], section, &len);
2941         ast_mutex_unlock(&vms->lock);
2942         if (body_content != NIL) {
2943                 snprintf(filename, sizeof(filename), "%s.%s", fn, format);
2944                 /* ast_debug(1,body_content); */
2945                 body_decoded = rfc822_base64((unsigned char *) body_content, len, &newlen);
2946                 /* If the body of the file is empty, return an error */
2947                 if (!newlen) {
2948                         return -1;
2949                 }
2950                 write_file(filename, (char *) body_decoded, newlen);
2951         } else {
2952                 ast_debug(5, "Body of message is NULL.\n");
2953                 return -1;
2954         }
2955         return 0;
2956 }
2957
2958 /*! 
2959  * \brief Get delimiter via mm_list callback 
2960  * \param stream
2961  *
2962  * Determines the delimiter character that is used by the underlying IMAP based mail store.
2963  */
2964 /* MUTEX should already be held */
2965 static void get_mailbox_delimiter(MAILSTREAM *stream) {
2966         char tmp[50];
2967         snprintf(tmp, sizeof(tmp), "{%s}", imapserver);
2968         mail_list(stream, tmp, "*");
2969 }
2970
2971 /*! 
2972  * \brief Check Quota for user 
2973  * \param vms a pointer to a vm_state struct, will use the mailstream property of this.
2974  * \param mailbox the mailbox to check the quota for.
2975  *
2976  * Calls imap_getquotaroot, which will populate its results into the vm_state vms input structure.
2977  */
2978 static void check_quota(struct vm_state *vms, char *mailbox) {
2979         ast_mutex_lock(&vms->lock);
2980         mail_parameters(NULL, SET_QUOTA, (void *) mm_parsequota);
2981         ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mailbox);
2982         if (vms && vms->mailstream != NULL) {
2983                 imap_getquotaroot(vms->mailstream, mailbox);
2984         } else {
2985                 ast_log(AST_LOG_WARNING, "Mailstream not available for mailbox: %s\n", mailbox);
2986         }
2987         ast_mutex_unlock(&vms->lock);
2988 }
2989
2990 #endif /* IMAP_STORAGE */
2991
2992 /*! \brief Lock file path
2993     only return failure if ast_lock_path returns 'timeout',
2994    not if the path does not exist or any other reason
2995 */
2996 static int vm_lock_path(const char *path)
2997 {
2998         switch (ast_lock_path(path)) {
2999         case AST_LOCK_TIMEOUT:
3000                 return -1;
3001         default:
3002                 return 0;
3003         }
3004 }
3005
3006
3007 #ifdef ODBC_STORAGE
3008 struct generic_prepare_struct {
3009         char *sql;
3010         int argc;
3011         char **argv;
3012 };
3013
3014 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
3015 {
3016         struct generic_prepare_struct *gps = data;
3017         int res, i;
3018         SQLHSTMT stmt;
3019
3020         res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
3021         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3022                 ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
3023                 return NULL;
3024         }
3025         res = SQLPrepare(stmt, (unsigned char *) gps->sql, SQL_NTS);
3026         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3027                 ast_log(AST_LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
3028                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3029                 return NULL;
3030         }
3031         for (i = 0; i < gps->argc; i++)
3032                 SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
3033
3034         return stmt;
3035 }
3036
3037 /*!
3038  * \brief Retrieves a file from an ODBC data store.
3039  * \param dir the path to the file to be retreived.
3040  * \param msgnum the message number, such as within a mailbox folder.
3041  * 
3042  * This method is used by the RETRIEVE macro when mailboxes are stored in an ODBC back end.
3043  * 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.
3044  *
3045  * The file is looked up by invoking a SQL on the odbc_table (default 'voicemessages') using the dir and msgnum input parameters.
3046  * The output is the message information file with the name msgnum and the extension .txt
3047  * and the message file with the extension of its format, in the directory with base file name of the msgnum.
3048  * 
3049  * \return 0 on success, -1 on error.
3050  */
3051 static int retrieve_file(char *dir, int msgnum)
3052 {
3053         int x = 0;
3054         int res;
3055         int fd = -1;
3056         size_t fdlen = 0;
3057         void *fdm = MAP_FAILED;
3058         SQLSMALLINT colcount = 0;
3059         SQLHSTMT stmt;
3060         char sql[PATH_MAX];
3061         char fmt[80]="";
3062         char *c;
3063         char coltitle[256];
3064         SQLSMALLINT collen;
3065         SQLSMALLINT datatype;
3066         SQLSMALLINT decimaldigits;
3067         SQLSMALLINT nullable;
3068         SQLULEN colsize;
3069         SQLLEN colsize2;
3070         FILE *f = NULL;
3071         char rowdata[80];
3072         char fn[PATH_MAX];
3073         char full_fn[PATH_MAX];
3074         char msgnums[80];
3075         char *argv[] = { dir, msgnums };
3076         struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
3077
3078         struct odbc_obj *obj;
3079         obj = ast_odbc_request_obj(odbc_database, 0);
3080         if (obj) {
3081                 ast_copy_string(fmt, vmfmts, sizeof(fmt));
3082                 c = strchr(fmt, '|');
3083                 if (c)
3084                         *c = '\0';
3085                 if (!strcasecmp(fmt, "wav49"))
3086                         strcpy(fmt, "WAV");
3087                 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
3088                 if (msgnum > -1)
3089                         make_file(fn, sizeof(fn), dir, msgnum);
3090                 else
3091                         ast_copy_string(fn, dir, sizeof(fn));
3092
3093                 /* Create the information file */
3094                 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
3095                 
3096                 if (!(f = fopen(full_fn, "w+"))) {
3097                         ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
3098                         goto yuck;
3099                 }
3100                 
3101                 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
3102                 snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?", odbc_table);
3103                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3104                 if (!stmt) {
3105                         ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3106                         ast_odbc_release_obj(obj);
3107                         goto yuck;
3108                 }
3109                 res = SQLFetch(stmt);
3110                 if (res == SQL_NO_DATA) {
3111                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3112                         ast_odbc_release_obj(obj);
3113                         goto yuck;
3114                 } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3115                         ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3116                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3117                         ast_odbc_release_obj(obj);
3118                         goto yuck;
3119                 }
3120                 fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
3121                 if (fd < 0) {
3122                         ast_log(AST_LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
3123                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3124                         ast_odbc_release_obj(obj);
3125                         goto yuck;
3126                 }
3127                 res = SQLNumResultCols(stmt, &colcount);
3128                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {   
3129                         ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
3130                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3131                         ast_odbc_release_obj(obj);
3132                         goto yuck;
3133                 }
3134                 if (f) 
3135                         fprintf(f, "[message]\n");
3136                 for (x = 0; x < colcount; x++) {
3137                         rowdata[0] = '\0';
3138                         collen = sizeof(coltitle);
3139                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *) coltitle, sizeof(coltitle), &collen, 
3140                                                 &datatype, &colsize, &decimaldigits, &nullable);
3141                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3142                                 ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
3143                                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3144                                 ast_odbc_release_obj(obj);
3145                                 goto yuck;
3146                         }
3147                         if (!strcasecmp(coltitle, "recording")) {
3148                                 off_t offset;
3149                                 res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
3150                                 fdlen = colsize2;
3151                                 if (fd > -1) {
3152                                         char tmp[1]="";
3153                                         lseek(fd, fdlen - 1, SEEK_SET);
3154                                         if (write(fd, tmp, 1) != 1) {
3155                                                 close(fd);
3156                                                 fd = -1;
3157                                                 continue;
3158                                         }
3159                                         /* Read out in small chunks */
3160                                         for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
3161                                                 if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
3162                                                         ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
3163                                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3164                                                         ast_odbc_release_obj(obj);
3165                                                         goto yuck;
3166                                                 } else {
3167                                                         res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
3168                                                         munmap(fdm, CHUNKSIZE);
3169                                                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3170                                                                 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
3171                                                                 unlink(full_fn);
3172                                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3173                                                                 ast_odbc_release_obj(obj);
3174                                                                 goto yuck;
3175                                                         }
3176                                                 }
3177                                         }
3178                                         if (truncate(full_fn, fdlen) < 0) {
3179                                                 ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
3180                                         }
3181                                 }
3182                         } else {
3183                                 res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3184                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3185                                         ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
3186                                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3187                                         ast_odbc_release_obj(obj);
3188                                         goto yuck;
3189                                 }
3190                                 if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
3191                                         fprintf(f, "%s=%s\n", coltitle, rowdata);
3192                         }
3193                 }
3194                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3195                 ast_odbc_release_obj(obj);
3196         } else
3197                 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3198 yuck:   
3199         if (f)
3200                 fclose(f);
3201         if (fd > -1)
3202                 close(fd);
3203         return x - 1;
3204 }
3205
3206 /*!
3207  * \brief Determines the highest message number in use for a given user and mailbox folder.
3208  * \param vmu 
3209  * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
3210  *
3211  * This method is used when mailboxes are stored in an ODBC back end.
3212  * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
3213  *
3214  * \return the value of zero or greaterto indicate the last message index in use, -1 to indicate none.
3215  */
3216 static int last_message_index(struct ast_vm_user *vmu, char *dir)
3217 {
3218         int x = 0;
3219         int res;
3220         SQLHSTMT stmt;
3221         char sql[PATH_MAX];
3222         char rowdata[20];
3223         char *argv[] = { dir };
3224         struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
3225
3226         struct odbc_obj *obj;
3227         obj = ast_odbc_request_obj(odbc_database, 0);
3228         if (obj) {
3229                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?", odbc_table);
3230                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3231                 if (!stmt) {
3232                         ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3233                         ast_odbc_release_obj(obj);
3234                         goto yuck;
3235                 }
3236                 res = SQLFetch(stmt);
3237                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3238                         ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3239                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3240                         ast_odbc_release_obj(obj);
3241                         goto yuck;
3242                 }
3243                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3244                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3245                         ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
3246                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3247                         ast_odbc_release_obj(obj);
3248                         goto yuck;
3249                 }
3250                 if (sscanf(rowdata, "%30d", &x) != 1)
3251                         ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
3252                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3253                 ast_odbc_release_obj(obj);
3254         } else
3255                 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3256 yuck:   
3257         return x - 1;
3258 }
3259
3260 /*!
3261  * \brief Determines if the specified message exists.
3262  * \param dir the folder the mailbox folder to look for messages. 
3263  * \param msgnum the message index to query for.
3264  *
3265  * This method is used when mailboxes are stored in an ODBC back end.
3266  *
3267  * \return greater than zero if the message exists, zero when the message does not exist or on error.
3268  */
3269 static int message_exists(char *dir, int msgnum)
3270 {
3271         int x = 0;
3272         int res;
3273         SQLHSTMT stmt;
3274         char sql[PATH_MAX];
3275         char rowdata[20];
3276         char msgnums[20];
3277         char *argv[] = { dir, msgnums };
3278         struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
3279
3280         struct odbc_obj *obj;
3281         obj = ast_odbc_request_obj(odbc_database, 0);
3282         if (obj) {
3283                 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
3284                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?", odbc_table);
3285                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3286                 if (!stmt) {
3287                         ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3288                         ast_odbc_release_obj(obj);
3289                         goto yuck;
3290                 }
3291                 res = SQLFetch(stmt);
3292                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3293                         ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3294                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3295                         ast_odbc_release_obj(obj);
3296                         goto yuck;
3297                 }
3298                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3299                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3300                         ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
3301                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3302                         ast_odbc_release_obj(obj);
3303                         goto yuck;
3304                 }
3305                 if (sscanf(rowdata, "%30d", &x) != 1)
3306                         ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
3307                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3308                 ast_odbc_release_obj(obj);
3309         } else
3310                 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3311 yuck:   
3312         return x;
3313 }
3314
3315 /*!
3316  * \brief returns the one-based count for messages.
3317  * \param vmu
3318  * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
3319  *
3320  * This method is used when mailboxes are stored in an ODBC back end.
3321  * The message index is zero-based, the first message will be index 0. For convenient display it is good to have the
3322  * one-based messages.
3323  * This method just calls last_message_index and returns +1 of its value.
3324  *
3325  * \return the value greater than zero on success to indicate the one-based count of messages, less than zero on error.
3326  */
3327 static int count_messages(struct ast_vm_user *vmu, char *dir)
3328 {
3329         return last_message_index(vmu, dir) + 1;
3330 }
3331
3332 /*!
3333  * \brief Deletes a message from the mailbox folder.
3334  * \param sdir The mailbox folder to work in.
3335  * \param smsg The message index to be deleted.
3336  *
3337  * This method is used when mailboxes are stored in an ODBC back end.
3338  * The specified message is directly deleted from the database 'voicemessages' table.
3339  * 
3340  * \return the value greater than zero on success to indicate the number of messages, less than zero on error.
3341  */
3342 static void delete_file(char *sdir, int smsg)
3343 {
3344         SQLHSTMT stmt;
3345         char sql[PATH_MAX];
3346         char msgnums[20];
3347         char *argv[] = { sdir, msgnums };
3348         struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
3349
3350         struct odbc_obj *obj;
3351         obj = ast_odbc_request_obj(odbc_database, 0);
3352         if (obj) {
3353                 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
3354                 snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?", odbc_table);
3355                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3356                 if (!stmt)
3357                         ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3358                 else
3359                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3360                 ast_odbc_release_obj(obj);
3361         } else
3362                 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3363         return; 
3364 }
3365
3366 /*!
3367  * \brief Copies a voicemail from one mailbox to another.
3368  * \param sdir the folder for which to look for the message to be copied.
3369  * \param smsg the index of the message to be copied.
3370  * \param ddir the destination folder to copy the message into.
3371  * \param dmsg the index to be used for the copied message.
3372  * \param dmailboxuser The user who owns the mailbox tha contains the destination folder.
3373  * \param dmailboxcontext The context for the destination user.
3374  *
3375  * This method is used for the COPY macro when mailboxes are stored in an ODBC back end.
3376  */
3377 static void copy_file(char *sdir, int smsg, char *ddir, int dmsg, char *dmailboxuser, char *dmailboxcontext)
3378 {
3379         SQLHSTMT stmt;
3380         char sql[512];
3381         char msgnums[20];
3382         char msgnumd[20];
3383         struct odbc_obj *obj;
3384         char *argv[] = { ddir, msgnumd, dmailboxuser, dmailboxcontext, sdir, msgnums };
3385         struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
3386
3387         delete_file(ddir, dmsg);
3388         obj = ast_odbc_request_obj(odbc_database, 0);
3389         if (obj) {
3390                 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
3391                 snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
3392                 snprintf(sql, sizeof(sql), "INSERT INTO %s (dir, msgnum, context, macrocontext, callerid, origtime, duration, recording, flag, mailboxuser, mailboxcontext) SELECT ?,?,context,macrocontext,callerid,origtime,duration,recording,flag,?,? FROM %s WHERE dir=? AND msgnum=?", odbc_table, odbc_table);
3393                 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3394                 if (!stmt)
3395                         ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
3396                 else
3397                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3398                 ast_odbc_release_obj(obj);
3399         } else
3400                 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3401         return; 
3402 }
3403
3404 struct insert_data {
3405         char *sql;
3406         char *dir;
3407         char *msgnums;
3408         void *data;
3409         SQLLEN datalen;
3410         SQLLEN indlen;
3411         const char *context;
3412         const char *macrocontext;
3413         const char *callerid;
3414         const char *origtime;
3415         const char *duration;
3416         char *mailboxuser;
3417         char *mailboxcontext;
3418         const char *category;
3419         const char *flag;
3420 };
3421
3422 static SQLHSTMT insert_data_cb(struct odbc_obj *obj, void *vdata)
3423 {
3424         struct insert_data *data = vdata;
3425         int res;
3426         SQLHSTMT stmt;
3427
3428         res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
3429         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3430                 ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
3431                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3432                 return NULL;
3433         }
3434
3435         SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->dir), 0, (void *) data->dir, 0, NULL);
3436         SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->msgnums), 0, (void *) data->msgnums, 0, NULL);
3437         SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, data->datalen, 0, (void *) data->data, data->datalen, &data->indlen);
3438         SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->context), 0, (void *) data->context, 0, NULL);
3439         SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->macrocontext), 0, (void *) data->macrocontext, 0, NULL);
3440         SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->callerid), 0, (void *) data->callerid, 0, NULL);
3441         SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->origtime), 0, (void *) data->origtime, 0, NULL);
3442         SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->duration), 0, (void *) data->duration, 0, NULL);
3443         SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxuser), 0, (void *) data->mailboxuser, 0, NULL);
3444         SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxcontext), 0, (void *) data->mailboxcontext, 0, NULL);
3445         SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->flag), 0, (void *) data->flag, 0, NULL);
3446         if (!ast_strlen_zero(data->category)) {
3447                 SQLBindParameter(stmt, 12, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->category), 0, (void *) data->category, 0, NULL);
3448         }
3449         res = SQLExecDirect(stmt, (unsigned char *) data->sql, SQL_NTS);
3450         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3451                 ast_log(AST_LOG_WARNING, "SQL Direct Execute failed!\n");
3452                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3453                 return NULL;
3454         }
3455
3456         return stmt;
3457 }
3458
3459 /*!
3460  * \brief Stores a voicemail into the database.
3461  * \param dir the folder the mailbox folder to store the message.
3462  * \param mailboxuser the user owning the mailbox folder.
3463  * \param mailboxcontext
3464  * \param msgnum the message index for the message to be stored.
3465  *
3466  * This method is used when mailboxes are stored in an ODBC back end.
3467  * The message sound file and information file is looked up on the file system. 
3468  * A SQL query is invoked to store the message into the (MySQL) database.
3469  *
3470  * \return the zero on success -1 on error.
3471  */
3472 static int store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum)
3473 {
3474         int res = 0;
3475         int fd = -1;
3476         void *fdm = MAP_FAILED;
3477         size_t fdlen = -1;
3478         SQLHSTMT stmt;
3479         char sql[PATH_MAX];
3480         char msgnums[20];
3481         char fn[PATH_MAX];
3482         char full_fn[PATH_MAX];
3483         char fmt[80]="";
3484         char *c;
3485         struct ast_config *cfg = NULL;
3486         struct odbc_obj *obj;
3487         struct insert_data idata = { .sql = sql, .msgnums = msgnums, .dir = dir, .mailboxuser = mailboxuser, .mailboxcontext = mailboxcontext,
3488                 .context = "", .macrocontext = "", .callerid = "", .origtime = "", .duration = "", .category = "", .flag = "" };
3489         struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
3490
3491         delete_file(dir, msgnum);
3492         if (!(obj = ast_odbc_request_obj(odbc_database, 0))) {
3493                 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3494                 return -1;
3495         }
3496
3497         do {
3498                 ast_copy_string(fmt, vmfmts, sizeof(fmt));
3499                 c = strchr(fmt, '|');
3500                 if (c)
3501                         *c = '\0';
3502                 if (!strcasecmp(fmt, "wav49"))
3503                         strcpy(fmt, "WAV");
3504                 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
3505                 if (msgnum > -1)
3506                         make_file(fn, sizeof(fn), dir, msgnum);
3507                 else
3508                         ast_copy_string(fn, dir, sizeof(fn));
3509                 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
3510                 cfg = ast_config_load(full_fn, config_flags);
3511                 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
3512                 fd = open(full_fn, O_RDWR);
3513                 if (fd < 0) {
3514                         ast_log(AST_LOG_WARNING, "Open of sound file '%s' failed: %s\n", full_fn, strerror(errno));
3515                         res = -1;
3516                         break;
3517                 }
3518                 if (cfg && cfg != CONFIG_STATUS_FILEINVALID) {
3519                         if (!(idata.context = ast_variable_retrieve(cfg, "message", "context"))) {
3520                                 idata.context = "";
3521                         }
3522                         if (!(idata.macrocontext = ast_variable_retrieve(cfg, "message", "macrocontext"))) {
3523                                 idata.macrocontext = "";
3524                         }
3525                         if (!(idata.callerid = ast_variable_retrieve(cfg, "message", "callerid"))) {
3526                                 idata.callerid = "";
3527                         }
3528                         if (!(idata.origtime = ast_variable_retrieve(cfg, "message", "origtime"))) {
3529                                 idata.origtime = "";
3530                         }
3531                         if (!(idata.duration = ast_variable_retrieve(cfg, "message", "duration"))) {
3532                                 idata.duration = "";
3533                         }
3534                         if (!(idata.category = ast_variable_retrieve(cfg, "message", "category"))) {
3535                                 idata.category = "";
3536                         }
3537                         if (!(idata.flag = ast_variable_retrieve(cfg, "message", "flag"))) {
3538                                 idata.flag = "";
3539                         }
3540                 }
3541                 fdlen = lseek(fd, 0, SEEK_END);
3542                 lseek(fd, 0, SEEK_SET);
3543                 printf("Length is %zd\n", fdlen);
3544                 fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
3545                 if (fdm == MAP_FAILED) {
3546                         ast_log(AST_LOG_WARNING, "Memory map failed!\n");
3547                         res = -1;
3548                         break;
3549                 } 
3550                 idata.data = fdm;
3551                 idata.datalen = idata.indlen = fdlen;
3552
3553                 if (!ast_strlen_zero(idata.category)) 
3554                         snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag,category) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", odbc_table); 
3555                 else
3556                         snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag) VALUES (?,?,?,?,?,?,?,?,?,?,?)", odbc_table);
3557
3558                 if ((stmt = ast_odbc_direct_execute(obj, insert_data_cb, &idata))) {
3559                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3560                 } else {
3561                         ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3562                         res = -1;
3563                 }
3564