Sat Mar 26 11:06:37 2011

Asterisk developer's documentation


app_voicemail.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*!
00020  * \file
00021  * \author Mark Spencer <markster@digium.com>
00022  * \brief Comedian Mail - Voicemail System
00023  *
00024  * \extref unixODBC (http://www.unixodbc.org/)
00025  * \extref A source distribution of University of Washington's IMAP c-client
00026  *         (http://www.washington.edu/imap/)
00027  *
00028  * \par See also
00029  * \arg \ref Config_vm
00030  * \note For information about voicemail IMAP storage, read doc/imapstorage.txt
00031  * \ingroup applications
00032  * \note This module requires res_adsi to load. This needs to be optional
00033  * during compilation.
00034  *
00035  * \note This file is now almost impossible to work with, due to all \#ifdefs.
00036  *       Feels like the database code before realtime. Someone - please come up
00037  *       with a plan to clean this up.
00038  */
00039 
00040 /*** MODULEINFO
00041    <use>res_adsi</use>
00042    <use>res_smdi</use>
00043  ***/
00044 
00045 /*** MAKEOPTS
00046 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" touch_on_change="apps/app_voicemail.c apps/app_directory.c">
00047    <member name="FILE_STORAGE" displayname="Storage of Voicemail using filesystem">
00048       <conflict>ODBC_STORAGE</conflict>
00049       <conflict>IMAP_STORAGE</conflict>
00050       <defaultenabled>yes</defaultenabled>
00051    </member>
00052    <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
00053       <depend>generic_odbc</depend>
00054       <depend>ltdl</depend>
00055       <conflict>IMAP_STORAGE</conflict>
00056       <conflict>FILE_STORAGE</conflict>
00057       <defaultenabled>no</defaultenabled>
00058    </member>
00059    <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
00060       <depend>imap_tk</depend>
00061       <conflict>ODBC_STORAGE</conflict>
00062       <conflict>FILE_STORAGE</conflict>
00063       <use>openssl</use>
00064       <defaultenabled>no</defaultenabled>
00065    </member>
00066 </category>
00067 ***/
00068 
00069 #include "asterisk.h"
00070 
00071 #ifdef IMAP_STORAGE
00072 #include <ctype.h>
00073 #include <signal.h>
00074 #include <pwd.h>
00075 #ifdef USE_SYSTEM_IMAP
00076 #include <imap/c-client.h>
00077 #include <imap/imap4r1.h>
00078 #include <imap/linkage.h>
00079 #elif defined (USE_SYSTEM_CCLIENT)
00080 #include <c-client/c-client.h>
00081 #include <c-client/imap4r1.h>
00082 #include <c-client/linkage.h>
00083 #else
00084 #include "c-client.h"
00085 #include "imap4r1.h"
00086 #include "linkage.h"
00087 #endif
00088 #endif
00089 
00090 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 292227 $")
00091 
00092 #include "asterisk/paths.h"   /* use ast_config_AST_SPOOL_DIR */
00093 #include <sys/time.h>
00094 #include <sys/stat.h>
00095 #include <sys/mman.h>
00096 #include <time.h>
00097 #include <dirent.h>
00098 #if defined(__FreeBSD__) || defined(__OpenBSD__)
00099 #include <sys/wait.h>
00100 #endif
00101 
00102 #include "asterisk/logger.h"
00103 #include "asterisk/lock.h"
00104 #include "asterisk/file.h"
00105 #include "asterisk/channel.h"
00106 #include "asterisk/pbx.h"
00107 #include "asterisk/config.h"
00108 #include "asterisk/say.h"
00109 #include "asterisk/module.h"
00110 #include "asterisk/adsi.h"
00111 #include "asterisk/app.h"
00112 #include "asterisk/manager.h"
00113 #include "asterisk/dsp.h"
00114 #include "asterisk/localtime.h"
00115 #include "asterisk/cli.h"
00116 #include "asterisk/utils.h"
00117 #include "asterisk/stringfields.h"
00118 #include "asterisk/smdi.h"
00119 #include "asterisk/astobj2.h"
00120 #include "asterisk/event.h"
00121 #include "asterisk/taskprocessor.h"
00122 #include "asterisk/test.h"
00123 
00124 #ifdef ODBC_STORAGE
00125 #include "asterisk/res_odbc.h"
00126 #endif
00127 
00128 #ifdef IMAP_STORAGE
00129 #include "asterisk/threadstorage.h"
00130 #endif
00131 
00132 /*** DOCUMENTATION
00133    <application name="VoiceMail" language="en_US">
00134       <synopsis>
00135          Leave a Voicemail message.
00136       </synopsis>
00137       <syntax>
00138          <parameter name="mailboxs" argsep="&amp;" required="true">
00139             <argument name="mailbox1" argsep="@" required="true">
00140                <argument name="mailbox" required="true" />
00141                <argument name="context" />
00142             </argument>
00143             <argument name="mailbox2" argsep="@" multiple="true">
00144                <argument name="mailbox" required="true" />
00145                <argument name="context" />
00146             </argument>
00147          </parameter>
00148          <parameter name="options">
00149             <optionlist>
00150                <option name="b">
00151                   <para>Play the <literal>busy</literal> greeting to the calling party.</para>
00152                </option>
00153                <option name="d">
00154                   <argument name="c" />
00155                   <para>Accept digits for a new extension in context <replaceable>c</replaceable>,
00156                   if played during the greeting. Context defaults to the current context.</para>
00157                </option>
00158                <option name="g">
00159                   <argument name="#" required="true" />
00160                   <para>Use the specified amount of gain when recording the voicemail
00161                   message. The units are whole-number decibels (dB). Only works on supported
00162                   technologies, which is DAHDI only.</para>
00163                </option>
00164                <option name="s">
00165                   <para>Skip the playback of instructions for leaving a message to the
00166                   calling party.</para>
00167                </option>
00168                <option name="u">
00169                   <para>Play the <literal>unavailable</literal> greeting.</para>
00170                </option>
00171                <option name="U">
00172                   <para>Mark message as <literal>URGENT</literal>.</para>
00173                </option>
00174                <option name="P">
00175                   <para>Mark message as <literal>PRIORITY</literal>.</para>
00176                </option>
00177             </optionlist>
00178          </parameter>
00179       </syntax>
00180       <description>
00181          <para>This application allows the calling party to leave a message for the specified
00182          list of mailboxes. When multiple mailboxes are specified, the greeting will be taken from
00183          the first mailbox specified. Dialplan execution will stop if the specified mailbox does not
00184          exist.</para>
00185          <para>The Voicemail application will exit if any of the following DTMF digits are received:</para>
00186          <enumlist>
00187             <enum name="0">
00188                <para>Jump to the <literal>o</literal> extension in the current dialplan context.</para>
00189             </enum>
00190             <enum name="*">
00191                <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
00192             </enum>
00193          </enumlist>
00194          <para>This application will set the following channel variable upon completion:</para>
00195          <variablelist>
00196             <variable name="VMSTATUS">
00197                <para>This indicates the status of the execution of the VoiceMail application.</para>
00198                <value name="SUCCESS" />
00199                <value name="USEREXIT" />
00200                <value name="FAILED" />
00201             </variable>
00202          </variablelist>
00203       </description>
00204    </application>
00205    <application name="VoiceMailMain" language="en_US">
00206       <synopsis>
00207          Check Voicemail messages.
00208       </synopsis>
00209       <syntax>
00210          <parameter name="mailbox" required="true" argsep="@">
00211             <argument name="mailbox" />
00212             <argument name="context" />
00213          </parameter>
00214          <parameter name="options">
00215             <optionlist>
00216                <option name="p">
00217                   <para>Consider the <replaceable>mailbox</replaceable> parameter as a prefix to
00218                   the mailbox that is entered by the caller.</para>
00219                </option>
00220                <option name="g">
00221                   <argument name="#" required="true" />
00222                   <para>Use the specified amount of gain when recording a voicemail message.
00223                   The units are whole-number decibels (dB).</para>
00224                </option>
00225                <option name="s">
00226                   <para>Skip checking the passcode for the mailbox.</para>
00227                </option>
00228                <option name="a">
00229                   <argument name="folder" required="true" />
00230                   <para>Skip folder prompt and go directly to <replaceable>folder</replaceable> specified.
00231                   Defaults to <literal>INBOX</literal> (or <literal>0</literal>).</para>
00232                   <enumlist>
00233                      <enum name="0"><para>INBOX</para></enum>
00234                      <enum name="1"><para>Old</para></enum>
00235                      <enum name="2"><para>Work</para></enum>
00236                      <enum name="3"><para>Family</para></enum>
00237                      <enum name="4"><para>Friends</para></enum>
00238                      <enum name="5"><para>Cust1</para></enum>
00239                      <enum name="6"><para>Cust2</para></enum>
00240                      <enum name="7"><para>Cust3</para></enum>
00241                      <enum name="8"><para>Cust4</para></enum>
00242                      <enum name="9"><para>Cust5</para></enum>
00243                   </enumlist>
00244                </option>
00245             </optionlist>
00246          </parameter>
00247       </syntax>
00248       <description>
00249          <para>This application allows the calling party to check voicemail messages. A specific
00250          <replaceable>mailbox</replaceable>, and optional corresponding <replaceable>context</replaceable>,
00251          may be specified. If a <replaceable>mailbox</replaceable> is not provided, the calling party will
00252          be prompted to enter one. If a <replaceable>context</replaceable> is not specified, the
00253          <literal>default</literal> context will be used.</para>
00254          <para>The VoiceMailMain application will exit if the following DTMF digit is entered as Mailbox
00255          or Password, and the extension exists:</para>
00256          <enumlist>
00257             <enum name="*">
00258                <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
00259             </enum>
00260          </enumlist>
00261       </description>
00262    </application>
00263    <application name="MailboxExists" language="en_US">
00264       <synopsis>
00265          Check to see if Voicemail mailbox exists.
00266       </synopsis>
00267       <syntax>
00268          <parameter name="mailbox" required="true" argsep="@">
00269             <argument name="mailbox" required="true" />
00270             <argument name="context" />
00271          </parameter>
00272          <parameter name="options">
00273             <para>None options.</para>
00274          </parameter>
00275       </syntax>
00276       <description>
00277          <para>Check to see if the specified <replaceable>mailbox</replaceable> exists. If no voicemail
00278          <replaceable>context</replaceable> is specified, the <literal>default</literal> context
00279          will be used.</para>
00280          <para>This application will set the following channel variable upon completion:</para>
00281          <variablelist>
00282             <variable name="VMBOXEXISTSSTATUS">
00283                <para>This will contain the status of the execution of the MailboxExists application.
00284                Possible values include:</para>
00285                <value name="SUCCESS" />
00286                <value name="FAILED" />
00287             </variable>
00288          </variablelist>
00289       </description>
00290    </application>
00291    <application name="VMAuthenticate" language="en_US">
00292       <synopsis>
00293          Authenticate with Voicemail passwords.
00294       </synopsis>
00295       <syntax>
00296          <parameter name="mailbox" required="true" argsep="@">
00297             <argument name="mailbox" />
00298             <argument name="context" />
00299          </parameter>
00300          <parameter name="options">
00301             <optionlist>
00302                <option name="s">
00303                   <para>Skip playing the initial prompts.</para>
00304                </option>
00305             </optionlist>
00306          </parameter>
00307       </syntax>
00308       <description>
00309          <para>This application behaves the same way as the Authenticate application, but the passwords
00310          are taken from <filename>voicemail.conf</filename>. If the <replaceable>mailbox</replaceable> is
00311          specified, only that mailbox's password will be considered valid. If the <replaceable>mailbox</replaceable>
00312          is not specified, the channel variable <variable>AUTH_MAILBOX</variable> will be set with the authenticated
00313          mailbox.</para>
00314          <para>The VMAuthenticate application will exit if the following DTMF digit is entered as Mailbox
00315          or Password, and the extension exists:</para>
00316          <enumlist>
00317             <enum name="*">
00318                <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
00319             </enum>
00320          </enumlist>
00321       </description>
00322    </application>
00323    <application name="VMSayName" language="en_US">
00324       <synopsis>
00325          Play the name of a voicemail user
00326       </synopsis>
00327       <syntax>
00328          <parameter name="mailbox" required="true" argsep="@">
00329             <argument name="mailbox" />
00330             <argument name="context" />
00331          </parameter>
00332       </syntax>
00333       <description>
00334          <para>This application will say the recorded name of the voicemail user specified as the
00335          argument to this application. If no context is provided, <literal>default</literal> is assumed.</para>
00336       </description>
00337    </application>
00338    <function name="MAILBOX_EXISTS" language="en_US">
00339       <synopsis>
00340          Tell if a mailbox is configured.
00341       </synopsis>
00342       <syntax argsep="@">
00343          <parameter name="mailbox" required="true" />
00344          <parameter name="context" />
00345       </syntax>
00346       <description>
00347          <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.
00348          If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
00349          context.</para>
00350       </description>
00351    </function>
00352    <manager name="VoicemailUsersList" language="en_US">
00353       <synopsis>
00354          List All Voicemail User Information.
00355       </synopsis>
00356       <syntax>
00357          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00358       </syntax>
00359       <description>
00360       </description>
00361    </manager>
00362  ***/
00363 
00364 #ifdef IMAP_STORAGE
00365 static char imapserver[48];
00366 static char imapport[8];
00367 static char imapflags[128];
00368 static char imapfolder[64];
00369 static char imapparentfolder[64] = "\0";
00370 static char greetingfolder[64];
00371 static char authuser[32];
00372 static char authpassword[42];
00373 static int imapversion = 1;
00374 
00375 static int expungeonhangup = 1;
00376 static int imapgreetings = 0;
00377 static char delimiter = '\0';
00378 
00379 struct vm_state;
00380 struct ast_vm_user;
00381 
00382 AST_THREADSTORAGE(ts_vmstate);
00383 
00384 /* Forward declarations for IMAP */
00385 static int init_mailstream(struct vm_state *vms, int box);
00386 static void write_file(char *filename, char *buffer, unsigned long len);
00387 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
00388 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu);
00389 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
00390 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive);
00391 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
00392 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
00393 static void vmstate_insert(struct vm_state *vms);
00394 static void vmstate_delete(struct vm_state *vms);
00395 static void set_update(MAILSTREAM * stream);
00396 static void init_vm_state(struct vm_state *vms);
00397 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
00398 static void get_mailbox_delimiter(MAILSTREAM *stream);
00399 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
00400 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
00401 static int imap_store_file(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms, const char *flag);
00402 static void update_messages_by_imapuser(const char *user, unsigned long number);
00403 static int vm_delete(char *file);
00404 
00405 static int imap_remove_file (char *dir, int msgnum);
00406 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
00407 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
00408 static void check_quota(struct vm_state *vms, char *mailbox);
00409 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
00410 struct vmstate {
00411    struct vm_state *vms;
00412    AST_LIST_ENTRY(vmstate) list;
00413 };
00414 
00415 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
00416 
00417 #endif
00418 
00419 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
00420 
00421 #define COMMAND_TIMEOUT 5000
00422 /* Don't modify these here; set your umask at runtime instead */
00423 #define  VOICEMAIL_DIR_MODE   0777
00424 #define  VOICEMAIL_FILE_MODE  0666
00425 #define  CHUNKSIZE   65536
00426 
00427 #define VOICEMAIL_CONFIG "voicemail.conf"
00428 #define ASTERISK_USERNAME "asterisk"
00429 
00430 /* Define fast-forward, pause, restart, and reverse keys
00431    while listening to a voicemail message - these are
00432    strings, not characters */
00433 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
00434 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
00435 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
00436 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
00437 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
00438 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
00439 
00440 /* Default mail command to mail voicemail. Change it with the
00441     mailcmd= command in voicemail.conf */
00442 #define SENDMAIL "/usr/sbin/sendmail -t"
00443 
00444 #define INTRO "vm-intro"
00445 
00446 #define MAXMSG 100
00447 #define MAXMSGLIMIT 9999
00448 
00449 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
00450 
00451 #define BASELINELEN 72
00452 #define BASEMAXINLINE 256
00453 #ifdef IMAP_STORAGE
00454 #define ENDL "\r\n"
00455 #else
00456 #define ENDL "\n"
00457 #endif
00458 
00459 #define MAX_DATETIME_FORMAT   512
00460 #define MAX_NUM_CID_CONTEXTS 10
00461 
00462 #define VM_REVIEW        (1 << 0)   /*!< After recording, permit the caller to review the recording before saving */
00463 #define VM_OPERATOR      (1 << 1)   /*!< Allow 0 to be pressed to go to 'o' extension */
00464 #define VM_SAYCID        (1 << 2)   /*!< Repeat the CallerID info during envelope playback */
00465 #define VM_SVMAIL        (1 << 3)   /*!< Allow the user to compose a new VM from within VoicemailMain */
00466 #define VM_ENVELOPE      (1 << 4)   /*!< Play the envelope information (who-from, time received, etc.) */
00467 #define VM_SAYDURATION   (1 << 5)   /*!< Play the length of the message during envelope playback */
00468 #define VM_SKIPAFTERCMD  (1 << 6)   /*!< After deletion, assume caller wants to go to the next message */
00469 #define VM_FORCENAME     (1 << 7)   /*!< Have new users record their name */
00470 #define VM_FORCEGREET    (1 << 8)   /*!< Have new users record their greetings */
00471 #define VM_PBXSKIP       (1 << 9)   /*!< Skip the [PBX] preamble in the Subject line of emails */
00472 #define VM_DIRECFORWARD  (1 << 10)  /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
00473 #define VM_ATTACH        (1 << 11)  /*!< Attach message to voicemail notifications? */
00474 #define VM_DELETE        (1 << 12)  /*!< Delete message after sending notification */
00475 #define VM_ALLOCED       (1 << 13)  /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
00476 #define VM_SEARCH        (1 << 14)  /*!< Search all contexts for a matching mailbox */
00477 #define VM_TEMPGREETWARN (1 << 15)  /*!< Remind user tempgreeting is set */
00478 #define VM_MOVEHEARD     (1 << 16)  /*!< Move a "heard" message to Old after listening to it */
00479 #define VM_MESSAGEWRAP   (1 << 17)  /*!< Wrap around from the last message to the first, and vice-versa */
00480 #define VM_FWDURGAUTO    (1 << 18)  /*!< Autoset of Urgent flag on forwarded Urgent messages set globally */
00481 #define ERROR_LOCK_PATH  -100
00482 #define OPERATOR_EXIT     300
00483 
00484 
00485 enum vm_box {
00486    NEW_FOLDER,
00487    OLD_FOLDER,
00488    WORK_FOLDER,
00489    FAMILY_FOLDER,
00490    FRIENDS_FOLDER,
00491    GREETINGS_FOLDER
00492 };
00493 
00494 enum vm_option_flags {
00495    OPT_SILENT =           (1 << 0),
00496    OPT_BUSY_GREETING =    (1 << 1),
00497    OPT_UNAVAIL_GREETING = (1 << 2),
00498    OPT_RECORDGAIN =       (1 << 3),
00499    OPT_PREPEND_MAILBOX =  (1 << 4),
00500    OPT_AUTOPLAY =         (1 << 6),
00501    OPT_DTMFEXIT =         (1 << 7),
00502    OPT_MESSAGE_Urgent =   (1 << 8),
00503    OPT_MESSAGE_PRIORITY = (1 << 9)
00504 };
00505 
00506 enum vm_option_args {
00507    OPT_ARG_RECORDGAIN = 0,
00508    OPT_ARG_PLAYFOLDER = 1,
00509    OPT_ARG_DTMFEXIT   = 2,
00510    /* This *must* be the last value in this enum! */
00511    OPT_ARG_ARRAY_SIZE = 3,
00512 };
00513 
00514 enum vm_passwordlocation {
00515    OPT_PWLOC_VOICEMAILCONF = 0,
00516    OPT_PWLOC_SPOOLDIR      = 1,
00517    OPT_PWLOC_USERSCONF     = 2,
00518 };
00519 
00520 AST_APP_OPTIONS(vm_app_options, {
00521    AST_APP_OPTION('s', OPT_SILENT),
00522    AST_APP_OPTION('b', OPT_BUSY_GREETING),
00523    AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
00524    AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
00525    AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
00526    AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
00527    AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
00528    AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
00529    AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY)
00530 });
00531 
00532 static int load_config(int reload);
00533 
00534 /*! \page vmlang Voicemail Language Syntaxes Supported
00535 
00536    \par Syntaxes supported, not really language codes.
00537    \arg \b en    - English
00538    \arg \b de    - German
00539    \arg \b es    - Spanish
00540    \arg \b fr    - French
00541    \arg \b it    - Italian
00542    \arg \b nl    - Dutch
00543    \arg \b pt    - Portuguese
00544    \arg \b pt_BR - Portuguese (Brazil)
00545    \arg \b gr    - Greek
00546    \arg \b no    - Norwegian
00547    \arg \b se    - Swedish
00548    \arg \b tw    - Chinese (Taiwan)
00549    \arg \b ua - Ukrainian
00550 
00551 German requires the following additional soundfile:
00552 \arg \b 1F  einE (feminine)
00553 
00554 Spanish requires the following additional soundfile:
00555 \arg \b 1M      un (masculine)
00556 
00557 Dutch, Portuguese & Spanish require the following additional soundfiles:
00558 \arg \b vm-INBOXs singular of 'new'
00559 \arg \b vm-Olds      singular of 'old/heard/read'
00560 
00561 NB these are plural:
00562 \arg \b vm-INBOX  nieuwe (nl)
00563 \arg \b vm-Old    oude (nl)
00564 
00565 Polish uses:
00566 \arg \b vm-new-a  'new', feminine singular accusative
00567 \arg \b vm-new-e  'new', feminine plural accusative
00568 \arg \b vm-new-ych   'new', feminine plural genitive
00569 \arg \b vm-old-a  'old', feminine singular accusative
00570 \arg \b vm-old-e  'old', feminine plural accusative
00571 \arg \b vm-old-ych   'old', feminine plural genitive
00572 \arg \b digits/1-a   'one', not always same as 'digits/1'
00573 \arg \b digits/2-ie  'two', not always same as 'digits/2'
00574 
00575 Swedish uses:
00576 \arg \b vm-nytt      singular of 'new'
00577 \arg \b vm-nya    plural of 'new'
00578 \arg \b vm-gammalt   singular of 'old'
00579 \arg \b vm-gamla  plural of 'old'
00580 \arg \b digits/ett   'one', not always same as 'digits/1'
00581 
00582 Norwegian uses:
00583 \arg \b vm-ny     singular of 'new'
00584 \arg \b vm-nye    plural of 'new'
00585 \arg \b vm-gammel singular of 'old'
00586 \arg \b vm-gamle  plural of 'old'
00587 
00588 Dutch also uses:
00589 \arg \b nl-om     'at'?
00590 
00591 Spanish also uses:
00592 \arg \b vm-youhaveno
00593 
00594 Italian requires the following additional soundfile:
00595 
00596 For vm_intro_it:
00597 \arg \b vm-nuovo  new
00598 \arg \b vm-nuovi  new plural
00599 \arg \b vm-vecchio   old
00600 \arg \b vm-vecchi old plural
00601 
00602 Chinese (Taiwan) requires the following additional soundfile:
00603 \arg \b vm-tong      A class-word for call (tong1)
00604 \arg \b vm-ri     A class-word for day (ri4)
00605 \arg \b vm-you    You (ni3)
00606 \arg \b vm-haveno   Have no (mei2 you3)
00607 \arg \b vm-have     Have (you3)
00608 \arg \b vm-listen   To listen (yao4 ting1)
00609 
00610 
00611 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
00612 spelled among others when you have to change folder. For the above reasons, vm-INBOX
00613 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
00614 
00615 */
00616 
00617 struct baseio {
00618    int iocp;
00619    int iolen;
00620    int linelength;
00621    int ateof;
00622    unsigned char iobuf[BASEMAXINLINE];
00623 };
00624 
00625 /*! Structure for linked list of users 
00626  * Use ast_vm_user_destroy() to free one of these structures. */
00627 struct ast_vm_user {
00628    char context[AST_MAX_CONTEXT];   /*!< Voicemail context */
00629    char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
00630    char password[80];               /*!< Secret pin code, numbers only */
00631    char fullname[80];               /*!< Full name, for directory app */
00632    char email[80];                  /*!< E-mail address */
00633    char *emailsubject;              /*!< E-mail subject */
00634    char *emailbody;                 /*!< E-mail body */
00635    char pager[80];                  /*!< E-mail address to pager (no attachment) */
00636    char serveremail[80];            /*!< From: Mail address */
00637    char mailcmd[160];               /*!< Configurable mail command */
00638    char language[MAX_LANGUAGE];     /*!< Config: Language setting */
00639    char zonetag[80];                /*!< Time zone */
00640    char locale[20];                 /*!< The locale (for presentation of date/time) */
00641    char callback[80];
00642    char dialout[80];
00643    char uniqueid[80];               /*!< Unique integer identifier */
00644    char exit[80];
00645    char attachfmt[20];              /*!< Attachment format */
00646    unsigned int flags;              /*!< VM_ flags */ 
00647    int saydurationm;
00648    int minsecs;                     /*!< Minimum number of seconds per message for this mailbox */
00649    int maxmsg;                      /*!< Maximum number of msgs per folder for this mailbox */
00650    int maxdeletedmsg;               /*!< Maximum number of deleted msgs saved for this mailbox */
00651    int maxsecs;                     /*!< Maximum number of seconds per message for this mailbox */
00652    int passwordlocation;            /*!< Storage location of the password */
00653 #ifdef IMAP_STORAGE
00654    char imapuser[80];               /*!< IMAP server login */
00655    char imappassword[80];           /*!< IMAP server password if authpassword not defined */
00656    char imapfolder[64];             /*!< IMAP voicemail folder */
00657    char imapvmshareid[80];          /*!< Shared mailbox ID to use rather than the dialed one */
00658    int imapversion;                 /*!< If configuration changes, use the new values */
00659 #endif
00660    double volgain;                  /*!< Volume gain for voicemails sent via email */
00661    AST_LIST_ENTRY(ast_vm_user) list;
00662 };
00663 
00664 /*! Voicemail time zones */
00665 struct vm_zone {
00666    AST_LIST_ENTRY(vm_zone) list;
00667    char name[80];
00668    char timezone[80];
00669    char msg_format[512];
00670 };
00671 
00672 #define VMSTATE_MAX_MSG_ARRAY 256
00673 
00674 /*! Voicemail mailbox state */
00675 struct vm_state {
00676    char curbox[80];
00677    char username[80];
00678    char context[80];
00679    char curdir[PATH_MAX];
00680    char vmbox[PATH_MAX];
00681    char fn[PATH_MAX];
00682    char intro[PATH_MAX];
00683    int *deleted;
00684    int *heard;
00685    int curmsg;
00686    int lastmsg;
00687    int newmessages;
00688    int oldmessages;
00689    int urgentmessages;
00690    int starting;
00691    int repeats;
00692 #ifdef IMAP_STORAGE
00693    ast_mutex_t lock;
00694    int updated;                         /*!< decremented on each mail check until 1 -allows delay */
00695    long msgArray[VMSTATE_MAX_MSG_ARRAY];
00696    MAILSTREAM *mailstream;
00697    int vmArrayIndex;
00698    char imapuser[80];                   /*!< IMAP server login */
00699    char imapfolder[64];                 /*!< IMAP voicemail folder */
00700    int imapversion;
00701    int interactive;
00702    char introfn[PATH_MAX];              /*!< Name of prepended file */
00703    unsigned int quota_limit;
00704    unsigned int quota_usage;
00705    struct vm_state *persist_vms;
00706 #endif
00707 };
00708 
00709 #ifdef ODBC_STORAGE
00710 static char odbc_database[80];
00711 static char odbc_table[80];
00712 #define RETRIEVE(a,b,c,d) retrieve_file(a,b)
00713 #define DISPOSE(a,b) remove_file(a,b)
00714 #define STORE(a,b,c,d,e,f,g,h,i,j) store_file(a,b,c,d)
00715 #define EXISTS(a,b,c,d) (message_exists(a,b))
00716 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
00717 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
00718 #define DELETE(a,b,c,d) (delete_file(a,b))
00719 #else
00720 #ifdef IMAP_STORAGE
00721 #define DISPOSE(a,b) (imap_remove_file(a,b))
00722 #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))
00723 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
00724 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
00725 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
00726 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
00727 #define DELETE(a,b,c,d) (vm_imap_delete(a,b,d))
00728 #else
00729 #define RETRIEVE(a,b,c,d)
00730 #define DISPOSE(a,b)
00731 #define STORE(a,b,c,d,e,f,g,h,i,j)
00732 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
00733 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
00734 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h)); 
00735 #define DELETE(a,b,c,d) (vm_delete(c))
00736 #endif
00737 #endif
00738 
00739 static char VM_SPOOL_DIR[PATH_MAX];
00740 
00741 static char ext_pass_cmd[128];
00742 static char ext_pass_check_cmd[128];
00743 
00744 static int my_umask;
00745 
00746 #define PWDCHANGE_INTERNAL (1 << 1)
00747 #define PWDCHANGE_EXTERNAL (1 << 2)
00748 static int pwdchange = PWDCHANGE_INTERNAL;
00749 
00750 #ifdef ODBC_STORAGE
00751 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
00752 #else
00753 # ifdef IMAP_STORAGE
00754 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
00755 # else
00756 # define tdesc "Comedian Mail (Voicemail System)"
00757 # endif
00758 #endif
00759 
00760 static char userscontext[AST_MAX_EXTENSION] = "default";
00761 
00762 static char *addesc = "Comedian Mail";
00763 
00764 /* Leave a message */
00765 static char *app = "VoiceMail";
00766 
00767 /* Check mail, control, etc */
00768 static char *app2 = "VoiceMailMain";
00769 
00770 static char *app3 = "MailboxExists";
00771 static char *app4 = "VMAuthenticate";
00772 
00773 static char *sayname_app = "VMSayName";
00774 
00775 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
00776 static AST_LIST_HEAD_STATIC(zones, vm_zone);
00777 static char zonetag[80];
00778 static char locale[20];
00779 static int maxsilence;
00780 static int maxmsg;
00781 static int maxdeletedmsg;
00782 static int silencethreshold = 128;
00783 static char serveremail[80];
00784 static char mailcmd[160];  /* Configurable mail cmd */
00785 static char externnotify[160]; 
00786 static struct ast_smdi_interface *smdi_iface = NULL;
00787 static char vmfmts[80];
00788 static double volgain;
00789 static int vmminsecs;
00790 static int vmmaxsecs;
00791 static int maxgreet;
00792 static int skipms;
00793 static int maxlogins;
00794 static int minpassword;
00795 static int passwordlocation;
00796 
00797 /*! Poll mailboxes for changes since there is something external to
00798  *  app_voicemail that may change them. */
00799 static unsigned int poll_mailboxes;
00800 
00801 /*! Polling frequency */
00802 static unsigned int poll_freq;
00803 /*! By default, poll every 30 seconds */
00804 #define DEFAULT_POLL_FREQ 30
00805 
00806 AST_MUTEX_DEFINE_STATIC(poll_lock);
00807 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
00808 static pthread_t poll_thread = AST_PTHREADT_NULL;
00809 static unsigned char poll_thread_run;
00810 
00811 /*! Subscription to ... MWI event subscriptions */
00812 static struct ast_event_sub *mwi_sub_sub;
00813 /*! Subscription to ... MWI event un-subscriptions */
00814 static struct ast_event_sub *mwi_unsub_sub;
00815 
00816 /*!
00817  * \brief An MWI subscription
00818  *
00819  * This is so we can keep track of which mailboxes are subscribed to.
00820  * This way, we know which mailboxes to poll when the pollmailboxes
00821  * option is being used.
00822  */
00823 struct mwi_sub {
00824    AST_RWLIST_ENTRY(mwi_sub) entry;
00825    int old_urgent;
00826    int old_new;
00827    int old_old;
00828    uint32_t uniqueid;
00829    char mailbox[1];
00830 };
00831 
00832 struct mwi_sub_task {
00833    const char *mailbox;
00834    const char *context;
00835    uint32_t uniqueid;
00836 };
00837 
00838 static struct ast_taskprocessor *mwi_subscription_tps;
00839 
00840 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
00841 
00842 /* custom audio control prompts for voicemail playback */
00843 static char listen_control_forward_key[12];
00844 static char listen_control_reverse_key[12];
00845 static char listen_control_pause_key[12];
00846 static char listen_control_restart_key[12];
00847 static char listen_control_stop_key[12];
00848 
00849 /* custom password sounds */
00850 static char vm_password[80] = "vm-password";
00851 static char vm_newpassword[80] = "vm-newpassword";
00852 static char vm_passchanged[80] = "vm-passchanged";
00853 static char vm_reenterpassword[80] = "vm-reenterpassword";
00854 static char vm_mismatch[80] = "vm-mismatch";
00855 static char vm_invalid_password[80] = "vm-invalid-password";
00856 static char vm_pls_try_again[80] = "vm-pls-try-again";
00857 
00858 static struct ast_flags globalflags = {0};
00859 
00860 static int saydurationminfo;
00861 
00862 static char dialcontext[AST_MAX_CONTEXT] = "";
00863 static char callcontext[AST_MAX_CONTEXT] = "";
00864 static char exitcontext[AST_MAX_CONTEXT] = "";
00865 
00866 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
00867 
00868 
00869 static char *emailbody = NULL;
00870 static char *emailsubject = NULL;
00871 static char *pagerbody = NULL;
00872 static char *pagersubject = NULL;
00873 static char fromstring[100];
00874 static char pagerfromstring[100];
00875 static char charset[32] = "ISO-8859-1";
00876 
00877 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
00878 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
00879 static int adsiver = 1;
00880 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
00881 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
00882 
00883 /* Forward declarations - generic */
00884 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
00885 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);
00886 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
00887 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
00888          char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
00889          signed char record_gain, struct vm_state *vms, char *flag);
00890 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
00891 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
00892 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);
00893 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);
00894 static void apply_options(struct ast_vm_user *vmu, const char *options);
00895 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);
00896 static int is_valid_dtmf(const char *key);
00897 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
00898 static int write_password_to_file(const char *secretfn, const char *password);
00899 
00900 struct ao2_container *inprocess_container;
00901 
00902 struct inprocess {
00903    int count;
00904    char *context;
00905    char mailbox[0];
00906 };
00907 
00908 static int inprocess_hash_fn(const void *obj, const int flags)
00909 {
00910    const struct inprocess *i = obj;
00911    return atoi(i->mailbox);
00912 }
00913 
00914 static int inprocess_cmp_fn(void *obj, void *arg, int flags)
00915 {
00916    struct inprocess *i = obj, *j = arg;
00917    if (!strcmp(i->mailbox, j->mailbox)) {
00918       return 0;
00919    }
00920    return !strcmp(i->context, j->context) ? CMP_MATCH : 0;
00921 }
00922 
00923 static int inprocess_count(const char *context, const char *mailbox, int delta)
00924 {
00925    struct inprocess *i, *arg = alloca(sizeof(*arg) + strlen(context) + strlen(mailbox) + 2);
00926    arg->context = arg->mailbox + strlen(mailbox) + 1;
00927    strcpy(arg->mailbox, mailbox); /* SAFE */
00928    strcpy(arg->context, context); /* SAFE */
00929    ao2_lock(inprocess_container);
00930    if ((i = ao2_find(inprocess_container, arg, 0))) {
00931       int ret = ast_atomic_fetchadd_int(&i->count, delta);
00932       ao2_unlock(inprocess_container);
00933       ao2_ref(i, -1);
00934       return ret;
00935    }
00936    if (!(i = ao2_alloc(sizeof(*i) + strlen(context) + strlen(mailbox) + 2, NULL))) {
00937       ao2_unlock(inprocess_container);
00938       return 0;
00939    }
00940    i->context = i->mailbox + strlen(mailbox) + 1;
00941    strcpy(i->mailbox, mailbox); /* SAFE */
00942    strcpy(i->context, context); /* SAFE */
00943    i->count = delta;
00944    ao2_link(inprocess_container, i);
00945    ao2_unlock(inprocess_container);
00946    ao2_ref(i, -1);
00947    return 0;
00948 }
00949 
00950 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
00951 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
00952 #endif
00953 
00954 /*!
00955  * \brief Strips control and non 7-bit clean characters from input string.
00956  *
00957  * \note To map control and none 7-bit characters to a 7-bit clean characters
00958  *  please use ast_str_encode_mine().
00959  */
00960 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
00961 {
00962    char *bufptr = buf;
00963    for (; *input; input++) {
00964       if (*input < 32) {
00965          continue;
00966       }
00967       *bufptr++ = *input;
00968       if (bufptr == buf + buflen - 1) {
00969          break;
00970       }
00971    }
00972    *bufptr = '\0';
00973    return buf;
00974 }
00975 
00976 
00977 /*!
00978  * \brief Sets default voicemail system options to a voicemail user.
00979  *
00980  * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
00981  * - all the globalflags
00982  * - the saydurationminfo
00983  * - the callcontext
00984  * - the dialcontext
00985  * - the exitcontext
00986  * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
00987  * - volume gain.
00988  */
00989 static void populate_defaults(struct ast_vm_user *vmu)
00990 {
00991    ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);   
00992    vmu->passwordlocation = passwordlocation;
00993    if (saydurationminfo) {
00994       vmu->saydurationm = saydurationminfo;
00995    }
00996    ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
00997    ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
00998    ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
00999    ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
01000    ast_copy_string(vmu->locale, locale, sizeof(vmu->locale));
01001    if (vmminsecs) {
01002       vmu->minsecs = vmminsecs;
01003    }
01004    if (vmmaxsecs) {
01005       vmu->maxsecs = vmmaxsecs;
01006    }
01007    if (maxmsg) {
01008       vmu->maxmsg = maxmsg;
01009    }
01010    if (maxdeletedmsg) {
01011       vmu->maxdeletedmsg = maxdeletedmsg;
01012    }
01013    vmu->volgain = volgain;
01014    vmu->emailsubject = NULL;
01015    vmu->emailbody = NULL;
01016 #ifdef IMAP_STORAGE
01017    ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
01018 #endif
01019 }
01020 
01021 /*!
01022  * \brief Sets a a specific property value.
01023  * \param vmu The voicemail user object to work with.
01024  * \param var The name of the property to be set.
01025  * \param value The value to be set to the property.
01026  * 
01027  * The property name must be one of the understood properties. See the source for details.
01028  */
01029 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
01030 {
01031    int x;
01032    if (!strcasecmp(var, "attach")) {
01033       ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
01034    } else if (!strcasecmp(var, "attachfmt")) {
01035       ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
01036    } else if (!strcasecmp(var, "serveremail")) {
01037       ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
01038    } else if (!strcasecmp(var, "language")) {
01039       ast_copy_string(vmu->language, value, sizeof(vmu->language));
01040    } else if (!strcasecmp(var, "tz")) {
01041       ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
01042    } else if (!strcasecmp(var, "locale")) {
01043       ast_copy_string(vmu->locale, value, sizeof(vmu->locale));
01044 #ifdef IMAP_STORAGE
01045    } else if (!strcasecmp(var, "imapuser")) {
01046       ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
01047       vmu->imapversion = imapversion;
01048    } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
01049       ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
01050       vmu->imapversion = imapversion;
01051    } else if (!strcasecmp(var, "imapfolder")) {
01052       ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
01053    } else if (!strcasecmp(var, "imapvmshareid")) {
01054       ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
01055       vmu->imapversion = imapversion;
01056 #endif
01057    } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
01058       ast_set2_flag(vmu, ast_true(value), VM_DELETE); 
01059    } else if (!strcasecmp(var, "saycid")){
01060       ast_set2_flag(vmu, ast_true(value), VM_SAYCID); 
01061    } else if (!strcasecmp(var, "sendvoicemail")){
01062       ast_set2_flag(vmu, ast_true(value), VM_SVMAIL); 
01063    } else if (!strcasecmp(var, "review")){
01064       ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
01065    } else if (!strcasecmp(var, "tempgreetwarn")){
01066       ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);   
01067    } else if (!strcasecmp(var, "messagewrap")){
01068       ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);  
01069    } else if (!strcasecmp(var, "operator")) {
01070       ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);  
01071    } else if (!strcasecmp(var, "envelope")){
01072       ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);  
01073    } else if (!strcasecmp(var, "moveheard")){
01074       ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
01075    } else if (!strcasecmp(var, "sayduration")){
01076       ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);  
01077    } else if (!strcasecmp(var, "saydurationm")){
01078       if (sscanf(value, "%30d", &x) == 1) {
01079          vmu->saydurationm = x;
01080       } else {
01081          ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
01082       }
01083    } else if (!strcasecmp(var, "forcename")){
01084       ast_set2_flag(vmu, ast_true(value), VM_FORCENAME); 
01085    } else if (!strcasecmp(var, "forcegreetings")){
01086       ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);   
01087    } else if (!strcasecmp(var, "callback")) {
01088       ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
01089    } else if (!strcasecmp(var, "dialout")) {
01090       ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
01091    } else if (!strcasecmp(var, "exitcontext")) {
01092       ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
01093    } else if (!strcasecmp(var, "minsecs")) {
01094       if (sscanf(value, "%30d", &x) == 1 && x >= 0) {
01095          vmu->minsecs = x;
01096       } else {
01097          ast_log(LOG_WARNING, "Invalid min message length of %s. Using global value %d\n", value, vmminsecs);
01098          vmu->minsecs = vmminsecs;
01099       }
01100    } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
01101       vmu->maxsecs = atoi(value);
01102       if (vmu->maxsecs <= 0) {
01103          ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
01104          vmu->maxsecs = vmmaxsecs;
01105       } else {
01106          vmu->maxsecs = atoi(value);
01107       }
01108       if (!strcasecmp(var, "maxmessage"))
01109          ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'.  Please make that change in your voicemail config.\n");
01110    } else if (!strcasecmp(var, "maxmsg")) {
01111       vmu->maxmsg = atoi(value);
01112       /* Accept maxmsg=0 (Greetings only voicemail) */
01113       if (vmu->maxmsg < 0) {
01114          ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
01115          vmu->maxmsg = MAXMSG;
01116       } else if (vmu->maxmsg > MAXMSGLIMIT) {
01117          ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
01118          vmu->maxmsg = MAXMSGLIMIT;
01119       }
01120    } else if (!strcasecmp(var, "nextaftercmd")) {
01121       ast_set2_flag(vmu, ast_true(value), VM_SKIPAFTERCMD);
01122    } else if (!strcasecmp(var, "backupdeleted")) {
01123       if (sscanf(value, "%30d", &x) == 1)
01124          vmu->maxdeletedmsg = x;
01125       else if (ast_true(value))
01126          vmu->maxdeletedmsg = MAXMSG;
01127       else
01128          vmu->maxdeletedmsg = 0;
01129 
01130       if (vmu->maxdeletedmsg < 0) {
01131          ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
01132          vmu->maxdeletedmsg = MAXMSG;
01133       } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
01134          ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
01135          vmu->maxdeletedmsg = MAXMSGLIMIT;
01136       }
01137    } else if (!strcasecmp(var, "volgain")) {
01138       sscanf(value, "%30lf", &vmu->volgain);
01139    } else if (!strcasecmp(var, "passwordlocation")) {
01140       if (!strcasecmp(value, "spooldir")) {
01141          vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
01142       } else {
01143          vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
01144       }
01145    } else if (!strcasecmp(var, "options")) {
01146       apply_options(vmu, value);
01147    }
01148 }
01149 
01150 static char *vm_check_password_shell(char *command, char *buf, size_t len) 
01151 {
01152    int fds[2], pid = 0;
01153 
01154    memset(buf, 0, len);
01155 
01156    if (pipe(fds)) {
01157       snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
01158    } else {
01159       /* good to go*/
01160       pid = ast_safe_fork(0);
01161 
01162       if (pid < 0) {
01163          /* ok maybe not */
01164          close(fds[0]);
01165          close(fds[1]);
01166          snprintf(buf, len, "FAILURE: Fork failed");
01167       } else if (pid) {
01168          /* parent */
01169          close(fds[1]);
01170          if (read(fds[0], buf, len) < 0) {
01171             ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
01172          }
01173          close(fds[0]);
01174       } else {
01175          /*  child */
01176          AST_DECLARE_APP_ARGS(arg,
01177             AST_APP_ARG(v)[20];
01178          );
01179          char *mycmd = ast_strdupa(command);
01180 
01181          close(fds[0]);
01182          dup2(fds[1], STDOUT_FILENO);
01183          close(fds[1]);
01184          ast_close_fds_above_n(STDOUT_FILENO);
01185 
01186          AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
01187 
01188          execv(arg.v[0], arg.v); 
01189          printf("FAILURE: %s", strerror(errno));
01190          _exit(0);
01191       }
01192    }
01193    return buf;
01194 }
01195 
01196 /*!
01197  * \brief Check that password meets minimum required length
01198  * \param vmu The voicemail user to change the password for.
01199  * \param password The password string to check
01200  *
01201  * \return zero on ok, 1 on not ok.
01202  */
01203 static int check_password(struct ast_vm_user *vmu, char *password)
01204 {
01205    /* check minimum length */
01206    if (strlen(password) < minpassword)
01207       return 1;
01208    if (!ast_strlen_zero(ext_pass_check_cmd)) {
01209       char cmd[255], buf[255];
01210 
01211       ast_log(AST_LOG_DEBUG, "Verify password policies for %s\n", password);
01212 
01213       snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
01214       if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
01215          ast_debug(5, "Result: %s\n", buf);
01216          if (!strncasecmp(buf, "VALID", 5)) {
01217             ast_debug(3, "Passed password check: '%s'\n", buf);
01218             return 0;
01219          } else if (!strncasecmp(buf, "FAILURE", 7)) {
01220             ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
01221             return 0;
01222          } else {
01223             ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
01224             return 1;
01225          }
01226       }
01227    }
01228    return 0;
01229 }
01230 
01231 /*! 
01232  * \brief Performs a change of the voicemail passowrd in the realtime engine.
01233  * \param vmu The voicemail user to change the password for.
01234  * \param password The new value to be set to the password for this user.
01235  * 
01236  * This only works if there is a realtime engine configured.
01237  * This is called from the (top level) vm_change_password.
01238  *
01239  * \return zero on success, -1 on error.
01240  */
01241 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
01242 {
01243    int res = -1;
01244    if (!strcmp(vmu->password, password)) {
01245       /* No change (but an update would return 0 rows updated, so we opt out here) */
01246       return 0;
01247    }
01248 
01249    if (strlen(password) > 10) {
01250       ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
01251    }
01252    if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
01253       ast_copy_string(vmu->password, password, sizeof(vmu->password));
01254       res = 0;
01255    }
01256    return res;
01257 }
01258 
01259 /*!
01260  * \brief Destructively Parse options and apply.
01261  */
01262 static void apply_options(struct ast_vm_user *vmu, const char *options)
01263 {  
01264    char *stringp;
01265    char *s;
01266    char *var, *value;
01267    stringp = ast_strdupa(options);
01268    while ((s = strsep(&stringp, "|"))) {
01269       value = s;
01270       if ((var = strsep(&value, "=")) && value) {
01271          apply_option(vmu, var, value);
01272       }
01273    }  
01274 }
01275 
01276 /*!
01277  * \brief Loads the options specific to a voicemail user.
01278  * 
01279  * This is called when a vm_user structure is being set up, such as from load_options.
01280  */
01281 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
01282 {
01283    for (; var; var = var->next) {
01284       if (!strcasecmp(var->name, "vmsecret")) {
01285          ast_copy_string(retval->password, var->value, sizeof(retval->password));
01286       } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
01287          if (ast_strlen_zero(retval->password))
01288             ast_copy_string(retval->password, var->value, sizeof(retval->password));
01289       } else if (!strcasecmp(var->name, "uniqueid")) {
01290          ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
01291       } else if (!strcasecmp(var->name, "pager")) {
01292          ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
01293       } else if (!strcasecmp(var->name, "email")) {
01294          ast_copy_string(retval->email, var->value, sizeof(retval->email));
01295       } else if (!strcasecmp(var->name, "fullname")) {
01296          ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
01297       } else if (!strcasecmp(var->name, "context")) {
01298          ast_copy_string(retval->context, var->value, sizeof(retval->context));
01299       } else if (!strcasecmp(var->name, "emailsubject")) {
01300          retval->emailsubject = ast_strdup(var->value);
01301       } else if (!strcasecmp(var->name, "emailbody")) {
01302          retval->emailbody = ast_strdup(var->value);
01303 #ifdef IMAP_STORAGE
01304       } else if (!strcasecmp(var->name, "imapuser")) {
01305          ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
01306          retval->imapversion = imapversion;
01307       } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
01308          ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
01309          retval->imapversion = imapversion;
01310       } else if (!strcasecmp(var->name, "imapfolder")) {
01311          ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
01312       } else if (!strcasecmp(var->name, "imapvmshareid")) {
01313          ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
01314          retval->imapversion = imapversion;
01315 #endif
01316       } else
01317          apply_option(retval, var->name, var->value);
01318    }
01319 }
01320 
01321 /*!
01322  * \brief Determines if a DTMF key entered is valid.
01323  * \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.
01324  *
01325  * Tests the character entered against the set of valid DTMF characters. 
01326  * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
01327  */
01328 static int is_valid_dtmf(const char *key)
01329 {
01330    int i;
01331    char *local_key = ast_strdupa(key);
01332 
01333    for (i = 0; i < strlen(key); ++i) {
01334       if (!strchr(VALID_DTMF, *local_key)) {
01335          ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
01336          return 0;
01337       }
01338       local_key++;
01339    }
01340    return 1;
01341 }
01342 
01343 /*!
01344  * \brief Finds a voicemail user from the realtime engine.
01345  * \param ivm
01346  * \param context
01347  * \param mailbox
01348  *
01349  * 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.
01350  *
01351  * \return The ast_vm_user structure for the user that was found.
01352  */
01353 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
01354 {
01355    struct ast_variable *var;
01356    struct ast_vm_user *retval;
01357 
01358    if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
01359       if (!ivm)
01360          ast_set_flag(retval, VM_ALLOCED);   
01361       else
01362          memset(retval, 0, sizeof(*retval));
01363       if (mailbox) 
01364          ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
01365       populate_defaults(retval);
01366       if (!context && ast_test_flag((&globalflags), VM_SEARCH))
01367          var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
01368       else
01369          var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
01370       if (var) {
01371          apply_options_full(retval, var);
01372          ast_variables_destroy(var);
01373       } else { 
01374          if (!ivm) 
01375             ast_free(retval);
01376          retval = NULL;
01377       }  
01378    } 
01379    return retval;
01380 }
01381 
01382 /*!
01383  * \brief Finds a voicemail user from the users file or the realtime engine.
01384  * \param ivm
01385  * \param context
01386  * \param mailbox
01387  * 
01388  * \return The ast_vm_user structure for the user that was found.
01389  */
01390 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
01391 {
01392    /* This function could be made to generate one from a database, too */
01393    struct ast_vm_user *vmu = NULL, *cur;
01394    AST_LIST_LOCK(&users);
01395 
01396    if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
01397       context = "default";
01398 
01399    AST_LIST_TRAVERSE(&users, cur, list) {
01400 #ifdef IMAP_STORAGE
01401       if (cur->imapversion != imapversion) {
01402          continue;
01403       }
01404 #endif
01405       if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
01406          break;
01407       if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
01408          break;
01409    }
01410    if (cur) {
01411       /* Make a copy, so that on a reload, we have no race */
01412       if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
01413          memcpy(vmu, cur, sizeof(*vmu));
01414          ast_set2_flag(vmu, !ivm, VM_ALLOCED);
01415          AST_LIST_NEXT(vmu, list) = NULL;
01416       }
01417    } else
01418       vmu = find_user_realtime(ivm, context, mailbox);
01419    AST_LIST_UNLOCK(&users);
01420    return vmu;
01421 }
01422 
01423 /*!
01424  * \brief Resets a user password to a specified password.
01425  * \param context
01426  * \param mailbox
01427  * \param newpass
01428  *
01429  * This does the actual change password work, called by the vm_change_password() function.
01430  *
01431  * \return zero on success, -1 on error.
01432  */
01433 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
01434 {
01435    /* This function could be made to generate one from a database, too */
01436    struct ast_vm_user *cur;
01437    int res = -1;
01438    AST_LIST_LOCK(&users);
01439    AST_LIST_TRAVERSE(&users, cur, list) {
01440       if ((!context || !strcasecmp(context, cur->context)) &&
01441          (!strcasecmp(mailbox, cur->mailbox)))
01442             break;
01443    }
01444    if (cur) {
01445       ast_copy_string(cur->password, newpass, sizeof(cur->password));
01446       res = 0;
01447    }
01448    AST_LIST_UNLOCK(&users);
01449    return res;
01450 }
01451 
01452 /*! 
01453  * \brief The handler for the change password option.
01454  * \param vmu The voicemail user to work with.
01455  * \param newpassword The new password (that has been gathered from the appropriate prompting).
01456  * 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.
01457  * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
01458  */
01459 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
01460 {
01461    struct ast_config   *cfg = NULL;
01462    struct ast_variable *var = NULL;
01463    struct ast_category *cat = NULL;
01464    char *category = NULL, *value = NULL, *new = NULL;
01465    const char *tmp = NULL;
01466    struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
01467    char secretfn[PATH_MAX] = "";
01468    int found = 0;
01469 
01470    if (!change_password_realtime(vmu, newpassword))
01471       return;
01472 
01473    /* check if we should store the secret in the spool directory next to the messages */
01474    switch (vmu->passwordlocation) {
01475    case OPT_PWLOC_SPOOLDIR:
01476       snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
01477       if (write_password_to_file(secretfn, newpassword) == 0) {
01478          ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
01479          reset_user_pw(vmu->context, vmu->mailbox, newpassword);
01480          ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
01481          break;
01482       } else {
01483          ast_verb(4, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
01484       }
01485       /* Fall-through */
01486    case OPT_PWLOC_VOICEMAILCONF:
01487       if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
01488          while ((category = ast_category_browse(cfg, category))) {
01489             if (!strcasecmp(category, vmu->context)) {
01490                if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
01491                   ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
01492                   break;
01493                }
01494                value = strstr(tmp, ",");
01495                if (!value) {
01496                   new = alloca(strlen(newpassword)+1);
01497                   sprintf(new, "%s", newpassword);
01498                } else {
01499                   new = alloca((strlen(value) + strlen(newpassword) + 1));
01500                   sprintf(new, "%s%s", newpassword, value);
01501                }
01502                if (!(cat = ast_category_get(cfg, category))) {
01503                   ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
01504                   break;
01505                }
01506                ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
01507                found = 1;
01508             }
01509          }
01510          /* save the results */
01511          if (found) {
01512             reset_user_pw(vmu->context, vmu->mailbox, newpassword);
01513             ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
01514             ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
01515             break;
01516          }
01517       }
01518       /* Fall-through */
01519    case OPT_PWLOC_USERSCONF:
01520       /* check users.conf and update the password stored for the mailbox */
01521       /* if no vmsecret entry exists create one. */
01522       if ((cfg = ast_config_load("users.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
01523          ast_debug(4, "we are looking for %s\n", vmu->mailbox);
01524          for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
01525             ast_debug(4, "users.conf: %s\n", category);
01526             if (!strcasecmp(category, vmu->mailbox)) {
01527                if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
01528                   ast_debug(3, "looks like we need to make vmsecret!\n");
01529                   var = ast_variable_new("vmsecret", newpassword, "");
01530                } else {
01531                   var = NULL;
01532                }
01533                new = alloca(strlen(newpassword) + 1);
01534                sprintf(new, "%s", newpassword);
01535                if (!(cat = ast_category_get(cfg, category))) {
01536                   ast_debug(4, "failed to get category!\n");
01537                   ast_free(var);
01538                   break;
01539                }
01540                if (!var) {
01541                   ast_variable_update(cat, "vmsecret", new, NULL, 0);
01542                } else {
01543                   ast_variable_append(cat, var);
01544                }
01545                found = 1;
01546                break;
01547             }
01548          }
01549          /* save the results and clean things up */
01550          if (found) {
01551             reset_user_pw(vmu->context, vmu->mailbox, newpassword);
01552             ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
01553             ast_config_text_file_save("users.conf", cfg, "AppVoicemail");
01554          }
01555       }
01556    }
01557 }
01558 
01559 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
01560 {
01561    char buf[255];
01562    snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
01563    if (!ast_safe_system(buf)) {
01564       ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
01565       /* Reset the password in memory, too */
01566       reset_user_pw(vmu->context, vmu->mailbox, newpassword);
01567    }
01568 }
01569 
01570 /*! 
01571  * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
01572  * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
01573  * \param len The length of the path string that was written out.
01574  * \param context
01575  * \param ext 
01576  * \param folder 
01577  * 
01578  * The path is constructed as 
01579  *    VM_SPOOL_DIRcontext/ext/folder
01580  *
01581  * \return zero on success, -1 on error.
01582  */
01583 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
01584 {
01585    return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
01586 }
01587 
01588 /*! 
01589  * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
01590  * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
01591  * \param len The length of the path string that was written out.
01592  * \param dir 
01593  * \param num 
01594  * 
01595  * The path is constructed as 
01596  *    VM_SPOOL_DIRcontext/ext/folder
01597  *
01598  * \return zero on success, -1 on error.
01599  */
01600 static int make_file(char *dest, const int len, const char *dir, const int num)
01601 {
01602    return snprintf(dest, len, "%s/msg%04d", dir, num);
01603 }
01604 
01605 /* same as mkstemp, but return a FILE * */
01606 static FILE *vm_mkftemp(char *template)
01607 {
01608    FILE *p = NULL;
01609    int pfd = mkstemp(template);
01610    chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
01611    if (pfd > -1) {
01612       p = fdopen(pfd, "w+");
01613       if (!p) {
01614          close(pfd);
01615          pfd = -1;
01616       }
01617    }
01618    return p;
01619 }
01620 
01621 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
01622  * \param dest    String. base directory.
01623  * \param len     Length of dest.
01624  * \param context String. Ignored if is null or empty string.
01625  * \param ext     String. Ignored if is null or empty string.
01626  * \param folder  String. Ignored if is null or empty string. 
01627  * \return -1 on failure, 0 on success.
01628  */
01629 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
01630 {
01631    mode_t   mode = VOICEMAIL_DIR_MODE;
01632    int res;
01633 
01634    make_dir(dest, len, context, ext, folder);
01635    if ((res = ast_mkdir(dest, mode))) {
01636       ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
01637       return -1;
01638    }
01639    return 0;
01640 }
01641 
01642 static const char * const mailbox_folders[] = {
01643 #ifdef IMAP_STORAGE
01644    imapfolder,
01645 #else
01646    "INBOX",
01647 #endif
01648    "Old",
01649    "Work",
01650    "Family",
01651    "Friends",
01652    "Cust1",
01653    "Cust2",
01654    "Cust3",
01655    "Cust4",
01656    "Cust5",
01657    "Deleted",
01658    "Urgent",
01659 };
01660 
01661 static const char *mbox(struct ast_vm_user *vmu, int id)
01662 {
01663 #ifdef IMAP_STORAGE
01664    if (vmu && id == 0) {
01665       return vmu->imapfolder;
01666    }
01667 #endif
01668    return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
01669 }
01670 
01671 static int get_folder_by_name(const char *name)
01672 {
01673    size_t i;
01674 
01675    for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
01676       if (strcasecmp(name, mailbox_folders[i]) == 0) {
01677          return i;
01678       }
01679    }
01680 
01681    return -1;
01682 }
01683 
01684 static void free_user(struct ast_vm_user *vmu)
01685 {
01686    if (ast_test_flag(vmu, VM_ALLOCED)) {
01687       if (vmu->emailbody != NULL) {
01688          ast_free(vmu->emailbody);
01689          vmu->emailbody = NULL;
01690       }
01691       if (vmu->emailsubject != NULL) {
01692          ast_free(vmu->emailsubject);
01693          vmu->emailsubject = NULL;
01694       }
01695       ast_free(vmu);
01696    }
01697 }
01698 
01699 /* All IMAP-specific functions should go in this block. This
01700  * keeps them from being spread out all over the code */
01701 #ifdef IMAP_STORAGE
01702 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
01703 {
01704    char arg[10];
01705    struct vm_state *vms;
01706    unsigned long messageNum;
01707 
01708    /* If greetings aren't stored in IMAP, just delete the file */
01709    if (msgnum < 0 && !imapgreetings) {
01710       ast_filedelete(file, NULL);
01711       return;
01712    }
01713 
01714    if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
01715       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);
01716       return;
01717    }
01718 
01719    /* find real message number based on msgnum */
01720    /* this may be an index into vms->msgArray based on the msgnum. */
01721    messageNum = vms->msgArray[msgnum];
01722    if (messageNum == 0) {
01723       ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
01724       return;
01725    }
01726    if (option_debug > 2)
01727       ast_log(LOG_DEBUG, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
01728    /* delete message */
01729    snprintf (arg, sizeof(arg), "%lu", messageNum);
01730    ast_mutex_lock(&vms->lock);
01731    mail_setflag (vms->mailstream, arg, "\\DELETED");
01732    mail_expunge(vms->mailstream);
01733    ast_mutex_unlock(&vms->lock);
01734 }
01735 
01736 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
01737 {
01738    struct vm_state *vms_p;
01739    char *file, *filename;
01740    char *attachment;
01741    int ret = 0, i;
01742    BODY *body;
01743 
01744    /* This function is only used for retrieval of IMAP greetings
01745     * regular messages are not retrieved this way, nor are greetings
01746     * if they are stored locally*/
01747    if (msgnum > -1 || !imapgreetings) {
01748       return 0;
01749    } else {
01750       file = strrchr(ast_strdupa(dir), '/');
01751       if (file)
01752          *file++ = '\0';
01753       else {
01754          ast_debug (1, "Failed to procure file name from directory passed.\n");
01755          return -1;
01756       }
01757    }
01758 
01759    /* check if someone is accessing this box right now... */
01760    if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && 
01761       !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
01762       /* Unlike when retrieving a message, it is reasonable not to be able to find a 
01763       * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
01764       * that's all we need to do.
01765       */
01766       if (!(vms_p = create_vm_state_from_user(vmu))) {
01767          ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
01768          return -1;
01769       }
01770    }
01771    
01772    /* Greetings will never have a prepended message */
01773    *vms_p->introfn = '\0';
01774 
01775    ast_mutex_lock(&vms_p->lock);
01776    ret = init_mailstream(vms_p, GREETINGS_FOLDER);
01777    if (!vms_p->mailstream) {
01778       ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL\n");
01779       ast_mutex_unlock(&vms_p->lock);
01780       return -1;
01781    }
01782 
01783    /*XXX Yuck, this could probably be done a lot better */
01784    for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
01785       mail_fetchstructure(vms_p->mailstream, i + 1, &body);
01786       /* We have the body, now we extract the file name of the first attachment. */
01787       if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
01788          attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
01789       } else {
01790          ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
01791          ast_mutex_unlock(&vms_p->lock);
01792          return -1;
01793       }
01794       filename = strsep(&attachment, ".");
01795       if (!strcmp(filename, file)) {
01796          ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
01797          vms_p->msgArray[vms_p->curmsg] = i + 1;
01798          save_body(body, vms_p, "2", attachment, 0);
01799          ast_mutex_unlock(&vms_p->lock);
01800          return 0;
01801       }
01802    }
01803    ast_mutex_unlock(&vms_p->lock);
01804 
01805    return -1;
01806 }
01807 
01808 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
01809 {
01810    BODY *body;
01811    char *header_content;
01812    char *attachedfilefmt;
01813    char buf[80];
01814    struct vm_state *vms;
01815    char text_file[PATH_MAX];
01816    FILE *text_file_ptr;
01817    int res = 0;
01818    struct ast_vm_user *vmu;
01819 
01820    if (!(vmu = find_user(NULL, context, mailbox))) {
01821       ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
01822       return -1;
01823    }
01824    
01825    if (msgnum < 0) {
01826       if (imapgreetings) {
01827          res = imap_retrieve_greeting(dir, msgnum, vmu);
01828          goto exit;
01829       } else {
01830          res = 0;
01831          goto exit;
01832       }
01833    }
01834 
01835    /* Before anything can happen, we need a vm_state so that we can
01836     * actually access the imap server through the vms->mailstream
01837     */
01838    if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
01839       /* This should not happen. If it does, then I guess we'd
01840        * need to create the vm_state, extract which mailbox to
01841        * open, and then set up the msgArray so that the correct
01842        * IMAP message could be accessed. If I have seen correctly
01843        * though, the vms should be obtainable from the vmstates list
01844        * and should have its msgArray properly set up.
01845        */
01846       ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
01847       res = -1;
01848       goto exit;
01849    }
01850    
01851    make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
01852    snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
01853 
01854    /* Don't try to retrieve a message from IMAP if it already is on the file system */
01855    if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
01856       res = 0;
01857       goto exit;
01858    }
01859 
01860    if (option_debug > 2)
01861       ast_log(LOG_DEBUG, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
01862    if (vms->msgArray[msgnum] == 0) {
01863       ast_log(LOG_WARNING, "Trying to access unknown message\n");
01864       res = -1;
01865       goto exit;
01866    }
01867 
01868    /* This will only work for new messages... */
01869    ast_mutex_lock(&vms->lock);
01870    header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
01871    ast_mutex_unlock(&vms->lock);
01872    /* empty string means no valid header */
01873    if (ast_strlen_zero(header_content)) {
01874       ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
01875       res = -1;
01876       goto exit;
01877    }
01878 
01879    ast_mutex_lock(&vms->lock);
01880    mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
01881    ast_mutex_unlock(&vms->lock);
01882 
01883    /* We have the body, now we extract the file name of the first attachment. */
01884    if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
01885       attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
01886    } else {
01887       ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
01888       res = -1;
01889       goto exit;
01890    }
01891    
01892    /* Find the format of the attached file */
01893 
01894    strsep(&attachedfilefmt, ".");
01895    if (!attachedfilefmt) {
01896       ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
01897       res = -1;
01898       goto exit;
01899    }
01900    
01901    save_body(body, vms, "2", attachedfilefmt, 0);
01902    if (save_body(body, vms, "3", attachedfilefmt, 1)) {
01903       *vms->introfn = '\0';
01904    }
01905 
01906    /* Get info from headers!! */
01907    snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
01908 
01909    if (!(text_file_ptr = fopen(text_file, "w"))) {
01910       ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
01911    }
01912 
01913    fprintf(text_file_ptr, "%s\n", "[message]");
01914 
01915    get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf));
01916    fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
01917    get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf));
01918    fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
01919    get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf));
01920    fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
01921    get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf));
01922    fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
01923    get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf));
01924    fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
01925    get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf));
01926    fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
01927    get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf));
01928    fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
01929    fclose(text_file_ptr);
01930 
01931 exit:
01932    free_user(vmu);
01933    return res;
01934 }
01935 
01936 static int folder_int(const char *folder)
01937 {
01938    /*assume a NULL folder means INBOX*/
01939    if (!folder) {
01940       return 0;
01941    }
01942    if (!strcasecmp(folder, imapfolder)) {
01943       return 0;
01944    } else if (!strcasecmp(folder, "Old")) {
01945       return 1;
01946    } else if (!strcasecmp(folder, "Work")) {
01947       return 2;
01948    } else if (!strcasecmp(folder, "Family")) {
01949       return 3;
01950    } else if (!strcasecmp(folder, "Friends")) {
01951       return 4;
01952    } else if (!strcasecmp(folder, "Cust1")) {
01953       return 5;
01954    } else if (!strcasecmp(folder, "Cust2")) {
01955       return 6;
01956    } else if (!strcasecmp(folder, "Cust3")) {
01957       return 7;
01958    } else if (!strcasecmp(folder, "Cust4")) {
01959       return 8;
01960    } else if (!strcasecmp(folder, "Cust5")) {
01961       return 9;
01962    } else if (!strcasecmp(folder, "Urgent")) {
01963       return 11;
01964    } else { /*assume they meant INBOX if folder is not found otherwise*/
01965       return 0;
01966    }
01967 }
01968 
01969 static int __messagecount(const char *context, const char *mailbox, const char *folder)
01970 {
01971    SEARCHPGM *pgm;
01972    SEARCHHEADER *hdr;
01973 
01974    struct ast_vm_user *vmu, vmus;
01975    struct vm_state *vms_p;
01976    int ret = 0;
01977    int fold = folder_int(folder);
01978    int urgent = 0;
01979    
01980    /* If URGENT, then look at INBOX */
01981    if (fold == 11) {
01982       fold = NEW_FOLDER;
01983       urgent = 1;
01984    }
01985 
01986    if (ast_strlen_zero(mailbox))
01987       return 0;
01988 
01989    /* We have to get the user before we can open the stream! */
01990    vmu = find_user(&vmus, context, mailbox);
01991    if (!vmu) {
01992       ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailbox, context);
01993       return -1;
01994    } else {
01995       /* No IMAP account available */
01996       if (vmu->imapuser[0] == '\0') {
01997          ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
01998          return -1;
01999       }
02000    }
02001    
02002    /* No IMAP account available */
02003    if (vmu->imapuser[0] == '\0') {
02004       ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
02005       free_user(vmu);
02006       return -1;
02007    }
02008 
02009    /* check if someone is accessing this box right now... */
02010    vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
02011    if (!vms_p) {
02012       vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
02013    }
02014    if (vms_p) {
02015       ast_debug(3, "Returning before search - user is logged in\n");
02016       if (fold == 0) { /* INBOX */
02017          return urgent ? vms_p->urgentmessages : vms_p->newmessages;
02018       }
02019       if (fold == 1) { /* Old messages */
02020          return vms_p->oldmessages;
02021       }
02022    }
02023 
02024    /* add one if not there... */
02025    vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
02026    if (!vms_p) {
02027       vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
02028    }
02029 
02030    if (!vms_p) {
02031       vms_p = create_vm_state_from_user(vmu);
02032    }
02033    ret = init_mailstream(vms_p, fold);
02034    if (!vms_p->mailstream) {
02035       ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
02036       return -1;
02037    }
02038    if (ret == 0) {
02039       ast_mutex_lock(&vms_p->lock);
02040       pgm = mail_newsearchpgm ();
02041       hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
02042       hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
02043       pgm->header = hdr;
02044       if (fold != OLD_FOLDER) {
02045          pgm->unseen = 1;
02046          pgm->seen = 0;
02047       }
02048       /* In the special case where fold is 1 (old messages) we have to do things a bit
02049        * differently. Old messages are stored in the INBOX but are marked as "seen"
02050        */
02051       else {
02052          pgm->unseen = 0;
02053          pgm->seen = 1;
02054       }
02055       /* look for urgent messages */
02056       if (fold == NEW_FOLDER) {
02057          if (urgent) {
02058             pgm->flagged = 1;
02059             pgm->unflagged = 0;
02060          } else {
02061             pgm->flagged = 0;
02062             pgm->unflagged = 1;
02063          }
02064       }
02065       pgm->undeleted = 1;
02066       pgm->deleted = 0;
02067 
02068       vms_p->vmArrayIndex = 0;
02069       mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
02070       if (fold == 0 && urgent == 0)
02071          vms_p->newmessages = vms_p->vmArrayIndex;
02072       if (fold == 1)
02073          vms_p->oldmessages = vms_p->vmArrayIndex;
02074       if (fold == 0 && urgent == 1)
02075          vms_p->urgentmessages = vms_p->vmArrayIndex;
02076       /*Freeing the searchpgm also frees the searchhdr*/
02077       mail_free_searchpgm(&pgm);
02078       ast_mutex_unlock(&vms_p->lock);
02079       vms_p->updated = 0;
02080       return vms_p->vmArrayIndex;
02081    } else {
02082       ast_mutex_lock(&vms_p->lock);
02083       mail_ping(vms_p->mailstream);
02084       ast_mutex_unlock(&vms_p->lock);
02085    }
02086    return 0;
02087 }
02088 
02089 static int imap_check_limits(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu, int msgnum)
02090 {
02091    /* Check if mailbox is full */
02092    check_quota(vms, vmu->imapfolder);
02093    if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
02094       ast_debug(1, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
02095       ast_play_and_wait(chan, "vm-mailboxfull");
02096       return -1;
02097    }
02098    
02099    /* Check if we have exceeded maxmsg */
02100    if (msgnum >= vmu->maxmsg  - inprocess_count(vmu->mailbox, vmu->context, 0)) {
02101       ast_log(AST_LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u > %u)\n", msgnum, vmu->maxmsg);
02102       ast_play_and_wait(chan, "vm-mailboxfull");
02103       return -1;
02104    }
02105 
02106    return 0;
02107 }
02108 
02109 /*!
02110  * \brief Gets the number of messages that exist in a mailbox folder.
02111  * \param context
02112  * \param mailbox
02113  * \param folder
02114  * 
02115  * This method is used when IMAP backend is used.
02116  * \return The number of messages in this mailbox folder (zero or more).
02117  */
02118 static int messagecount(const char *context, const char *mailbox, const char *folder)
02119 {
02120    if (ast_strlen_zero(folder) || !strcmp(folder, "INBOX")) {
02121       return __messagecount(context, mailbox, "INBOX") + __messagecount(context, mailbox, "Urgent");
02122    } else {
02123       return __messagecount(context, mailbox, folder);
02124    }
02125 }
02126 
02127 static int imap_store_file(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms, const char *flag)
02128 {
02129    char *myserveremail = serveremail;
02130    char fn[PATH_MAX];
02131    char introfn[PATH_MAX];
02132    char mailbox[256];
02133    char *stringp;
02134    FILE *p = NULL;
02135    char tmp[80] = "/tmp/astmail-XXXXXX";
02136    long len;
02137    void *buf;
02138    int tempcopy = 0;
02139    STRING str;
02140    int ret; /* for better error checking */
02141    char *imap_flags = NIL;
02142    int msgcount = (messagecount(vmu->context, vmu->mailbox, "INBOX") + messagecount(vmu->context, vmu->mailbox, "Old"));
02143 
02144     /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
02145     if (msgnum < 0 && !imapgreetings) {
02146         return 0;
02147     }
02148    
02149    if (imap_check_limits(chan, vms, vmu, msgcount)) {
02150       return -1;
02151    }
02152 
02153    /* Set urgent flag for IMAP message */
02154    if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
02155       ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
02156       imap_flags = "\\FLAGGED";
02157    }
02158    
02159    /* Attach only the first format */
02160    fmt = ast_strdupa(fmt);
02161    stringp = fmt;
02162    strsep(&stringp, "|");
02163 
02164    if (!ast_strlen_zero(vmu->serveremail))
02165       myserveremail = vmu->serveremail;
02166 
02167    if (msgnum > -1)
02168       make_file(fn, sizeof(fn), dir, msgnum);
02169    else
02170       ast_copy_string (fn, dir, sizeof(fn));
02171 
02172    snprintf(introfn, sizeof(introfn), "%sintro", fn);
02173    if (ast_fileexists(introfn, NULL, NULL) <= 0) {
02174       *introfn = '\0';
02175    }
02176    
02177    if (ast_strlen_zero(vmu->email)) {
02178       /* We need the vmu->email to be set when we call make_email_file, but
02179        * if we keep it set, a duplicate e-mail will be created. So at the end
02180        * of this function, we will revert back to an empty string if tempcopy
02181        * is 1.
02182        */
02183       ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
02184       tempcopy = 1;
02185    }
02186 
02187    if (!strcmp(fmt, "wav49"))
02188       fmt = "WAV";
02189    ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
02190 
02191    /* Make a temporary file instead of piping directly to sendmail, in case the mail
02192       command hangs. */
02193    if (!(p = vm_mkftemp(tmp))) {
02194       ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
02195       if (tempcopy)
02196          *(vmu->email) = '\0';
02197       return -1;
02198    }
02199 
02200    if (msgnum < 0 && imapgreetings) {
02201       if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
02202          ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
02203          return -1;
02204       }
02205       imap_delete_old_greeting(fn, vms);
02206    }
02207 
02208    make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, "INBOX",
02209       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
02210       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
02211       fn, introfn, fmt, duration, 1, chan, NULL, 1, flag);
02212    /* read mail file to memory */
02213    len = ftell(p);
02214    rewind(p);
02215    if (!(buf = ast_malloc(len + 1))) {
02216       ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
02217       fclose(p);
02218       if (tempcopy)
02219          *(vmu->email) = '\0';
02220       return -1;
02221    }
02222    if (fread(buf, len, 1, p) < len) {
02223       if (ferror(p)) {
02224          ast_log(LOG_ERROR, "Short read while reading in mail file.\n");
02225          return -1;
02226       }
02227    }
02228    ((char *) buf)[len] = '\0';
02229    INIT(&str, mail_string, buf, len);
02230    ret = init_mailstream(vms, NEW_FOLDER);
02231    if (ret == 0) {
02232       imap_mailbox_name(mailbox, sizeof(mailbox), vms, NEW_FOLDER, 1);
02233       ast_mutex_lock(&vms->lock);
02234       if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
02235          ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
02236       ast_mutex_unlock(&vms->lock);
02237       fclose(p);
02238       unlink(tmp);
02239       ast_free(buf);
02240    } else {
02241       ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
02242       fclose(p);
02243       unlink(tmp);
02244       ast_free(buf);
02245       return -1;
02246    }
02247    ast_debug(3, "%s stored\n", fn);
02248    
02249    if (tempcopy)
02250       *(vmu->email) = '\0';
02251    
02252    return 0;
02253 
02254 }
02255 
02256 /*!
02257  * \brief Gets the number of messages that exist in the inbox folder.
02258  * \param mailbox_context
02259  * \param newmsgs The variable that is updated with the count of new messages within this inbox.
02260  * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
02261  * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
02262  * 
02263  * This method is used when IMAP backend is used.
02264  * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
02265  *
02266  * \return zero on success, -1 on error.
02267  */
02268 
02269 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
02270 {
02271    char tmp[PATH_MAX] = "";
02272    char *mailboxnc;
02273    char *context;
02274    char *mb;
02275    char *cur;
02276    if (newmsgs)
02277       *newmsgs = 0;
02278    if (oldmsgs)
02279       *oldmsgs = 0;
02280    if (urgentmsgs)
02281       *urgentmsgs = 0;
02282 
02283    ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
02284    /* If no mailbox, return immediately */
02285    if (ast_strlen_zero(mailbox_context))
02286       return 0;
02287    
02288    ast_copy_string(tmp, mailbox_context, sizeof(tmp));
02289    context = strchr(tmp, '@');
02290    if (strchr(mailbox_context, ',')) {
02291       int tmpnew, tmpold, tmpurgent;
02292       ast_copy_string(tmp, mailbox_context, sizeof(tmp));
02293       mb = tmp;
02294       while ((cur = strsep(&mb, ", "))) {
02295          if (!ast_strlen_zero(cur)) {
02296             if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
02297                return -1;
02298             else {
02299                if (newmsgs)
02300                   *newmsgs += tmpnew; 
02301                if (oldmsgs)
02302                   *oldmsgs += tmpold;
02303                if (urgentmsgs)
02304                   *urgentmsgs += tmpurgent;
02305             }
02306          }
02307       }
02308       return 0;
02309    }
02310    if (context) {
02311       *context = '\0';
02312       mailboxnc = tmp;
02313       context++;
02314    } else {
02315       context = "default";
02316       mailboxnc = (char *) mailbox_context;
02317    }
02318 
02319    if (newmsgs) {
02320       struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
02321       if (!vmu) {
02322          ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
02323          return -1;
02324       }
02325       if ((*newmsgs = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
02326          return -1;
02327       }
02328    }
02329    if (oldmsgs) {
02330       if ((*oldmsgs = __messagecount(context, mailboxnc, "Old")) < 0) {
02331          return -1;
02332       }
02333    }
02334    if (urgentmsgs) {
02335       if ((*urgentmsgs = __messagecount(context, mailboxnc, "Urgent")) < 0) {
02336          return -1;
02337       }
02338    }
02339    return 0;
02340 }
02341 
02342 /** 
02343  * \brief Determines if the given folder has messages.
02344  * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
02345  * \param folder the folder to look in
02346  *
02347  * This function is used when the mailbox is stored in an IMAP back end.
02348  * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
02349  * \return 1 if the folder has one or more messages. zero otherwise.
02350  */
02351 
02352 static int has_voicemail(const char *mailbox, const char *folder)
02353 {
02354    char tmp[256], *tmp2, *box, *context;
02355    ast_copy_string(tmp, mailbox, sizeof(tmp));
02356    tmp2 = tmp;
02357    if (strchr(tmp2, ',') || strchr(tmp2, '&')) {
02358       while ((box = strsep(&tmp2, ",&"))) {
02359          if (!ast_strlen_zero(box)) {
02360             if (has_voicemail(box, folder)) {
02361                return 1;
02362             }
02363          }
02364       }
02365    }
02366    if ((context = strchr(tmp, '@'))) {
02367       *context++ = '\0';
02368    } else {
02369       context = "default";
02370    }
02371    return __messagecount(context, tmp, folder) ? 1 : 0;
02372 }
02373 
02374 /*!
02375  * \brief Copies a message from one mailbox to another.
02376  * \param chan
02377  * \param vmu
02378  * \param imbox
02379  * \param msgnum
02380  * \param duration
02381  * \param recip
02382  * \param fmt
02383  * \param dir
02384  *
02385  * This works with IMAP storage based mailboxes.
02386  *
02387  * \return zero on success, -1 on error.
02388  */
02389 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)
02390 {
02391    struct vm_state *sendvms = NULL, *destvms = NULL;
02392    char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
02393    if (msgnum >= recip->maxmsg) {
02394       ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
02395       return -1;
02396    }
02397    if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
02398       ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
02399       return -1;
02400    }
02401    if (!(destvms = get_vm_state_by_imapuser(recip->imapuser, 0))) {
02402       ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
02403       return -1;
02404    }
02405    snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
02406    ast_mutex_lock(&sendvms->lock);
02407    if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
02408       ast_mutex_unlock(&sendvms->lock);
02409       return 0;
02410    }
02411    ast_mutex_unlock(&sendvms->lock);
02412    ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
02413    return -1;
02414 }
02415 
02416 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
02417 {
02418    char tmp[256], *t = tmp;
02419    size_t left = sizeof(tmp);
02420    
02421    if (box == OLD_FOLDER) {
02422       ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
02423    } else {
02424       ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
02425    }
02426 
02427    if (box == NEW_FOLDER) {
02428       ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
02429    } else {
02430       snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
02431    }
02432 
02433    /* Build up server information */
02434    ast_build_string(&t, &left, "{%s:%s/imap", imapserver, imapport);
02435 
02436    /* Add authentication user if present */
02437    if (!ast_strlen_zero(authuser))
02438       ast_build_string(&t, &left, "/authuser=%s", authuser);
02439 
02440    /* Add flags if present */
02441    if (!ast_strlen_zero(imapflags))
02442       ast_build_string(&t, &left, "/%s", imapflags);
02443 
02444    /* End with username */
02445 #if 1
02446    ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
02447 #else
02448    ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
02449 #endif
02450    if (box == NEW_FOLDER || box == OLD_FOLDER)
02451       snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
02452    else if (box == GREETINGS_FOLDER)
02453       snprintf(spec, len, "%s%s", tmp, greetingfolder);
02454    else {   /* Other folders such as Friends, Family, etc... */
02455       if (!ast_strlen_zero(imapparentfolder)) {
02456          /* imapparentfolder would typically be set to INBOX */
02457          snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
02458       } else {
02459          snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
02460       }
02461    }
02462 }
02463 
02464 static int init_mailstream(struct vm_state *vms, int box)
02465 {
02466    MAILSTREAM *stream = NIL;
02467    long debug;
02468    char tmp[256];
02469    
02470    if (!vms) {
02471       ast_log(LOG_ERROR, "vm_state is NULL!\n");
02472       return -1;
02473    }
02474    if (option_debug > 2)
02475       ast_log(LOG_DEBUG, "vm_state user is:%s\n", vms->imapuser);
02476    if (vms->mailstream == NIL || !vms->mailstream) {
02477       if (option_debug)
02478          ast_log(LOG_DEBUG, "mailstream not set.\n");
02479    } else {
02480       stream = vms->mailstream;
02481    }
02482    /* debug = T;  user wants protocol telemetry? */
02483    debug = NIL;  /* NO protocol telemetry? */
02484 
02485    if (delimiter == '\0') {      /* did not probe the server yet */
02486       char *cp;
02487 #ifdef USE_SYSTEM_IMAP
02488 #include <imap/linkage.c>
02489 #elif defined(USE_SYSTEM_CCLIENT)
02490 #include <c-client/linkage.c>
02491 #else
02492 #include "linkage.c"
02493 #endif
02494       /* Connect to INBOX first to get folders delimiter */
02495       imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
02496       ast_mutex_lock(&vms->lock);
02497       stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
02498       ast_mutex_unlock(&vms->lock);
02499       if (stream == NIL) {
02500          ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
02501          return -1;
02502       }
02503       get_mailbox_delimiter(stream);
02504       /* update delimiter in imapfolder */
02505       for (cp = vms->imapfolder; *cp; cp++)
02506          if (*cp == '/')
02507             *cp = delimiter;
02508    }
02509    /* Now connect to the target folder */
02510    imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
02511    if (option_debug > 2)
02512       ast_log(LOG_DEBUG, "Before mail_open, server: %s, box:%d\n", tmp, box);
02513    ast_mutex_lock(&vms->lock);
02514    vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
02515    ast_mutex_unlock(&vms->lock);
02516    if (vms->mailstream == NIL) {
02517       return -1;
02518    } else {
02519       return 0;
02520    }
02521 }
02522 
02523 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
02524 {
02525    SEARCHPGM *pgm;
02526    SEARCHHEADER *hdr;
02527    int ret, urgent = 0;
02528 
02529    /* If Urgent, then look at INBOX */
02530    if (box == 11) {
02531       box = NEW_FOLDER;
02532       urgent = 1;
02533    }
02534 
02535    ast_copy_string(vms->imapuser, vmu->imapuser, sizeof(vms->imapuser));
02536    ast_copy_string(vms->imapfolder, vmu->imapfolder, sizeof(vms->imapfolder));
02537    vms->imapversion = vmu->imapversion;
02538    ast_debug(3, "Before init_mailstream, user is %s\n", vmu->imapuser);
02539 
02540    if ((ret = init_mailstream(vms, box)) || !vms->mailstream) {
02541       ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
02542       return -1;
02543    }
02544    
02545    create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
02546    
02547    /* Check Quota */
02548    if  (box == 0)  {
02549       ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(vmu, box));
02550       check_quota(vms, (char *) mbox(vmu, box));
02551    }
02552 
02553    ast_mutex_lock(&vms->lock);
02554    pgm = mail_newsearchpgm();
02555 
02556    /* Check IMAP folder for Asterisk messages only... */
02557    hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : vmu->mailbox));
02558    hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", vmu->context);
02559    pgm->header = hdr;
02560    pgm->deleted = 0;
02561    pgm->undeleted = 1;
02562 
02563    /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
02564    if (box == NEW_FOLDER && urgent == 1) {
02565       pgm->unseen = 1;
02566       pgm->seen = 0;
02567       pgm->flagged = 1;
02568       pgm->unflagged = 0;
02569    } else if (box == NEW_FOLDER && urgent == 0) {
02570       pgm->unseen = 1;
02571       pgm->seen = 0;
02572       pgm->flagged = 0;
02573       pgm->unflagged = 1;
02574    } else if (box == OLD_FOLDER) {
02575       pgm->seen = 1;
02576       pgm->unseen = 0;
02577    }
02578 
02579    ast_debug(3, "Before mail_search_full, user is %s\n", vmu->imapuser);
02580 
02581    vms->vmArrayIndex = 0;
02582    mail_search_full (vms->mailstream, NULL, pgm, NIL);
02583    vms->lastmsg = vms->vmArrayIndex - 1;
02584    mail_free_searchpgm(&pgm);
02585 
02586    ast_mutex_unlock(&vms->lock);
02587    return 0;
02588 }
02589 
02590 static void write_file(char *filename, char *buffer, unsigned long len)
02591 {
02592    FILE *output;
02593 
02594    output = fopen (filename, "w");
02595    if (fwrite(buffer, len, 1, output) != 1) {
02596       if (ferror(output)) {
02597          ast_log(LOG_ERROR, "Short write while writing e-mail body: %s.\n", strerror(errno));
02598       }
02599    }
02600    fclose (output);
02601 }
02602 
02603 static void update_messages_by_imapuser(const char *user, unsigned long number)
02604 {
02605    struct vm_state *vms = get_vm_state_by_imapuser(user, 1);
02606 
02607    if (!vms && !(vms = get_vm_state_by_imapuser(user, 0))) {
02608       return;
02609    }
02610 
02611    ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vms->vmArrayIndex, vms->interactive);
02612    vms->msgArray[vms->vmArrayIndex++] = number;
02613 }
02614 
02615 void mm_searched(MAILSTREAM *stream, unsigned long number)
02616 {
02617    char *mailbox = stream->mailbox, buf[1024] = "", *user;
02618 
02619    if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
02620       return;
02621 
02622    update_messages_by_imapuser(user, number);
02623 }
02624 
02625 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
02626 {
02627    struct ast_variable *var;
02628    struct ast_vm_user *vmu;
02629 
02630    vmu = ast_calloc(1, sizeof *vmu);
02631    if (!vmu)
02632       return NULL;
02633    ast_set_flag(vmu, VM_ALLOCED);
02634    populate_defaults(vmu);
02635 
02636    var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
02637    if (var) {
02638       apply_options_full(vmu, var);
02639       ast_variables_destroy(var);
02640       return vmu;
02641    } else {
02642       ast_free(vmu);
02643       return NULL;
02644    }
02645 }
02646 
02647 /* Interfaces to C-client */
02648 
02649 void mm_exists(MAILSTREAM * stream, unsigned long number)
02650 {
02651    /* mail_ping will callback here if new mail! */
02652    ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
02653    if (number == 0) return;
02654    set_update(stream);
02655 }
02656 
02657 
02658 void mm_expunged(MAILSTREAM * stream, unsigned long number)
02659 {
02660    /* mail_ping will callback here if expunged mail! */
02661    ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
02662    if (number == 0) return;
02663    set_update(stream);
02664 }
02665 
02666 
02667 void mm_flags(MAILSTREAM * stream, unsigned long number)
02668 {
02669    /* mail_ping will callback here if read mail! */
02670    ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
02671    if (number == 0) return;
02672    set_update(stream);
02673 }
02674 
02675 
02676 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
02677 {
02678    ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
02679    mm_log (string, errflg);
02680 }
02681 
02682 
02683 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
02684 {
02685    if (delimiter == '\0') {
02686       delimiter = delim;
02687    }
02688 
02689    ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
02690    if (attributes & LATT_NOINFERIORS)
02691       ast_debug(5, "no inferiors\n");
02692    if (attributes & LATT_NOSELECT)
02693       ast_debug(5, "no select\n");
02694    if (attributes & LATT_MARKED)
02695       ast_debug(5, "marked\n");
02696    if (attributes & LATT_UNMARKED)
02697       ast_debug(5, "unmarked\n");
02698 }
02699 
02700 
02701 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
02702 {
02703    ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
02704    if (attributes & LATT_NOINFERIORS)
02705       ast_debug(5, "no inferiors\n");
02706    if (attributes & LATT_NOSELECT)
02707       ast_debug(5, "no select\n");
02708    if (attributes & LATT_MARKED)
02709       ast_debug(5, "marked\n");
02710    if (attributes & LATT_UNMARKED)
02711       ast_debug(5, "unmarked\n");
02712 }
02713 
02714 
02715 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
02716 {
02717    ast_log(AST_LOG_NOTICE, " Mailbox %s", mailbox);
02718    if (status->flags & SA_MESSAGES)
02719       ast_log(AST_LOG_NOTICE, ", %lu messages", status->messages);
02720    if (status->flags & SA_RECENT)
02721       ast_log(AST_LOG_NOTICE, ", %lu recent", status->recent);
02722    if (status->flags & SA_UNSEEN)
02723       ast_log(AST_LOG_NOTICE, ", %lu unseen", status->unseen);
02724    if (status->flags & SA_UIDVALIDITY)
02725       ast_log(AST_LOG_NOTICE, ", %lu UID validity", status->uidvalidity);
02726    if (status->flags & SA_UIDNEXT)
02727       ast_log(AST_LOG_NOTICE, ", %lu next UID", status->uidnext);
02728    ast_log(AST_LOG_NOTICE, "\n");
02729 }
02730 
02731 
02732 void mm_log(char *string, long errflg)
02733 {
02734    switch ((short) errflg) {
02735       case NIL:
02736          ast_debug(1, "IMAP Info: %s\n", string);
02737          break;
02738       case PARSE:
02739       case WARN:
02740          ast_log(AST_LOG_WARNING, "IMAP Warning: %s\n", string);
02741          break;
02742       case ERROR:
02743          ast_log(AST_LOG_ERROR, "IMAP Error: %s\n", string);
02744          break;
02745    }
02746 }
02747 
02748 
02749 void mm_dlog(char *string)
02750 {
02751    ast_log(AST_LOG_NOTICE, "%s\n", string);
02752 }
02753 
02754 
02755 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
02756 {
02757    struct ast_vm_user *vmu;
02758 
02759    ast_debug(4, "Entering callback mm_login\n");
02760 
02761    ast_copy_string(user, mb->user, MAILTMPLEN);
02762 
02763    /* We should only do this when necessary */
02764    if (!ast_strlen_zero(authpassword)) {
02765       ast_copy_string(pwd, authpassword, MAILTMPLEN);
02766    } else {
02767       AST_LIST_TRAVERSE(&users, vmu, list) {
02768          if (!strcasecmp(mb->user, vmu->imapuser)) {
02769             ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
02770             break;
02771          }
02772       }
02773       if (!vmu) {
02774          if ((vmu = find_user_realtime_imapuser(mb->user))) {
02775             ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
02776             free_user(vmu);
02777          }
02778       }
02779    }
02780 }
02781 
02782 
02783 void mm_critical(MAILSTREAM * stream)
02784 {
02785 }
02786 
02787 
02788 void mm_nocritical(MAILSTREAM * stream)
02789 {
02790 }
02791 
02792 
02793 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
02794 {
02795    kill (getpid (), SIGSTOP);
02796    return NIL;
02797 }
02798 
02799 
02800 void mm_fatal(char *string)
02801 {
02802    ast_log(AST_LOG_ERROR, "IMAP access FATAL error: %s\n", string);
02803 }
02804 
02805 /* C-client callback to handle quota */
02806 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
02807 {
02808    struct vm_state *vms;
02809    char *mailbox = stream->mailbox, *user;
02810    char buf[1024] = "";
02811    unsigned long usage = 0, limit = 0;
02812    
02813    while (pquota) {
02814       usage = pquota->usage;
02815       limit = pquota->limit;
02816       pquota = pquota->next;
02817    }
02818    
02819    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)))) {
02820       ast_log(AST_LOG_ERROR, "No state found.\n");
02821       return;
02822    }
02823 
02824    ast_debug(3, "User %s usage is %lu, limit is %lu\n", user, usage, limit);
02825 
02826    vms->quota_usage = usage;
02827    vms->quota_limit = limit;
02828 }
02829 
02830 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len)
02831 {
02832    char *start, *eol_pnt;
02833    int taglen;
02834 
02835    if (ast_strlen_zero(header) || ast_strlen_zero(tag))
02836       return NULL;
02837 
02838    taglen = strlen(tag) + 1;
02839    if (taglen < 1)
02840       return NULL;
02841 
02842    if (!(start = strstr(header, tag)))
02843       return NULL;
02844 
02845    /* Since we can be called multiple times we should clear our buffer */
02846    memset(buf, 0, len);
02847 
02848    ast_copy_string(buf, start+taglen, len);
02849    if ((eol_pnt = strchr(buf,'\r')) || (eol_pnt = strchr(buf,'\n')))
02850       *eol_pnt = '\0';
02851    return buf;
02852 }
02853 
02854 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len)
02855 {
02856    char *start, *quote, *eol_pnt;
02857 
02858    if (ast_strlen_zero(mailbox))
02859       return NULL;
02860 
02861    if (!(start = strstr(mailbox, "/user=")))
02862       return NULL;
02863 
02864    ast_copy_string(buf, start+6, len);
02865 
02866    if (!(quote = strchr(buf, '\"'))) {
02867       if (!(eol_pnt = strchr(buf, '/')))
02868          eol_pnt = strchr(buf,'}');
02869       *eol_pnt = '\0';
02870       return buf;
02871    } else {
02872       eol_pnt = strchr(buf+1,'\"');
02873       *eol_pnt = '\0';
02874       return buf+1;
02875    }
02876 }
02877 
02878 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
02879 {
02880    struct vm_state *vms_p;
02881 
02882    pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
02883    if ((vms_p = pthread_getspecific(ts_vmstate.key)) && !strcmp(vms_p->imapuser, vmu->imapuser) && !strcmp(vms_p->username, vmu->mailbox)) {
02884       return vms_p;
02885    }
02886    if (option_debug > 4)
02887       ast_log(AST_LOG_DEBUG, "Adding new vmstate for %s\n", vmu->imapuser);
02888    if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
02889       return NULL;
02890    ast_copy_string(vms_p->imapuser, vmu->imapuser, sizeof(vms_p->imapuser));
02891    ast_copy_string(vms_p->imapfolder, vmu->imapfolder, sizeof(vms_p->imapfolder));
02892    ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
02893    ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
02894    vms_p->mailstream = NIL; /* save for access from interactive entry point */
02895    vms_p->imapversion = vmu->imapversion;
02896    if (option_debug > 4)
02897       ast_log(AST_LOG_DEBUG, "Copied %s to %s\n", vmu->imapuser, vms_p->imapuser);
02898    vms_p->updated = 1;
02899    /* set mailbox to INBOX! */
02900    ast_copy_string(vms_p->curbox, mbox(vmu, 0), sizeof(vms_p->curbox));
02901    init_vm_state(vms_p);
02902    vmstate_insert(vms_p);
02903    return vms_p;
02904 }
02905 
02906 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive)
02907 {
02908    struct vmstate *vlist = NULL;
02909 
02910    if (interactive) {
02911       struct vm_state *vms;
02912       pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
02913       vms = pthread_getspecific(ts_vmstate.key);
02914       return vms;
02915    }
02916 
02917    AST_LIST_LOCK(&vmstates);
02918    AST_LIST_TRAVERSE(&vmstates, vlist, list) {
02919       if (!vlist->vms) {
02920          ast_debug(3, "error: vms is NULL for %s\n", user);
02921          continue;
02922       }
02923       if (vlist->vms->imapversion != imapversion) {
02924          continue;
02925       }
02926       if (!vlist->vms->imapuser) {
02927          ast_debug(3, "error: imapuser is NULL for %s\n", user);
02928          continue;
02929       }
02930 
02931       if (!strcmp(vlist->vms->imapuser, user) && (interactive == 2 || vlist->vms->interactive == interactive)) {
02932          AST_LIST_UNLOCK(&vmstates);
02933          return vlist->vms;
02934       }
02935    }
02936    AST_LIST_UNLOCK(&vmstates);
02937 
02938    ast_debug(3, "%s not found in vmstates\n", user);
02939 
02940    return NULL;
02941 }
02942 
02943 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
02944 {
02945 
02946    struct vmstate *vlist = NULL;
02947    const char *local_context = S_OR(context, "default");
02948 
02949    if (interactive) {
02950       struct vm_state *vms;
02951       pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
02952       vms = pthread_getspecific(ts_vmstate.key);
02953       return vms;
02954    }
02955 
02956    AST_LIST_LOCK(&vmstates);
02957    AST_LIST_TRAVERSE(&vmstates, vlist, list) {
02958       if (!vlist->vms) {
02959          ast_debug(3, "error: vms is NULL for %s\n", mailbox);
02960          continue;
02961       }
02962       if (vlist->vms->imapversion != imapversion) {
02963          continue;
02964       }
02965       if (!vlist->vms->username || !vlist->vms->context) {
02966          ast_debug(3, "error: username is NULL for %s\n", mailbox);
02967          continue;
02968       }
02969 
02970       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);
02971       
02972       if (!strcmp(vlist->vms->username, mailbox) && !strcmp(vlist->vms->context, local_context) && vlist->vms->interactive == interactive) {
02973          ast_debug(3, "Found it!\n");
02974          AST_LIST_UNLOCK(&vmstates);
02975          return vlist->vms;
02976       }
02977    }
02978    AST_LIST_UNLOCK(&vmstates);
02979 
02980    ast_debug(3, "%s not found in vmstates\n", mailbox);
02981 
02982    return NULL;
02983 }
02984 
02985 static void vmstate_insert(struct vm_state *vms) 
02986 {
02987    struct vmstate *v;
02988    struct vm_state *altvms;
02989 
02990    /* If interactive, it probably already exists, and we should
02991       use the one we already have since it is more up to date.
02992       We can compare the username to find the duplicate */
02993    if (vms->interactive == 1) {
02994       altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
02995       if (altvms) {  
02996          ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
02997          vms->newmessages = altvms->newmessages;
02998          vms->oldmessages = altvms->oldmessages;
02999          vms->vmArrayIndex = altvms->vmArrayIndex;
03000          vms->lastmsg = altvms->lastmsg;
03001          vms->curmsg = altvms->curmsg;
03002          /* get a pointer to the persistent store */
03003          vms->persist_vms = altvms;
03004          /* Reuse the mailstream? */
03005 #ifdef REALLY_FAST_EVEN_IF_IT_MEANS_RESOURCE_LEAKS
03006          vms->mailstream = altvms->mailstream;
03007 #else
03008          vms->mailstream = NIL;
03009 #endif
03010       }
03011       return;
03012    }
03013 
03014    if (!(v = ast_calloc(1, sizeof(*v))))
03015       return;
03016    
03017    v->vms = vms;
03018 
03019    ast_debug(3, "Inserting vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
03020 
03021    AST_LIST_LOCK(&vmstates);
03022    AST_LIST_INSERT_TAIL(&vmstates, v, list);
03023    AST_LIST_UNLOCK(&vmstates);
03024 }
03025 
03026 static void vmstate_delete(struct vm_state *vms) 
03027 {
03028    struct vmstate *vc = NULL;
03029    struct vm_state *altvms = NULL;
03030 
03031    /* If interactive, we should copy pertinent info
03032       back to the persistent state (to make update immediate) */
03033    if (vms->interactive == 1 && (altvms = vms->persist_vms)) {
03034       ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
03035       altvms->newmessages = vms->newmessages;
03036       altvms->oldmessages = vms->oldmessages;
03037       altvms->updated = 1;
03038       vms->mailstream = mail_close(vms->mailstream);
03039 
03040       /* Interactive states are not stored within the persistent list */
03041       return;
03042    }
03043    
03044    ast_debug(3, "Removing vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
03045    
03046    AST_LIST_LOCK(&vmstates);
03047    AST_LIST_TRAVERSE_SAFE_BEGIN(&vmstates, vc, list) {
03048       if (vc->vms == vms) {
03049          AST_LIST_REMOVE_CURRENT(list);
03050          break;
03051       }
03052    }
03053    AST_LIST_TRAVERSE_SAFE_END
03054    AST_LIST_UNLOCK(&vmstates);
03055    
03056    if (vc) {
03057       ast_mutex_destroy(&vc->vms->lock);
03058       ast_free(vc);
03059    }
03060    else
03061       ast_log(AST_LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n", vms->imapuser, vms->username);
03062 }
03063 
03064 static void set_update(MAILSTREAM * stream) 
03065 {
03066    struct vm_state *vms;
03067    char *mailbox = stream->mailbox, *user;
03068    char buf[1024] = "";
03069 
03070    if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || !(vms = get_vm_state_by_imapuser(user, 0))) {
03071       if (user && option_debug > 2)
03072          ast_log(AST_LOG_WARNING, "User %s mailbox not found for update.\n", user);
03073       return;
03074    }
03075 
03076    ast_debug(3, "User %s mailbox set for update.\n", user);
03077 
03078    vms->updated = 1; /* Set updated flag since mailbox changed */
03079 }
03080 
03081 static void init_vm_state(struct vm_state *vms) 
03082 {
03083    int x;
03084    vms->vmArrayIndex = 0;
03085    for (x = 0; x < VMSTATE_MAX_MSG_ARRAY; x++) {
03086       vms->msgArray[x] = 0;
03087    }
03088    ast_mutex_init(&vms->lock);
03089 }
03090 
03091 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro) 
03092 {
03093    char *body_content;
03094    char *body_decoded;
03095    char *fn = is_intro ? vms->introfn : vms->fn;
03096    unsigned long len;
03097    unsigned long newlen;
03098    char filename[256];
03099    
03100    if (!body || body == NIL)
03101       return -1;
03102 
03103    ast_mutex_lock(&vms->lock);
03104    body_content = mail_fetchbody(vms->mailstream, vms->msgArray[vms->curmsg], section, &len);
03105    ast_mutex_unlock(&vms->lock);
03106    if (body_content != NIL) {
03107       snprintf(filename, sizeof(filename), "%s.%s", fn, format);
03108       /* ast_debug(1,body_content); */
03109       body_decoded = rfc822_base64((unsigned char *) body_content, len, &newlen);
03110       /* If the body of the file is empty, return an error */
03111       if (!newlen) {
03112          return -1;
03113       }
03114       write_file(filename, (char *) body_decoded, newlen);
03115    } else {
03116       ast_debug(5, "Body of message is NULL.\n");
03117       return -1;
03118    }
03119    return 0;
03120 }
03121 
03122 /*! 
03123  * \brief Get delimiter via mm_list callback 
03124  * \param stream
03125  *
03126  * Determines the delimiter character that is used by the underlying IMAP based mail store.
03127  */
03128 /* MUTEX should already be held */
03129 static void get_mailbox_delimiter(MAILSTREAM *stream) {
03130    char tmp[50];
03131    snprintf(tmp, sizeof(tmp), "{%s}", imapserver);
03132    mail_list(stream, tmp, "*");
03133 }
03134 
03135 /*! 
03136  * \brief Check Quota for user 
03137  * \param vms a pointer to a vm_state struct, will use the mailstream property of this.
03138  * \param mailbox the mailbox to check the quota for.
03139  *
03140  * Calls imap_getquotaroot, which will populate its results into the vm_state vms input structure.
03141  */
03142 static void check_quota(struct vm_state *vms, char *mailbox) {
03143    ast_mutex_lock(&vms->lock);
03144    mail_parameters(NULL, SET_QUOTA, (void *) mm_parsequota);
03145    ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mailbox);
03146    if (vms && vms->mailstream != NULL) {
03147       imap_getquotaroot(vms->mailstream, mailbox);
03148    } else {
03149       ast_log(AST_LOG_WARNING, "Mailstream not available for mailbox: %s\n", mailbox);
03150    }
03151    ast_mutex_unlock(&vms->lock);
03152 }
03153 
03154 #endif /* IMAP_STORAGE */
03155 
03156 /*! \brief Lock file path
03157     only return failure if ast_lock_path returns 'timeout',
03158    not if the path does not exist or any other reason
03159 */
03160 static int vm_lock_path(const char *path)
03161 {
03162    switch (ast_lock_path(path)) {
03163    case AST_LOCK_TIMEOUT:
03164       return -1;
03165    default:
03166       return 0;
03167    }
03168 }
03169 
03170 
03171 #ifdef ODBC_STORAGE
03172 struct generic_prepare_struct {
03173    char *sql;
03174    int argc;
03175    char **argv;
03176 };
03177 
03178 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
03179 {
03180    struct generic_prepare_struct *gps = data;
03181    int res, i;
03182    SQLHSTMT stmt;
03183 
03184    res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
03185    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03186       ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
03187       return NULL;
03188    }
03189    res = SQLPrepare(stmt, (unsigned char *) gps->sql, SQL_NTS);
03190    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03191       ast_log(AST_LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
03192       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03193       return NULL;
03194    }
03195    for (i = 0; i < gps->argc; i++)
03196       SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
03197 
03198    return stmt;
03199 }
03200 
03201 /*!
03202  * \brief Retrieves a file from an ODBC data store.
03203  * \param dir the path to the file to be retreived.
03204  * \param msgnum the message number, such as within a mailbox folder.
03205  * 
03206  * This method is used by the RETRIEVE macro when mailboxes are stored in an ODBC back end.
03207  * 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.
03208  *
03209  * The file is looked up by invoking a SQL on the odbc_table (default 'voicemessages') using the dir and msgnum input parameters.
03210  * The output is the message information file with the name msgnum and the extension .txt
03211  * and the message file with the extension of its format, in the directory with base file name of the msgnum.
03212  * 
03213  * \return 0 on success, -1 on error.
03214  */
03215 static int retrieve_file(char *dir, int msgnum)
03216 {
03217    int x = 0;
03218    int res;
03219    int fd = -1;
03220    size_t fdlen = 0;
03221    void *fdm = MAP_FAILED;
03222    SQLSMALLINT colcount = 0;
03223    SQLHSTMT stmt;
03224    char sql[PATH_MAX];
03225    char fmt[80]="";
03226    char *c;
03227    char coltitle[256];
03228    SQLSMALLINT collen;
03229    SQLSMALLINT datatype;
03230    SQLSMALLINT decimaldigits;
03231    SQLSMALLINT nullable;
03232    SQLULEN colsize;
03233    SQLLEN colsize2;
03234    FILE *f = NULL;
03235    char rowdata[80];
03236    char fn[PATH_MAX];
03237    char full_fn[PATH_MAX];
03238    char msgnums[80];
03239    char *argv[] = { dir, msgnums };
03240    struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
03241 
03242    struct odbc_obj *obj;
03243    obj = ast_odbc_request_obj(odbc_database, 0);
03244    if (obj) {
03245       ast_copy_string(fmt, vmfmts, sizeof(fmt));
03246       c = strchr(fmt, '|');
03247       if (c)
03248          *c = '\0';
03249       if (!strcasecmp(fmt, "wav49"))
03250          strcpy(fmt, "WAV");
03251       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
03252       if (msgnum > -1)
03253          make_file(fn, sizeof(fn), dir, msgnum);
03254       else
03255          ast_copy_string(fn, dir, sizeof(fn));
03256 
03257       /* Create the information file */
03258       snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
03259       
03260       if (!(f = fopen(full_fn, "w+"))) {
03261          ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
03262          goto yuck;
03263       }
03264       
03265       snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
03266       snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?", odbc_table);
03267       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03268       if (!stmt) {
03269          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03270          ast_odbc_release_obj(obj);
03271          goto yuck;
03272       }
03273       res = SQLFetch(stmt);
03274       if (res == SQL_NO_DATA) {
03275          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03276          ast_odbc_release_obj(obj);
03277          goto yuck;
03278       } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03279          ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
03280          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03281          ast_odbc_release_obj(obj);
03282          goto yuck;
03283       }
03284       fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
03285       if (fd < 0) {
03286          ast_log(AST_LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
03287          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03288          ast_odbc_release_obj(obj);
03289          goto yuck;
03290       }
03291       res = SQLNumResultCols(stmt, &colcount);
03292       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {  
03293          ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
03294          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03295          ast_odbc_release_obj(obj);
03296          goto yuck;
03297       }
03298       if (f) 
03299          fprintf(f, "[message]\n");
03300       for (x = 0; x < colcount; x++) {
03301          rowdata[0] = '\0';
03302          collen = sizeof(coltitle);
03303          res = SQLDescribeCol(stmt, x + 1, (unsigned char *) coltitle, sizeof(coltitle), &collen, 
03304                   &datatype, &colsize, &decimaldigits, &nullable);
03305          if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03306             ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
03307             SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03308             ast_odbc_release_obj(obj);
03309             goto yuck;
03310          }
03311          if (!strcasecmp(coltitle, "recording")) {
03312             off_t offset;
03313             res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
03314             fdlen = colsize2;
03315             if (fd > -1) {
03316                char tmp[1]="";
03317                lseek(fd, fdlen - 1, SEEK_SET);
03318                if (write(fd, tmp, 1) != 1) {
03319                   close(fd);
03320                   fd = -1;
03321                   continue;
03322                }
03323                /* Read out in small chunks */
03324                for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
03325                   if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
03326                      ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
03327                      SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03328                      ast_odbc_release_obj(obj);
03329                      goto yuck;
03330                   } else {
03331                      res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
03332                      munmap(fdm, CHUNKSIZE);
03333                      if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03334                         ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
03335                         unlink(full_fn);
03336                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03337                         ast_odbc_release_obj(obj);
03338                         goto yuck;
03339                      }
03340                   }
03341                }
03342                if (truncate(full_fn, fdlen) < 0) {
03343                   ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
03344                }
03345             }
03346          } else {
03347             res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
03348             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03349                ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
03350                SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03351                ast_odbc_release_obj(obj);
03352                goto yuck;
03353             }
03354             if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
03355                fprintf(f, "%s=%s\n", coltitle, rowdata);
03356          }
03357       }
03358       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03359       ast_odbc_release_obj(obj);
03360    } else
03361       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03362 yuck: 
03363    if (f)
03364       fclose(f);
03365    if (fd > -1)
03366       close(fd);
03367    return x - 1;
03368 }
03369 
03370 /*!
03371  * \brief Determines the highest message number in use for a given user and mailbox folder.
03372  * \param vmu 
03373  * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
03374  *
03375  * This method is used when mailboxes are stored in an ODBC back end.
03376  * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
03377  *
03378  * \return the value of zero or greaterto indicate the last message index in use, -1 to indicate none.
03379  */
03380 static int last_message_index(struct ast_vm_user *vmu, char *dir)
03381 {
03382    int x = 0;
03383    int res;
03384    SQLHSTMT stmt;
03385    char sql[PATH_MAX];
03386    char rowdata[20];
03387    char *argv[] = { dir };
03388    struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
03389 
03390    struct odbc_obj *obj;
03391    obj = ast_odbc_request_obj(odbc_database, 0);
03392    if (obj) {
03393       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?", odbc_table);
03394       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03395       if (!stmt) {
03396          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03397          ast_odbc_release_obj(obj);
03398          goto yuck;
03399       }
03400       res = SQLFetch(stmt);
03401       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03402          ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
03403          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03404          ast_odbc_release_obj(obj);
03405          goto yuck;
03406       }
03407       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
03408       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03409          ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
03410          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03411          ast_odbc_release_obj(obj);
03412          goto yuck;
03413       }
03414       if (sscanf(rowdata, "%30d", &x) != 1)
03415          ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
03416       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03417       ast_odbc_release_obj(obj);
03418    } else
03419       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03420 yuck: 
03421    return x - 1;
03422 }
03423 
03424 /*!
03425  * \brief Determines if the specified message exists.
03426  * \param dir the folder the mailbox folder to look for messages. 
03427  * \param msgnum the message index to query for.
03428  *
03429  * This method is used when mailboxes are stored in an ODBC back end.
03430  *
03431  * \return greater than zero if the message exists, zero when the message does not exist or on error.
03432  */
03433 static int message_exists(char *dir, int msgnum)
03434 {
03435    int x = 0;
03436    int res;
03437    SQLHSTMT stmt;
03438    char sql[PATH_MAX];
03439    char rowdata[20];
03440    char msgnums[20];
03441    char *argv[] = { dir, msgnums };
03442    struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
03443 
03444    struct odbc_obj *obj;
03445    obj = ast_odbc_request_obj(odbc_database, 0);
03446    if (obj) {
03447       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
03448       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?", odbc_table);
03449       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03450       if (!stmt) {
03451          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03452          ast_odbc_release_obj(obj);
03453          goto yuck;
03454       }
03455       res = SQLFetch(stmt);
03456       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03457          ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
03458          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03459          ast_odbc_release_obj(obj);
03460          goto yuck;
03461       }
03462       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
03463       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03464          ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
03465          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03466          ast_odbc_release_obj(obj);
03467          goto yuck;
03468       }
03469       if (sscanf(rowdata, "%30d", &x) != 1)
03470          ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
03471       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03472       ast_odbc_release_obj(obj);
03473    } else
03474       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03475 yuck: 
03476    return x;
03477 }
03478 
03479 /*!
03480  * \brief returns the one-based count for messages.
03481  * \param vmu
03482  * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
03483  *
03484  * This method is used when mailboxes are stored in an ODBC back end.
03485  * The message index is zero-based, the first message will be index 0. For convenient display it is good to have the
03486  * one-based messages.
03487  * This method just calls last_message_index and returns +1 of its value.
03488  *
03489  * \return the value greater than zero on success to indicate the one-based count of messages, less than zero on error.
03490  */
03491 static int count_messages(struct ast_vm_user *vmu, char *dir)
03492 {
03493    return last_message_index(vmu, dir) + 1;
03494 }
03495 
03496 /*!
03497  * \brief Deletes a message from the mailbox folder.
03498  * \param sdir The mailbox folder to work in.
03499  * \param smsg The message index to be deleted.
03500  *
03501  * This method is used when mailboxes are stored in an ODBC back end.
03502  * The specified message is directly deleted from the database 'voicemessages' table.
03503  * 
03504  * \return the value greater than zero on success to indicate the number of messages, less than zero on error.
03505  */
03506 static void delete_file(const char *sdir, int smsg)
03507 {
03508    SQLHSTMT stmt;
03509    char sql[PATH_MAX];
03510    char msgnums[20];
03511    char *argv[] = { NULL, msgnums };
03512    struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
03513    struct odbc_obj *obj;
03514 
03515    argv[0] = ast_strdupa(sdir);
03516 
03517    obj = ast_odbc_request_obj(odbc_database, 0);
03518    if (obj) {
03519       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
03520       snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?", odbc_table);
03521       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03522       if (!stmt)
03523          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03524       else
03525          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03526       ast_odbc_release_obj(obj);
03527    } else
03528       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03529    return;  
03530 }
03531 
03532 /*!
03533  * \brief Copies a voicemail from one mailbox to another.
03534  * \param sdir the folder for which to look for the message to be copied.
03535  * \param smsg the index of the message to be copied.
03536  * \param ddir the destination folder to copy the message into.
03537  * \param dmsg the index to be used for the copied message.
03538  * \param dmailboxuser The user who owns the mailbox tha contains the destination folder.
03539  * \param dmailboxcontext The context for the destination user.
03540  *
03541  * This method is used for the COPY macro when mailboxes are stored in an ODBC back end.
03542  */
03543 static void copy_file(char *sdir, int smsg, char *ddir, int dmsg, char *dmailboxuser, char *dmailboxcontext)
03544 {
03545    SQLHSTMT stmt;
03546    char sql[512];
03547    char msgnums[20];
03548    char msgnumd[20];
03549    struct odbc_obj *obj;
03550    char *argv[] = { ddir, msgnumd, dmailboxuser, dmailboxcontext, sdir, msgnums };
03551    struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
03552 
03553    delete_file(ddir, dmsg);
03554    obj = ast_odbc_request_obj(odbc_database, 0);
03555    if (obj) {
03556       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
03557       snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
03558       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);
03559       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03560       if (!stmt)
03561          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
03562       else
03563          SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03564       ast_odbc_release_obj(obj);
03565    } else
03566       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03567    return;  
03568 }
03569 
03570 struct insert_data {
03571    char *sql;
03572    const char *dir;
03573    const char *msgnums;
03574    void *data;
03575    SQLLEN datalen;
03576    SQLLEN indlen;
03577    const char *context;
03578    const char *macrocontext;
03579    const char *callerid;
03580    const char *origtime;
03581    const char *duration;
03582    const char *mailboxuser;
03583    const char *mailboxcontext;
03584    const char *category;
03585    const char *flag;
03586 };
03587 
03588 static SQLHSTMT insert_data_cb(struct odbc_obj *obj, void *vdata)
03589 {
03590    struct insert_data *data = vdata;
03591    int res;
03592    SQLHSTMT stmt;
03593 
03594    res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
03595    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03596       ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
03597       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03598       return NULL;
03599    }
03600 
03601    SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->dir), 0, (void *) data->dir, 0, NULL);
03602    SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->msgnums), 0, (void *) data->msgnums, 0, NULL);
03603    SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, data->datalen, 0, (void *) data->data, data->datalen, &data->indlen);
03604    SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->context), 0, (void *) data->context, 0, NULL);
03605    SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->macrocontext), 0, (void *) data->macrocontext, 0, NULL);
03606    SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->callerid), 0, (void *) data->callerid, 0, NULL);
03607    SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->origtime), 0, (void *) data->origtime, 0, NULL);
03608    SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->duration), 0, (void *) data->duration, 0, NULL);
03609    SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxuser), 0, (void *) data->mailboxuser, 0, NULL);
03610    SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxcontext), 0, (void *) data->mailboxcontext, 0, NULL);
03611    SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->flag), 0, (void *) data->flag, 0, NULL);
03612    if (!ast_strlen_zero(data->category)) {
03613       SQLBindParameter(stmt, 12, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->category), 0, (void *) data->category, 0, NULL);
03614    }
03615    res = SQLExecDirect(stmt, (unsigned char *) data->sql, SQL_NTS);
03616    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03617       ast_log(AST_LOG_WARNING, "SQL Direct Execute failed!\n");
03618       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03619       return NULL;
03620    }
03621 
03622    return stmt;
03623 }
03624 
03625 /*!
03626  * \brief Stores a voicemail into the database.
03627  * \param dir the folder the mailbox folder to store the message.
03628  * \param mailboxuser the user owning the mailbox folder.
03629  * \param mailboxcontext
03630  * \param msgnum the message index for the message to be stored.
03631  *
03632  * This method is used when mailboxes are stored in an ODBC back end.
03633  * The message sound file and information file is looked up on the file system. 
03634  * A SQL query is invoked to store the message into the (MySQL) database.
03635  *
03636  * \return the zero on success -1 on error.
03637  */
03638 static int store_file(const char *dir, const char *mailboxuser, const char *mailboxcontext, int msgnum)
03639 {
03640    int res = 0;
03641    int fd = -1;
03642    void *fdm = MAP_FAILED;
03643    size_t fdlen = -1;
03644    SQLHSTMT stmt;
03645    char sql[PATH_MAX];
03646    char msgnums[20];
03647    char fn[PATH_MAX];
03648    char full_fn[PATH_MAX];
03649    char fmt[80]="";
03650    char *c;
03651    struct ast_config *cfg = NULL;
03652    struct odbc_obj *obj;
03653    struct insert_data idata = { .sql = sql, .msgnums = msgnums, .dir = dir, .mailboxuser = mailboxuser, .mailboxcontext = mailboxcontext,
03654       .context = "", .macrocontext = "", .callerid = "", .origtime = "", .duration = "", .category = "", .flag = "" };
03655    struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
03656 
03657    delete_file(dir, msgnum);
03658    if (!(obj = ast_odbc_request_obj(odbc_database, 0))) {
03659       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03660       return -1;
03661    }
03662 
03663    do {
03664       ast_copy_string(fmt, vmfmts, sizeof(fmt));
03665       c = strchr(fmt, '|');
03666       if (c)
03667          *c = '\0';
03668       if (!strcasecmp(fmt, "wav49"))
03669          strcpy(fmt, "WAV");
03670       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
03671       if (msgnum > -1)
03672          make_file(fn, sizeof(fn), dir, msgnum);
03673       else
03674          ast_copy_string(fn, dir, sizeof(fn));
03675       snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
03676       cfg = ast_config_load(full_fn, config_flags);
03677       snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
03678       fd = open(full_fn, O_RDWR);
03679       if (fd < 0) {
03680          ast_log(AST_LOG_WARNING, "Open of sound file '%s' failed: %s\n", full_fn, strerror(errno));
03681          res = -1;
03682          break;
03683       }
03684       if (cfg && cfg != CONFIG_STATUS_FILEINVALID) {
03685          if (!(idata.context = ast_variable_retrieve(cfg, "message", "context"))) {
03686             idata.context = "";
03687          }
03688          if (!(idata.macrocontext = ast_variable_retrieve(cfg, "message", "macrocontext"))) {
03689             idata.macrocontext = "";
03690          }
03691          if (!(idata.callerid = ast_variable_retrieve(cfg, "message", "callerid"))) {
03692             idata.callerid = "";
03693          }
03694          if (!(idata.origtime = ast_variable_retrieve(cfg, "message", "origtime"))) {
03695             idata.origtime = "";
03696          }
03697          if (!(idata.duration = ast_variable_retrieve(cfg, "message", "duration"))) {
03698             idata.duration = "";
03699          }
03700          if (!(idata.category = ast_variable_retrieve(cfg, "message", "category"))) {
03701             idata.category = "";
03702          }
03703          if (!(idata.flag = ast_variable_retrieve(cfg, "message", "flag"))) {
03704             idata.flag = "";
03705          }
03706       }
03707       fdlen = lseek(fd, 0, SEEK_END);
03708       lseek(fd, 0, SEEK_SET);
03709       printf("Length is %zd\n", fdlen);
03710       fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
03711       if (fdm == MAP_FAILED) {
03712          ast_log(AST_LOG_WARNING, "Memory map failed!\n");
03713          res = -1;
03714          break;
03715       } 
03716       idata.data = fdm;
03717       idata.datalen = idata.indlen = fdlen;
03718 
03719       if (!ast_strlen_zero(idata.category)) 
03720          snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag,category) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", odbc_table); 
03721       else
03722          snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag) VALUES (?,?,?,?,?,?,?,?,?,?,?)", odbc_table);
03723 
03724       if ((stmt = ast_odbc_direct_execute(obj, insert_data_cb, &idata))) {
03725          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03726       } else {
03727          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03728          res = -1;
03729       }
03730    } while (0);
03731    if (obj) {
03732       ast_odbc_release_obj(obj);
03733    }
03734    if (cfg)
03735       ast_config_destroy(cfg);
03736    if (fdm != MAP_FAILED)
03737       munmap(fdm, fdlen);
03738    if (fd > -1)
03739       close(fd);
03740    return res;
03741 }
03742 
03743 /*!
03744  * \brief Renames a message in a mailbox folder.
03745  * \param sdir The folder of the message to be renamed.
03746  * \param smsg The index of the message to be renamed.
03747  * \param mailboxuser The user to become the owner of the message after it is renamed. Usually this will be the same as the original owner.
03748  * \param mailboxcontext The context to be set for the message. Usually this will be the same as the original context.
03749  * \param ddir The destination folder for the message to be renamed into
03750  * \param dmsg The destination message for the message to be renamed.
03751  *
03752  * This method is used by the RENAME macro when mailboxes are stored in an ODBC back end.
03753  * The is usually used to resequence the messages in the mailbox, such as to delete messag index 0, it would be called successively to slide all the other messages down one index.
03754  * But in theory, because the SQL query performs an update on (dir, msgnum, mailboxuser, mailboxcontext) in the database, it should be possible to have the message relocated to another mailbox or context as well.
03755  */
03756 static void rename_file(char *sdir, int smsg, char *mailboxuser, char *mailboxcontext, char *ddir, int dmsg)
03757 {
03758    SQLHSTMT stmt;
03759    char sql[PATH_MAX];
03760    char msgnums[20];
03761    char msgnumd[20];
03762    struct odbc_obj *obj;
03763    char *argv[] = { ddir, msgnumd, mailboxuser, mailboxcontext, sdir, msgnums };
03764    struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
03765 
03766    delete_file(ddir, dmsg);
03767    obj = ast_odbc_request_obj(odbc_database, 0);
03768    if (obj) {
03769       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
03770       snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
03771       snprintf(sql, sizeof(sql), "UPDATE %s SET dir=?, msgnum=?, mailboxuser=?, mailboxcontext=? WHERE dir=? AND msgnum=?", odbc_table);
03772       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03773       if (!stmt)
03774          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03775       else
03776          SQLFreeHandle(SQL_HANDLE_STMT, stmt);
03777       ast_odbc_release_obj(obj);
03778    } else
03779       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03780    return;  
03781 }
03782 
03783 /*!
03784  * \brief Removes a voicemail message file.
03785  * \param dir the path to the message file.
03786  * \param msgnum the unique number for the message within the mailbox.
03787  *
03788  * Removes the message content file and the information file.
03789  * This method is used by the DISPOSE macro when mailboxes are stored in an ODBC back end.
03790  * Typical use is to clean up after a RETRIEVE operation. 
03791  * Note that this does not remove the message from the mailbox folders, to do that we would use delete_file().
03792  * \return zero on success, -1 on error.
03793  */
03794 static int remove_file(char *dir, int msgnum)
03795 {
03796    char fn[PATH_MAX];
03797    char full_fn[PATH_MAX];
03798    char msgnums[80];
03799    
03800    if (msgnum > -1) {
03801       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
03802       make_file(fn, sizeof(fn), dir, msgnum);
03803    } else
03804       ast_copy_string(fn, dir, sizeof(fn));
03805    ast_filedelete(fn, NULL);  
03806    snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
03807    unlink(full_fn);
03808    return 0;
03809 }
03810 #else
03811 #ifndef IMAP_STORAGE
03812 /*!
03813  * \brief Find all .txt files - even if they are not in sequence from 0000.
03814  * \param vmu
03815  * \param dir
03816  *
03817  * This method is used when mailboxes are stored on the filesystem. (not ODBC and not IMAP).
03818  *
03819  * \return the count of messages, zero or more.
03820  */
03821 static int count_messages(struct ast_vm_user *vmu, char *dir)
03822 {
03823 
03824    int vmcount = 0;
03825    DIR *vmdir = NULL;
03826    struct dirent *vment = NULL;
03827 
03828    if (vm_lock_path(dir))
03829       return ERROR_LOCK_PATH;
03830 
03831    if ((vmdir = opendir(dir))) {
03832       while ((vment = readdir(vmdir))) {
03833          if (strlen(vment->d_name) > 7 && !strncmp(vment->d_name + 7, ".txt", 4)) {
03834             vmcount++;
03835          }
03836       }
03837       closedir(vmdir);
03838    }
03839    ast_unlock_path(dir);
03840    
03841    return vmcount;
03842 }
03843 
03844 /*!
03845  * \brief Renames a message in a mailbox folder.
03846  * \param sfn The path to the mailbox information and data file to be renamed.
03847  * \param dfn The path for where the message data and information files will be renamed to.
03848  *
03849  * This method is used by the RENAME macro when mailboxes are stored on the filesystem. (not ODBC and not IMAP).
03850  */
03851 static void rename_file(char *sfn, char *dfn)
03852 {
03853    char stxt[PATH_MAX];
03854    char dtxt[PATH_MAX];
03855    ast_filerename(sfn, dfn, NULL);
03856    snprintf(stxt, sizeof(stxt), "%s.txt", sfn);
03857    snprintf(dtxt, sizeof(dtxt), "%s.txt", dfn);
03858    if (ast_check_realtime("voicemail_data")) {
03859       ast_update_realtime("voicemail_data", "filename", sfn, "filename", dfn, SENTINEL);
03860    }
03861    rename(stxt, dtxt);
03862 }
03863 
03864 /*! 
03865  * \brief Determines the highest message number in use for a given user and mailbox folder.
03866  * \param vmu 
03867  * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
03868  *
03869  * This method is used when mailboxes are stored on the filesystem. (not ODBC and not IMAP).
03870  * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
03871  *
03872  * \note Should always be called with a lock already set on dir.
03873  * \return the value of zero or greaterto indicate the last message index in use, -1 to indicate none.
03874  */
03875 static int last_message_index(struct ast_vm_user *vmu, char *dir)
03876 {
03877    int x;
03878    unsigned char map[MAXMSGLIMIT] = "";
03879    DIR *msgdir;
03880    struct dirent *msgdirent;
03881    int msgdirint;
03882 
03883    /* Reading the entire directory into a file map scales better than
03884     * doing a stat repeatedly on a predicted sequence.  I suspect this
03885     * is partially due to stat(2) internally doing a readdir(2) itself to
03886     * find each file. */
03887    if (!(msgdir = opendir(dir))) {
03888       return -1;
03889    }
03890 
03891    while ((msgdirent = readdir(msgdir))) {
03892       if (sscanf(msgdirent->d_name, "msg%30d", &msgdirint) == 1 && msgdirint < MAXMSGLIMIT)
03893          map[msgdirint] = 1;
03894    }
03895    closedir(msgdir);
03896 
03897    for (x = 0; x < vmu->maxmsg; x++) {
03898       if (map[x] == 0)
03899          break;
03900    }
03901 
03902    return x - 1;
03903 }
03904 
03905 #endif /* #ifndef IMAP_STORAGE */
03906 #endif /* #else of #ifdef ODBC_STORAGE */
03907 #ifndef IMAP_STORAGE
03908 /*!
03909  * \brief Utility function to copy a file.
03910  * \param infile The path to the file to be copied. The file must be readable, it is opened in read only mode.
03911  * \param outfile The path for which to copy the file to. The directory permissions must allow the creation (or truncation) of the file, and allow for opening the file in write only mode.
03912  *
03913  * When the compiler option HARDLINK_WHEN_POSSIBLE is set, the copy operation will attempt to use the hard link facility instead of copy the file (to save disk space). If the link operation fails, it falls back to the copy operation.
03914  * The copy operation copies up to 4096 bytes at once.
03915  *
03916  * \return zero on success, -1 on error.
03917  */
03918 static int copy(char *infile, char *outfile)
03919 {
03920    int ifd;
03921    int ofd;
03922    int res;
03923    int len;
03924    char buf[4096];
03925 
03926 #ifdef HARDLINK_WHEN_POSSIBLE
03927    /* Hard link if possible; saves disk space & is faster */
03928    if (link(infile, outfile)) {
03929 #endif
03930       if ((ifd = open(infile, O_RDONLY)) < 0) {
03931          ast_log(AST_LOG_WARNING, "Unable to open %s in read-only mode: %s\n", infile, strerror(errno));
03932          return -1;
03933       }
03934       if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, VOICEMAIL_FILE_MODE)) < 0) {
03935          ast_log(AST_LOG_WARNING, "Unable to open %s in write-only mode: %s\n", outfile, strerror(errno));
03936          close(ifd);
03937          return -1;
03938       }
03939       do {
03940          len = read(ifd, buf, sizeof(buf));
03941          if (len < 0) {
03942             ast_log(AST_LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
03943             close(ifd);
03944             close(ofd);
03945             unlink(outfile);
03946          }
03947          if (len) {
03948             res = write(ofd, buf, len);
03949             if (errno == ENOMEM || errno == ENOSPC || res != len) {
03950                ast_log(AST_LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
03951                close(ifd);
03952                close(ofd);
03953                unlink(outfile);
03954             }
03955          }
03956       } while (len);
03957       close(ifd);
03958       close(ofd);
03959       return 0;
03960 #ifdef HARDLINK_WHEN_POSSIBLE
03961    } else {
03962       /* Hard link succeeded */
03963       return 0;
03964    }
03965 #endif
03966 }
03967 
03968 /*!
03969  * \brief Copies a voicemail information (envelope) file.
03970  * \param frompath
03971  * \param topath 
03972  *
03973  * Every voicemail has the data (.wav) file, and the information file.
03974  * This function performs the file system copying of the information file for a voicemail, handling the internal fields and their values.
03975  * This is used by the COPY macro when not using IMAP storage.
03976  */
03977 static void copy_plain_file(char *frompath, char *topath)
03978 {
03979    char frompath2[PATH_MAX], topath2[PATH_MAX];
03980    struct ast_variable *tmp,*var = NULL;
03981    const char *origmailbox = NULL, *context = NULL, *macrocontext = NULL, *exten = NULL, *priority = NULL, *callerchan = NULL, *callerid = NULL, *origdate = NULL, *origtime = NULL, *category = NULL, *duration = NULL;
03982    ast_filecopy(frompath, topath, NULL);
03983    snprintf(frompath2, sizeof(frompath2), "%s.txt", frompath);
03984    snprintf(topath2, sizeof(topath2), "%s.txt", topath);
03985    if (ast_check_realtime("voicemail_data")) {
03986       var = ast_load_realtime("voicemail_data", "filename", frompath, SENTINEL);
03987       /* This cycle converts ast_variable linked list, to va_list list of arguments, may be there is a better way to do it? */
03988       for (tmp = var; tmp; tmp = tmp->next) {
03989          if (!strcasecmp(tmp->name, "origmailbox")) {
03990             origmailbox = tmp->value;
03991          } else if (!strcasecmp(tmp->name, "context")) {
03992             context = tmp->value;
03993          } else if (!strcasecmp(tmp->name, "macrocontext")) {
03994             macrocontext = tmp->value;
03995          } else if (!strcasecmp(tmp->name, "exten")) {
03996             exten = tmp->value;
03997          } else if (!strcasecmp(tmp->name, "priority")) {
03998             priority = tmp->value;
03999          } else if (!strcasecmp(tmp->name, "callerchan")) {
04000             callerchan = tmp->value;
04001          } else if (!strcasecmp(tmp->name, "callerid")) {
04002             callerid = tmp->value;
04003          } else if (!strcasecmp(tmp->name, "origdate")) {
04004             origdate = tmp->value;
04005          } else if (!strcasecmp(tmp->name, "origtime")) {
04006             origtime = tmp->value;
04007          } else if (!strcasecmp(tmp->name, "category")) {
04008             category = tmp->value;
04009          } else if (!strcasecmp(tmp->name, "duration")) {
04010             duration = tmp->value;
04011          }
04012       }
04013       ast_store_realtime("voicemail_data", "filename", topath, "origmailbox", origmailbox, "context", context, "macrocontext", macrocontext, "exten", exten, "priority", priority, "callerchan", callerchan, "callerid", callerid, "origdate", origdate, "origtime", origtime, "category", category, "duration", duration, SENTINEL);
04014    }
04015    copy(frompath2, topath2);
04016    ast_variables_destroy(var);
04017 }
04018 #endif
04019 
04020 /*! 
04021  * \brief Removes the voicemail sound and information file.
04022  * \param file The path to the sound file. This will be the the folder and message index, without the extension.
04023  *
04024  * This is used by the DELETE macro when voicemails are stored on the file system.
04025  *
04026  * \return zero on success, -1 on error.
04027  */
04028 static int vm_delete(char *file)
04029 {
04030    char *txt;
04031    int txtsize = 0;
04032 
04033    txtsize = (strlen(file) + 5)*sizeof(char);
04034    txt = alloca(txtsize);
04035    /* Sprintf here would safe because we alloca'd exactly the right length,
04036     * but trying to eliminate all sprintf's anyhow
04037     */
04038    if (ast_check_realtime("voicemail_data")) {
04039       ast_destroy_realtime("voicemail_data", "filename", file, SENTINEL);
04040    }
04041    snprintf(txt, txtsize, "%s.txt", file);
04042    unlink(txt);
04043    return ast_filedelete(file, NULL);
04044 }
04045 
04046 /*!
04047  * \brief utility used by inchar(), for base_encode()
04048  */
04049 static int inbuf(struct baseio *bio, FILE *fi)
04050 {
04051    int l;
04052 
04053    if (bio->ateof)
04054       return 0;
04055 
04056    if ((l = fread(bio->iobuf, 1, BASEMAXINLINE, fi)) <= 0) {
04057       if (ferror(fi))
04058          return -1;
04059 
04060       bio->ateof = 1;
04061       return 0;
04062    }
04063 
04064    bio->iolen = l;
04065    bio->iocp = 0;
04066 
04067    return 1;
04068 }
04069 
04070 /*!
04071  * \brief utility used by base_encode()
04072  */
04073 static int inchar(struct baseio *bio, FILE *fi)
04074 {
04075    if (bio->iocp>=bio->iolen) {
04076       if (!inbuf(bio, fi))
04077          return EOF;
04078    }
04079 
04080    return bio->iobuf[bio->iocp++];
04081 }
04082 
04083 /*!
04084  * \brief utility used by base_encode()
04085  */
04086 static int ochar(struct baseio *bio, int c, FILE *so)
04087 {
04088    if (bio->linelength >= BASELINELEN) {
04089       if (fputs(ENDL, so) == EOF) {
04090          return -1;
04091       }
04092 
04093       bio->linelength = 0;
04094    }
04095 
04096    if (putc(((unsigned char) c), so) == EOF) {
04097       return -1;
04098    }
04099 
04100    bio->linelength++;
04101 
04102    return 1;
04103 }
04104 
04105 /*!
04106  * \brief Performs a base 64 encode algorithm on the contents of a File
04107  * \param filename The path to the file to be encoded. Must be readable, file is opened in read mode.
04108  * \param so A FILE handle to the output file to receive the base 64 encoded contents of the input file, identified by filename.
04109  *
04110  * TODO: shouldn't this (and the above 3 support functions) be put into some kind of external utility location, such as funcs/func_base64.c ?
04111  *
04112  * \return zero on success, -1 on error.
04113  */
04114 static int base_encode(char *filename, FILE *so)
04115 {
04116    static const unsigned char dtable[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
04117       'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
04118       'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
04119       '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
04120    int i, hiteof = 0;
04121    FILE *fi;
04122    struct baseio bio;
04123 
04124    memset(&bio, 0, sizeof(bio));
04125    bio.iocp = BASEMAXINLINE;
04126 
04127    if (!(fi = fopen(filename, "rb"))) {
04128       ast_log(AST_LOG_WARNING, "Failed to open file: %s: %s\n", filename, strerror(errno));
04129       return -1;
04130    }
04131 
04132    while (!hiteof){
04133       unsigned char igroup[3], ogroup[4];
04134       int c, n;
04135 
04136       memset(igroup, 0, sizeof(igroup));
04137 
04138       for (n = 0; n < 3; n++) {
04139          if ((c = inchar(&bio, fi)) == EOF) {
04140             hiteof = 1;
04141             break;
04142          }
04143 
04144          igroup[n] = (unsigned char) c;
04145       }
04146 
04147       if (n > 0) {
04148          ogroup[0]= dtable[igroup[0] >> 2];
04149          ogroup[1]= dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
04150          ogroup[2]= dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
04151          ogroup[3]= dtable[igroup[2] & 0x3F];
04152 
04153          if (n < 3) {
04154             ogroup[3] = '=';
04155 
04156             if (n < 2)
04157                ogroup[2] = '=';
04158          }
04159 
04160          for (i = 0; i < 4; i++)
04161             ochar(&bio, ogroup[i], so);
04162       }
04163    }
04164 
04165    fclose(fi);
04166    
04167    if (fputs(ENDL, so) == EOF) {
04168       return 0;
04169    }
04170 
04171    return 1;
04172 }
04173 
04174 static void prep_email_sub_vars(struct ast_channel *ast, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, const char *fromfolder, char *cidnum, char *cidname, char *dur, char *date, const char *category, const char *flag)
04175 {
04176    char callerid[256];
04177    char num[12];
04178    char fromdir[256], fromfile[256];
04179    struct ast_config *msg_cfg;
04180    const char *origcallerid, *origtime;
04181    char origcidname[80], origcidnum[80], origdate[80];
04182    int inttime;
04183    struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
04184 
04185    /* Prepare variables for substitution in email body and subject */
04186    pbx_builtin_setvar_helper(ast, "VM_NAME", vmu->fullname);
04187    pbx_builtin_setvar_helper(ast, "VM_DUR", dur);
04188    snprintf(num, sizeof(num), "%d", msgnum);
04189    pbx_builtin_setvar_helper(ast, "VM_MSGNUM", num);
04190    pbx_builtin_setvar_helper(ast, "VM_CONTEXT", context);
04191    pbx_builtin_setvar_helper(ast, "VM_MAILBOX", mailbox);
04192    pbx_builtin_setvar_helper(ast, "VM_CALLERID", (!ast_strlen_zero(cidname) || !ast_strlen_zero(cidnum)) ?
04193       ast_callerid_merge(callerid, sizeof(callerid), cidname, cidnum, NULL) : "an unknown caller");
04194    pbx_builtin_setvar_helper(ast, "VM_CIDNAME", (!ast_strlen_zero(cidname) ? cidname : "an unknown caller"));
04195    pbx_builtin_setvar_helper(ast, "VM_CIDNUM", (!ast_strlen_zero(cidnum) ? cidnum : "an unknown caller"));
04196    pbx_builtin_setvar_helper(ast, "VM_DATE", date);
04197    pbx_builtin_setvar_helper(ast, "VM_CATEGORY", category ? ast_strdupa(category) : "no category");
04198    pbx_builtin_setvar_helper(ast, "VM_FLAG", flag);
04199 
04200    /* Retrieve info from VM attribute file */
04201    make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, fromfolder);
04202    make_file(fromfile, sizeof(fromfile), fromdir, msgnum - 1);
04203    if (strlen(fromfile) < sizeof(fromfile) - 5) {
04204       strcat(fromfile, ".txt");
04205    }
04206    if (!(msg_cfg = ast_config_load(fromfile, config_flags))) {
04207       if (option_debug > 0) {
04208          ast_log(LOG_DEBUG, "Config load for message text file '%s' failed\n", fromfile);
04209       }
04210       return;
04211    }
04212 
04213    if ((origcallerid = ast_variable_retrieve(msg_cfg, "message", "callerid"))) {
04214       pbx_builtin_setvar_helper(ast, "ORIG_VM_CALLERID", origcallerid);
04215       ast_callerid_split(origcallerid, origcidname, sizeof(origcidname), origcidnum, sizeof(origcidnum));
04216       pbx_builtin_setvar_helper(ast, "ORIG_VM_CIDNAME", origcidname);
04217       pbx_builtin_setvar_helper(ast, "ORIG_VM_CIDNUM", origcidnum);
04218    }
04219 
04220    if ((origtime = ast_variable_retrieve(msg_cfg, "message", "origtime")) && sscanf(origtime, "%30d", &inttime) == 1) {
04221       struct timeval tv = { inttime, };
04222       struct ast_tm tm;
04223       ast_localtime(&tv, &tm, NULL);
04224       ast_strftime_locale(origdate, sizeof(origdate), emaildateformat, &tm, S_OR(vmu->locale, NULL));
04225       pbx_builtin_setvar_helper(ast, "ORIG_VM_DATE", origdate);
04226    }
04227    ast_config_destroy(msg_cfg);
04228 }
04229 
04230 /*!
04231  * \brief Wraps a character sequence in double quotes, escaping occurences of quotes within the string.
04232  * \param from The string to work with.
04233  * \param buf The buffer into which to write the modified quoted string.
04234  * \param maxlen Always zero, but see \see ast_str
04235  * 
04236  * \return The destination string with quotes wrapped on it (the to field).
04237  */
04238 static const char *ast_str_quote(struct ast_str **buf, ssize_t maxlen, const char *from)
04239 {
04240    const char *ptr;
04241 
04242    /* We're only ever passing 0 to maxlen, so short output isn't possible */
04243    ast_str_set(buf, maxlen, "\"");
04244    for (ptr = from; *ptr; ptr++) {
04245       if (*ptr == '"' || *ptr == '\\') {
04246          ast_str_append(buf, maxlen, "\\%c", *ptr);
04247       } else {
04248          ast_str_append(buf, maxlen, "%c", *ptr);
04249       }
04250    }
04251    ast_str_append(buf, maxlen, "\"");
04252 
04253    return ast_str_buffer(*buf);
04254 }
04255 
04256 /*! \brief
04257  * fill in *tm for current time according to the proper timezone, if any.
04258  * \return tm so it can be used as a function argument.
04259  */
04260 static const struct ast_tm *vmu_tm(const struct ast_vm_user *vmu, struct ast_tm *tm)
04261 {
04262    const struct vm_zone *z = NULL;
04263    struct timeval t = ast_tvnow();
04264 
04265    /* Does this user have a timezone specified? */
04266    if (!ast_strlen_zero(vmu->zonetag)) {
04267       /* Find the zone in the list */
04268       AST_LIST_LOCK(&zones);
04269       AST_LIST_TRAVERSE(&zones, z, list) {
04270          if (!strcmp(z->name, vmu->zonetag))
04271             break;
04272       }
04273       AST_LIST_UNLOCK(&zones);
04274    }
04275    ast_localtime(&t, tm, z ? z->timezone : NULL);
04276    return tm;
04277 }
04278 
04279 /*!\brief Check if the string would need encoding within the MIME standard, to
04280  * avoid confusing certain mail software that expects messages to be 7-bit
04281  * clean.
04282  */
04283 static int check_mime(const char *str)
04284 {
04285    for (; *str; str++) {
04286       if (*str > 126 || *str < 32 || strchr("()<>@,:;/\"[]?.=", *str)) {
04287          return 1;
04288       }
04289    }
04290    return 0;
04291 }
04292 
04293 /*!\brief Encode a string according to the MIME rules for encoding strings
04294  * that are not 7-bit clean or contain control characters.
04295  *
04296  * Additionally, if the encoded string would exceed the MIME limit of 76
04297  * characters per line, then the encoding will be broken up into multiple
04298  * sections, separated by a space character, in order to facilitate
04299  * breaking up the associated header across multiple lines.
04300  *
04301  * \param end An expandable buffer for holding the result
04302  * \param maxlen Always zero, but see \see ast_str
04303  * \param start A string to be encoded
04304  * \param preamble The length of the first line already used for this string,
04305  * to ensure that each line maintains a maximum length of 76 chars.
04306  * \param postamble the length of any additional characters appended to the
04307  * line, used to ensure proper field wrapping.
04308  * \retval The encoded string.
04309  */
04310 static const char *ast_str_encode_mime(struct ast_str **end, ssize_t maxlen, const char *start, size_t preamble, size_t postamble)
04311 {
04312    struct ast_str *tmp = ast_str_alloca(80);
04313    int first_section = 1;
04314 
04315    ast_str_reset(*end);
04316    ast_str_set(&tmp, -1, "=?%s?Q?", charset);
04317    for (; *start; start++) {
04318       int need_encoding = 0;
04319       if (*start < 33 || *start > 126 || strchr("()<>@,:;/\"[]?.=_", *start)) {
04320          need_encoding = 1;
04321       }
04322       if ((first_section && need_encoding && preamble + ast_str_strlen(tmp) > 70) ||
04323          (first_section && !need_encoding && preamble + ast_str_strlen(tmp) > 72) ||
04324          (!first_section && need_encoding && ast_str_strlen(tmp) > 70) ||
04325          (!first_section && !need_encoding && ast_str_strlen(tmp) > 72)) {
04326          /* Start new line */
04327          ast_str_append(end, maxlen, "%s%s?=", first_section ? "" : " ", ast_str_buffer(tmp));
04328          ast_str_set(&tmp, -1, "=?%s?Q?", charset);
04329          first_section = 0;
04330       }
04331       if (need_encoding && *start == ' ') {
04332          ast_str_append(&tmp, -1, "_");
04333       } else if (need_encoding) {
04334          ast_str_append(&tmp, -1, "=%hhX", *start);
04335       } else {
04336          ast_str_append(&tmp, -1, "%c", *start);
04337       }
04338    }
04339    ast_str_append(end, maxlen, "%s%s?=%s", first_section ? "" : " ", ast_str_buffer(tmp), ast_str_strlen(tmp) + postamble > 74 ? " " : "");
04340    return ast_str_buffer(*end);
04341 }
04342 
04343 /*!
04344  * \brief Creates the email file to be sent to indicate a new voicemail exists for a user.
04345  * \param p The output file to generate the email contents into.
04346  * \param srcemail The email address to send the email to, presumably the email address for the owner of the mailbox.
04347  * \param vmu The voicemail user who is sending the voicemail.
04348  * \param msgnum The message index in the mailbox folder.
04349  * \param context 
04350  * \param mailbox The voicemail box to read the voicemail to be notified in this email.
04351  * \param fromfolder
04352  * \param cidnum The caller ID number.
04353  * \param cidname The caller ID name.
04354  * \param attach the name of the sound file to be attached to the email, if attach_user_voicemail == 1.
04355  * \param attach2 
04356  * \param format The message sound file format. i.e. .wav
04357  * \param duration The time of the message content, in seconds.
04358  * \param attach_user_voicemail if 1, the sound file is attached to the email.
04359  * \param chan
04360  * \param category
04361  * \param imap if == 1, indicates the target folder for the email notification to be sent to will be an IMAP mailstore. This causes additional mailbox headers to be set, which would facilitate searching for the email in the destination IMAP folder.
04362  * \param flag
04363  *
04364  * The email body, and base 64 encoded attachement (if any) are stored to the file identified by *p. This method does not actually send the email.  That is done by invoking the configure 'mailcmd' and piping this generated file into it, or with the sendemail() function.
04365  */
04366 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)
04367 {
04368    char date[256];
04369    char host[MAXHOSTNAMELEN] = "";
04370    char who[256];
04371    char bound[256];
04372    char dur[256];
04373    struct ast_tm tm;
04374    char enc_cidnum[256] = "", enc_cidname[256] = "";
04375    struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
04376    char *greeting_attachment; 
04377    char filename[256];
04378 
04379    if (!str1 || !str2) {
04380       ast_free(str1);
04381       ast_free(str2);
04382       return;
04383    }
04384 
04385    if (cidnum) {
04386       strip_control_and_high(cidnum, enc_cidnum, sizeof(enc_cidnum));
04387    }
04388    if (cidname) {
04389       strip_control_and_high(cidname, enc_cidname, sizeof(enc_cidname));
04390    }
04391    gethostname(host, sizeof(host) - 1);
04392 
04393    if (strchr(srcemail, '@')) {
04394       ast_copy_string(who, srcemail, sizeof(who));
04395    } else {
04396       snprintf(who, sizeof(who), "%s@%s", srcemail, host);
04397    }
04398 
04399    greeting_attachment = strrchr(ast_strdupa(attach), '/');
04400    if (greeting_attachment) {
04401       *greeting_attachment++ = '\0';
04402    }
04403 
04404    snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
04405    ast_strftime_locale(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm), S_OR(vmu->locale, NULL));
04406    fprintf(p, "Date: %s" ENDL, date);
04407 
04408    /* Set date format for voicemail mail */
04409    ast_strftime_locale(date, sizeof(date), emaildateformat, &tm, S_OR(vmu->locale, NULL));
04410 
04411    if (!ast_strlen_zero(fromstring)) {
04412       struct ast_channel *ast;
04413       if ((ast = ast_dummy_channel_alloc())) {
04414          char *ptr;
04415          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, enc_cidnum, enc_cidname, dur, date, category, flag);
04416          ast_str_substitute_variables(&str1, 0, ast, fromstring);
04417 
04418          if (check_mime(ast_str_buffer(str1))) {
04419             int first_line = 1;
04420             ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("From: "), strlen(who) + 3);
04421             while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
04422                *ptr = '\0';
04423                fprintf(p, "%s %s" ENDL, first_line ? "From:" : "", ast_str_buffer(str2));
04424                first_line = 0;
04425                /* Substring is smaller, so this will never grow */
04426                ast_str_set(&str2, 0, "%s", ptr + 1);
04427             }
04428             fprintf(p, "%s %s <%s>" ENDL, first_line ? "From:" : "", ast_str_buffer(str2), who);
04429          } else {
04430             fprintf(p, "From: %s <%s>" ENDL, ast_str_quote(&str2, 0, ast_str_buffer(str1)), who);
04431          }
04432          ast = ast_channel_release(ast);
04433       } else {
04434          ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
04435       }
04436    } else {
04437       fprintf(p, "From: Asterisk PBX <%s>" ENDL, who);
04438    }
04439 
04440    if (check_mime(vmu->fullname)) {
04441       int first_line = 1;
04442       char *ptr;
04443       ast_str_encode_mime(&str2, 0, vmu->fullname, strlen("To: "), strlen(vmu->email) + 3);
04444       while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
04445          *ptr = '\0';
04446          fprintf(p, "%s %s" ENDL, first_line ? "To:" : "", ast_str_buffer(str2));
04447          first_line = 0;
04448          /* Substring is smaller, so this will never grow */
04449          ast_str_set(&str2, 0, "%s", ptr + 1);
04450       }
04451       fprintf(p, "%s %s <%s>" ENDL, first_line ? "To:" : "", ast_str_buffer(str2), vmu->email);
04452    } else {
04453       fprintf(p, "To: %s <%s>" ENDL, ast_str_quote(&str2, 0, vmu->fullname), vmu->email);
04454    }
04455 
04456    if (!ast_strlen_zero(emailsubject) || !ast_strlen_zero(vmu->emailsubject)) {
04457       char *e_subj = !ast_strlen_zero(vmu->emailsubject) ? vmu->emailsubject : emailsubject;
04458       struct ast_channel *ast;
04459       if ((ast = ast_dummy_channel_alloc())) {
04460          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
04461          ast_str_substitute_variables(&str1, 0, ast, e_subj);
04462          if (check_mime(ast_str_buffer(str1))) {
04463             int first_line = 1;
04464             char *ptr;
04465             ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("Subject: "), 0);
04466             while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
04467                *ptr = '\0';
04468                fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
04469                first_line = 0;
04470                /* Substring is smaller, so this will never grow */
04471                ast_str_set(&str2, 0, "%s", ptr + 1);
04472             }
04473             fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
04474          } else {
04475             fprintf(p, "Subject: %s" ENDL, ast_str_buffer(str1));
04476          }
04477          ast = ast_channel_release(ast);
04478       } else {
04479          ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
04480       }
04481    } else if (ast_test_flag((&globalflags), VM_PBXSKIP)) {
04482       if (ast_strlen_zero(flag)) {
04483          fprintf(p, "Subject: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
04484       } else {
04485          fprintf(p, "Subject: New %s message %d in mailbox %s" ENDL, flag, msgnum + 1, mailbox);
04486       }
04487    } else {
04488       if (ast_strlen_zero(flag)) {
04489          fprintf(p, "Subject: [PBX]: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
04490       } else {
04491          fprintf(p, "Subject: [PBX]: New %s message %d in mailbox %s" ENDL, flag, msgnum + 1, mailbox);
04492       }
04493    }
04494 
04495    fprintf(p, "Message-ID: <Asterisk-%d-%d-%s-%d@%s>" ENDL, msgnum + 1,
04496       (unsigned int) ast_random(), mailbox, (int) getpid(), host);
04497    if (imap) {
04498       /* additional information needed for IMAP searching */
04499       fprintf(p, "X-Asterisk-VM-Message-Num: %d" ENDL, msgnum + 1);
04500       /* fprintf(p, "X-Asterisk-VM-Orig-Mailbox: %s" ENDL, ext); */
04501       fprintf(p, "X-Asterisk-VM-Server-Name: %s" ENDL, fromstring);
04502       fprintf(p, "X-Asterisk-VM-Context: %s" ENDL, context);
04503 #ifdef IMAP_STORAGE
04504       fprintf(p, "X-Asterisk-VM-Extension: %s" ENDL, (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
04505 #else
04506       fprintf(p, "X-Asterisk-VM-Extension: %s" ENDL, mailbox);
04507 #endif
04508       /* flag added for Urgent */
04509       fprintf(p, "X-Asterisk-VM-Flag: %s" ENDL, flag);
04510       fprintf(p, "X-Asterisk-VM-Priority: %d" ENDL, chan->priority);
04511       fprintf(p, "X-Asterisk-VM-Caller-channel: %s" ENDL, chan->name);
04512       fprintf(p, "X-Asterisk-VM-Caller-ID-Num: %s" ENDL, enc_cidnum);
04513       fprintf(p, "X-Asterisk-VM-Caller-ID-Name: %s" ENDL, enc_cidname);
04514       fprintf(p, "X-Asterisk-VM-Duration: %d" ENDL, duration);
04515       if (!ast_strlen_zero(category)) {
04516          fprintf(p, "X-Asterisk-VM-Category: %s" ENDL, category);
04517       } else {
04518          fprintf(p, "X-Asterisk-VM-Category: " ENDL);
04519       }
04520       fprintf(p, "X-Asterisk-VM-Message-Type: %s" ENDL, msgnum > -1 ? "Message" : greeting_attachment);
04521       fprintf(p, "X-Asterisk-VM-Orig-date: %s" ENDL, date);
04522       fprintf(p, "X-Asterisk-VM-Orig-time: %ld" ENDL, (long) time(NULL));
04523    }
04524    if (!ast_strlen_zero(cidnum)) {
04525       fprintf(p, "X-Asterisk-CallerID: %s" ENDL, enc_cidnum);
04526    }
04527    if (!ast_strlen_zero(cidname)) {
04528       fprintf(p, "X-Asterisk-CallerIDName: %s" ENDL, enc_cidname);
04529    }
04530    fprintf(p, "MIME-Version: 1.0" ENDL);
04531    if (attach_user_voicemail) {
04532       /* Something unique. */
04533       snprintf(bound, sizeof(bound), "----voicemail_%d%s%d%d", msgnum + 1, mailbox,
04534          (int) getpid(), (unsigned int) ast_random());
04535 
04536       fprintf(p, "Content-Type: multipart/mixed; boundary=\"%s\"" ENDL, bound);
04537       fprintf(p, ENDL ENDL "This is a multi-part message in MIME format." ENDL ENDL);
04538       fprintf(p, "--%s" ENDL, bound);
04539    }
04540    fprintf(p, "Content-Type: text/plain; charset=%s" ENDL "Content-Transfer-Encoding: 8bit" ENDL ENDL, charset);
04541    if (emailbody || vmu->emailbody) {
04542       char* e_body = vmu->emailbody ? vmu->emailbody : emailbody;
04543       struct ast_channel *ast;
04544       if ((ast = ast_dummy_channel_alloc())) {
04545          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
04546          ast_str_substitute_variables(&str1, 0, ast, e_body);
04547 #ifdef IMAP_STORAGE
04548             {
04549                /* Convert body to native line terminators for IMAP backend */
04550                char *line = ast_str_buffer(str1), *next;
04551                do {
04552                   /* Terminate line before outputting it to the file */
04553                   if ((next = strchr(line, '\n'))) {
04554                      *next++ = '\0';
04555                   }
04556                   fprintf(p, "%s" ENDL, line);
04557                   line = next;
04558                } while (!ast_strlen_zero(line));
04559             }
04560 #else
04561          fprintf(p, "%s" ENDL, ast_str_buffer(str1));
04562 #endif
04563          ast = ast_channel_release(ast);
04564       } else {
04565          ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
04566       }
04567    } else if (msgnum > -1) {
04568       if (strcmp(vmu->mailbox, mailbox)) {
04569          /* Forwarded type */
04570          struct ast_config *msg_cfg;
04571          const char *v;
04572          int inttime;
04573          char fromdir[256], fromfile[256], origdate[80] = "", origcallerid[80] = "";
04574          struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
04575          /* Retrieve info from VM attribute file */
04576          make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, fromfolder);
04577          make_file(fromfile, sizeof(fromfile), fromdir, msgnum);
04578          if (strlen(fromfile) < sizeof(fromfile) - 5) {
04579             strcat(fromfile, ".txt");
04580          }
04581          if ((msg_cfg = ast_config_load(fromfile, config_flags))) {
04582             if ((v = ast_variable_retrieve(msg_cfg, "message", "callerid"))) {
04583                ast_copy_string(origcallerid, v, sizeof(origcallerid));
04584             }
04585 
04586             /* You might be tempted to do origdate, except that a) it's in the wrong
04587              * format, and b) it's missing for IMAP recordings. */
04588             if ((v = ast_variable_retrieve(msg_cfg, "message", "origtime")) && sscanf(v, "%30d", &inttime) == 1) {
04589                struct timeval tv = { inttime, };
04590                struct ast_tm tm;
04591                ast_localtime(&tv, &tm, NULL);
04592                ast_strftime_locale(origdate, sizeof(origdate), emaildateformat, &tm, S_OR(vmu->locale, NULL));
04593             }
04594             fprintf(p, "Dear %s:" ENDL ENDL "\tJust wanted to let you know you were just forwarded"
04595                " a %s long message (number %d)" ENDL "in mailbox %s from %s, on %s" ENDL
04596                "(originally sent by %s on %s)" ENDL "so you might want to check it when you get a"
04597                " chance.  Thanks!" ENDL ENDL "\t\t\t\t--Asterisk" ENDL ENDL, vmu->fullname, dur,
04598                msgnum + 1, mailbox, (cidname ? cidname : (cidnum ? cidnum : "an unknown caller")),
04599                date, origcallerid, origdate);
04600             ast_config_destroy(msg_cfg);
04601          } else {
04602             goto plain_message;
04603          }
04604       } else {
04605 plain_message:
04606          fprintf(p, "Dear %s:" ENDL ENDL "\tJust wanted to let you know you were just left a "
04607             "%s long message (number %d)" ENDL "in mailbox %s from %s, on %s so you might" ENDL
04608             "want to check it when you get a chance.  Thanks!" ENDL ENDL "\t\t\t\t--Asterisk"
04609             ENDL ENDL, vmu->fullname, dur, msgnum + 1, mailbox,
04610             (cidname ? cidname : (cidnum ? cidnum : "an unknown caller")), date);
04611       }
04612    } else {
04613       fprintf(p, "This message is to let you know that your greeting was changed on %s." ENDL
04614             "Please do not delete this message, lest your greeting vanish with it." ENDL ENDL, date);
04615    }
04616 
04617    if (imap || attach_user_voicemail) {
04618       if (!ast_strlen_zero(attach2)) {
04619          snprintf(filename, sizeof(filename), "msg%04d.%s", msgnum, format);
04620          ast_debug(5, "creating second attachment filename %s\n", filename);
04621          add_email_attachment(p, vmu, format, attach, greeting_attachment, mailbox, bound, filename, 0, msgnum);
04622          snprintf(filename, sizeof(filename), "msgintro%04d.%s", msgnum, format);
04623          ast_debug(5, "creating attachment filename %s\n", filename);
04624          add_email_attachment(p, vmu, format, attach2, greeting_attachment, mailbox, bound, filename, 1, msgnum);
04625       } else {
04626          snprintf(filename, sizeof(filename), "msg%04d.%s", msgnum, format);
04627          ast_debug(5, "creating attachment filename %s, no second attachment.\n", filename);
04628          add_email_attachment(p, vmu, format, attach, greeting_attachment, mailbox, bound, filename, 1, msgnum);
04629       }
04630    }
04631    ast_free(str1);
04632    ast_free(str2);
04633 }
04634 
04635 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)
04636 {
04637    char tmpdir[256], newtmp[256];
04638    char fname[256];
04639    char tmpcmd[256];
04640    int tmpfd = -1;
04641 
04642    /* Eww. We want formats to tell us their own MIME type */
04643    char *ctype = (!strcasecmp(format, "ogg")) ? "application/" : "audio/x-";
04644 
04645    if (vmu->volgain < -.001 || vmu->volgain > .001) {
04646       create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, vmu->mailbox, "tmp");
04647       snprintf(newtmp, sizeof(newtmp), "%s/XXXXXX", tmpdir);
04648       tmpfd = mkstemp(newtmp);
04649       chmod(newtmp, VOICEMAIL_FILE_MODE & ~my_umask);
04650       ast_debug(3, "newtmp: %s\n", newtmp);
04651       if (tmpfd > -1) {
04652          int soxstatus;
04653          snprintf(tmpcmd, sizeof(tmpcmd), "sox -v %.4f %s.%s %s.%s", vmu->volgain, attach, format, newtmp, format);
04654          if ((soxstatus = ast_safe_system(tmpcmd)) == 0) {
04655             attach = newtmp;
04656             ast_debug(3, "VOLGAIN: Stored at: %s.%s - Level: %.4f - Mailbox: %s\n", attach, format, vmu->volgain, mailbox);
04657          } else {
04658             ast_log(LOG_WARNING, "Sox failed to re-encode %s.%s: %s (have you installed support for all sox file formats?)\n", attach, format,
04659                soxstatus == 1 ? "Problem with command line options" : "An error occurred during file processing");
04660             ast_log(LOG_WARNING, "Voicemail attachment will have no volume gain.\n");
04661          }
04662       }
04663    }
04664    fprintf(p, "--%s" ENDL, bound);
04665    if (msgnum > -1)
04666       fprintf(p, "Content-Type: %s%s; name=\"%s\"" ENDL, ctype, format, filename);
04667    else
04668       fprintf(p, "Content-Type: %s%s; name=\"%s.%s\"" ENDL, ctype, format, greeting_attachment, format);
04669    fprintf(p, "Content-Transfer-Encoding: base64" ENDL);
04670    fprintf(p, "Content-Description: Voicemail sound attachment." ENDL);
04671    if (msgnum > -1)
04672       fprintf(p, "Content-Disposition: attachment; filename=\"%s\"" ENDL ENDL, filename);
04673    else
04674       fprintf(p, "Content-Disposition: attachment; filename=\"%s.%s\"" ENDL ENDL, greeting_attachment, format);
04675    snprintf(fname, sizeof(fname), "%s.%s", attach, format);
04676    base_encode(fname, p);
04677    if (last)
04678       fprintf(p, ENDL ENDL "--%s--" ENDL "." ENDL, bound);
04679    if (tmpfd > -1) {
04680       unlink(fname);
04681       close(tmpfd);
04682       unlink(newtmp);
04683    }
04684    return 0;
04685 }
04686 
04687 static int sendmail(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, const char *flag)
04688 {
04689    FILE *p = NULL;
04690    char tmp[80] = "/tmp/astmail-XXXXXX";
04691    char tmp2[256];
04692 
04693    if (vmu && ast_strlen_zero(vmu->email)) {
04694       ast_log(AST_LOG_WARNING, "E-mail address missing for mailbox [%s].  E-mail will not be sent.\n", vmu->mailbox);
04695       return(0);
04696    }
04697    if (!strcmp(format, "wav49"))
04698       format = "WAV";
04699    ast_debug(3, "Attaching file '%s', format '%s', uservm is '%d', global is %d\n", attach, format, attach_user_voicemail, ast_test_flag((&globalflags), VM_ATTACH));
04700    /* Make a temporary file instead of piping directly to sendmail, in case the mail
04701       command hangs */
04702    if ((p = vm_mkftemp(tmp)) == NULL) {
04703       ast_log(AST_LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
04704       return -1;
04705    } else {
04706       make_email_file(p, srcemail, vmu, msgnum, context, mailbox, fromfolder, cidnum, cidname, attach, attach2, format, duration, attach_user_voicemail, chan, category, 0, flag);
04707       fclose(p);
04708       snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
04709       ast_safe_system(tmp2);
04710       ast_debug(1, "Sent mail to %s with command '%s'\n", vmu->email, mailcmd);
04711    }
04712    return 0;
04713 }
04714 
04715 static int sendpage(char *srcemail, char *pager, int msgnum, char *context, char *mailbox, const char *fromfolder, char *cidnum, char *cidname, int duration, struct ast_vm_user *vmu, const char *category, const char *flag)
04716 {
04717    char enc_cidnum[256], enc_cidname[256];
04718    char date[256];
04719    char host[MAXHOSTNAMELEN] = "";
04720    char who[256];
04721    char dur[PATH_MAX];
04722    char tmp[80] = "/tmp/astmail-XXXXXX";
04723    char tmp2[PATH_MAX];
04724    struct ast_tm tm;
04725    FILE *p;
04726    struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
04727 
04728    if (!str1 || !str2) {
04729       ast_free(str1);
04730       ast_free(str2);
04731       return -1;
04732    }
04733 
04734    if (cidnum) {
04735       strip_control_and_high(cidnum, enc_cidnum, sizeof(enc_cidnum));
04736    }
04737    if (cidname) {
04738       strip_control_and_high(cidname, enc_cidname, sizeof(enc_cidname));
04739    }
04740 
04741    if ((p = vm_mkftemp(tmp)) == NULL) {
04742       ast_log(AST_LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
04743       ast_free(str1);
04744       ast_free(str2);
04745       return -1;
04746    }
04747    gethostname(host, sizeof(host)-1);
04748    if (strchr(srcemail, '@')) {
04749       ast_copy_string(who, srcemail, sizeof(who));
04750    } else {
04751       snprintf(who, sizeof(who), "%s@%s", srcemail, host);
04752    }
04753    snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
04754    ast_strftime_locale(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm), S_OR(vmu->locale, NULL));
04755    fprintf(p, "Date: %s\n", date);
04756 
04757    /* Reformat for custom pager format */
04758    ast_strftime_locale(date, sizeof(date), pagerdateformat, vmu_tm(vmu, &tm), S_OR(vmu->locale, NULL));
04759 
04760    if (!ast_strlen_zero(pagerfromstring)) {
04761       struct ast_channel *ast;
04762       if ((ast = ast_dummy_channel_alloc())) {
04763          char *ptr;
04764          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, enc_cidnum, enc_cidname, dur, date, category, flag);
04765          ast_str_substitute_variables(&str1, 0, ast, pagerfromstring);
04766 
04767          if (check_mime(ast_str_buffer(str1))) {
04768             int first_line = 1;
04769             ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("From: "), strlen(who) + 3);
04770             while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
04771                *ptr = '\0';
04772                fprintf(p, "%s %s" ENDL, first_line ? "From:" : "", ast_str_buffer(str2));
04773                first_line = 0;
04774                /* Substring is smaller, so this will never grow */
04775                ast_str_set(&str2, 0, "%s", ptr + 1);
04776             }
04777             fprintf(p, "%s %s <%s>" ENDL, first_line ? "From:" : "", ast_str_buffer(str2), who);
04778          } else {
04779             fprintf(p, "From: %s <%s>" ENDL, ast_str_quote(&str2, 0, ast_str_buffer(str1)), who);
04780          }
04781          ast = ast_channel_release(ast);
04782       } else {
04783          ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
04784       }
04785    } else {
04786       fprintf(p, "From: Asterisk PBX <%s>" ENDL, who);
04787    }
04788 
04789    if (check_mime(vmu->fullname)) {
04790       int first_line = 1;
04791       char *ptr;
04792       ast_str_encode_mime(&str2, 0, vmu->fullname, strlen("To: "), strlen(pager) + 3);
04793       while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
04794          *ptr = '\0';
04795          fprintf(p, "%s %s" ENDL, first_line ? "To:" : "", ast_str_buffer(str2));
04796          first_line = 0;
04797          /* Substring is smaller, so this will never grow */
04798          ast_str_set(&str2, 0, "%s", ptr + 1);
04799       }
04800       fprintf(p, "%s %s <%s>" ENDL, first_line ? "To:" : "", ast_str_buffer(str2), pager);
04801    } else {
04802       fprintf(p, "To: %s <%s>" ENDL, ast_str_quote(&str2, 0, vmu->fullname), pager);
04803    }
04804 
04805    if (!ast_strlen_zero(pagersubject)) {
04806       struct ast_channel *ast;
04807       if ((ast = ast_dummy_channel_alloc())) {
04808          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
04809          ast_str_substitute_variables(&str1, 0, ast, pagersubject);
04810          if (check_mime(ast_str_buffer(str1))) {
04811             int first_line = 1;
04812             char *ptr;
04813             ast_str_encode_mime(&str2, 0, ast_str_buffer(str1), strlen("Subject: "), 0);
04814             while ((ptr = strchr(ast_str_buffer(str2), ' '))) {
04815                *ptr = '\0';
04816                fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
04817                first_line = 0;
04818                /* Substring is smaller, so this will never grow */
04819                ast_str_set(&str2, 0, "%s", ptr + 1);
04820             }
04821             fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", ast_str_buffer(str2));
04822          } else {
04823             fprintf(p, "Subject: %s" ENDL, ast_str_buffer(str1));
04824          }
04825          ast = ast_channel_release(ast);
04826       } else {
04827          ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
04828       }
04829    } else {
04830       if (ast_strlen_zero(flag)) {
04831          fprintf(p, "Subject: New VM\n\n");
04832       } else {
04833          fprintf(p, "Subject: New %s VM\n\n", flag);
04834       }
04835    }
04836 
04837    if (pagerbody) {
04838       struct ast_channel *ast;
04839       if ((ast = ast_dummy_channel_alloc())) {
04840          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, fromfolder, cidnum, cidname, dur, date, category, flag);
04841          ast_str_substitute_variables(&str1, 0, ast, pagerbody);
04842          fprintf(p, "%s" ENDL, ast_str_buffer(str1));
04843          ast = ast_channel_release(ast);
04844       } else {
04845          ast_log(AST_LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
04846       }
04847    } else {
04848       fprintf(p, "New %s long %s msg in box %s\n"
04849             "from %s, on %s", dur, flag, mailbox, (cidname ? cidname : (cidnum ? cidnum : "unknown")), date);
04850    }
04851 
04852    fclose(p);
04853    snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
04854    ast_safe_system(tmp2);
04855    ast_debug(1, "Sent page to %s with command '%s'\n", pager, mailcmd);
04856    ast_free(str1);
04857    ast_free(str2);
04858    return 0;
04859 }
04860 
04861 /*!
04862  * \brief Gets the current date and time, as formatted string.
04863  * \param s The buffer to hold the output formatted date.
04864  * \param len the length of the buffer. Used to prevent buffer overflow in ast_strftime.
04865  * 
04866  * The date format string used is "%a %b %e %r UTC %Y".
04867  * 
04868  * \return zero on success, -1 on error.
04869  */
04870 static int get_date(char *s, int len)
04871 {
04872    struct ast_tm tm;
04873    struct timeval t = ast_tvnow();
04874    
04875    ast_localtime(&t, &tm, "UTC");
04876 
04877    return ast_strftime(s, len, "%a %b %e %r UTC %Y", &tm);
04878 }
04879 
04880 static int invent_message(struct ast_channel *chan, char *context, char *ext, int busy, char *ecodes)
04881 {
04882    int res;
04883    char fn[PATH_MAX];
04884    char dest[PATH_MAX];
04885 
04886    snprintf(fn, sizeof(fn), "%s%s/%s/greet", VM_SPOOL_DIR, context, ext);
04887 
04888    if ((res = create_dirpath(dest, sizeof(dest), context, ext, ""))) {
04889       ast_log(AST_LOG_WARNING, "Failed to make directory(%s)\n", fn);
04890       return -1;
04891    }
04892 
04893    RETRIEVE(fn, -1, ext, context);
04894    if (ast_fileexists(fn, NULL, NULL) > 0) {
04895       res = ast_stream_and_wait(chan, fn, ecodes);
04896       if (res) {
04897          DISPOSE(fn, -1);
04898          return res;
04899       }
04900    } else {
04901       /* Dispose just in case */
04902       DISPOSE(fn, -1);
04903       res = ast_stream_and_wait(chan, "vm-theperson", ecodes);
04904       if (res)
04905          return res;
04906       res = ast_say_digit_str(chan, ext, ecodes, chan->language);
04907       if (res)
04908          return res;
04909    }
04910    res = ast_stream_and_wait(chan, busy ? "vm-isonphone" : "vm-isunavail", ecodes);
04911    return res;
04912 }
04913 
04914 static void free_zone(struct vm_zone *z)
04915 {
04916    ast_free(z);
04917 }
04918 
04919 #ifdef ODBC_STORAGE
04920 static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
04921 {
04922    int x = -1;
04923    int res;
04924    SQLHSTMT stmt = NULL;
04925    char sql[PATH_MAX];
04926    char rowdata[20];
04927    char tmp[PATH_MAX] = "";
04928    struct odbc_obj *obj = NULL;
04929    char *context;
04930    struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
04931 
04932    if (newmsgs)
04933       *newmsgs = 0;
04934    if (oldmsgs)
04935       *oldmsgs = 0;
04936    if (urgentmsgs)
04937       *urgentmsgs = 0;
04938 
04939    /* If no mailbox, return immediately */
04940    if (ast_strlen_zero(mailbox))
04941       return 0;
04942 
04943    ast_copy_string(tmp, mailbox, sizeof(tmp));
04944 
04945    if (strchr(mailbox, ' ') || strchr(mailbox, ',')) {
04946       int u, n, o;
04947       char *next, *remaining = tmp;
04948       while ((next = strsep(&remaining, " ,"))) {
04949          if (inboxcount2(next, urgentmsgs ? &u : NULL, &n, &o)) {
04950             return -1;
04951          }
04952          if (urgentmsgs) {
04953             *urgentmsgs += u;
04954          }
04955          if (newmsgs) {
04956             *newmsgs += n;
04957          }
04958          if (oldmsgs) {
04959             *oldmsgs += o;
04960          }
04961       }
04962       return 0;
04963    }
04964 
04965    context = strchr(tmp, '@');
04966    if (context) {
04967       *context = '\0';
04968       context++;
04969    } else
04970       context = "default";
04971 
04972    if ((obj = ast_odbc_request_obj(odbc_database, 0))) {
04973       do {
04974          if (newmsgs) {
04975             snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "INBOX");
04976             if (!(stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps))) {
04977                ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
04978                break;
04979             }
04980             res = SQLFetch(stmt);
04981             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
04982                ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
04983                break;
04984             }
04985             res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
04986             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
04987                ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
04988                break;
04989             }
04990             *newmsgs = atoi(rowdata);
04991             SQLFreeHandle (SQL_HANDLE_STMT, stmt);
04992          }
04993 
04994          if (oldmsgs) {
04995             snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "Old");
04996             if (!(stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps))) {
04997                ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
04998                break;
04999             }
05000             res = SQLFetch(stmt);
05001             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
05002                ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
05003                break;
05004             }
05005             res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
05006             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
05007                ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
05008                break;
05009             }
05010             SQLFreeHandle(SQL_HANDLE_STMT, stmt);
05011             *oldmsgs = atoi(rowdata);
05012          }
05013 
05014          if (urgentmsgs) {
05015             snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "Urgent");
05016             if (!(stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps))) {
05017                ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
05018                break;
05019             }
05020             res = SQLFetch(stmt);
05021             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
05022                ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
05023                break;
05024             }
05025             res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
05026             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
05027                ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
05028                break;
05029             }
05030             *urgentmsgs = atoi(rowdata);
05031          }
05032 
05033          x = 0;
05034       } while (0);
05035    } else {
05036       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
05037    }
05038 
05039    if (stmt) {
05040       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
05041    }
05042    if (obj) {
05043       ast_odbc_release_obj(obj);
05044    }
05045 
05046    return x;
05047 }
05048 
05049 /*!
05050  * \brief Gets the number of messages that exist in a mailbox folder.
05051  * \param context
05052  * \param mailbox
05053  * \param folder
05054  * 
05055  * This method is used when ODBC backend is used.
05056  * \return The number of messages in this mailbox folder (zero or more).
05057  */
05058 static int messagecount(const char *context, const char *mailbox, const char *folder)
05059 {
05060    struct odbc_obj *obj = NULL;
05061    int nummsgs = 0;
05062    int res;
05063    SQLHSTMT stmt = NULL;
05064    char sql[PATH_MAX];
05065    char rowdata[20];
05066    struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
05067    if (!folder)
05068       folder = "INBOX";
05069    /* If no mailbox, return immediately */
05070    if (ast_strlen_zero(mailbox))
05071       return 0;
05072 
05073    obj = ast_odbc_request_obj(odbc_database, 0);
05074    if (obj) {
05075       if (!strcmp(folder, "INBOX")) {
05076          snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/INBOX' OR dir = '%s%s/%s/Urgent'", odbc_table, VM_SPOOL_DIR, context, mailbox, VM_SPOOL_DIR, context, mailbox);
05077       } else {
05078          snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
05079       }
05080       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
05081       if (!stmt) {
05082          ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
05083          goto yuck;
05084       }
05085       res = SQLFetch(stmt);
05086       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
05087          ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
05088          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
05089          goto yuck;
05090       }
05091       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
05092       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
05093          ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
05094          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
05095          goto yuck;
05096       }
05097       nummsgs = atoi(rowdata);
05098       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
05099    } else
05100       ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
05101 
05102 yuck:
05103    if (obj)
05104       ast_odbc_release_obj(obj);
05105    return nummsgs;
05106 }
05107 
05108 /** 
05109  * \brief Determines if the given folder has messages.
05110  * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
05111  * 
05112  * This function is used when the mailbox is stored in an ODBC back end.
05113  * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
05114  * \return 1 if the folder has one or more messages. zero otherwise.
05115  */
05116 static int has_voicemail(const char *mailbox, const char *folder)
05117 {
05118    char tmp[256], *tmp2 = tmp, *box, *context;
05119    ast_copy_string(tmp, mailbox, sizeof(tmp));
05120    while ((context = box = strsep(&tmp2, ",&"))) {
05121       strsep(&context, "@");
05122       if (ast_strlen_zero(context))
05123          context = "default";
05124       if (messagecount(context, box, folder))
05125          return 1;
05126    }
05127    return 0;
05128 }
05129 #endif
05130 #ifndef IMAP_STORAGE
05131 /*! 
05132  * \brief Copies a message from one mailbox to another.
05133  * \param chan
05134  * \param vmu
05135  * \param imbox
05136  * \param msgnum
05137  * \param duration
05138  * \param recip
05139  * \param fmt
05140  * \param dir
05141  * \param flag
05142  *
05143  * This is only used by file storage based mailboxes.
05144  *
05145  * \return zero on success, -1 on error.
05146  */
05147 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, const char *flag)
05148 {
05149    char fromdir[PATH_MAX], todir[PATH_MAX], frompath[PATH_MAX], topath[PATH_MAX];
05150    const char *frombox = mbox(vmu, imbox);
05151    int recipmsgnum;
05152    int res = 0;
05153 
05154    ast_log(AST_LOG_NOTICE, "Copying message from %s@%s to %s@%s\n", vmu->mailbox, vmu->context, recip->mailbox, recip->context);
05155 
05156    if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) { /* If urgent, copy to Urgent folder */
05157       create_dirpath(todir, sizeof(todir), recip->context, recip->mailbox, "Urgent");
05158    } else {
05159       create_dirpath(todir, sizeof(todir), recip->context, recip->mailbox, "INBOX");
05160    }
05161    
05162    if (!dir)
05163       make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, frombox);
05164    else
05165       ast_copy_string(fromdir, dir, sizeof(fromdir));
05166 
05167    make_file(frompath, sizeof(frompath), fromdir, msgnum);
05168    make_dir(todir, sizeof(todir), recip->context, recip->mailbox, "INBOX");
05169 
05170    if (vm_lock_path(todir))
05171       return ERROR_LOCK_PATH;
05172 
05173    recipmsgnum = last_message_index(recip, todir) + 1;
05174    if (recipmsgnum < recip->maxmsg - (imbox ? 0 : inprocess_count(vmu->mailbox, vmu->context, 0))) {
05175       make_file(topath, sizeof(topath), todir, recipmsgnum);
05176       /* If we are prepending a message for ODBC, then the message already
05177        * exists in the database, but we want to force copying from the
05178        * filesystem (since only the FS contains the prepend). */
05179       copy_plain_file(frompath, topath);
05180       STORE(todir, recip->mailbox, recip->context, recipmsgnum, chan, recip, fmt, duration, NULL, NULL);
05181       vm_delete(topath);
05182    } else {
05183       ast_log(AST_LOG_ERROR, "Recipient mailbox %s@%s is full\n", recip->mailbox, recip->context);
05184       res = -1;
05185    }
05186    ast_unlock_path(todir);
05187    notify_new_message(chan, recip, NULL, recipmsgnum, duration, fmt,
05188       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
05189       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
05190       flag);
05191    
05192    return res;
05193 }
05194 #endif
05195 #if !(defined(IMAP_STORAGE) || defined(ODBC_STORAGE))
05196 
05197 static int messagecount(const char *context, const char *mailbox, const char *folder)
05198 {
05199    return __has_voicemail(context, mailbox, folder, 0) + (folder && strcmp(folder, "INBOX") ? 0 : __has_voicemail(context, mailbox, "Urgent", 0));
05200 }
05201 
05202 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit)
05203 {
05204    DIR *dir;
05205    struct dirent *de;
05206    char fn[256];
05207    int ret = 0;
05208 
05209    /* If no mailbox, return immediately */
05210    if (ast_strlen_zero(mailbox))
05211       return 0;
05212 
05213    if (ast_strlen_zero(folder))
05214       folder = "INBOX";
05215    if (ast_strlen_zero(context))
05216       context = "default";
05217 
05218    snprintf(fn, sizeof(fn), "%s%s/%s/%s", VM_SPOOL_DIR, context, mailbox, folder);
05219 
05220    if (!(dir = opendir(fn)))
05221       return 0;
05222 
05223    while ((de = readdir(dir))) {
05224       if (!strncasecmp(de->d_name, "msg", 3)) {
05225          if (shortcircuit) {
05226             ret = 1;
05227             break;
05228          } else if (!strncasecmp(de->d_name + 8, "txt", 3)) {
05229             ret++;
05230          }
05231       }
05232    }
05233 
05234    closedir(dir);
05235 
05236    return ret;
05237 }
05238 
05239 /** 
05240  * \brief Determines if the given folder has messages.
05241  * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
05242  * \param folder the folder to look in
05243  *
05244  * This function is used when the mailbox is stored in a filesystem back end.
05245  * This invokes the __has_voicemail(). Here we are interested in the presence of messages (> 0) only, not the actual count.
05246  * \return 1 if the folder has one or more messages. zero otherwise.
05247  */
05248 static int has_voicemail(const char *mailbox, const char *folder)
05249 {
05250    char tmp[256], *tmp2 = tmp, *box, *context;
05251    ast_copy_string(tmp, mailbox, sizeof(tmp));
05252    if (ast_strlen_zero(folder)) {
05253       folder = "INBOX";
05254    }
05255    while ((box = strsep(&tmp2, ",&"))) {
05256       if ((context = strchr(box, '@')))
05257          *context++ = '\0';
05258       else
05259          context = "default";
05260       if (__has_voicemail(context, box, folder, 1))
05261          return 1;
05262       /* If we are checking INBOX, we should check Urgent as well */
05263       if (!strcmp(folder, "INBOX") && __has_voicemail(context, box, "Urgent", 1)) {
05264          return 1;
05265       }
05266    }
05267    return 0;
05268 }
05269 
05270 
05271 static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
05272 {
05273    char tmp[256];
05274    char *context;
05275 
05276    /* If no mailbox, return immediately */
05277    if (ast_strlen_zero(mailbox))
05278       return 0;
05279 
05280    if (newmsgs)
05281       *newmsgs = 0;
05282    if (oldmsgs)
05283       *oldmsgs = 0;
05284    if (urgentmsgs)
05285       *urgentmsgs = 0;
05286 
05287    if (strchr(mailbox, ',')) {
05288       int tmpnew, tmpold, tmpurgent;
05289       char *mb, *cur;
05290 
05291       ast_copy_string(tmp, mailbox, sizeof(tmp));
05292       mb = tmp;
05293       while ((cur = strsep(&mb, ", "))) {
05294          if (!ast_strlen_zero(cur)) {
05295             if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
05296                return -1;
05297             else {
05298                if (newmsgs)
05299                   *newmsgs += tmpnew; 
05300                if (oldmsgs)
05301                   *oldmsgs += tmpold;
05302                if (urgentmsgs)
05303                   *urgentmsgs += tmpurgent;
05304             }
05305          }
05306       }
05307       return 0;
05308    }
05309 
05310    ast_copy_string(tmp, mailbox, sizeof(tmp));
05311    
05312    if ((context = strchr(tmp, '@')))
05313       *context++ = '\0';
05314    else
05315       context = "default";
05316 
05317    if (newmsgs)
05318       *newmsgs = __has_voicemail(context, tmp, "INBOX", 0);
05319    if (oldmsgs)
05320       *oldmsgs = __has_voicemail(context, tmp, "Old", 0);
05321    if (urgentmsgs)
05322       *urgentmsgs = __has_voicemail(context, tmp, "Urgent", 0);
05323 
05324    return 0;
05325 }
05326 
05327 #endif
05328 
05329 /* Exactly the same function for file-based, ODBC-based, and IMAP-based, so why create 3 different copies? */
05330 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
05331 {
05332    int urgentmsgs = 0;
05333    int res = inboxcount2(mailbox, &urgentmsgs, newmsgs, oldmsgs);
05334    if (newmsgs) {
05335       *newmsgs += urgentmsgs;
05336    }
05337    return res;
05338 }
05339 
05340 static void run_externnotify(char *context, char *extension, const char *flag)
05341 {
05342    char arguments[255];
05343    char ext_context[256] = "";
05344    int newvoicemails = 0, oldvoicemails = 0, urgentvoicemails = 0;
05345    struct ast_smdi_mwi_message *mwi_msg;
05346 
05347    if (!ast_strlen_zero(context))
05348       snprintf(ext_context, sizeof(ext_context), "%s@%s", extension, context);
05349    else
05350       ast_copy_string(ext_context, extension, sizeof(ext_context));
05351 
05352    if (smdi_iface) {
05353       if (ast_app_has_voicemail(ext_context, NULL)) 
05354          ast_smdi_mwi_set(smdi_iface, extension);
05355       else
05356          ast_smdi_mwi_unset(smdi_iface, extension);
05357 
05358       if ((mwi_msg = ast_smdi_mwi_message_wait_station(smdi_iface, SMDI_MWI_WAIT_TIMEOUT, extension))) {
05359          ast_log(AST_LOG_ERROR, "Error executing SMDI MWI change for %s\n", extension);
05360          if (!strncmp(mwi_msg->cause, "INV", 3))
05361             ast_log(AST_LOG_ERROR, "Invalid MWI extension: %s\n", mwi_msg->fwd_st);
05362          else if (!strncmp(mwi_msg->cause, "BLK", 3))
05363             ast_log(AST_LOG_WARNING, "MWI light was already on or off for %s\n", mwi_msg->fwd_st);
05364          ast_log(AST_LOG_WARNING, "The switch reported '%s'\n", mwi_msg->cause);
05365          ASTOBJ_UNREF(mwi_msg, ast_smdi_mwi_message_destroy);
05366       } else {
05367          ast_debug(1, "Successfully executed SMDI MWI change for %s\n", extension);
05368       }
05369    }
05370 
05371    if (!ast_strlen_zero(externnotify)) {
05372       if (inboxcount2(ext_context, &urgentvoicemails, &newvoicemails, &oldvoicemails)) {
05373          ast_log(AST_LOG_ERROR, "Problem in calculating number of voicemail messages available for extension %s\n", extension);
05374       } else {
05375          snprintf(arguments, sizeof(arguments), "%s %s %s %d %d %d &", externnotify, context, extension, newvoicemails, oldvoicemails, urgentvoicemails);
05376          ast_debug(1, "Executing %s\n", arguments);
05377          ast_safe_system(arguments);
05378       }
05379    }
05380 }
05381 
05382 /*!
05383  * \brief Variables used for saving a voicemail.
05384  *
05385  * This includes the record gain, mode flags, and the exit context of the chanel that was used for leaving the voicemail.
05386  */
05387 struct leave_vm_options {
05388    unsigned int flags;
05389    signed char record_gain;
05390    char *exitcontext;
05391 };
05392 
05393 /*!
05394  * \brief Prompts the user and records a voicemail to a mailbox.
05395  * \param chan
05396  * \param ext
05397  * \param options OPT_BUSY_GREETING, OPT_UNAVAIL_GREETING
05398  * 
05399  * 
05400  * 
05401  * \return zero on success, -1 on error.
05402  */
05403 static int leave_voicemail(struct ast_channel *chan, char *ext, struct leave_vm_options *options)
05404 {
05405 #ifdef IMAP_STORAGE
05406    int newmsgs, oldmsgs;
05407 #else
05408    char urgdir[PATH_MAX];
05409 #endif
05410    char txtfile[PATH_MAX];
05411    char tmptxtfile[PATH_MAX];
05412    struct vm_state *vms = NULL;
05413    char callerid[256];
05414    FILE *txt;
05415    char date[256];
05416    int txtdes;
05417    int res = 0;
05418    int msgnum;
05419    int duration = 0;
05420    int ausemacro = 0;
05421    int ousemacro = 0;
05422    int ouseexten = 0;
05423    char tmpdur[16];
05424    char priority[16];
05425    char origtime[16];
05426    char dir[PATH_MAX];
05427    char tmpdir[PATH_MAX];
05428    char fn[PATH_MAX];
05429    char prefile[PATH_MAX] = "";
05430    char tempfile[PATH_MAX] = "";
05431    char ext_context[256] = "";
05432    char fmt[80];
05433    char *context;
05434    char ecodes[17] = "#";
05435    struct ast_str *tmp = ast_str_create(16);
05436    char *tmpptr;
05437    struct ast_vm_user *vmu;
05438    struct ast_vm_user svm;
05439    const char *category = NULL;
05440    const char *code;
05441    const char *alldtmf = "0123456789ABCD*#";
05442    char flag[80];
05443 
05444    if (!tmp) {
05445       return -1;
05446    }
05447 
05448    ast_str_set(&tmp, 0, "%s", ext);
05449    ext = ast_str_buffer(tmp);
05450    if ((context = strchr(ext, '@'))) {
05451       *context++ = '\0';
05452       tmpptr = strchr(context, '&');
05453    } else {
05454       tmpptr = strchr(ext, '&');
05455    }
05456 
05457    if (tmpptr)
05458       *tmpptr++ = '\0';
05459 
05460    ast_channel_lock(chan);
05461    if ((category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY"))) {
05462       category = ast_strdupa(category);
05463    }
05464    ast_channel_unlock(chan);
05465 
05466    if (ast_test_flag(options, OPT_MESSAGE_Urgent)) {
05467       ast_copy_string(flag, "Urgent", sizeof(flag));
05468    } else if (ast_test_flag(options, OPT_MESSAGE_PRIORITY)) {
05469       ast_copy_string(flag, "PRIORITY", sizeof(flag));
05470    } else {
05471       flag[0] = '\0';
05472    }
05473 
05474    ast_debug(3, "Before find_user\n");
05475    if (!(vmu = find_user(&svm, context, ext))) {
05476       ast_log(AST_LOG_WARNING, "No entry in voicemail config file for '%s'\n", ext);
05477       pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
05478       ast_free(tmp);
05479       return res;
05480    }
05481    /* Setup pre-file if appropriate */
05482    if (strcmp(vmu->context, "default"))
05483       snprintf(ext_context, sizeof(ext_context), "%s@%s", ext, vmu->context);
05484    else
05485       ast_copy_string(ext_context, vmu->mailbox, sizeof(ext_context));
05486 
05487    /* Set the path to the prefile. Will be one of 
05488       VM_SPOOL_DIRcontext/ext/busy
05489       VM_SPOOL_DIRcontext/ext/unavail
05490       Depending on the flag set in options.
05491    */
05492    if (ast_test_flag(options, OPT_BUSY_GREETING)) {
05493       snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, ext);
05494    } else if (ast_test_flag(options, OPT_UNAVAIL_GREETING)) {
05495       snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, ext);
05496    }
05497    /* Set the path to the tmpfile as
05498       VM_SPOOL_DIR/context/ext/temp
05499       and attempt to create the folder structure.
05500    */
05501    snprintf(tempfile, sizeof(tempfile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, ext);
05502    if ((res = create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, ext, "tmp"))) {
05503       ast_log(AST_LOG_WARNING, "Failed to make directory (%s)\n", tempfile);
05504       ast_free(tmp);
05505       return -1;
05506    }
05507    RETRIEVE(tempfile, -1, vmu->mailbox, vmu->context);
05508    if (ast_fileexists(tempfile, NULL, NULL) > 0)
05509       ast_copy_string(prefile, tempfile, sizeof(prefile));
05510 
05511    DISPOSE(tempfile, -1);
05512    /* It's easier just to try to make it than to check for its existence */
05513    create_dirpath(dir, sizeof(dir), vmu->context, ext, "INBOX");
05514 
05515    /* Check current or macro-calling context for special extensions */
05516    if (ast_test_flag(vmu, VM_OPERATOR)) {
05517       if (!ast_strlen_zero(vmu->exit)) {
05518          if (ast_exists_extension(chan, vmu->exit, "o", 1,
05519             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05520             strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
05521             ouseexten = 1;
05522          }
05523       } else if (ast_exists_extension(chan, chan->context, "o", 1,
05524          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05525          strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
05526          ouseexten = 1;
05527       } else if (!ast_strlen_zero(chan->macrocontext)
05528          && ast_exists_extension(chan, chan->macrocontext, "o", 1,
05529             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05530          strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
05531          ousemacro = 1;
05532       }
05533    }
05534 
05535    if (!ast_strlen_zero(vmu->exit)) {
05536       if (ast_exists_extension(chan, vmu->exit, "a", 1,
05537          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05538          strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
05539       }
05540    } else if (ast_exists_extension(chan, chan->context, "a", 1,
05541       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05542       strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
05543    } else if (!ast_strlen_zero(chan->macrocontext)
05544       && ast_exists_extension(chan, chan->macrocontext, "a", 1,
05545          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05546       strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
05547       ausemacro = 1;
05548    }
05549 
05550    if (ast_test_flag(options, OPT_DTMFEXIT)) {
05551       for (code = alldtmf; *code; code++) {
05552          char e[2] = "";
05553          e[0] = *code;
05554          if (strchr(ecodes, e[0]) == NULL
05555             && ast_canmatch_extension(chan, chan->context, e, 1,
05556                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
05557             strncat(ecodes, e, sizeof(ecodes) - strlen(ecodes) - 1);
05558          }
05559       }
05560    }
05561 
05562    /* Play the beginning intro if desired */
05563    if (!ast_strlen_zero(prefile)) {
05564 #ifdef ODBC_STORAGE
05565       int success = 
05566 #endif
05567          RETRIEVE(prefile, -1, ext, context);
05568       if (ast_fileexists(prefile, NULL, NULL) > 0) {
05569          if (ast_streamfile(chan, prefile, chan->language) > -1) 
05570             res = ast_waitstream(chan, ecodes);
05571 #ifdef ODBC_STORAGE
05572          if (success == -1) {
05573             /* We couldn't retrieve the file from the database, but we found it on the file system. Let's put it in the database. */
05574             ast_debug(1, "Greeting not retrieved from database, but found in file storage. Inserting into database\n");
05575             store_file(prefile, vmu->mailbox, vmu->context, -1);
05576          }
05577 #endif
05578       } else {
05579          ast_debug(1, "%s doesn't exist, doing what we can\n", prefile);
05580          res = invent_message(chan, vmu->context, ext, ast_test_flag(options, OPT_BUSY_GREETING), ecodes);
05581       }
05582       DISPOSE(prefile, -1);
05583       if (res < 0) {
05584          ast_debug(1, "Hang up during prefile playback\n");
05585          free_user(vmu);
05586          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
05587          ast_free(tmp);
05588          return -1;
05589       }
05590    }
05591    if (res == '#') {
05592       /* On a '#' we skip the instructions */
05593       ast_set_flag(options, OPT_SILENT);
05594       res = 0;
05595    }
05596    /* If maxmsg is zero, act as a "greetings only" voicemail: Exit successfully without recording */
05597    if (vmu->maxmsg == 0) {
05598       if (option_debug > 2)
05599          ast_log(LOG_DEBUG, "Greetings only VM (maxmsg=0), Skipping voicemail recording\n");
05600       pbx_builtin_setvar_helper(chan, "VMSTATUS", "SUCCESS");
05601       goto leave_vm_out;
05602    }
05603    if (!res && !ast_test_flag(options, OPT_SILENT)) {
05604       res = ast_stream_and_wait(chan, INTRO, ecodes);
05605       if (res == '#') {
05606          ast_set_flag(options, OPT_SILENT);
05607          res = 0;
05608       }
05609    }
05610    if (res > 0)
05611       ast_stopstream(chan);
05612    /* Check for a '*' here in case the caller wants to escape from voicemail to something
05613     other than the operator -- an automated attendant or mailbox login for example */
05614    if (res == '*') {
05615       chan->exten[0] = 'a';
05616       chan->exten[1] = '\0';
05617       if (!ast_strlen_zero(vmu->exit)) {
05618          ast_copy_string(chan->context, vmu->exit, sizeof(chan->context));
05619       } else if (ausemacro && !ast_strlen_zero(chan->macrocontext)) {
05620          ast_copy_string(chan->context, chan->macrocontext, sizeof(chan->context));
05621       }
05622       chan->priority = 0;
05623       free_user(vmu);
05624       pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
05625       ast_free(tmp);
05626       return 0;
05627    }
05628 
05629    /* Check for a '0' here */
05630    if (ast_test_flag(vmu, VM_OPERATOR) && res == '0') {
05631    transfer:
05632       if (ouseexten || ousemacro) {
05633          chan->exten[0] = 'o';
05634          chan->exten[1] = '\0';
05635          if (!ast_strlen_zero(vmu->exit)) {
05636             ast_copy_string(chan->context, vmu->exit, sizeof(chan->context));
05637          } else if (ousemacro && !ast_strlen_zero(chan->macrocontext)) {
05638             ast_copy_string(chan->context, chan->macrocontext, sizeof(chan->context));
05639          }
05640          ast_play_and_wait(chan, "transfer");
05641          chan->priority = 0;
05642          free_user(vmu);
05643          pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
05644       }
05645       ast_free(tmp);
05646       return OPERATOR_EXIT;
05647    }
05648 
05649    /* Allow all other digits to exit Voicemail and return to the dialplan */
05650    if (ast_test_flag(options, OPT_DTMFEXIT) && res > 0) {
05651       if (!ast_strlen_zero(options->exitcontext))
05652          ast_copy_string(chan->context, options->exitcontext, sizeof(chan->context));
05653       free_user(vmu);
05654       pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
05655       ast_free(tmp);
05656       return res;
05657    }
05658 
05659    if (res < 0) {
05660       free_user(vmu);
05661       pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
05662       ast_free(tmp);
05663       return -1;
05664    }
05665    /* The meat of recording the message...  All the announcements and beeps have been played*/
05666    ast_copy_string(fmt, vmfmts, sizeof(fmt));
05667    if (!ast_strlen_zero(fmt)) {
05668       msgnum = 0;
05669 
05670 #ifdef IMAP_STORAGE
05671       /* Is ext a mailbox? */
05672       /* must open stream for this user to get info! */
05673       res = inboxcount(ext_context, &newmsgs, &oldmsgs);
05674       if (res < 0) {
05675          ast_log(AST_LOG_NOTICE, "Can not leave voicemail, unable to count messages\n");
05676          ast_free(tmp);
05677          return -1;
05678       }
05679       if (!(vms = get_vm_state_by_mailbox(ext, context, 0))) {
05680       /* It is possible under certain circumstances that inboxcount did not
05681        * create a vm_state when it was needed. This is a catchall which will
05682        * rarely be used.
05683        */
05684          if (!(vms = create_vm_state_from_user(vmu))) {
05685             ast_log(AST_LOG_ERROR, "Couldn't allocate necessary space\n");
05686             ast_free(tmp);
05687             return -1;
05688          }
05689       }
05690       vms->newmessages++;
05691       
05692       /* here is a big difference! We add one to it later */
05693       msgnum = newmsgs + oldmsgs;
05694       ast_debug(3, "Messagecount set to %d\n", msgnum);
05695       snprintf(fn, sizeof(fn), "%s/imap/msg%s%04d", VM_SPOOL_DIR, vmu->mailbox, msgnum);
05696       /* set variable for compatibility */
05697       pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", "IMAP_STORAGE");
05698 
05699       if ((res = imap_check_limits(chan, vms, vmu, msgnum))) {
05700          goto leave_vm_out;
05701       }
05702 #else
05703       if (count_messages(vmu, dir) >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
05704          res = ast_streamfile(chan, "vm-mailboxfull", chan->language);
05705          if (!res)
05706             res = ast_waitstream(chan, "");
05707          ast_log(AST_LOG_WARNING, "No more messages possible\n");
05708          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
05709          inprocess_count(vmu->mailbox, vmu->context, -1);
05710          goto leave_vm_out;
05711       }
05712 
05713 #endif
05714       snprintf(tmptxtfile, sizeof(tmptxtfile), "%s/XXXXXX", tmpdir);
05715       txtdes = mkstemp(tmptxtfile);
05716       chmod(tmptxtfile, VOICEMAIL_FILE_MODE & ~my_umask);
05717       if (txtdes < 0) {
05718          res = ast_streamfile(chan, "vm-mailboxfull", chan->language);
05719          if (!res)
05720             res = ast_waitstream(chan, "");
05721          ast_log(AST_LOG_ERROR, "Unable to create message file: %s\n", strerror(errno));
05722          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
05723          inprocess_count(vmu->mailbox, vmu->context, -1);
05724          goto leave_vm_out;
05725       }
05726 
05727       /* Now play the beep once we have the message number for our next message. */
05728       if (res >= 0) {
05729          /* Unless we're *really* silent, try to send the beep */
05730          res = ast_stream_and_wait(chan, "beep", "");
05731       }
05732             
05733       /* Store information in real-time storage */
05734       if (ast_check_realtime("voicemail_data")) {
05735          snprintf(priority, sizeof(priority), "%d", chan->priority);
05736          snprintf(origtime, sizeof(origtime), "%ld", (long) time(NULL));
05737          get_date(date, sizeof(date));
05738          ast_callerid_merge(callerid, sizeof(callerid),
05739             S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
05740             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
05741             "Unknown");
05742          ast_store_realtime("voicemail_data",
05743             "origmailbox", ext,
05744             "context", chan->context,
05745             "macrocontext", chan->macrocontext,
05746             "exten", chan->exten,
05747             "priority", priority,
05748             "callerchan", chan->name,
05749             "callerid", callerid,
05750             "origdate", date,
05751             "origtime", origtime,
05752             "category", S_OR(category, ""),
05753             "filename", tmptxtfile,
05754             SENTINEL);
05755       }
05756 
05757       /* Store information */
05758       txt = fdopen(txtdes, "w+");
05759       if (txt) {
05760          get_date(date, sizeof(date));
05761          ast_callerid_merge(callerid, sizeof(callerid),
05762             S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
05763             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
05764             "Unknown");
05765          fprintf(txt, 
05766             ";\n"
05767             "; Message Information file\n"
05768             ";\n"
05769             "[message]\n"
05770             "origmailbox=%s\n"
05771             "context=%s\n"
05772             "macrocontext=%s\n"
05773             "exten=%s\n"
05774             "rdnis=%s\n"
05775             "priority=%d\n"
05776             "callerchan=%s\n"
05777             "callerid=%s\n"
05778             "origdate=%s\n"
05779             "origtime=%ld\n"
05780             "category=%s\n",
05781             ext,
05782             chan->context,
05783             chan->macrocontext, 
05784             chan->exten,
05785             S_COR(chan->redirecting.from.number.valid,
05786                chan->redirecting.from.number.str, "unknown"),
05787             chan->priority,
05788             chan->name,
05789             callerid,
05790             date, (long) time(NULL),
05791             category ? category : "");
05792       } else {
05793          ast_log(AST_LOG_WARNING, "Error opening text file for output\n");
05794          inprocess_count(vmu->mailbox, vmu->context, -1);
05795          if (ast_check_realtime("voicemail_data")) {
05796             ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
05797          }
05798          res = ast_streamfile(chan, "vm-mailboxfull", chan->language);
05799          goto leave_vm_out;
05800       }
05801       res = play_record_review(chan, NULL, tmptxtfile, vmu->maxsecs, fmt, 1, vmu, &duration, NULL, options->record_gain, vms, flag);
05802 
05803       if (txt) {
05804          fprintf(txt, "flag=%s\n", flag);
05805          if (duration < vmu->minsecs) {
05806             fclose(txt);
05807             ast_verb(3, "Recording was %d seconds long but needs to be at least %d - abandoning\n", duration, vmu->minsecs);
05808             ast_filedelete(tmptxtfile, NULL);
05809             unlink(tmptxtfile);
05810             if (ast_check_realtime("voicemail_data")) {
05811                ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
05812             }
05813             inprocess_count(vmu->mailbox, vmu->context, -1);
05814          } else {
05815             fprintf(txt, "duration=%d\n", duration);
05816             fclose(txt);
05817             if (vm_lock_path(dir)) {
05818                ast_log(AST_LOG_ERROR, "Couldn't lock directory %s.  Voicemail will be lost.\n", dir);
05819                /* Delete files */
05820                ast_filedelete(tmptxtfile, NULL);
05821                unlink(tmptxtfile);
05822                inprocess_count(vmu->mailbox, vmu->context, -1);
05823             } else if (ast_fileexists(tmptxtfile, NULL, NULL) <= 0) {
05824                ast_debug(1, "The recorded media file is gone, so we should remove the .txt file too!\n");
05825                unlink(tmptxtfile);
05826                ast_unlock_path(dir);
05827                inprocess_count(vmu->mailbox, vmu->context, -1);
05828                if (ast_check_realtime("voicemail_data")) {
05829                   ast_destroy_realtime("voicemail_data", "filename", tmptxtfile, SENTINEL);
05830                }
05831             } else {
05832 #ifndef IMAP_STORAGE
05833                msgnum = last_message_index(vmu, dir) + 1;
05834 #endif
05835                make_file(fn, sizeof(fn), dir, msgnum);
05836 
05837                /* assign a variable with the name of the voicemail file */ 
05838 #ifndef IMAP_STORAGE
05839                pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", fn);
05840 #else
05841                pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", "IMAP_STORAGE");
05842 #endif
05843 
05844                snprintf(txtfile, sizeof(txtfile), "%s.txt", fn);
05845                ast_filerename(tmptxtfile, fn, NULL);
05846                rename(tmptxtfile, txtfile);
05847                inprocess_count(vmu->mailbox, vmu->context, -1);
05848 
05849                /* Properly set permissions on voicemail text descriptor file.
05850                   Unfortunately mkstemp() makes this file 0600 on most unix systems. */
05851                if (chmod(txtfile, VOICEMAIL_FILE_MODE) < 0)
05852                   ast_log(AST_LOG_ERROR, "Couldn't set permissions on voicemail text file %s: %s", txtfile, strerror(errno));
05853 
05854                ast_unlock_path(dir);
05855                if (ast_check_realtime("voicemail_data")) {
05856                   snprintf(tmpdur, sizeof(tmpdur), "%d", duration);
05857                   ast_update_realtime("voicemail_data", "filename", tmptxtfile, "filename", fn, "duration", tmpdur, SENTINEL);
05858                }
05859                /* We must store the file first, before copying the message, because
05860                 * ODBC storage does the entire copy with SQL.
05861                 */
05862                if (ast_fileexists(fn, NULL, NULL) > 0) {
05863                   STORE(dir, vmu->mailbox, vmu->context, msgnum, chan, vmu, fmt, duration, vms, flag);
05864                }
05865 
05866                /* Are there to be more recipients of this message? */
05867                while (tmpptr) {
05868                   struct ast_vm_user recipu, *recip;
05869                   char *exten, *cntx;
05870                
05871                   exten = strsep(&tmpptr, "&");
05872                   cntx = strchr(exten, '@');
05873                   if (cntx) {
05874                      *cntx = '\0';
05875                      cntx++;
05876                   }
05877                   if ((recip = find_user(&recipu, cntx, exten))) {
05878                      copy_message(chan, vmu, 0, msgnum, duration, recip, fmt, dir, flag);
05879                      free_user(recip);
05880                   }
05881                }
05882 #ifndef IMAP_STORAGE
05883                if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) { /* If this is an Urgent message */
05884                   /* Move the message from INBOX to Urgent folder if this is urgent! */
05885                   char sfn[PATH_MAX];
05886                   char dfn[PATH_MAX];
05887                   int x;
05888                   /* It's easier just to try to make it than to check for its existence */
05889                   create_dirpath(urgdir, sizeof(urgdir), vmu->context, ext, "Urgent");
05890                   x = last_message_index(vmu, urgdir) + 1;
05891                   make_file(sfn, sizeof(sfn), dir, msgnum);
05892                   make_file(dfn, sizeof(dfn), urgdir, x);
05893                   ast_debug(5, "Created an Urgent message, moving file from %s to %s.\n", sfn, dfn);
05894                   RENAME(dir, msgnum, vmu->mailbox, vmu->context, urgdir, x, sfn, dfn);
05895                   /* Notification must happen for this new message in Urgent folder, not INBOX */
05896                   ast_copy_string(fn, dfn, sizeof(fn));
05897                   msgnum = x;
05898                }
05899 #endif
05900                /* Notification needs to happen after the copy, though. */
05901                if (ast_fileexists(fn, NULL, NULL)) {
05902 #ifdef IMAP_STORAGE
05903                   notify_new_message(chan, vmu, vms, msgnum, duration, fmt,
05904                      S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
05905                      S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
05906                      flag);
05907 #else
05908                   notify_new_message(chan, vmu, NULL, msgnum, duration, fmt,
05909                      S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
05910                      S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
05911                      flag);
05912 #endif
05913                }
05914 
05915                /* Disposal needs to happen after the optional move and copy */
05916                if (ast_fileexists(fn, NULL, NULL)) {
05917                   DISPOSE(dir, msgnum);
05918                }
05919             }
05920          }
05921       } else {
05922          inprocess_count(vmu->mailbox, vmu->context, -1);
05923       }
05924       if (res == '0') {
05925          goto transfer;
05926       } else if (res > 0)
05927          res = 0;
05928 
05929       if (duration < vmu->minsecs)
05930          /* XXX We should really give a prompt too short/option start again, with leave_vm_out called only after a timeout XXX */
05931          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
05932       else
05933          pbx_builtin_setvar_helper(chan, "VMSTATUS", "SUCCESS");
05934    } else
05935       ast_log(AST_LOG_WARNING, "No format for saving voicemail?\n");
05936 leave_vm_out:
05937    free_user(vmu);
05938 
05939 #ifdef IMAP_STORAGE
05940    /* expunge message - use UID Expunge if supported on IMAP server*/
05941    ast_debug(3, "*** Checking if we can expunge, expungeonhangup set to %d\n", expungeonhangup);
05942    if (expungeonhangup == 1) {
05943       ast_mutex_lock(&vms->lock);
05944 #ifdef HAVE_IMAP_TK2006
05945       if (LEVELUIDPLUS (vms->mailstream)) {
05946          mail_expunge_full(vms->mailstream, NIL, EX_UID);
05947       } else 
05948 #endif
05949          mail_expunge(vms->mailstream);
05950       ast_mutex_unlock(&vms->lock);
05951    }
05952 #endif
05953 
05954    ast_free(tmp);
05955    return res;
05956 }
05957 
05958 static int say_and_wait(struct ast_channel *chan, int num, const char *language)
05959 {
05960    int d;
05961    d = ast_say_number(chan, num, AST_DIGIT_ANY, language, NULL);
05962    return d;
05963 }
05964 
05965 static int save_to_folder(struct ast_vm_user *vmu, struct vm_state *vms, int msg, int box)
05966 {
05967 #ifdef IMAP_STORAGE
05968    /* we must use mbox(x) folder names, and copy the message there */
05969    /* simple. huh? */
05970    char sequence[10];
05971    char mailbox[256];
05972    int res;
05973 
05974    /* get the real IMAP message number for this message */
05975    snprintf(sequence, sizeof(sequence), "%ld", vms->msgArray[msg]);
05976    
05977    ast_debug(3, "Copying sequence %s to mailbox %s\n", sequence, mbox(vmu, box));
05978    ast_mutex_lock(&vms->lock);
05979    /* if save to Old folder, put in INBOX as read */
05980    if (box == OLD_FOLDER) {
05981       mail_setflag(vms->mailstream, sequence, "\\Seen");
05982       mail_clearflag(vms->mailstream, sequence, "\\Unseen");
05983    } else if (box == NEW_FOLDER) {
05984       mail_setflag(vms->mailstream, sequence, "\\Unseen");
05985       mail_clearflag(vms->mailstream, sequence, "\\Seen");
05986    }
05987    if (!strcasecmp(mbox(vmu, NEW_FOLDER), vms->curbox) && (box == NEW_FOLDER || box == OLD_FOLDER)) {
05988       ast_mutex_unlock(&vms->lock);
05989       return 0;
05990    }
05991    /* Create the folder if it don't exist */
05992    imap_mailbox_name(mailbox, sizeof(mailbox), vms, box, 1); /* Get the full mailbox name */
05993    ast_debug(5, "Checking if folder exists: %s\n", mailbox);
05994    if (mail_create(vms->mailstream, mailbox) == NIL) 
05995       ast_debug(5, "Folder exists.\n");
05996    else
05997       ast_log(AST_LOG_NOTICE, "Folder %s created!\n", mbox(vmu, box));
05998    res = !mail_copy(vms->mailstream, sequence, (char *) mbox(vmu, box));
05999    ast_mutex_unlock(&vms->lock);
06000    return res;
06001 #else
06002    char *dir = vms->curdir;
06003    char *username = vms->username;
06004    char *context = vmu->context;
06005    char sfn[PATH_MAX];
06006    char dfn[PATH_MAX];
06007    char ddir[PATH_MAX];
06008    const char *dbox = mbox(vmu, box);
06009    int x, i;
06010    create_dirpath(ddir, sizeof(ddir), context, username, dbox);
06011 
06012    if (vm_lock_path(ddir))
06013       return ERROR_LOCK_PATH;
06014 
06015    x = last_message_index(vmu, ddir) + 1;
06016 
06017    if (box == 10 && x >= vmu->maxdeletedmsg) { /* "Deleted" folder*/
06018       x--;
06019       for (i = 1; i <= x; i++) {
06020          /* Push files down a "slot".  The oldest file (msg0000) will be deleted. */
06021          make_file(sfn, sizeof(sfn), ddir, i);
06022          make_file(dfn, sizeof(dfn), ddir, i - 1);
06023          if (EXISTS(ddir, i, sfn, NULL)) {
06024             RENAME(ddir, i, vmu->mailbox, vmu->context, ddir, i - 1, sfn, dfn);
06025          } else
06026             break;
06027       }
06028    } else {
06029       if (x >= vmu->maxmsg) {
06030          ast_unlock_path(ddir);
06031          return -1;
06032       }
06033    }
06034    make_file(sfn, sizeof(sfn), dir, msg);
06035    make_file(dfn, sizeof(dfn), ddir, x);
06036    if (strcmp(sfn, dfn)) {
06037       COPY(dir, msg, ddir, x, username, context, sfn, dfn);
06038    }
06039    ast_unlock_path(ddir);
06040 #endif
06041    return 0;
06042 }
06043 
06044 static int adsi_logo(unsigned char *buf)
06045 {
06046    int bytes = 0;
06047    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_CENT, 0, "Comedian Mail", "");
06048    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_CENT, 0, "(C)2002-2006 Digium, Inc.", "");
06049    return bytes;
06050 }
06051 
06052 static int adsi_load_vmail(struct ast_channel *chan, int *useadsi)
06053 {
06054    unsigned char buf[256];
06055    int bytes = 0;
06056    int x;
06057    char num[5];
06058 
06059    *useadsi = 0;
06060    bytes += ast_adsi_data_mode(buf + bytes);
06061    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06062 
06063    bytes = 0;
06064    bytes += adsi_logo(buf);
06065    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Downloading Scripts", "");
06066 #ifdef DISPLAY
06067    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   .", "");
06068 #endif
06069    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06070    bytes += ast_adsi_data_mode(buf + bytes);
06071    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06072 
06073    if (ast_adsi_begin_download(chan, addesc, adsifdn, adsisec, adsiver)) {
06074       bytes = 0;
06075       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Load Cancelled.", "");
06076       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "ADSI Unavailable", "");
06077       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06078       bytes += ast_adsi_voice_mode(buf + bytes, 0);
06079       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06080       return 0;
06081    }
06082 
06083 #ifdef DISPLAY
06084    /* Add a dot */
06085    bytes = 0;
06086    bytes += ast_adsi_logo(buf);
06087    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Downloading Scripts", "");
06088    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   ..", "");
06089    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06090    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06091 #endif
06092    bytes = 0;
06093    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 0, "Listen", "Listen", "1", 1);
06094    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 1, "Folder", "Folder", "2", 1);
06095    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 2, "Advanced", "Advnced", "3", 1);
06096    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 3, "Options", "Options", "0", 1);
06097    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 4, "Help", "Help", "*", 1);
06098    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 5, "Exit", "Exit", "#", 1);
06099    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
06100 
06101 #ifdef DISPLAY
06102    /* Add another dot */
06103    bytes = 0;
06104    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   ...", "");
06105    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06106 
06107    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06108    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06109 #endif
06110 
06111    bytes = 0;
06112    /* These buttons we load but don't use yet */
06113    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 6, "Previous", "Prev", "4", 1);
06114    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 8, "Repeat", "Repeat", "5", 1);
06115    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 7, "Delete", "Delete", "7", 1);
06116    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 9, "Next", "Next", "6", 1);
06117    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 10, "Save", "Save", "9", 1);
06118    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 11, "Undelete", "Restore", "7", 1);
06119    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
06120 
06121 #ifdef DISPLAY
06122    /* Add another dot */
06123    bytes = 0;
06124    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   ....", "");
06125    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06126    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06127 #endif
06128 
06129    bytes = 0;
06130    for (x = 0; x < 5; x++) {
06131       snprintf(num, sizeof(num), "%d", x);
06132       bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 12 + x, mbox(NULL, x), mbox(NULL, x), num, 1);
06133    }
06134    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 12 + 5, "Cancel", "Cancel", "#", 1);
06135    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
06136 
06137 #ifdef DISPLAY
06138    /* Add another dot */
06139    bytes = 0;
06140    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   .....", "");
06141    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06142    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06143 #endif
06144 
06145    if (ast_adsi_end_download(chan)) {
06146       bytes = 0;
06147       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Download Unsuccessful.", "");
06148       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "ADSI Unavailable", "");
06149       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06150       bytes += ast_adsi_voice_mode(buf + bytes, 0);
06151       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06152       return 0;
06153    }
06154    bytes = 0;
06155    bytes += ast_adsi_download_disconnect(buf + bytes);
06156    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06157    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
06158 
06159    ast_debug(1, "Done downloading scripts...\n");
06160 
06161 #ifdef DISPLAY
06162    /* Add last dot */
06163    bytes = 0;
06164    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "   ......", "");
06165    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06166 #endif
06167    ast_debug(1, "Restarting session...\n");
06168 
06169    bytes = 0;
06170    /* Load the session now */
06171    if (ast_adsi_load_session(chan, adsifdn, adsiver, 1) == 1) {
06172       *useadsi = 1;
06173       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Scripts Loaded!", "");
06174    } else
06175       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Load Failed!", "");
06176 
06177    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06178    return 0;
06179 }
06180 
06181 static void adsi_begin(struct ast_channel *chan, int *useadsi)
06182 {
06183    int x;
06184    if (!ast_adsi_available(chan))
06185       return;
06186    x = ast_adsi_load_session(chan, adsifdn, adsiver, 1);
06187    if (x < 0)
06188       return;
06189    if (!x) {
06190       if (adsi_load_vmail(chan, useadsi)) {
06191          ast_log(AST_LOG_WARNING, "Unable to upload voicemail scripts\n");
06192          return;
06193       }
06194    } else
06195       *useadsi = 1;
06196 }
06197 
06198 static void adsi_login(struct ast_channel *chan)
06199 {
06200    unsigned char buf[256];
06201    int bytes = 0;
06202    unsigned char keys[8];
06203    int x;
06204    if (!ast_adsi_available(chan))
06205       return;
06206 
06207    for (x = 0; x < 8; x++)
06208       keys[x] = 0;
06209    /* Set one key for next */
06210    keys[3] = ADSI_KEY_APPS + 3;
06211 
06212    bytes += adsi_logo(buf + bytes);
06213    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, " ", "");
06214    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, " ", "");
06215    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06216    bytes += ast_adsi_input_format(buf + bytes, 1, ADSI_DIR_FROM_LEFT, 0, "Mailbox: ******", "");
06217    bytes += ast_adsi_input_control(buf + bytes, ADSI_COMM_PAGE, 4, 1, 1, ADSI_JUST_LEFT);
06218    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 3, "Enter", "Enter", "#", 1);
06219    bytes += ast_adsi_set_keys(buf + bytes, keys);
06220    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06221    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06222 }
06223 
06224 static void adsi_password(struct ast_channel *chan)
06225 {
06226    unsigned char buf[256];
06227    int bytes = 0;
06228    unsigned char keys[8];
06229    int x;
06230    if (!ast_adsi_available(chan))
06231       return;
06232 
06233    for (x = 0; x < 8; x++)
06234       keys[x] = 0;
06235    /* Set one key for next */
06236    keys[3] = ADSI_KEY_APPS + 3;
06237 
06238    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06239    bytes += ast_adsi_input_format(buf + bytes, 1, ADSI_DIR_FROM_LEFT, 0, "Password: ******", "");
06240    bytes += ast_adsi_input_control(buf + bytes, ADSI_COMM_PAGE, 4, 0, 1, ADSI_JUST_LEFT);
06241    bytes += ast_adsi_set_keys(buf + bytes, keys);
06242    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06243    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06244 }
06245 
06246 static void adsi_folders(struct ast_channel *chan, int start, char *label)
06247 {
06248    unsigned char buf[256];
06249    int bytes = 0;
06250    unsigned char keys[8];
06251    int x, y;
06252 
06253    if (!ast_adsi_available(chan))
06254       return;
06255 
06256    for (x = 0; x < 5; x++) {
06257       y = ADSI_KEY_APPS + 12 + start + x;
06258       if (y > ADSI_KEY_APPS + 12 + 4)
06259          y = 0;
06260       keys[x] = ADSI_KEY_SKT | y;
06261    }
06262    keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 17);
06263    keys[6] = 0;
06264    keys[7] = 0;
06265 
06266    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_CENT, 0, label, "");
06267    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_CENT, 0, " ", "");
06268    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06269    bytes += ast_adsi_set_keys(buf + bytes, keys);
06270    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06271 
06272    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06273 }
06274 
06275 static void adsi_message(struct ast_channel *chan, struct vm_state *vms)
06276 {
06277    int bytes = 0;
06278    unsigned char buf[256]; 
06279    char buf1[256], buf2[256];
06280    char fn2[PATH_MAX];
06281 
06282    char cid[256] = "";
06283    char *val;
06284    char *name, *num;
06285    char datetime[21] = "";
06286    FILE *f;
06287 
06288    unsigned char keys[8];
06289 
06290    int x;
06291 
06292    if (!ast_adsi_available(chan))
06293       return;
06294 
06295    /* Retrieve important info */
06296    snprintf(fn2, sizeof(fn2), "%s.txt", vms->fn);
06297    f = fopen(fn2, "r");
06298    if (f) {
06299       while (!feof(f)) {   
06300          if (!fgets((char *) buf, sizeof(buf), f)) {
06301             continue;
06302          }
06303          if (!feof(f)) {
06304             char *stringp = NULL;
06305             stringp = (char *) buf;
06306             strsep(&stringp, "=");
06307             val = strsep(&stringp, "=");
06308             if (!ast_strlen_zero(val)) {
06309                if (!strcmp((char *) buf, "callerid"))
06310                   ast_copy_string(cid, val, sizeof(cid));
06311                if (!strcmp((char *) buf, "origdate"))
06312                   ast_copy_string(datetime, val, sizeof(datetime));
06313             }
06314          }
06315       }
06316       fclose(f);
06317    }
06318    /* New meaning for keys */
06319    for (x = 0; x < 5; x++)
06320       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 6 + x);
06321    keys[6] = 0x0;
06322    keys[7] = 0x0;
06323 
06324    if (!vms->curmsg) {
06325       /* No prev key, provide "Folder" instead */
06326       keys[0] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
06327    }
06328    if (vms->curmsg >= vms->lastmsg) {
06329       /* If last message ... */
06330       if (vms->curmsg) {
06331          /* but not only message, provide "Folder" instead */
06332          keys[3] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
06333          bytes += ast_adsi_voice_mode(buf + bytes, 0);
06334 
06335       } else {
06336          /* Otherwise if only message, leave blank */
06337          keys[3] = 1;
06338       }
06339    }
06340 
06341    if (!ast_strlen_zero(cid)) {
06342       ast_callerid_parse(cid, &name, &num);
06343       if (!name)
06344          name = num;
06345    } else
06346       name = "Unknown Caller";
06347 
06348    /* If deleted, show "undeleted" */
06349 
06350    if (vms->deleted[vms->curmsg])
06351       keys[1] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 11);
06352 
06353    /* Except "Exit" */
06354    keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 5);
06355    snprintf(buf1, sizeof(buf1), "%s%s", vms->curbox,
06356       strcasecmp(vms->curbox, "INBOX") ? " Messages" : "");
06357    snprintf(buf2, sizeof(buf2), "Message %d of %d", vms->curmsg + 1, vms->lastmsg + 1);
06358 
06359    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
06360    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
06361    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, name, "");
06362    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, datetime, "");
06363    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06364    bytes += ast_adsi_set_keys(buf + bytes, keys);
06365    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06366 
06367    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06368 }
06369 
06370 static void adsi_delete(struct ast_channel *chan, struct vm_state *vms)
06371 {
06372    int bytes = 0;
06373    unsigned char buf[256];
06374    unsigned char keys[8];
06375 
06376    int x;
06377 
06378    if (!ast_adsi_available(chan))
06379       return;
06380 
06381    /* New meaning for keys */
06382    for (x = 0; x < 5; x++)
06383       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 6 + x);
06384 
06385    keys[6] = 0x0;
06386    keys[7] = 0x0;
06387 
06388    if (!vms->curmsg) {
06389       /* No prev key, provide "Folder" instead */
06390       keys[0] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
06391    }
06392    if (vms->curmsg >= vms->lastmsg) {
06393       /* If last message ... */
06394       if (vms->curmsg) {
06395          /* but not only message, provide "Folder" instead */
06396          keys[3] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
06397       } else {
06398          /* Otherwise if only message, leave blank */
06399          keys[3] = 1;
06400       }
06401    }
06402 
06403    /* If deleted, show "undeleted" */
06404    if (vms->deleted[vms->curmsg]) 
06405       keys[1] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 11);
06406 
06407    /* Except "Exit" */
06408    keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 5);
06409    bytes += ast_adsi_set_keys(buf + bytes, keys);
06410    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06411 
06412    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06413 }
06414 
06415 static void adsi_status(struct ast_channel *chan, struct vm_state *vms)
06416 {
06417    unsigned char buf[256] = "";
06418    char buf1[256] = "", buf2[256] = "";
06419    int bytes = 0;
06420    unsigned char keys[8];
06421    int x;
06422 
06423    char *newm = (vms->newmessages == 1) ? "message" : "messages";
06424    char *oldm = (vms->oldmessages == 1) ? "message" : "messages";
06425    if (!ast_adsi_available(chan))
06426       return;
06427    if (vms->newmessages) {
06428       snprintf(buf1, sizeof(buf1), "You have %d new", vms->newmessages);
06429       if (vms->oldmessages) {
06430          strncat(buf1, " and", sizeof(buf1) - strlen(buf1) - 1);
06431          snprintf(buf2, sizeof(buf2), "%d old %s.", vms->oldmessages, oldm);
06432       } else {
06433          snprintf(buf2, sizeof(buf2), "%s.", newm);
06434       }
06435    } else if (vms->oldmessages) {
06436       snprintf(buf1, sizeof(buf1), "You have %d old", vms->oldmessages);
06437       snprintf(buf2, sizeof(buf2), "%s.", oldm);
06438    } else {
06439       strcpy(buf1, "You have no messages.");
06440       buf2[0] = ' ';
06441       buf2[1] = '\0';
06442    }
06443    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
06444    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
06445    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06446 
06447    for (x = 0; x < 6; x++)
06448       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + x);
06449    keys[6] = 0;
06450    keys[7] = 0;
06451 
06452    /* Don't let them listen if there are none */
06453    if (vms->lastmsg < 0)
06454       keys[0] = 1;
06455    bytes += ast_adsi_set_keys(buf + bytes, keys);
06456 
06457    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06458 
06459    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06460 }
06461 
06462 static void adsi_status2(struct ast_channel *chan, struct vm_state *vms)
06463 {
06464    unsigned char buf[256] = "";
06465    char buf1[256] = "", buf2[256] = "";
06466    int bytes = 0;
06467    unsigned char keys[8];
06468    int x;
06469 
06470    char *mess = (vms->lastmsg == 0) ? "message" : "messages";
06471 
06472    if (!ast_adsi_available(chan))
06473       return;
06474 
06475    /* Original command keys */
06476    for (x = 0; x < 6; x++)
06477       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + x);
06478 
06479    keys[6] = 0;
06480    keys[7] = 0;
06481 
06482    if ((vms->lastmsg + 1) < 1)
06483       keys[0] = 0;
06484 
06485    snprintf(buf1, sizeof(buf1), "%s%s has", vms->curbox,
06486       strcasecmp(vms->curbox, "INBOX") ? " folder" : "");
06487 
06488    if (vms->lastmsg + 1)
06489       snprintf(buf2, sizeof(buf2), "%d %s.", vms->lastmsg + 1, mess);
06490    else
06491       strcpy(buf2, "no messages.");
06492    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
06493    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
06494    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, "", "");
06495    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06496    bytes += ast_adsi_set_keys(buf + bytes, keys);
06497 
06498    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06499 
06500    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06501    
06502 }
06503 
06504 /*
06505 static void adsi_clear(struct ast_channel *chan)
06506 {
06507    char buf[256];
06508    int bytes=0;
06509    if (!ast_adsi_available(chan))
06510       return;
06511    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06512    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06513 
06514    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06515 }
06516 */
06517 
06518 static void adsi_goodbye(struct ast_channel *chan)
06519 {
06520    unsigned char buf[256];
06521    int bytes = 0;
06522 
06523    if (!ast_adsi_available(chan))
06524       return;
06525    bytes += adsi_logo(buf + bytes);
06526    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, " ", "");
06527    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Goodbye", "");
06528    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06529    bytes += ast_adsi_voice_mode(buf + bytes, 0);
06530 
06531    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06532 }
06533 
06534 /*!\brief get_folder: Folder menu
06535  * Plays "press 1 for INBOX messages" etc.
06536  * Should possibly be internationalized
06537  */
06538 static int get_folder(struct ast_channel *chan, int start)
06539 {
06540    int x;
06541    int d;
06542    char fn[PATH_MAX];
06543    d = ast_play_and_wait(chan, "vm-press");  /* "Press" */
06544    if (d)
06545       return d;
06546    for (x = start; x < 5; x++) { /* For all folders */
06547       if ((d = ast_say_number(chan, x, AST_DIGIT_ANY, chan->language, NULL)))
06548          return d;
06549       d = ast_play_and_wait(chan, "vm-for"); /* "for" */
06550       if (d)
06551          return d;
06552       snprintf(fn, sizeof(fn), "vm-%s", mbox(NULL, x));  /* Folder name */
06553       d = vm_play_folder_name(chan, fn);
06554       if (d)
06555          return d;
06556       d = ast_waitfordigit(chan, 500);
06557       if (d)
06558          return d;
06559    }
06560    d = ast_play_and_wait(chan, "vm-tocancel"); /* "or pound to cancel" */
06561    if (d)
06562       return d;
06563    d = ast_waitfordigit(chan, 4000);
06564    return d;
06565 }
06566 
06567 /*!
06568  * \brief plays a prompt and waits for a keypress.
06569  * \param chan
06570  * \param fn the name of the voice prompt file to be played. For example, 'vm-changeto', 'vm-savefolder'
06571  * \param start Does not appear to be used at this time.
06572  *
06573  * This is used by the main menu option to move a message to a folder or to save a message into a folder.
06574  * After playing the  message identified by the fn parameter value, it calls get_folder(), which plays the 
06575  * prompting for the number inputs that correspond to the available folders.
06576  * 
06577  * \return zero on success, or -1 on error.
06578  */
06579 static int get_folder2(struct ast_channel *chan, char *fn, int start)
06580 {
06581    int res = 0;
06582    int loops = 0;
06583    res = ast_play_and_wait(chan, fn);  /* Folder name */
06584    while (((res < '0') || (res > '9')) &&
06585          (res != '#') && (res >= 0) &&
06586          loops < 4) {
06587       res = get_folder(chan, 0);
06588       loops++;
06589    }
06590    if (loops == 4) { /* give up */
06591       return '#';
06592    }
06593    return res;
06594 }
06595 
06596 /*!
06597  * \brief presents the option to prepend to an existing message when forwarding it.
06598  * \param chan
06599  * \param vmu
06600  * \param curdir
06601  * \param curmsg
06602  * \param vm_fmts
06603  * \param context
06604  * \param record_gain
06605  * \param duration
06606  * \param vms
06607  * \param flag 
06608  *
06609  * Presents a prompt for 1 to prepend the current message, 2 to forward the message without prepending, or * to return to the main menu.
06610  *
06611  * This is invoked from forward_message() when performing a forward operation (option 8 from main menu).
06612  * \return zero on success, -1 on error.
06613  */
06614 static int vm_forwardoptions(struct ast_channel *chan, struct ast_vm_user *vmu, char *curdir, int curmsg, char *vm_fmts,
06615          char *context, signed char record_gain, long *duration, struct vm_state *vms, char *flag)
06616 {
06617 #ifdef IMAP_STORAGE
06618    int res;
06619 #endif
06620    int cmd = 0;
06621    int retries = 0, prepend_duration = 0, already_recorded = 0;
06622    char msgfile[PATH_MAX], backup[PATH_MAX], backup_textfile[PATH_MAX];
06623    char textfile[PATH_MAX];
06624    struct ast_config *msg_cfg;
06625    struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
06626 #ifndef IMAP_STORAGE
06627    signed char zero_gain = 0;
06628 #endif
06629    const char *duration_str;
06630 
06631    /* Must always populate duration correctly */
06632    make_file(msgfile, sizeof(msgfile), curdir, curmsg);
06633    strcpy(textfile, msgfile);
06634    strcpy(backup, msgfile);
06635    strcpy(backup_textfile, msgfile);
06636    strncat(textfile, ".txt", sizeof(textfile) - strlen(textfile) - 1);
06637    strncat(backup, "-bak", sizeof(backup) - strlen(backup) - 1);
06638    strncat(backup_textfile, "-bak.txt", sizeof(backup_textfile) - strlen(backup_textfile) - 1);
06639 
06640    if ((msg_cfg = ast_config_load(textfile, config_flags)) && msg_cfg != CONFIG_STATUS_FILEINVALID && (duration_str = ast_variable_retrieve(msg_cfg, "message", "duration"))) {
06641       *duration = atoi(duration_str);
06642    } else {
06643       *duration = 0;
06644    }
06645 
06646    while ((cmd >= 0) && (cmd != 't') && (cmd != '*')) {
06647       if (cmd)
06648          retries = 0;
06649       switch (cmd) {
06650       case '1': 
06651 
06652 #ifdef IMAP_STORAGE
06653          /* Record new intro file */
06654          make_file(vms->introfn, sizeof(vms->introfn), curdir, curmsg);
06655          strncat(vms->introfn, "intro", sizeof(vms->introfn));
06656          res = ast_play_and_wait(chan, INTRO);
06657          res = ast_play_and_wait(chan, "beep");
06658          res = play_record_review(chan, NULL, vms->introfn, vmu->maxsecs, vm_fmts, 1, vmu, (int *) duration, NULL, record_gain, vms, flag);
06659          cmd = 't';
06660 #else
06661 
06662          /* prepend a message to the current message, update the metadata and return */
06663 
06664          make_file(msgfile, sizeof(msgfile), curdir, curmsg);
06665          strcpy(textfile, msgfile);
06666          strncat(textfile, ".txt", sizeof(textfile) - 1);
06667          *duration = 0;
06668 
06669          /* if we can't read the message metadata, stop now */
06670          if (!msg_cfg) {
06671             cmd = 0;
06672             break;
06673          }
06674          
06675          /* Back up the original file, so we can retry the prepend and restore it after forward. */
06676          if (already_recorded) {
06677             ast_filecopy(backup, msgfile, NULL);
06678             copy(backup_textfile, textfile);
06679          }
06680          else {
06681             ast_filecopy(msgfile, backup, NULL);
06682             copy(textfile,backup_textfile);
06683          }
06684          already_recorded = 1;
06685 
06686          if (record_gain)
06687             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &record_gain, sizeof(record_gain), 0);
06688 
06689          cmd = ast_play_and_prepend(chan, NULL, msgfile, 0, vm_fmts, &prepend_duration, 1, silencethreshold, maxsilence);
06690          if (record_gain)
06691             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &zero_gain, sizeof(zero_gain), 0);
06692 
06693          
06694          if ((duration_str = ast_variable_retrieve(msg_cfg, "message", "duration")))
06695             *duration = atoi(duration_str);
06696 
06697          if (prepend_duration) {
06698             struct ast_category *msg_cat;
06699             /* need enough space for a maximum-length message duration */
06700             char duration_buf[12];
06701 
06702             *duration += prepend_duration;
06703             msg_cat = ast_category_get(msg_cfg, "message");
06704             snprintf(duration_buf, 11, "%ld", *duration);
06705             if (!ast_variable_update(msg_cat, "duration", duration_buf, NULL, 0)) {
06706                ast_config_text_file_save(textfile, msg_cfg, "app_voicemail");
06707             }
06708          }
06709 
06710 #endif
06711          break;
06712       case '2': 
06713          /* NULL out introfile so we know there is no intro! */
06714 #ifdef IMAP_STORAGE
06715          *vms->introfn = '\0';
06716 #endif
06717          cmd = 't';
06718          break;
06719       case '*':
06720          cmd = '*';
06721          break;
06722       default: 
06723          cmd = ast_play_and_wait(chan, "vm-forwardoptions");
06724             /* "Press 1 to prepend a message or 2 to forward the message without prepending" */
06725          if (!cmd)
06726             cmd = ast_play_and_wait(chan, "vm-starmain");
06727             /* "press star to return to the main menu" */
06728          if (!cmd)
06729             cmd = ast_waitfordigit(chan, 6000);
06730          if (!cmd)
06731             retries++;
06732          if (retries > 3)
06733             cmd = 't';
06734       }
06735    }
06736 
06737    if (msg_cfg)
06738       ast_config_destroy(msg_cfg);
06739    if (prepend_duration)
06740       *duration = prepend_duration;
06741 
06742    if (already_recorded && cmd == -1) {
06743       /* restore original message if prepention cancelled */
06744       ast_filerename(backup, msgfile, NULL);
06745       rename(backup_textfile, textfile);
06746    }
06747 
06748    if (cmd == 't' || cmd == 'S')
06749       cmd = 0;
06750    return cmd;
06751 }
06752 
06753 static void queue_mwi_event(const char *box, int urgent, int new, int old)
06754 {
06755    struct ast_event *event;
06756    char *mailbox, *context;
06757 
06758    /* Strip off @default */
06759    context = mailbox = ast_strdupa(box);
06760    strsep(&context, "@");
06761    if (ast_strlen_zero(context))
06762       context = "default";
06763 
06764    if (!(event = ast_event_new(AST_EVENT_MWI,
06765          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
06766          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
06767          AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, (new+urgent),
06768          AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, old,
06769          AST_EVENT_IE_END))) {
06770       return;
06771    }
06772 
06773    ast_event_queue_and_cache(event);
06774 }
06775 
06776 /*!
06777  * \brief Sends email notification that a user has a new voicemail waiting for them.
06778  * \param chan
06779  * \param vmu
06780  * \param vms
06781  * \param msgnum
06782  * \param duration
06783  * \param fmt
06784  * \param cidnum The Caller ID phone number value.
06785  * \param cidname The Caller ID name value.
06786  * \param flag
06787  *
06788  * \return zero on success, -1 on error.
06789  */
06790 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)
06791 {
06792    char todir[PATH_MAX], fn[PATH_MAX], ext_context[PATH_MAX], *stringp;
06793    int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;
06794    const char *category;
06795    char *myserveremail = serveremail;
06796 
06797    ast_channel_lock(chan);
06798    if ((category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY"))) {
06799       category = ast_strdupa(category);
06800    }
06801    ast_channel_unlock(chan);
06802 
06803    make_dir(todir, sizeof(todir), vmu->context, vmu->mailbox, !ast_strlen_zero(flag) && !strcmp(flag, "Urgent") ? "Urgent" : "INBOX");
06804    make_file(fn, sizeof(fn), todir, msgnum);
06805    snprintf(ext_context, sizeof(ext_context), "%s@%s", vmu->mailbox, vmu->context);
06806 
06807    if (!ast_strlen_zero(vmu->attachfmt)) {
06808       if (strstr(fmt, vmu->attachfmt))
06809          fmt = vmu->attachfmt;
06810       else
06811          ast_log(AST_LOG_WARNING, "Attachment format '%s' is not one of the recorded formats '%s'.  Falling back to default format for '%s@%s'.\n", vmu->attachfmt, fmt, vmu->mailbox, vmu->context);
06812    }
06813 
06814    /* Attach only the first format */
06815    fmt = ast_strdupa(fmt);
06816    stringp = fmt;
06817    strsep(&stringp, "|");
06818 
06819    if (!ast_strlen_zero(vmu->serveremail))
06820       myserveremail = vmu->serveremail;
06821 
06822    if (!ast_strlen_zero(vmu->email)) {
06823       int attach_user_voicemail = ast_test_flag(vmu, VM_ATTACH);
06824 
06825       if (attach_user_voicemail)
06826          RETRIEVE(todir, msgnum, vmu->mailbox, vmu->context);
06827 
06828       /* XXX possible imap issue, should category be NULL XXX */
06829       sendmail(myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, mbox(vmu, 0), cidnum, cidname, fn, NULL, fmt, duration, attach_user_voicemail, chan, category, flag);
06830 
06831       if (attach_user_voicemail)
06832          DISPOSE(todir, msgnum);
06833    }
06834 
06835    if (!ast_strlen_zero(vmu->pager)) {
06836       sendpage(myserveremail, vmu->pager, msgnum, vmu->context, vmu->mailbox, mbox(vmu, 0), cidnum, cidname, duration, vmu, category, flag);
06837    }
06838 
06839    if (ast_test_flag(vmu, VM_DELETE))
06840       DELETE(todir, msgnum, fn, vmu);
06841 
06842    /* Leave voicemail for someone */
06843    if (ast_app_has_voicemail(ext_context, NULL)) 
06844       ast_app_inboxcount2(ext_context, &urgentmsgs, &newmsgs, &oldmsgs);
06845 
06846    queue_mwi_event(ext_context, urgentmsgs, newmsgs, oldmsgs);
06847 
06848    ast_manager_event(chan, EVENT_FLAG_CALL, "MessageWaiting", "Mailbox: %s@%s\r\nWaiting: %d\r\nNew: %d\r\nOld: %d\r\n", vmu->mailbox, vmu->context, ast_app_has_voicemail(ext_context, NULL), newmsgs, oldmsgs);
06849    run_externnotify(vmu->context, vmu->mailbox, flag);
06850 
06851 #ifdef IMAP_STORAGE
06852    vm_delete(fn);  /* Delete the file, but not the IMAP message */
06853    if (ast_test_flag(vmu, VM_DELETE))  { /* Delete the IMAP message if delete = yes */
06854       vm_imap_delete(NULL, vms->curmsg, vmu);
06855       vms->newmessages--;  /* Fix new message count */
06856    }
06857 #endif
06858 
06859    return 0;
06860 }
06861 
06862 /*!
06863  * \brief Sends a voicemail message to a mailbox recipient.
06864  * \param chan
06865  * \param context
06866  * \param vms
06867  * \param sender
06868  * \param fmt
06869  * \param is_new_message Used to indicate the mode for which this method was invoked. 
06870  *             Will be 0 when called to forward an existing message (option 8)
06871  *             Will be 1 when called to leave a message (option 3->5)
06872  * \param record_gain 
06873  * \param urgent
06874  *
06875  * Reads the destination mailbox(es) from keypad input for CID, or if use_directory feature is enabled, the Directory.
06876  * 
06877  * When in the leave message mode (is_new_message == 1):
06878  *   - allow the leaving of a message for ourselves. (Will not allow us to forward a message to ourselves, when is_new_message == 0).
06879  *   - attempt to determine the context and and mailbox, and then invoke leave_message() function to record and store the message.
06880  *
06881  * When in the forward message mode (is_new_message == 0):
06882  *   - retreives the current message to be forwarded
06883  *   - copies the original message to a temporary file, so updates to the envelope can be done.
06884  *   - determines the target mailbox and folders
06885  *   - copies the message into the target mailbox, using copy_message() or by generating the message into an email attachment if using imap folders.
06886  *
06887  * \return zero on success, -1 on error.
06888  */
06889 static int forward_message(struct ast_channel *chan, char *context, struct vm_state *vms, struct ast_vm_user *sender, char *fmt, int is_new_message, signed char record_gain, int urgent)
06890 {
06891 #ifdef IMAP_STORAGE
06892    int todircount = 0;
06893    struct vm_state *dstvms;
06894 #endif
06895    char username[70]="";
06896    char fn[PATH_MAX]; /* for playback of name greeting */
06897    char ecodes[16] = "#";
06898    int res = 0, cmd = 0;
06899    struct ast_vm_user *receiver = NULL, *vmtmp;
06900    AST_LIST_HEAD_NOLOCK_STATIC(extensions, ast_vm_user);
06901    char *stringp;
06902    const char *s;
06903    int saved_messages = 0;
06904    int valid_extensions = 0;
06905    char *dir;
06906    int curmsg;
06907    char urgent_str[7] = "";
06908    char tmptxtfile[PATH_MAX];
06909    int prompt_played = 0;
06910 #ifndef IMAP_STORAGE
06911    char msgfile[PATH_MAX], textfile[PATH_MAX], backup[PATH_MAX], backup_textfile[PATH_MAX];
06912 #endif
06913    if (ast_test_flag((&globalflags), VM_FWDURGAUTO)) {
06914       ast_copy_string(urgent_str, urgent ? "Urgent" : "", sizeof(urgent_str));
06915    }
06916 
06917    if (vms == NULL) return -1;
06918    dir = vms->curdir;
06919    curmsg = vms->curmsg;
06920 
06921    tmptxtfile[0] = '\0';
06922    while (!res && !valid_extensions) {
06923       int use_directory = 0;
06924       if (ast_test_flag((&globalflags), VM_DIRECFORWARD)) {
06925          int done = 0;
06926          int retries = 0;
06927          cmd = 0;
06928          while ((cmd >= 0) && !done ){
06929             if (cmd)
06930                retries = 0;
06931             switch (cmd) {
06932             case '1': 
06933                use_directory = 0;
06934                done = 1;
06935                break;
06936             case '2': 
06937                use_directory = 1;
06938                done = 1;
06939                break;
06940             case '*': 
06941                cmd = 't';
06942                done = 1;
06943                break;
06944             default: 
06945                /* Press 1 to enter an extension press 2 to use the directory */
06946                cmd = ast_play_and_wait(chan, "vm-forward");
06947                if (!cmd)
06948                   cmd = ast_waitfordigit(chan, 3000);
06949                if (!cmd)
06950                   retries++;
06951                if (retries > 3) {
06952                   cmd = 't';
06953                   done = 1;
06954                }
06955                
06956             }
06957          }
06958          if (cmd < 0 || cmd == 't')
06959             break;
06960       }
06961       
06962       if (use_directory) {
06963          /* use app_directory */
06964          
06965          char old_context[sizeof(chan->context)];
06966          char old_exten[sizeof(chan->exten)];
06967          int old_priority;
06968          struct ast_app* directory_app;
06969 
06970          directory_app = pbx_findapp("Directory");
06971          if (directory_app) {
06972             char vmcontext[256];
06973             /* make backup copies */
06974             memcpy(old_context, chan->context, sizeof(chan->context));
06975             memcpy(old_exten, chan->exten, sizeof(chan->exten));
06976             old_priority = chan->priority;
06977             
06978             /* call the the Directory, changes the channel */
06979             snprintf(vmcontext, sizeof(vmcontext), "%s,,v", context ? context : "default");
06980             res = pbx_exec(chan, directory_app, vmcontext);
06981             
06982             ast_copy_string(username, chan->exten, sizeof(username));
06983             
06984             /* restore the old context, exten, and priority */
06985             memcpy(chan->context, old_context, sizeof(chan->context));
06986             memcpy(chan->exten, old_exten, sizeof(chan->exten));
06987             chan->priority = old_priority;
06988          } else {
06989             ast_log(AST_LOG_WARNING, "Could not find the Directory application, disabling directory_forward\n");
06990             ast_clear_flag((&globalflags), VM_DIRECFORWARD);
06991          }
06992       } else {
06993          /* Ask for an extension */
06994          res = ast_streamfile(chan, "vm-extension", chan->language); /* "extension" */
06995          prompt_played++;
06996          if (res || prompt_played > 4)
06997             break;
06998          if ((res = ast_readstring(chan, username, sizeof(username) - 1, 2000, 10000, "#") < 0))
06999             break;
07000       }
07001       
07002       /* start all over if no username */
07003       if (ast_strlen_zero(username))
07004          continue;
07005       stringp = username;
07006       s = strsep(&stringp, "*");
07007       /* start optimistic */
07008       valid_extensions = 1;
07009       while (s) {
07010          if ((is_new_message == 1 || strcmp(s, sender->mailbox)) && (receiver = find_user(NULL, context, s))) {
07011             int oldmsgs;
07012             int newmsgs;
07013             int capacity;
07014             if (inboxcount(s, &newmsgs, &oldmsgs)) {
07015                ast_log(LOG_ERROR, "Problem in calculating number of voicemail messages available for extension %s\n", s);
07016                /* Shouldn't happen, but allow trying another extension if it does */
07017                res = ast_play_and_wait(chan, "pbx-invalid");
07018                valid_extensions = 0;
07019                break;
07020             }
07021             capacity = receiver->maxmsg - inprocess_count(receiver->mailbox, receiver->context, +1);
07022             if ((newmsgs + oldmsgs) >= capacity) {
07023                ast_log(LOG_NOTICE, "Mailbox '%s' is full with capacity of %d, prompting for another extension.\n", s, capacity);
07024                res = ast_play_and_wait(chan, "vm-mailboxfull");
07025                valid_extensions = 0;
07026                while ((vmtmp = AST_LIST_REMOVE_HEAD(&extensions, list))) {
07027                   inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
07028                   free_user(vmtmp);
07029                }
07030                inprocess_count(receiver->mailbox, receiver->context, -1);
07031                break;
07032             }
07033             AST_LIST_INSERT_HEAD(&extensions, receiver, list);
07034          } else {
07035             /* XXX Optimization for the future.  When we encounter a single bad extension,
07036              * bailing out on all of the extensions may not be the way to go.  We should
07037              * probably just bail on that single extension, then allow the user to enter
07038              * several more. XXX
07039              */
07040             while ((receiver = AST_LIST_REMOVE_HEAD(&extensions, list))) {
07041                free_user(receiver);
07042             }
07043             ast_log(LOG_NOTICE, "'%s' is not a valid mailbox\n", s);
07044             /* "I am sorry, that's not a valid extension.  Please try again." */
07045             res = ast_play_and_wait(chan, "pbx-invalid");
07046             valid_extensions = 0;
07047             break;
07048          }
07049 
07050          /* play name if available, else play extension number */
07051          snprintf(fn, sizeof(fn), "%s%s/%s/greet", VM_SPOOL_DIR, receiver->context, s);
07052          RETRIEVE(fn, -1, s, receiver->context);
07053          if (ast_fileexists(fn, NULL, NULL) > 0) {
07054             res = ast_stream_and_wait(chan, fn, ecodes);
07055             if (res) {
07056                DISPOSE(fn, -1);
07057                return res;
07058             }
07059          } else {
07060             res = ast_say_digit_str(chan, s, ecodes, chan->language);
07061          }
07062          DISPOSE(fn, -1);
07063 
07064          s = strsep(&stringp, "*");
07065       }
07066       /* break from the loop of reading the extensions */
07067       if (valid_extensions)
07068          break;
07069    }
07070    /* check if we're clear to proceed */
07071    if (AST_LIST_EMPTY(&extensions) || !valid_extensions)
07072       return res;
07073    if (is_new_message == 1) {
07074       struct leave_vm_options leave_options;
07075       char mailbox[AST_MAX_EXTENSION * 2 + 2];
07076       snprintf(mailbox, sizeof(mailbox), "%s@%s", username, context);
07077 
07078       /* Send VoiceMail */
07079       memset(&leave_options, 0, sizeof(leave_options));
07080       leave_options.record_gain = record_gain;
07081       cmd = leave_voicemail(chan, mailbox, &leave_options);
07082    } else {
07083       /* Forward VoiceMail */
07084       long duration = 0;
07085       struct vm_state vmstmp;
07086       int copy_msg_result = 0;
07087       memcpy(&vmstmp, vms, sizeof(vmstmp));
07088 
07089       RETRIEVE(dir, curmsg, sender->mailbox, sender->context);
07090 
07091       cmd = vm_forwardoptions(chan, sender, vmstmp.curdir, curmsg, vmfmts, S_OR(context, "default"), record_gain, &duration, &vmstmp, urgent_str);
07092       if (!cmd) {
07093          AST_LIST_TRAVERSE_SAFE_BEGIN(&extensions, vmtmp, list) {
07094 #ifdef IMAP_STORAGE
07095             int attach_user_voicemail;
07096             char *myserveremail = serveremail;
07097             
07098             /* get destination mailbox */
07099             dstvms = get_vm_state_by_mailbox(vmtmp->mailbox, vmtmp->context, 0);
07100             if (!dstvms) {
07101                dstvms = create_vm_state_from_user(vmtmp);
07102             }
07103             if (dstvms) {
07104                init_mailstream(dstvms, 0);
07105                if (!dstvms->mailstream) {
07106                   ast_log(AST_LOG_ERROR, "IMAP mailstream for %s is NULL\n", vmtmp->mailbox);
07107                } else {
07108                   copy_msg_result = STORE(vmstmp.curdir, vmtmp->mailbox, vmtmp->context, dstvms->curmsg, chan, vmtmp, fmt, duration, dstvms, urgent_str);
07109                   run_externnotify(vmtmp->context, vmtmp->mailbox, urgent_str); 
07110                }
07111             } else {
07112                ast_log(AST_LOG_ERROR, "Could not find state information for mailbox %s\n", vmtmp->mailbox);
07113             }
07114             if (!ast_strlen_zero(vmtmp->serveremail))
07115                myserveremail = vmtmp->serveremail;
07116             attach_user_voicemail = ast_test_flag(vmtmp, VM_ATTACH);
07117             /* NULL category for IMAP storage */
07118             sendmail(myserveremail, vmtmp, todircount, vmtmp->context, vmtmp->mailbox,
07119                dstvms->curbox,
07120                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
07121                S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
07122                vmstmp.fn, vmstmp.introfn, fmt, duration, attach_user_voicemail, chan,
07123                NULL, urgent_str);
07124 #else
07125             copy_msg_result = copy_message(chan, sender, 0, curmsg, duration, vmtmp, fmt, dir, urgent_str);
07126 #endif
07127             saved_messages++;
07128             AST_LIST_REMOVE_CURRENT(list);
07129             inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
07130             free_user(vmtmp);
07131             if (res)
07132                break;
07133          }
07134          AST_LIST_TRAVERSE_SAFE_END;
07135          if (saved_messages > 0 && !copy_msg_result) {
07136             /* give confirmation that the message was saved */
07137             /* commented out since we can't forward batches yet
07138             if (saved_messages == 1)
07139                res = ast_play_and_wait(chan, "vm-message");
07140             else
07141                res = ast_play_and_wait(chan, "vm-messages");
07142             if (!res)
07143                res = ast_play_and_wait(chan, "vm-saved"); */
07144 #ifdef IMAP_STORAGE
07145             /* If forwarded with intro, DON'T PLAY THIS MESSAGE AGAIN! */
07146             if (ast_strlen_zero(vmstmp.introfn))
07147 #endif
07148             res = ast_play_and_wait(chan, "vm-msgsaved");
07149          }
07150 #ifndef IMAP_STORAGE
07151          else {
07152             /* with IMAP, mailbox full warning played by imap_check_limits */
07153             res = ast_play_and_wait(chan, "vm-mailboxfull");
07154          }
07155          /* Restore original message without prepended message if backup exists */
07156          make_file(msgfile, sizeof(msgfile), dir, curmsg);
07157          strcpy(textfile, msgfile);
07158          strcpy(backup, msgfile);
07159          strcpy(backup_textfile, msgfile);
07160          strncat(textfile, ".txt", sizeof(textfile) - strlen(textfile) - 1);
07161          strncat(backup, "-bak", sizeof(backup) - strlen(backup) - 1);
07162          strncat(backup_textfile, "-bak.txt", sizeof(backup_textfile) - strlen(backup_textfile) - 1);
07163          if (ast_fileexists(backup, NULL, NULL) > 0) {
07164             ast_filerename(backup, msgfile, NULL);
07165             rename(backup_textfile, textfile);
07166          }
07167 #endif
07168       }
07169       DISPOSE(dir, curmsg);
07170    }
07171 
07172    /* If anything failed above, we still have this list to free */
07173    while ((vmtmp = AST_LIST_REMOVE_HEAD(&extensions, list))) {
07174       inprocess_count(vmtmp->mailbox, vmtmp->context, -1);
07175       free_user(vmtmp);
07176    }
07177    return res ? res : cmd;
07178 }
07179 
07180 static int wait_file2(struct ast_channel *chan, struct vm_state *vms, char *file)
07181 {
07182    int res;
07183    if ((res = ast_stream_and_wait(chan, file, AST_DIGIT_ANY)) < 0) 
07184       ast_log(AST_LOG_WARNING, "Unable to play message %s\n", file); 
07185    return res;
07186 }
07187 
07188 static int wait_file(struct ast_channel *chan, struct vm_state *vms, char *file) 
07189 {
07190    return ast_control_streamfile(chan, file, listen_control_forward_key, listen_control_reverse_key, listen_control_stop_key, listen_control_pause_key, listen_control_restart_key, skipms, NULL);
07191 }
07192 
07193 static int play_message_category(struct ast_channel *chan, const char *category)
07194 {
07195    int res = 0;
07196 
07197    if (!ast_strlen_zero(category))
07198       res = ast_play_and_wait(chan, category);
07199 
07200    if (res) {
07201       ast_log(AST_LOG_WARNING, "No sound file for category '%s' was found.\n", category);
07202       res = 0;
07203    }
07204 
07205    return res;
07206 }
07207 
07208 static int play_message_datetime(struct ast_channel *chan, struct ast_vm_user *vmu, const char *origtime, const char *filename)
07209 {
07210    int res = 0;
07211    struct vm_zone *the_zone = NULL;
07212    time_t t;
07213 
07214    if (ast_get_time_t(origtime, &t, 0, NULL)) {
07215       ast_log(AST_LOG_WARNING, "Couldn't find origtime in %s\n", filename);
07216       return 0;
07217    }
07218 
07219    /* Does this user have a timezone specified? */
07220    if (!ast_strlen_zero(vmu->zonetag)) {
07221       /* Find the zone in the list */
07222       struct vm_zone *z;
07223       AST_LIST_LOCK(&zones);
07224       AST_LIST_TRAVERSE(&zones, z, list) {
07225          if (!strcmp(z->name, vmu->zonetag)) {
07226             the_zone = z;
07227             break;
07228          }
07229       }
07230       AST_LIST_UNLOCK(&zones);
07231    }
07232 
07233 /* No internal variable parsing for now, so we'll comment it out for the time being */
07234 #if 0
07235    /* Set the DIFF_* variables */
07236    ast_localtime(&t, &time_now, NULL);
07237    tv_now = ast_tvnow();
07238    ast_localtime(&tv_now, &time_then, NULL);
07239 
07240    /* Day difference */
07241    if (time_now.tm_year == time_then.tm_year)
07242       snprintf(temp, sizeof(temp), "%d", time_now.tm_yday);
07243    else
07244       snprintf(temp, sizeof(temp), "%d", (time_now.tm_year - time_then.tm_year) * 365 + (time_now.tm_yday - time_then.tm_yday));
07245    pbx_builtin_setvar_helper(chan, "DIFF_DAY", temp);
07246 
07247    /* Can't think of how other diffs might be helpful, but I'm sure somebody will think of something. */
07248 #endif
07249    if (the_zone) {
07250       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, the_zone->msg_format, the_zone->timezone);
07251    } else if (!strncasecmp(chan->language, "de", 2)) {     /* GERMAN syntax */
07252       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Q 'digits/at' HM", NULL);
07253    } else if (!strncasecmp(chan->language, "gr", 2)) {     /* GREEK syntax */
07254       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q  H 'digits/kai' M ", NULL);
07255    } else if (!strncasecmp(chan->language, "it", 2)) {     /* ITALIAN syntax */
07256       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q 'digits/at' 'digits/hours' k 'digits/e' M 'digits/minutes'", NULL);
07257    } else if (!strncasecmp(chan->language, "nl", 2)) {     /* DUTCH syntax */
07258       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q 'digits/nl-om' HM", NULL);
07259    } else if (!strncasecmp(chan->language, "no", 2)) {     /* NORWEGIAN syntax */
07260       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Q 'digits/at' HM", NULL);
07261    } else if (!strncasecmp(chan->language, "pl", 2)) {     /* POLISH syntax */
07262       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Q HM", NULL);
07263    } else if (!strncasecmp(chan->language, "pt_BR", 5)) {  /* Brazillian PORTUGUESE syntax */
07264       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Ad 'digits/pt-de' B 'digits/pt-de' Y 'digits/pt-as' HM ", NULL);
07265    } else if (!strncasecmp(chan->language, "se", 2)) {     /* SWEDISH syntax */
07266       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' dB 'digits/at' k 'and' M", NULL);
07267    } else if (!strncasecmp(chan->language, "zh", 2)) {     /* CHINESE (Taiwan) syntax */
07268       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "qR 'vm-received'", NULL);
07269    } else if (!strncasecmp(chan->language, "vi", 2)) {     /* VIETNAMESE syntax */
07270       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' A 'digits/day' dB 'digits/year' Y 'digits/at' k 'hours' M 'minutes'", NULL);
07271    } else {
07272       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q 'digits/at' IMp", NULL);
07273    }
07274 #if 0
07275    pbx_builtin_setvar_helper(chan, "DIFF_DAY", NULL);
07276 #endif
07277    return res;
07278 }
07279 
07280 
07281 
07282 static int play_message_callerid(struct ast_channel *chan, struct vm_state *vms, char *cid, const char *context, int callback)
07283 {
07284    int res = 0;
07285    int i;
07286    char *callerid, *name;
07287    char prefile[PATH_MAX] = "";
07288    
07289 
07290    /* If voicemail cid is not enabled, or we didn't get cid or context from
07291     * the attribute file, leave now.
07292     *
07293     * TODO Still need to change this so that if this function is called by the
07294     * message envelope (and someone is explicitly requesting to hear the CID),
07295     * it does not check to see if CID is enabled in the config file.
07296     */
07297    if ((cid == NULL)||(context == NULL))
07298       return res;
07299 
07300    /* Strip off caller ID number from name */
07301    ast_debug(1, "VM-CID: composite caller ID received: %s, context: %s\n", cid, context);
07302    ast_callerid_parse(cid, &name, &callerid);
07303    if ((!ast_strlen_zero(callerid)) && strcmp(callerid, "Unknown")) {
07304       /* Check for internal contexts and only */
07305       /* say extension when the call didn't come from an internal context in the list */
07306       for (i = 0 ; i < MAX_NUM_CID_CONTEXTS ; i++){
07307          ast_debug(1, "VM-CID: comparing internalcontext: %s\n", cidinternalcontexts[i]);
07308          if ((strcmp(cidinternalcontexts[i], context) == 0))
07309             break;
07310       }
07311       if (i != MAX_NUM_CID_CONTEXTS){ /* internal context? */
07312          if (!res) {
07313             snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, context, callerid);
07314             if (!ast_strlen_zero(prefile)) {
07315             /* See if we can find a recorded name for this person instead of their extension number */
07316                if (ast_fileexists(prefile, NULL, NULL) > 0) {
07317                   ast_verb(3, "Playing envelope info: CID number '%s' matches mailbox number, playing recorded name\n", callerid);
07318                   if (!callback)
07319                      res = wait_file2(chan, vms, "vm-from");
07320                   res = ast_stream_and_wait(chan, prefile, "");
07321                } else {
07322                   ast_verb(3, "Playing envelope info: message from '%s'\n", callerid);
07323                   /* Say "from extension" as one saying to sound smoother */
07324                   if (!callback)
07325                      res = wait_file2(chan, vms, "vm-from-extension");
07326                   res = ast_say_digit_str(chan, callerid, "", chan->language);
07327                }
07328             }
07329          }
07330       } else if (!res) {
07331          ast_debug(1, "VM-CID: Numeric caller id: (%s)\n", callerid);
07332          /* Since this is all nicely figured out, why not say "from phone number" in this case? */
07333          if (!callback)
07334             res = wait_file2(chan, vms, "vm-from-phonenumber");
07335          res = ast_say_digit_str(chan, callerid, AST_DIGIT_ANY, chan->language);
07336       }
07337    } else {
07338       /* Number unknown */
07339       ast_debug(1, "VM-CID: From an unknown number\n");
07340       /* Say "from an unknown caller" as one phrase - it is already recorded by "the voice" anyhow */
07341       res = wait_file2(chan, vms, "vm-unknown-caller");
07342    }
07343    return res;
07344 }
07345 
07346 static int play_message_duration(struct ast_channel *chan, struct vm_state *vms, const char *duration, int minduration)
07347 {
07348    int res = 0;
07349    int durationm;
07350    int durations;
07351    /* Verify that we have a duration for the message */
07352    if (duration == NULL)
07353       return res;
07354 
07355    /* Convert from seconds to minutes */
07356    durations = atoi(duration);
07357    durationm = (durations / 60);
07358 
07359    ast_debug(1, "VM-Duration: duration is: %d seconds converted to: %d minutes\n", durations, durationm);
07360 
07361    if ((!res) && (durationm >= minduration)) {
07362       res = wait_file2(chan, vms, "vm-duration");
07363 
07364       /* POLISH syntax */
07365       if (!strncasecmp(chan->language, "pl", 2)) {
07366          div_t num = div(durationm, 10);
07367 
07368          if (durationm == 1) {
07369             res = ast_play_and_wait(chan, "digits/1z");
07370             res = res ? res : ast_play_and_wait(chan, "vm-minute-ta");
07371          } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
07372             if (num.rem == 2) {
07373                if (!num.quot) {
07374                   res = ast_play_and_wait(chan, "digits/2-ie");
07375                } else {
07376                   res = say_and_wait(chan, durationm - 2 , chan->language);
07377                   res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
07378                }
07379             } else {
07380                res = say_and_wait(chan, durationm, chan->language);
07381             }
07382             res = res ? res : ast_play_and_wait(chan, "vm-minute-ty");
07383          } else {
07384             res = say_and_wait(chan, durationm, chan->language);
07385             res = res ? res : ast_play_and_wait(chan, "vm-minute-t");
07386          }
07387       /* DEFAULT syntax */
07388       } else {
07389          res = ast_say_number(chan, durationm, AST_DIGIT_ANY, chan->language, NULL);
07390          res = wait_file2(chan, vms, "vm-minutes");
07391       }
07392    }
07393    return res;
07394 }
07395 
07396 static int play_message(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms)
07397 {
07398    int res = 0;
07399    char filename[256], *cid;
07400    const char *origtime, *context, *category, *duration, *flag;
07401    struct ast_config *msg_cfg;
07402    struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
07403 
07404    vms->starting = 0;
07405    make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
07406    adsi_message(chan, vms);
07407    if (!vms->curmsg)
07408       res = wait_file2(chan, vms, "vm-first");  /* "First" */
07409    else if (vms->curmsg == vms->lastmsg)
07410       res = wait_file2(chan, vms, "vm-last");      /* "last" */
07411 
07412    snprintf(filename, sizeof(filename), "%s.txt", vms->fn);
07413    RETRIEVE(vms->curdir, vms->curmsg, vmu->mailbox, vmu->context);
07414    msg_cfg = ast_config_load(filename, config_flags);
07415    if (!msg_cfg || msg_cfg == CONFIG_STATUS_FILEINVALID) {
07416       ast_log(LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
07417       return 0;
07418    }
07419    flag = ast_variable_retrieve(msg_cfg, "message", "flag");
07420 
07421    /* Play the word urgent if we are listening to urgent messages */
07422    if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
07423       res = wait_file2(chan, vms, "vm-Urgent"); /* "urgent" */
07424    }
07425 
07426    if (!res) {
07427       /* XXX Why are we playing messages above, and then playing the same language-specific stuff here? */
07428       /* POLISH syntax */
07429       if (!strncasecmp(chan->language, "pl", 2)) {
07430          if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
07431             int ten, one;
07432             char nextmsg[256];
07433             ten = (vms->curmsg + 1) / 10;
07434             one = (vms->curmsg + 1) % 10;
07435 
07436             if (vms->curmsg < 20) {
07437                snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", vms->curmsg + 1);
07438                res = wait_file2(chan, vms, nextmsg);
07439             } else {
07440                snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", ten * 10);
07441                res = wait_file2(chan, vms, nextmsg);
07442                if (one > 0) {
07443                   if (!res) {
07444                      snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", one);
07445                      res = wait_file2(chan, vms, nextmsg);
07446                   }
07447                }
07448             }
07449          }
07450          if (!res)
07451             res = wait_file2(chan, vms, "vm-message");
07452       /* HEBREW syntax */
07453       } else if (!strncasecmp(chan->language, "he", 2)) {
07454          if (!vms->curmsg) {
07455             res = wait_file2(chan, vms, "vm-message");
07456             res = wait_file2(chan, vms, "vm-first");
07457          } else if (vms->curmsg == vms->lastmsg) {
07458             res = wait_file2(chan, vms, "vm-message");
07459             res = wait_file2(chan, vms, "vm-last");
07460          } else {
07461             res = wait_file2(chan, vms, "vm-message");
07462             res = wait_file2(chan, vms, "vm-number");
07463             res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, chan->language, "f");
07464          }
07465       /* VIETNAMESE syntax */
07466       } else if (!strncasecmp(chan->language, "vi", 2)) {
07467          if (!vms->curmsg) {
07468             res = wait_file2(chan, vms, "vm-message");
07469             res = wait_file2(chan, vms, "vm-first");
07470          } else if (vms->curmsg == vms->lastmsg) {
07471             res = wait_file2(chan, vms, "vm-message");
07472             res = wait_file2(chan, vms, "vm-last");
07473          } else {
07474             res = wait_file2(chan, vms, "vm-message");
07475             res = wait_file2(chan, vms, "vm-number");
07476             res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, chan->language, "f");
07477          }
07478       } else {
07479          if (!strncasecmp(chan->language, "se", 2)) { /* SWEDISH syntax */
07480             res = wait_file2(chan, vms, "vm-meddelandet");  /* "message" */
07481          } else { /* DEFAULT syntax */
07482             res = wait_file2(chan, vms, "vm-message");
07483          }
07484          if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
07485             if (!res) {
07486                res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, chan->language, NULL);
07487             }
07488          }
07489       }
07490    }
07491 
07492    if (!msg_cfg) {
07493       ast_log(AST_LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
07494       return 0;
07495    }
07496 
07497    if (!(origtime = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
07498       ast_log(AST_LOG_WARNING, "No origtime?!\n");
07499       DISPOSE(vms->curdir, vms->curmsg);
07500       ast_config_destroy(msg_cfg);
07501       return 0;
07502    }
07503 
07504    cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
07505    duration = ast_variable_retrieve(msg_cfg, "message", "duration");
07506    category = ast_variable_retrieve(msg_cfg, "message", "category");
07507 
07508    context = ast_variable_retrieve(msg_cfg, "message", "context");
07509    if (!strncasecmp("macro", context, 5)) /* Macro names in contexts are useless for our needs */
07510       context = ast_variable_retrieve(msg_cfg, "message", "macrocontext");
07511    if (!res) {
07512       res = play_message_category(chan, category);
07513    }
07514    if ((!res) && (ast_test_flag(vmu, VM_ENVELOPE)))
07515       res = play_message_datetime(chan, vmu, origtime, filename);
07516    if ((!res) && (ast_test_flag(vmu, VM_SAYCID)))
07517       res = play_message_callerid(chan, vms, cid, context, 0);
07518    if ((!res) && (ast_test_flag(vmu, VM_SAYDURATION)))
07519       res = play_message_duration(chan, vms, duration, vmu->saydurationm);
07520    /* Allow pressing '1' to skip envelope / callerid */
07521    if (res == '1')
07522       res = 0;
07523    ast_config_destroy(msg_cfg);
07524 
07525    if (!res) {
07526       make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
07527       vms->heard[vms->curmsg] = 1;
07528 #ifdef IMAP_STORAGE
07529       /*IMAP storage stores any prepended message from a forward
07530        * as a separate file from the rest of the message
07531        */
07532       if (!ast_strlen_zero(vms->introfn) && ast_fileexists(vms->introfn, NULL, NULL) > 0) {
07533          wait_file(chan, vms, vms->introfn);
07534       }
07535 #endif
07536       if ((res = wait_file(chan, vms, vms->fn)) < 0) {
07537          ast_log(AST_LOG_WARNING, "Playback of message %s failed\n", vms->fn);
07538          res = 0;
07539       }
07540    }
07541    DISPOSE(vms->curdir, vms->curmsg);
07542    return res;
07543 }
07544 
07545 #ifdef IMAP_STORAGE
07546 static int imap_remove_file(char *dir, int msgnum)
07547 {
07548    char fn[PATH_MAX];
07549    char full_fn[PATH_MAX];
07550    char intro[PATH_MAX] = {0,};
07551    
07552    if (msgnum > -1) {
07553       make_file(fn, sizeof(fn), dir, msgnum);
07554       snprintf(intro, sizeof(intro), "%sintro", fn);
07555    } else
07556       ast_copy_string(fn, dir, sizeof(fn));
07557    
07558    if ((msgnum < 0 && imapgreetings) || msgnum > -1) {
07559       ast_filedelete(fn, NULL);
07560       if (!ast_strlen_zero(intro)) {
07561          ast_filedelete(intro, NULL);
07562       }
07563       snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
07564       unlink(full_fn);
07565    }
07566    return 0;
07567 }
07568 
07569 
07570 
07571 static int imap_delete_old_greeting (char *dir, struct vm_state *vms)
07572 {
07573    char *file, *filename;
07574    char *attachment;
07575    char arg[10];
07576    int i;
07577    BODY* body;
07578 
07579    file = strrchr(ast_strdupa(dir), '/');
07580    if (file) {
07581       *file++ = '\0';
07582    } else {
07583       ast_log(AST_LOG_ERROR, "Failed to procure file name from directory passed. You should never see this.\n");
07584       return -1;
07585    }
07586 
07587    ast_mutex_lock(&vms->lock);
07588    for (i = 0; i < vms->mailstream->nmsgs; i++) {
07589       mail_fetchstructure(vms->mailstream, i + 1, &body);
07590       /* We have the body, now we extract the file name of the first attachment. */
07591       if (body->nested.part->next && body->nested.part->next->body.parameter->value) {
07592          attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
07593       } else {
07594          ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
07595          ast_mutex_unlock(&vms->lock);
07596          return -1;
07597       }
07598       filename = strsep(&attachment, ".");
07599       if (!strcmp(filename, file)) {
07600          sprintf(arg, "%d", i + 1);
07601          mail_setflag(vms->mailstream, arg, "\\DELETED");
07602       }
07603    }
07604    mail_expunge(vms->mailstream);
07605    ast_mutex_unlock(&vms->lock);
07606    return 0;
07607 }
07608 
07609 #elif !defined(IMAP_STORAGE)
07610 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
07611 {
07612    int count_msg, last_msg;
07613 
07614    ast_copy_string(vms->curbox, mbox(vmu, box), sizeof(vms->curbox));
07615 
07616    /* Rename the member vmbox HERE so that we don't try to return before
07617     * we know what's going on.
07618     */
07619    snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", vms->curbox);
07620 
07621    /* Faster to make the directory than to check if it exists. */
07622    create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
07623 
07624    count_msg = count_messages(vmu, vms->curdir);
07625    if (count_msg < 0) {
07626       return count_msg;
07627    } else {
07628       vms->lastmsg = count_msg - 1;
07629    }
07630 
07631    /*
07632    The following test is needed in case sequencing gets messed up.
07633    There appears to be more than one way to mess up sequence, so
07634    we will not try to find all of the root causes--just fix it when
07635    detected.
07636    */
07637 
07638    if (vm_lock_path(vms->curdir)) {
07639       ast_log(AST_LOG_ERROR, "Could not open mailbox %s:  mailbox is locked\n", vms->curdir);
07640       return -1;
07641    }
07642 
07643    last_msg = last_message_index(vmu, vms->curdir);
07644    ast_unlock_path(vms->curdir);
07645 
07646    if (last_msg < 0) {
07647       return last_msg;
07648    }
07649 
07650    return 0;
07651 }
07652 #endif
07653 
07654 static int close_mailbox(struct vm_state *vms, struct ast_vm_user *vmu)
07655 {
07656    int x = 0;
07657 #ifndef IMAP_STORAGE
07658    int res = 0, nummsg;
07659    char fn2[PATH_MAX];
07660 #endif
07661 
07662    if (vms->lastmsg <= -1) {
07663       goto done;
07664    }
07665 
07666    vms->curmsg = -1;
07667 #ifndef IMAP_STORAGE
07668    /* Get the deleted messages fixed */
07669    if (vm_lock_path(vms->curdir)) {
07670       return ERROR_LOCK_PATH;
07671    }
07672 
07673    for (x = 0; x < vmu->maxmsg; x++) {
07674       if (!vms->deleted[x] && ((strcasecmp(vms->curbox, "INBOX") && strcasecmp(vms->curbox, "Urgent")) || !vms->heard[x] || (vms->heard[x] && !ast_test_flag(vmu, VM_MOVEHEARD)))) {
07675          /* Save this message.  It's not in INBOX or hasn't been heard */
07676          make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
07677          if (!EXISTS(vms->curdir, x, vms->fn, NULL)) {
07678             break;
07679          }
07680          vms->curmsg++;
07681          make_file(fn2, sizeof(fn2), vms->curdir, vms->curmsg);
07682          if (strcmp(vms->fn, fn2)) {
07683             RENAME(vms->curdir, x, vmu->mailbox, vmu->context, vms->curdir, vms->curmsg, vms->fn, fn2);
07684          }
07685       } else if ((!strcasecmp(vms->curbox, "INBOX") || !strcasecmp(vms->curbox, "Urgent")) && vms->heard[x] && ast_test_flag(vmu, VM_MOVEHEARD) && !vms->deleted[x]) {
07686          /* Move to old folder before deleting */
07687          res = save_to_folder(vmu, vms, x, 1);
07688          if (res == ERROR_LOCK_PATH) {
07689             /* If save failed do not delete the message */
07690             ast_log(AST_LOG_WARNING, "Save failed.  Not moving message: %s.\n", res == ERROR_LOCK_PATH ? "unable to lock path" : "destination folder full");
07691             vms->deleted[x] = 0;
07692             vms->heard[x] = 0;
07693             --x;
07694          }
07695       } else if (vms->deleted[x] && vmu->maxdeletedmsg) {
07696          /* Move to deleted folder */
07697          res = save_to_folder(vmu, vms, x, 10);
07698          if (res == ERROR_LOCK_PATH) {
07699             /* If save failed do not delete the message */
07700             vms->deleted[x] = 0;
07701             vms->heard[x] = 0;
07702             --x;
07703          }
07704       } else if (vms->deleted[x] && ast_check_realtime("voicemail_data")) {
07705          /* If realtime storage enabled - we should explicitly delete this message,
07706          cause RENAME() will overwrite files, but will keep duplicate records in RT-storage */
07707          make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
07708          if (EXISTS(vms->curdir, x, vms->fn, NULL)) {
07709             DELETE(vms->curdir, x, vms->fn, vmu);
07710          }
07711       }
07712    }
07713 
07714    /* Delete ALL remaining messages */
07715    nummsg = x - 1;
07716    for (x = vms->curmsg + 1; x <= nummsg; x++) {
07717       make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
07718       if (EXISTS(vms->curdir, x, vms->fn, NULL)) {
07719          DELETE(vms->curdir, x, vms->fn, vmu);
07720       }
07721    }
07722    ast_unlock_path(vms->curdir);
07723 #else /* defined(IMAP_STORAGE) */
07724    if (vms->deleted) {
07725       /* Since we now expunge after each delete, deleting in reverse order
07726        * ensures that no reordering occurs between each step. */
07727       for (x = vmu->maxmsg - 1; x >= 0; x--) {
07728          if (vms->deleted[x]) {
07729             ast_debug(3, "IMAP delete of %d\n", x);
07730             DELETE(vms->curdir, x, vms->fn, vmu);
07731          }
07732       }
07733    }
07734 #endif
07735 
07736 done:
07737    if (vms->deleted && vmu->maxmsg) {
07738       memset(vms->deleted, 0, vmu->maxmsg * sizeof(int));
07739    }
07740    if (vms->heard && vmu->maxmsg) {
07741       memset(vms->heard, 0, vmu->maxmsg * sizeof(int));
07742    }
07743 
07744    return 0;
07745 }
07746 
07747 /* In Greek even though we CAN use a syntax like "friends messages"
07748  * ("filika mynhmata") it is not elegant. This also goes for "work/family messages"
07749  * ("ergasiaka/oikogeniaka mynhmata"). Therefore it is better to use a reversed
07750  * syntax for the above three categories which is more elegant.
07751  */
07752 
07753 static int vm_play_folder_name_gr(struct ast_channel *chan, char *box)
07754 {
07755    int cmd;
07756    char *buf;
07757 
07758    buf = alloca(strlen(box) + 2);
07759    strcpy(buf, box);
07760    strcat(buf, "s");
07761 
07762    if (!strcasecmp(box, "vm-INBOX") || !strcasecmp(box, "vm-Old")){
07763       cmd = ast_play_and_wait(chan, buf); /* "NEA / PALIA" */
07764       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages"); /* "messages" -> "MYNHMATA" */
07765    } else {
07766       cmd = ast_play_and_wait(chan, "vm-messages"); /* "messages" -> "MYNHMATA" */
07767       return cmd ? cmd : ast_play_and_wait(chan, box); /* friends/family/work... -> "FILWN"/"OIKOGENIAS"/"DOULEIAS"*/
07768    }
07769 }
07770 
07771 static int vm_play_folder_name_pl(struct ast_channel *chan, char *box)
07772 {
07773    int cmd;
07774 
07775    if (!strcasecmp(box, "vm-INBOX") || !strcasecmp(box, "vm-Old")) {
07776       if (!strcasecmp(box, "vm-INBOX"))
07777          cmd = ast_play_and_wait(chan, "vm-new-e");
07778       else
07779          cmd = ast_play_and_wait(chan, "vm-old-e");
07780       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
07781    } else {
07782       cmd = ast_play_and_wait(chan, "vm-messages");
07783       return cmd ? cmd : ast_play_and_wait(chan, box);
07784    }
07785 }
07786 
07787 static int vm_play_folder_name_ua(struct ast_channel *chan, char *box)
07788 {
07789    int cmd;
07790 
07791    if (!strcasecmp(box, "vm-Family") || !strcasecmp(box, "vm-Friends") || !strcasecmp(box, "vm-Work")){
07792       cmd = ast_play_and_wait(chan, "vm-messages");
07793       return cmd ? cmd : ast_play_and_wait(chan, box);
07794    } else {
07795       cmd = ast_play_and_wait(chan, box);
07796       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
07797    }
07798 }
07799 
07800 static int vm_play_folder_name(struct ast_channel *chan, char *box)
07801 {
07802    int cmd;
07803 
07804    if (  !strncasecmp(chan->language, "it", 2) ||
07805         !strncasecmp(chan->language, "es", 2) ||
07806         !strncasecmp(chan->language, "pt", 2)) { /* Italian, Spanish, or Portuguese syntax */
07807       cmd = ast_play_and_wait(chan, "vm-messages"); /* "messages */
07808       return cmd ? cmd : ast_play_and_wait(chan, box);
07809    } else if (!strncasecmp(chan->language, "gr", 2)) {
07810       return vm_play_folder_name_gr(chan, box);
07811    } else if (!strncasecmp(chan->language, "he", 2)) {  /* Hebrew syntax */
07812       return ast_play_and_wait(chan, box);
07813    } else if (!strncasecmp(chan->language, "pl", 2)) {
07814       return vm_play_folder_name_pl(chan, box);
07815    } else if (!strncasecmp(chan->language, "ua", 2)) {  /* Ukrainian syntax */
07816       return vm_play_folder_name_ua(chan, box);
07817    } else if (!strncasecmp(chan->language, "vi", 2)) {
07818       return ast_play_and_wait(chan, box);
07819    } else {  /* Default English */
07820       cmd = ast_play_and_wait(chan, box);
07821       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages"); /* "messages */
07822    }
07823 }
07824 
07825 /* GREEK SYNTAX
07826    In greek the plural for old/new is
07827    different so we need the following files
07828    We also need vm-denExeteMynhmata because
07829    this syntax is different.
07830 
07831    -> vm-Olds.wav : "Palia"
07832    -> vm-INBOXs.wav : "Nea"
07833    -> vm-denExeteMynhmata : "den exete mynhmata"
07834 */
07835 
07836 
07837 static int vm_intro_gr(struct ast_channel *chan, struct vm_state *vms)
07838 {
07839    int res = 0;
07840 
07841    if (vms->newmessages) {
07842       res = ast_play_and_wait(chan, "vm-youhave");
07843       if (!res) 
07844          res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, NULL);
07845       if (!res) {
07846          if ((vms->newmessages == 1)) {
07847             res = ast_play_and_wait(chan, "vm-INBOX");
07848             if (!res)
07849                res = ast_play_and_wait(chan, "vm-message");
07850          } else {
07851             res = ast_play_and_wait(chan, "vm-INBOXs");
07852             if (!res)
07853                res = ast_play_and_wait(chan, "vm-messages");
07854          }
07855       }
07856    } else if (vms->oldmessages){
07857       res = ast_play_and_wait(chan, "vm-youhave");
07858       if (!res)
07859          res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, NULL);
07860       if ((vms->oldmessages == 1)){
07861          res = ast_play_and_wait(chan, "vm-Old");
07862          if (!res)
07863             res = ast_play_and_wait(chan, "vm-message");
07864       } else {
07865          res = ast_play_and_wait(chan, "vm-Olds");
07866          if (!res)
07867             res = ast_play_and_wait(chan, "vm-messages");
07868       }
07869    } else if (!vms->oldmessages && !vms->newmessages) 
07870       res = ast_play_and_wait(chan, "vm-denExeteMynhmata"); 
07871    return res;
07872 }
07873 
07874 /* Version of vm_intro() designed to work for many languages.
07875  *
07876  * It is hoped that this function can prevent the proliferation of 
07877  * language-specific vm_intro() functions and in time replace the language-
07878  * specific functions which already exist.  An examination of the language-
07879  * specific functions revealed that they all corrected the same deficiencies
07880  * in vm_intro_en() (which was the default function). Namely:
07881  *
07882  *  1) The vm-Old and vm-INBOX sound files were overloaded.  The English 
07883  *     wording of the voicemail greeting hides this problem.  For example,
07884  *     vm-INBOX contains only the word "new".  This means that both of these
07885  *     sequences produce valid utterances:
07886  *      * vm-youhave digit/1 vm-INBOX vm-message (you have one new message)
07887  *      * vm-press digit/1 vm-for vm-INBOX vm-messages (press 1 for new messages)
07888  *     However, if we rerecord vm-INBOX to say "the new" (which is unavoidable
07889  *     in many languages) the first utterance becomes "you have 1 the new message".
07890  *  2) The function contains hardcoded rules for pluralizing the word "message".
07891  *     These rules are correct for English, but not for many other languages.
07892  *  3) No attempt is made to pluralize the adjectives ("old" and "new") as
07893  *     required in many languages.
07894  *  4) The gender of the word for "message" is not specified. This is a problem
07895  *     because in many languages the gender of the number in phrases such
07896  *     as "you have one new message" must match the gender of the word
07897  *     meaning "message".
07898  *
07899  * Fixing these problems for each new language has meant duplication of effort.
07900  * This new function solves the problems in the following general ways:
07901  *  1) Add new sound files vm-new and vm-old.  These can be linked to vm-INBOX
07902  *     and vm-Old respectively for those languages where it makes sense.
07903  *  2) Call ast_say_counted_noun() to put the proper gender and number prefix
07904  *     on vm-message.
07905  *  3) Call ast_say_counted_adjective() to put the proper gender and number
07906  *     prefix on vm-new and vm-old (none for English).
07907  *  4) Pass the gender of the language's word for "message" as an agument to
07908  *     this function which is can in turn pass on to the functions which 
07909  *     say numbers and put endings on nounds and adjectives.
07910  *
07911  * All languages require these messages:
07912  *  vm-youhave    "You have..."
07913  *  vm-and     "and"
07914  *  vm-no      "no" (in the sense of "none", as in "you have no messages")
07915  *
07916  * To use it for English, you will need these additional sound files:
07917  *  vm-new     "new"
07918  *  vm-message    "message", singular
07919  *  vm-messages      "messages", plural
07920  *
07921  * If you use it for Russian and other slavic languages, you will need these additional sound files:
07922  *
07923  *  vm-newn    "novoye" (singular, neuter)
07924  *  vm-newx    "novikh" (counting plural form, genative plural)
07925  *  vm-message    "sobsheniye" (singular form)
07926  *  vm-messagex1  "sobsheniya" (first counting plural form, genative singular)
07927  *  vm-messagex2  "sobsheniy" (second counting plural form, genative plural)
07928  *  digits/1n     "odno" (neuter singular for phrases such as "one message" or "thirty one messages")
07929  *  digits/2n     "dva" (neuter singular)
07930  */
07931 static int vm_intro_multilang(struct ast_channel *chan, struct vm_state *vms, const char message_gender[])
07932 {
07933    int res;
07934    int lastnum = 0;
07935 
07936    res = ast_play_and_wait(chan, "vm-youhave");
07937 
07938    if (!res && vms->newmessages) {
07939       lastnum = vms->newmessages;
07940 
07941       if (!(res = ast_say_number(chan, lastnum, AST_DIGIT_ANY, chan->language, message_gender))) {
07942          res = ast_say_counted_adjective(chan, lastnum, "vm-new", message_gender);
07943       }
07944 
07945       if (!res && vms->oldmessages) {
07946          res = ast_play_and_wait(chan, "vm-and");
07947       }
07948    }
07949 
07950    if (!res && vms->oldmessages) {
07951       lastnum = vms->oldmessages;
07952 
07953       if (!(res = ast_say_number(chan, lastnum, AST_DIGIT_ANY, chan->language, message_gender))) {
07954          res = ast_say_counted_adjective(chan, lastnum, "vm-old", message_gender);
07955       }
07956    }
07957 
07958    if (!res) {
07959       if (lastnum == 0) {
07960          res = ast_play_and_wait(chan, "vm-no");
07961       }
07962       if (!res) {
07963          res = ast_say_counted_noun(chan, lastnum, "vm-message");
07964       }
07965    }
07966 
07967    return res;
07968 }
07969 
07970 /* Default Hebrew syntax */
07971 static int vm_intro_he(struct ast_channel *chan, struct vm_state *vms)
07972 {
07973    int res = 0;
07974 
07975    /* Introduce messages they have */
07976    if (!res) {
07977       if ((vms->newmessages) || (vms->oldmessages)) {
07978          res = ast_play_and_wait(chan, "vm-youhave");
07979       }
07980       /*
07981        * The word "shtei" refers to the number 2 in hebrew when performing a count
07982        * of elements. In Hebrew, there are 6 forms of enumerating the number 2 for
07983        * an element, this is one of them.
07984        */
07985       if (vms->newmessages) {
07986          if (!res) {
07987             if (vms->newmessages == 1) {
07988                res = ast_play_and_wait(chan, "vm-INBOX1");
07989             } else {
07990                if (vms->newmessages == 2) {
07991                   res = ast_play_and_wait(chan, "vm-shtei");
07992                } else {
07993                   res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, "f");
07994                }
07995                res = ast_play_and_wait(chan, "vm-INBOX");
07996             }
07997          }
07998          if (vms->oldmessages && !res) {
07999             res = ast_play_and_wait(chan, "vm-and");
08000             if (vms->oldmessages == 1) {
08001                res = ast_play_and_wait(chan, "vm-Old1");
08002             } else {
08003                if (vms->oldmessages == 2) {
08004                   res = ast_play_and_wait(chan, "vm-shtei");
08005                } else {
08006                   res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");
08007                }
08008                res = ast_play_and_wait(chan, "vm-Old");
08009             }
08010          }
08011       }
08012       if (!res && vms->oldmessages && !vms->newmessages) {
08013          if (!res) {
08014             if (vms->oldmessages == 1) {
08015                res = ast_play_and_wait(chan, "vm-Old1");
08016             } else {
08017                if (vms->oldmessages == 2) {
08018                   res = ast_play_and_wait(chan, "vm-shtei");
08019                } else {
08020                   res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");            
08021                }
08022                res = ast_play_and_wait(chan, "vm-Old");
08023             }
08024          }
08025       }
08026       if (!res) {
08027          if (!vms->oldmessages && !vms->newmessages) {
08028             if (!res) {
08029                res = ast_play_and_wait(chan, "vm-nomessages");
08030             }
08031          }
08032       }
08033    }
08034    return res;
08035 }
08036    
08037 /* Default English syntax */
08038 static int vm_intro_en(struct ast_channel *chan, struct vm_state *vms)
08039 {
08040    int res;
08041 
08042    /* Introduce messages they have */
08043    res = ast_play_and_wait(chan, "vm-youhave");
08044    if (!res) {
08045       if (vms->urgentmessages) {
08046          res = say_and_wait(chan, vms->urgentmessages, chan->language);
08047          if (!res)
08048             res = ast_play_and_wait(chan, "vm-Urgent");
08049          if ((vms->oldmessages || vms->newmessages) && !res) {
08050             res = ast_play_and_wait(chan, "vm-and");
08051          } else if (!res) {
08052             if ((vms->urgentmessages == 1))
08053                res = ast_play_and_wait(chan, "vm-message");
08054             else
08055                res = ast_play_and_wait(chan, "vm-messages");
08056          }
08057       }
08058       if (vms->newmessages) {
08059          res = say_and_wait(chan, vms->newmessages, chan->language);
08060          if (!res)
08061             res = ast_play_and_wait(chan, "vm-INBOX");
08062          if (vms->oldmessages && !res)
08063             res = ast_play_and_wait(chan, "vm-and");
08064          else if (!res) {
08065             if ((vms->newmessages == 1))
08066                res = ast_play_and_wait(chan, "vm-message");
08067             else
08068                res = ast_play_and_wait(chan, "vm-messages");
08069          }
08070             
08071       }
08072       if (!res && vms->oldmessages) {
08073          res = say_and_wait(chan, vms->oldmessages, chan->language);
08074          if (!res)
08075             res = ast_play_and_wait(chan, "vm-Old");
08076          if (!res) {
08077             if (vms->oldmessages == 1)
08078                res = ast_play_and_wait(chan, "vm-message");
08079             else
08080                res = ast_play_and_wait(chan, "vm-messages");
08081          }
08082       }
08083       if (!res) {
08084          if (!vms->urgentmessages && !vms->oldmessages && !vms->newmessages) {
08085             res = ast_play_and_wait(chan, "vm-no");
08086             if (!res)
08087                res = ast_play_and_wait(chan, "vm-messages");
08088          }
08089       }
08090    }
08091    return res;
08092 }
08093 
08094 /* ITALIAN syntax */
08095 static int vm_intro_it(struct ast_channel *chan, struct vm_state *vms)
08096 {
08097    /* Introduce messages they have */
08098    int res;
08099    if (!vms->oldmessages && !vms->newmessages &&!vms->urgentmessages)
08100       res = ast_play_and_wait(chan, "vm-no") ||
08101          ast_play_and_wait(chan, "vm-message");
08102    else
08103       res = ast_play_and_wait(chan, "vm-youhave");
08104    if (!res && vms->newmessages) {
08105       res = (vms->newmessages == 1) ?
08106          ast_play_and_wait(chan, "digits/un") ||
08107          ast_play_and_wait(chan, "vm-nuovo") ||
08108          ast_play_and_wait(chan, "vm-message") :
08109          /* 2 or more new messages */
08110          say_and_wait(chan, vms->newmessages, chan->language) ||
08111          ast_play_and_wait(chan, "vm-nuovi") ||
08112          ast_play_and_wait(chan, "vm-messages");
08113       if (!res && vms->oldmessages)
08114          res = ast_play_and_wait(chan, "vm-and");
08115    }
08116    if (!res && vms->oldmessages) {
08117       res = (vms->oldmessages == 1) ?
08118          ast_play_and_wait(chan, "digits/un") ||
08119          ast_play_and_wait(chan, "vm-vecchio") ||
08120          ast_play_and_wait(chan, "vm-message") :
08121          /* 2 or more old messages */
08122          say_and_wait(chan, vms->oldmessages, chan->language) ||
08123          ast_play_and_wait(chan, "vm-vecchi") ||
08124          ast_play_and_wait(chan, "vm-messages");
08125    }
08126    return res;
08127 }
08128 
08129 /* POLISH syntax */
08130 static int vm_intro_pl(struct ast_channel *chan, struct vm_state *vms)
08131 {
08132    /* Introduce messages they have */
08133    int res;
08134    div_t num;
08135 
08136    if (!vms->oldmessages && !vms->newmessages) {
08137       res = ast_play_and_wait(chan, "vm-no");
08138       res = res ? res : ast_play_and_wait(chan, "vm-messages");
08139       return res;
08140    } else {
08141       res = ast_play_and_wait(chan, "vm-youhave");
08142    }
08143 
08144    if (vms->newmessages) {
08145       num = div(vms->newmessages, 10);
08146       if (vms->newmessages == 1) {
08147          res = ast_play_and_wait(chan, "digits/1-a");
08148          res = res ? res : ast_play_and_wait(chan, "vm-new-a");
08149          res = res ? res : ast_play_and_wait(chan, "vm-message");
08150       } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
08151          if (num.rem == 2) {
08152             if (!num.quot) {
08153                res = ast_play_and_wait(chan, "digits/2-ie");
08154             } else {
08155                res = say_and_wait(chan, vms->newmessages - 2 , chan->language);
08156                res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
08157             }
08158          } else {
08159             res = say_and_wait(chan, vms->newmessages, chan->language);
08160          }
08161          res = res ? res : ast_play_and_wait(chan, "vm-new-e");
08162          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08163       } else {
08164          res = say_and_wait(chan, vms->newmessages, chan->language);
08165          res = res ? res : ast_play_and_wait(chan, "vm-new-ych");
08166          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08167       }
08168       if (!res && vms->oldmessages)
08169          res = ast_play_and_wait(chan, "vm-and");
08170    }
08171    if (!res && vms->oldmessages) {
08172       num = div(vms->oldmessages, 10);
08173       if (vms->oldmessages == 1) {
08174          res = ast_play_and_wait(chan, "digits/1-a");
08175          res = res ? res : ast_play_and_wait(chan, "vm-old-a");
08176          res = res ? res : ast_play_and_wait(chan, "vm-message");
08177       } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
08178          if (num.rem == 2) {
08179             if (!num.quot) {
08180                res = ast_play_and_wait(chan, "digits/2-ie");
08181             } else {
08182                res = say_and_wait(chan, vms->oldmessages - 2 , chan->language);
08183                res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
08184             }
08185          } else {
08186             res = say_and_wait(chan, vms->oldmessages, chan->language);
08187          }
08188          res = res ? res : ast_play_and_wait(chan, "vm-old-e");
08189          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08190       } else {
08191          res = say_and_wait(chan, vms->oldmessages, chan->language);
08192          res = res ? res : ast_play_and_wait(chan, "vm-old-ych");
08193          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08194       }
08195    }
08196 
08197    return res;
08198 }
08199 
08200 /* SWEDISH syntax */
08201 static int vm_intro_se(struct ast_channel *chan, struct vm_state *vms)
08202 {
08203    /* Introduce messages they have */
08204    int res;
08205 
08206    res = ast_play_and_wait(chan, "vm-youhave");
08207    if (res)
08208       return res;
08209 
08210    if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08211       res = ast_play_and_wait(chan, "vm-no");
08212       res = res ? res : ast_play_and_wait(chan, "vm-messages");
08213       return res;
08214    }
08215 
08216    if (vms->newmessages) {
08217       if ((vms->newmessages == 1)) {
08218          res = ast_play_and_wait(chan, "digits/ett");
08219          res = res ? res : ast_play_and_wait(chan, "vm-nytt");
08220          res = res ? res : ast_play_and_wait(chan, "vm-message");
08221       } else {
08222          res = say_and_wait(chan, vms->newmessages, chan->language);
08223          res = res ? res : ast_play_and_wait(chan, "vm-nya");
08224          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08225       }
08226       if (!res && vms->oldmessages)
08227          res = ast_play_and_wait(chan, "vm-and");
08228    }
08229    if (!res && vms->oldmessages) {
08230       if (vms->oldmessages == 1) {
08231          res = ast_play_and_wait(chan, "digits/ett");
08232          res = res ? res : ast_play_and_wait(chan, "vm-gammalt");
08233          res = res ? res : ast_play_and_wait(chan, "vm-message");
08234       } else {
08235          res = say_and_wait(chan, vms->oldmessages, chan->language);
08236          res = res ? res : ast_play_and_wait(chan, "vm-gamla");
08237          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08238       }
08239    }
08240 
08241    return res;
08242 }
08243 
08244 /* NORWEGIAN syntax */
08245 static int vm_intro_no(struct ast_channel *chan, struct vm_state *vms)
08246 {
08247    /* Introduce messages they have */
08248    int res;
08249 
08250    res = ast_play_and_wait(chan, "vm-youhave");
08251    if (res)
08252       return res;
08253 
08254    if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08255       res = ast_play_and_wait(chan, "vm-no");
08256       res = res ? res : ast_play_and_wait(chan, "vm-messages");
08257       return res;
08258    }
08259 
08260    if (vms->newmessages) {
08261       if ((vms->newmessages == 1)) {
08262          res = ast_play_and_wait(chan, "digits/1");
08263          res = res ? res : ast_play_and_wait(chan, "vm-ny");
08264          res = res ? res : ast_play_and_wait(chan, "vm-message");
08265       } else {
08266          res = say_and_wait(chan, vms->newmessages, chan->language);
08267          res = res ? res : ast_play_and_wait(chan, "vm-nye");
08268          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08269       }
08270       if (!res && vms->oldmessages)
08271          res = ast_play_and_wait(chan, "vm-and");
08272    }
08273    if (!res && vms->oldmessages) {
08274       if (vms->oldmessages == 1) {
08275          res = ast_play_and_wait(chan, "digits/1");
08276          res = res ? res : ast_play_and_wait(chan, "vm-gamel");
08277          res = res ? res : ast_play_and_wait(chan, "vm-message");
08278       } else {
08279          res = say_and_wait(chan, vms->oldmessages, chan->language);
08280          res = res ? res : ast_play_and_wait(chan, "vm-gamle");
08281          res = res ? res : ast_play_and_wait(chan, "vm-messages");
08282       }
08283    }
08284 
08285    return res;
08286 }
08287 
08288 /* GERMAN syntax */
08289 static int vm_intro_de(struct ast_channel *chan, struct vm_state *vms)
08290 {
08291    /* Introduce messages they have */
08292    int res;
08293    res = ast_play_and_wait(chan, "vm-youhave");
08294    if (!res) {
08295       if (vms->newmessages) {
08296          if ((vms->newmessages == 1))
08297             res = ast_play_and_wait(chan, "digits/1F");
08298          else
08299             res = say_and_wait(chan, vms->newmessages, chan->language);
08300          if (!res)
08301             res = ast_play_and_wait(chan, "vm-INBOX");
08302          if (vms->oldmessages && !res)
08303             res = ast_play_and_wait(chan, "vm-and");
08304          else if (!res) {
08305             if ((vms->newmessages == 1))
08306                res = ast_play_and_wait(chan, "vm-message");
08307             else
08308                res = ast_play_and_wait(chan, "vm-messages");
08309          }
08310             
08311       }
08312       if (!res && vms->oldmessages) {
08313          if (vms->oldmessages == 1)
08314             res = ast_play_and_wait(chan, "digits/1F");
08315          else
08316             res = say_and_wait(chan, vms->oldmessages, chan->language);
08317          if (!res)
08318             res = ast_play_and_wait(chan, "vm-Old");
08319          if (!res) {
08320             if (vms->oldmessages == 1)
08321                res = ast_play_and_wait(chan, "vm-message");
08322             else
08323                res = ast_play_and_wait(chan, "vm-messages");
08324          }
08325       }
08326       if (!res) {
08327          if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08328             res = ast_play_and_wait(chan, "vm-no");
08329             if (!res)
08330                res = ast_play_and_wait(chan, "vm-messages");
08331          }
08332       }
08333    }
08334    return res;
08335 }
08336 
08337 /* SPANISH syntax */
08338 static int vm_intro_es(struct ast_channel *chan, struct vm_state *vms)
08339 {
08340    /* Introduce messages they have */
08341    int res;
08342    if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08343       res = ast_play_and_wait(chan, "vm-youhaveno");
08344       if (!res)
08345          res = ast_play_and_wait(chan, "vm-messages");
08346    } else {
08347       res = ast_play_and_wait(chan, "vm-youhave");
08348    }
08349    if (!res) {
08350       if (vms->newmessages) {
08351          if (!res) {
08352             if ((vms->newmessages == 1)) {
08353                res = ast_play_and_wait(chan, "digits/1M");
08354                if (!res)
08355                   res = ast_play_and_wait(chan, "vm-message");
08356                if (!res)
08357                   res = ast_play_and_wait(chan, "vm-INBOXs");
08358             } else {
08359                res = say_and_wait(chan, vms->newmessages, chan->language);
08360                if (!res)
08361                   res = ast_play_and_wait(chan, "vm-messages");
08362                if (!res)
08363                   res = ast_play_and_wait(chan, "vm-INBOX");
08364             }
08365          }
08366          if (vms->oldmessages && !res)
08367             res = ast_play_and_wait(chan, "vm-and");
08368       }
08369       if (vms->oldmessages) {
08370          if (!res) {
08371             if (vms->oldmessages == 1) {
08372                res = ast_play_and_wait(chan, "digits/1M");
08373                if (!res)
08374                   res = ast_play_and_wait(chan, "vm-message");
08375                if (!res)
08376                   res = ast_play_and_wait(chan, "vm-Olds");
08377             } else {
08378                res = say_and_wait(chan, vms->oldmessages, chan->language);
08379                if (!res)
08380                   res = ast_play_and_wait(chan, "vm-messages");
08381                if (!res)
08382                   res = ast_play_and_wait(chan, "vm-Old");
08383             }
08384          }
08385       }
08386    }
08387 return res;
08388 }
08389 
08390 /* BRAZILIAN PORTUGUESE syntax */
08391 static int vm_intro_pt_BR(struct ast_channel *chan, struct vm_state *vms) {
08392    /* Introduce messages they have */
08393    int res;
08394    if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08395       res = ast_play_and_wait(chan, "vm-nomessages");
08396       return res;
08397    } else {
08398       res = ast_play_and_wait(chan, "vm-youhave");
08399    }
08400    if (vms->newmessages) {
08401       if (!res)
08402          res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, "f");
08403       if ((vms->newmessages == 1)) {
08404          if (!res)
08405             res = ast_play_and_wait(chan, "vm-message");
08406          if (!res)
08407             res = ast_play_and_wait(chan, "vm-INBOXs");
08408       } else {
08409          if (!res)
08410             res = ast_play_and_wait(chan, "vm-messages");
08411          if (!res)
08412             res = ast_play_and_wait(chan, "vm-INBOX");
08413       }
08414       if (vms->oldmessages && !res)
08415          res = ast_play_and_wait(chan, "vm-and");
08416    }
08417    if (vms->oldmessages) {
08418       if (!res)
08419          res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");
08420       if (vms->oldmessages == 1) {
08421          if (!res)
08422             res = ast_play_and_wait(chan, "vm-message");
08423          if (!res)
08424             res = ast_play_and_wait(chan, "vm-Olds");
08425       } else {
08426          if (!res)
08427             res = ast_play_and_wait(chan, "vm-messages");
08428          if (!res)
08429             res = ast_play_and_wait(chan, "vm-Old");
08430       }
08431    }
08432    return res;
08433 }
08434 
08435 /* FRENCH syntax */
08436 static int vm_intro_fr(struct ast_channel *chan, struct vm_state *vms)
08437 {
08438    /* Introduce messages they have */
08439    int res;
08440    res = ast_play_and_wait(chan, "vm-youhave");
08441    if (!res) {
08442       if (vms->newmessages) {
08443          res = say_and_wait(chan, vms->newmessages, chan->language);
08444          if (!res)
08445             res = ast_play_and_wait(chan, "vm-INBOX");
08446          if (vms->oldmessages && !res)
08447             res = ast_play_and_wait(chan, "vm-and");
08448          else if (!res) {
08449             if ((vms->newmessages == 1))
08450                res = ast_play_and_wait(chan, "vm-message");
08451             else
08452                res = ast_play_and_wait(chan, "vm-messages");
08453          }
08454             
08455       }
08456       if (!res && vms->oldmessages) {
08457          res = say_and_wait(chan, vms->oldmessages, chan->language);
08458          if (!res)
08459             res = ast_play_and_wait(chan, "vm-Old");
08460          if (!res) {
08461             if (vms->oldmessages == 1)
08462                res = ast_play_and_wait(chan, "vm-message");
08463             else
08464                res = ast_play_and_wait(chan, "vm-messages");
08465          }
08466       }
08467       if (!res) {
08468          if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08469             res = ast_play_and_wait(chan, "vm-no");
08470             if (!res)
08471                res = ast_play_and_wait(chan, "vm-messages");
08472          }
08473       }
08474    }
08475    return res;
08476 }
08477 
08478 /* DUTCH syntax */
08479 static int vm_intro_nl(struct ast_channel *chan, struct vm_state *vms)
08480 {
08481    /* Introduce messages they have */
08482    int res;
08483    res = ast_play_and_wait(chan, "vm-youhave");
08484    if (!res) {
08485       if (vms->newmessages) {
08486          res = say_and_wait(chan, vms->newmessages, chan->language);
08487          if (!res) {
08488             if (vms->newmessages == 1)
08489                res = ast_play_and_wait(chan, "vm-INBOXs");
08490             else
08491                res = ast_play_and_wait(chan, "vm-INBOX");
08492          }
08493          if (vms->oldmessages && !res)
08494             res = ast_play_and_wait(chan, "vm-and");
08495          else if (!res) {
08496             if ((vms->newmessages == 1))
08497                res = ast_play_and_wait(chan, "vm-message");
08498             else
08499                res = ast_play_and_wait(chan, "vm-messages");
08500          }
08501             
08502       }
08503       if (!res && vms->oldmessages) {
08504          res = say_and_wait(chan, vms->oldmessages, chan->language);
08505          if (!res) {
08506             if (vms->oldmessages == 1)
08507                res = ast_play_and_wait(chan, "vm-Olds");
08508             else
08509                res = ast_play_and_wait(chan, "vm-Old");
08510          }
08511          if (!res) {
08512             if (vms->oldmessages == 1)
08513                res = ast_play_and_wait(chan, "vm-message");
08514             else
08515                res = ast_play_and_wait(chan, "vm-messages");
08516          }
08517       }
08518       if (!res) {
08519          if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08520             res = ast_play_and_wait(chan, "vm-no");
08521             if (!res)
08522                res = ast_play_and_wait(chan, "vm-messages");
08523          }
08524       }
08525    }
08526    return res;
08527 }
08528 
08529 /* PORTUGUESE syntax */
08530 static int vm_intro_pt(struct ast_channel *chan, struct vm_state *vms)
08531 {
08532    /* Introduce messages they have */
08533    int res;
08534    res = ast_play_and_wait(chan, "vm-youhave");
08535    if (!res) {
08536       if (vms->newmessages) {
08537          res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, "f");
08538          if (!res) {
08539             if ((vms->newmessages == 1)) {
08540                res = ast_play_and_wait(chan, "vm-message");
08541                if (!res)
08542                   res = ast_play_and_wait(chan, "vm-INBOXs");
08543             } else {
08544                res = ast_play_and_wait(chan, "vm-messages");
08545                if (!res)
08546                   res = ast_play_and_wait(chan, "vm-INBOX");
08547             }
08548          }
08549          if (vms->oldmessages && !res)
08550             res = ast_play_and_wait(chan, "vm-and");
08551       }
08552       if (!res && vms->oldmessages) {
08553          res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");
08554          if (!res) {
08555             if (vms->oldmessages == 1) {
08556                res = ast_play_and_wait(chan, "vm-message");
08557                if (!res)
08558                   res = ast_play_and_wait(chan, "vm-Olds");
08559             } else {
08560                res = ast_play_and_wait(chan, "vm-messages");
08561                if (!res)
08562                   res = ast_play_and_wait(chan, "vm-Old");
08563             }
08564          }
08565       }
08566       if (!res) {
08567          if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08568             res = ast_play_and_wait(chan, "vm-no");
08569             if (!res)
08570                res = ast_play_and_wait(chan, "vm-messages");
08571          }
08572       }
08573    }
08574    return res;
08575 }
08576 
08577 
08578 /* CZECH syntax */
08579 /* in czech there must be declension of word new and message
08580  * czech        : english        : czech      : english
08581  * --------------------------------------------------------
08582  * vm-youhave   : you have 
08583  * vm-novou     : one new        : vm-zpravu  : message
08584  * vm-nove      : 2-4 new        : vm-zpravy  : messages
08585  * vm-novych    : 5-infinite new : vm-zprav   : messages
08586  * vm-starou   : one old
08587  * vm-stare     : 2-4 old 
08588  * vm-starych   : 5-infinite old
08589  * jednu        : one   - falling 4. 
08590  * vm-no        : no  ( no messages )
08591  */
08592 
08593 static int vm_intro_cs(struct ast_channel *chan, struct vm_state *vms)
08594 {
08595    int res;
08596    res = ast_play_and_wait(chan, "vm-youhave");
08597    if (!res) {
08598       if (vms->newmessages) {
08599          if (vms->newmessages == 1) {
08600             res = ast_play_and_wait(chan, "digits/jednu");
08601          } else {
08602             res = say_and_wait(chan, vms->newmessages, chan->language);
08603          }
08604          if (!res) {
08605             if ((vms->newmessages == 1))
08606                res = ast_play_and_wait(chan, "vm-novou");
08607             if ((vms->newmessages) > 1 && (vms->newmessages < 5))
08608                res = ast_play_and_wait(chan, "vm-nove");
08609             if (vms->newmessages > 4)
08610                res = ast_play_and_wait(chan, "vm-novych");
08611          }
08612          if (vms->oldmessages && !res)
08613             res = ast_play_and_wait(chan, "vm-and");
08614          else if (!res) {
08615             if ((vms->newmessages == 1))
08616                res = ast_play_and_wait(chan, "vm-zpravu");
08617             if ((vms->newmessages) > 1 && (vms->newmessages < 5))
08618                res = ast_play_and_wait(chan, "vm-zpravy");
08619             if (vms->newmessages > 4)
08620                res = ast_play_and_wait(chan, "vm-zprav");
08621          }
08622       }
08623       if (!res && vms->oldmessages) {
08624          res = say_and_wait(chan, vms->oldmessages, chan->language);
08625          if (!res) {
08626             if ((vms->oldmessages == 1))
08627                res = ast_play_and_wait(chan, "vm-starou");
08628             if ((vms->oldmessages) > 1 && (vms->oldmessages < 5))
08629                res = ast_play_and_wait(chan, "vm-stare");
08630             if (vms->oldmessages > 4)
08631                res = ast_play_and_wait(chan, "vm-starych");
08632          }
08633          if (!res) {
08634             if ((vms->oldmessages == 1))
08635                res = ast_play_and_wait(chan, "vm-zpravu");
08636             if ((vms->oldmessages) > 1 && (vms->oldmessages < 5))
08637                res = ast_play_and_wait(chan, "vm-zpravy");
08638             if (vms->oldmessages > 4)
08639                res = ast_play_and_wait(chan, "vm-zprav");
08640          }
08641       }
08642       if (!res) {
08643          if (!vms->oldmessages && !vms->newmessages && !vms->urgentmessages) {
08644             res = ast_play_and_wait(chan, "vm-no");
08645             if (!res)
08646                res = ast_play_and_wait(chan, "vm-zpravy");
08647          }
08648       }
08649    }
08650    return res;
08651 }
08652 
08653 /* CHINESE (Taiwan) syntax */
08654 static int vm_intro_zh(struct ast_channel *chan, struct vm_state *vms)
08655 {
08656    int res;
08657    /* Introduce messages they have */
08658    res = ast_play_and_wait(chan, "vm-you");
08659 
08660    if (!res && vms->newmessages) {
08661       res = ast_play_and_wait(chan, "vm-have");
08662       if (!res)
08663          res = say_and_wait(chan, vms->newmessages, chan->language);
08664       if (!res)
08665          res = ast_play_and_wait(chan, "vm-tong");
08666       if (!res)
08667          res = ast_play_and_wait(chan, "vm-INBOX");
08668       if (vms->oldmessages && !res)
08669          res = ast_play_and_wait(chan, "vm-and");
08670       else if (!res) 
08671          res = ast_play_and_wait(chan, "vm-messages");
08672    }
08673    if (!res && vms->oldmessages) {
08674       res = ast_play_and_wait(chan, "vm-have");
08675       if (!res)
08676          res = say_and_wait(chan, vms->oldmessages, chan->language);
08677       if (!res)
08678          res = ast_play_and_wait(chan, "vm-tong");
08679       if (!res)
08680          res = ast_play_and_wait(chan, "vm-Old");
08681       if (!res)
08682          res = ast_play_and_wait(chan, "vm-messages");
08683    }
08684    if (!res && !vms->oldmessages && !vms->newmessages) {
08685       res = ast_play_and_wait(chan, "vm-haveno");
08686       if (!res)
08687          res = ast_play_and_wait(chan, "vm-messages");
08688    }
08689    return res;
08690 }
08691 
08692 /* Vietnamese syntax */
08693 static int vm_intro_vi(struct ast_channel *chan, struct vm_state *vms)
08694 {
08695    int res;
08696 
08697    /* Introduce messages they have */
08698    res = ast_play_and_wait(chan, "vm-youhave");
08699    if (!res) {
08700       if (vms->newmessages) {
08701          res = say_and_wait(chan, vms->newmessages, chan->language);
08702          if (!res)
08703             res = ast_play_and_wait(chan, "vm-INBOX");
08704          if (vms->oldmessages && !res)
08705             res = ast_play_and_wait(chan, "vm-and");
08706       }
08707       if (!res && vms->oldmessages) {
08708          res = say_and_wait(chan, vms->oldmessages, chan->language);
08709          if (!res)
08710             res = ast_play_and_wait(chan, "vm-Old");        
08711       }
08712       if (!res) {
08713          if (!vms->oldmessages && !vms->newmessages) {
08714             res = ast_play_and_wait(chan, "vm-no");
08715             if (!res)
08716                res = ast_play_and_wait(chan, "vm-message");
08717          }
08718       }
08719    }
08720    return res;
08721 }
08722 
08723 static int vm_intro(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms)
08724 {
08725    char prefile[256];
08726    
08727    /* Notify the user that the temp greeting is set and give them the option to remove it */
08728    snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
08729    if (ast_test_flag(vmu, VM_TEMPGREETWARN)) {
08730       RETRIEVE(prefile, -1, vmu->mailbox, vmu->context);
08731       if (ast_fileexists(prefile, NULL, NULL) > 0) {
08732          ast_play_and_wait(chan, "vm-tempgreetactive");
08733       }
08734       DISPOSE(prefile, -1);
08735    }
08736 
08737    /* Play voicemail intro - syntax is different for different languages */
08738    if (0) {
08739       return 0;
08740    } else if (!strncasecmp(chan->language, "cs", 2)) {  /* CZECH syntax */
08741       return vm_intro_cs(chan, vms);
08742    } else if (!strncasecmp(chan->language, "cz", 2)) {  /* deprecated CZECH syntax */
08743       static int deprecation_warning = 0;
08744       if (deprecation_warning++ % 10 == 0) {
08745          ast_log(LOG_WARNING, "cz is not a standard language code.  Please switch to using cs instead.\n");
08746       }
08747       return vm_intro_cs(chan, vms);
08748    } else if (!strncasecmp(chan->language, "de", 2)) {  /* GERMAN syntax */
08749       return vm_intro_de(chan, vms);
08750    } else if (!strncasecmp(chan->language, "es", 2)) {  /* SPANISH syntax */
08751       return vm_intro_es(chan, vms);
08752    } else if (!strncasecmp(chan->language, "fr", 2)) {  /* FRENCH syntax */
08753       return vm_intro_fr(chan, vms);
08754    } else if (!strncasecmp(chan->language, "gr", 2)) {  /* GREEK syntax */
08755       return vm_intro_gr(chan, vms);
08756    } else if (!strncasecmp(chan->language, "he", 2)) {  /* HEBREW syntax */
08757       return vm_intro_he(chan, vms);
08758    } else if (!strncasecmp(chan->language, "it", 2)) {  /* ITALIAN syntax */
08759       return vm_intro_it(chan, vms);
08760    } else if (!strncasecmp(chan->language, "nl", 2)) {  /* DUTCH syntax */
08761       return vm_intro_nl(chan, vms);
08762    } else if (!strncasecmp(chan->language, "no", 2)) {  /* NORWEGIAN syntax */
08763       return vm_intro_no(chan, vms);
08764    } else if (!strncasecmp(chan->language, "pl", 2)) {  /* POLISH syntax */
08765       return vm_intro_pl(chan, vms);
08766    } else if (!strncasecmp(chan->language, "pt_BR", 5)) {  /* BRAZILIAN PORTUGUESE syntax */
08767       return vm_intro_pt_BR(chan, vms);
08768    } else if (!strncasecmp(chan->language, "pt", 2)) {  /* PORTUGUESE syntax */
08769       return vm_intro_pt(chan, vms);
08770    } else if (!strncasecmp(chan->language, "ru", 2)) {  /* RUSSIAN syntax */
08771       return vm_intro_multilang(chan, vms, "n");
08772    } else if (!strncasecmp(chan->language, "se", 2)) {  /* SWEDISH syntax */
08773       return vm_intro_se(chan, vms);
08774    } else if (!strncasecmp(chan->language, "ua", 2)) {  /* UKRAINIAN syntax */
08775       return vm_intro_multilang(chan, vms, "n");
08776    } else if (!strncasecmp(chan->language, "vi", 2)) { /* VIETNAMESE syntax */
08777       return vm_intro_vi(chan, vms);
08778    } else if (!strncasecmp(chan->language, "zh", 2)) { /* CHINESE (Taiwan) syntax */
08779       return vm_intro_zh(chan, vms);
08780    } else {                                             /* Default to ENGLISH */
08781       return vm_intro_en(chan, vms);
08782    }
08783 }
08784 
08785 static int vm_instructions_en(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int skipadvanced, int in_urgent)
08786 {
08787    int res = 0;
08788    /* Play instructions and wait for new command */
08789    while (!res) {
08790       if (vms->starting) {
08791          if (vms->lastmsg > -1) {
08792             if (skipadvanced)
08793                res = ast_play_and_wait(chan, "vm-onefor-full");
08794             else
08795                res = ast_play_and_wait(chan, "vm-onefor");
08796             if (!res)
08797                res = vm_play_folder_name(chan, vms->vmbox);
08798          }
08799          if (!res) {
08800             if (skipadvanced)
08801                res = ast_play_and_wait(chan, "vm-opts-full");
08802             else
08803                res = ast_play_and_wait(chan, "vm-opts");
08804          }
08805       } else {
08806          /* Added for additional help */
08807          if (skipadvanced) {
08808             res = ast_play_and_wait(chan, "vm-onefor-full");
08809             if (!res)
08810                res = vm_play_folder_name(chan, vms->vmbox);
08811             res = ast_play_and_wait(chan, "vm-opts-full");
08812          }
08813          /* Logic:
08814           * If the current message is not the first OR
08815           * if we're listening to the first new message and there are
08816           * also urgent messages, then prompt for navigation to the
08817           * previous message
08818           */
08819          if (vms->curmsg || (!in_urgent && vms->urgentmessages > 0) || (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms->lastmsg > 0)) {
08820             res = ast_play_and_wait(chan, "vm-prev");
08821          }
08822          if (!res && !skipadvanced)
08823             res = ast_play_and_wait(chan, "vm-advopts");
08824          if (!res)
08825             res = ast_play_and_wait(chan, "vm-repeat");
08826          /* Logic:
08827           * If we're not listening to the last message OR
08828           * we're listening to the last urgent message and there are
08829           * also new non-urgent messages, then prompt for navigation
08830           * to the next message
08831           */
08832          if (!res && ((vms->curmsg != vms->lastmsg) || (in_urgent && vms->newmessages > 0) ||
08833             (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms->lastmsg > 0) )) {
08834             res = ast_play_and_wait(chan, "vm-next");
08835          }
08836          if (!res) {
08837             if (!vms->deleted[vms->curmsg])
08838                res = ast_play_and_wait(chan, "vm-delete");
08839             else
08840                res = ast_play_and_wait(chan, "vm-undelete");
08841             if (!res)
08842                res = ast_play_and_wait(chan, "vm-toforward");
08843             if (!res)
08844                res = ast_play_and_wait(chan, "vm-savemessage");
08845          }
08846       }
08847       if (!res) {
08848          res = ast_play_and_wait(chan, "vm-helpexit");
08849       }
08850       if (!res)
08851          res = ast_waitfordigit(chan, 6000);
08852       if (!res) {
08853          vms->repeats++;
08854          if (vms->repeats > 2) {
08855             res = 't';
08856          }
08857       }
08858    }
08859    return res;
08860 }
08861 
08862 static int vm_instructions_zh(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms,  int skipadvanced, int in_urgent)
08863 {
08864    int res = 0;
08865    /* Play instructions and wait for new command */
08866    while (!res) {
08867       if (vms->lastmsg > -1) {
08868          res = ast_play_and_wait(chan, "vm-listen");
08869          if (!res)
08870             res = vm_play_folder_name(chan, vms->vmbox);
08871          if (!res)
08872             res = ast_play_and_wait(chan, "press");
08873          if (!res)
08874             res = ast_play_and_wait(chan, "digits/1");
08875       }
08876       if (!res)
08877          res = ast_play_and_wait(chan, "vm-opts");
08878       if (!res) {
08879          vms->starting = 0;
08880          return vm_instructions_en(chan, vmu, vms, skipadvanced, in_urgent);
08881       }
08882    }
08883    return res;
08884 }
08885 
08886 static int vm_instructions(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int skipadvanced, int in_urgent)
08887 {
08888    if (vms->starting && !strncasecmp(chan->language, "zh", 2)) { /* CHINESE (Taiwan) syntax */
08889       return vm_instructions_zh(chan, vmu, vms, skipadvanced, in_urgent);
08890    } else {             /* Default to ENGLISH */
08891       return vm_instructions_en(chan, vmu, vms, skipadvanced, in_urgent);
08892    }
08893 }
08894 
08895 
08896 static int vm_newuser(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
08897 {
08898    int cmd = 0;
08899    int duration = 0;
08900    int tries = 0;
08901    char newpassword[80] = "";
08902    char newpassword2[80] = "";
08903    char prefile[PATH_MAX] = "";
08904    unsigned char buf[256];
08905    int bytes = 0;
08906 
08907    if (ast_adsi_available(chan)) {
08908       bytes += adsi_logo(buf + bytes);
08909       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "New User Setup", "");
08910       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
08911       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
08912       bytes += ast_adsi_voice_mode(buf + bytes, 0);
08913       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
08914    }
08915 
08916    /* First, have the user change their password 
08917       so they won't get here again */
08918    for (;;) {
08919       newpassword[1] = '\0';
08920       newpassword[0] = cmd = ast_play_and_wait(chan, vm_newpassword);
08921       if (cmd == '#')
08922          newpassword[0] = '\0';
08923       if (cmd < 0 || cmd == 't' || cmd == '#')
08924          return cmd;
08925       cmd = ast_readstring(chan, newpassword + strlen(newpassword), sizeof(newpassword) - 1, 2000, 10000, "#");
08926       if (cmd < 0 || cmd == 't' || cmd == '#')
08927          return cmd;
08928       cmd = check_password(vmu, newpassword); /* perform password validation */
08929       if (cmd != 0) {
08930          ast_log(AST_LOG_NOTICE, "Invalid password for user %s (%s)\n", vms->username, newpassword);
08931          cmd = ast_play_and_wait(chan, vm_invalid_password);
08932       } else {
08933          newpassword2[1] = '\0';
08934          newpassword2[0] = cmd = ast_play_and_wait(chan, vm_reenterpassword);
08935          if (cmd == '#')
08936             newpassword2[0] = '\0';
08937          if (cmd < 0 || cmd == 't' || cmd == '#')
08938             return cmd;
08939          cmd = ast_readstring(chan, newpassword2 + strlen(newpassword2), sizeof(newpassword2) - 1, 2000, 10000, "#");
08940          if (cmd < 0 || cmd == 't' || cmd == '#')
08941             return cmd;
08942          if (!strcmp(newpassword, newpassword2))
08943             break;
08944          ast_log(AST_LOG_NOTICE, "Password mismatch for user %s (%s != %s)\n", vms->username, newpassword, newpassword2);
08945          cmd = ast_play_and_wait(chan, vm_mismatch);
08946       }
08947       if (++tries == 3)
08948          return -1;
08949       if (cmd != 0) {
08950          cmd = ast_play_and_wait(chan, vm_pls_try_again);
08951       }
08952    }
08953    if (pwdchange & PWDCHANGE_INTERNAL)
08954       vm_change_password(vmu, newpassword);
08955    if ((pwdchange & PWDCHANGE_EXTERNAL) && !ast_strlen_zero(ext_pass_cmd))
08956       vm_change_password_shell(vmu, newpassword);
08957 
08958    ast_debug(1, "User %s set password to %s of length %d\n", vms->username, newpassword, (int) strlen(newpassword));
08959    cmd = ast_play_and_wait(chan, vm_passchanged);
08960 
08961    /* If forcename is set, have the user record their name */  
08962    if (ast_test_flag(vmu, VM_FORCENAME)) {
08963       snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, vms->username);
08964       if (ast_fileexists(prefile, NULL, NULL) < 1) {
08965          cmd = play_record_review(chan, "vm-rec-name", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
08966          if (cmd < 0 || cmd == 't' || cmd == '#')
08967             return cmd;
08968       }
08969    }
08970 
08971    /* If forcegreetings is set, have the user record their greetings */
08972    if (ast_test_flag(vmu, VM_FORCEGREET)) {
08973       snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, vms->username);
08974       if (ast_fileexists(prefile, NULL, NULL) < 1) {
08975          cmd = play_record_review(chan, "vm-rec-unv", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
08976          if (cmd < 0 || cmd == 't' || cmd == '#')
08977             return cmd;
08978       }
08979 
08980       snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, vms->username);
08981       if (ast_fileexists(prefile, NULL, NULL) < 1) {
08982          cmd = play_record_review(chan, "vm-rec-busy", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
08983          if (cmd < 0 || cmd == 't' || cmd == '#')
08984             return cmd;
08985       }
08986    }
08987 
08988    return cmd;
08989 }
08990 
08991 static int vm_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
08992 {
08993    int cmd = 0;
08994    int retries = 0;
08995    int duration = 0;
08996    char newpassword[80] = "";
08997    char newpassword2[80] = "";
08998    char prefile[PATH_MAX] = "";
08999    unsigned char buf[256];
09000    int bytes = 0;
09001 
09002    if (ast_adsi_available(chan)) {
09003       bytes += adsi_logo(buf + bytes);
09004       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Options Menu", "");
09005       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
09006       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
09007       bytes += ast_adsi_voice_mode(buf + bytes, 0);
09008       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
09009    }
09010    while ((cmd >= 0) && (cmd != 't')) {
09011       if (cmd)
09012          retries = 0;
09013       switch (cmd) {
09014       case '1': /* Record your unavailable message */
09015          snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, vms->username);
09016          cmd = play_record_review(chan, "vm-rec-unv", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
09017          break;
09018       case '2':  /* Record your busy message */
09019          snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, vms->username);
09020          cmd = play_record_review(chan, "vm-rec-busy", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
09021          break;
09022       case '3': /* Record greeting */
09023          snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, vms->username);
09024          cmd = play_record_review(chan, "vm-rec-name", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
09025          break;
09026       case '4':  /* manage the temporary greeting */
09027          cmd = vm_tempgreeting(chan, vmu, vms, fmtc, record_gain);
09028          break;
09029       case '5': /* change password */
09030          if (vmu->password[0] == '-') {
09031             cmd = ast_play_and_wait(chan, "vm-no");
09032             break;
09033          }
09034          newpassword[1] = '\0';
09035          newpassword[0] = cmd = ast_play_and_wait(chan, vm_newpassword);
09036          if (cmd == '#')
09037             newpassword[0] = '\0';
09038          else {
09039             if (cmd < 0)
09040                break;
09041             if ((cmd = ast_readstring(chan, newpassword + strlen(newpassword), sizeof(newpassword) - 1, 2000, 10000, "#")) < 0) {
09042                break;
09043             }
09044          }
09045          cmd = check_password(vmu, newpassword); /* perform password validation */
09046          if (cmd != 0) {
09047             ast_log(AST_LOG_NOTICE, "Invalid password for user %s (%s)\n", vms->username, newpassword);
09048             cmd = ast_play_and_wait(chan, vm_invalid_password);
09049             if (!cmd) {
09050                cmd = ast_play_and_wait(chan, vm_pls_try_again);
09051             }
09052             break;
09053          }
09054          newpassword2[1] = '\0';
09055          newpassword2[0] = cmd = ast_play_and_wait(chan, vm_reenterpassword);
09056          if (cmd == '#')
09057             newpassword2[0] = '\0';
09058          else {
09059             if (cmd < 0)
09060                break;
09061 
09062             if ((cmd = ast_readstring(chan, newpassword2 + strlen(newpassword2), sizeof(newpassword2) - 1, 2000, 10000, "#")) < 0) {
09063                break;
09064             }
09065          }
09066          if (strcmp(newpassword, newpassword2)) {
09067             ast_log(AST_LOG_NOTICE, "Password mismatch for user %s (%s != %s)\n", vms->username, newpassword, newpassword2);
09068             cmd = ast_play_and_wait(chan, vm_mismatch);
09069             if (!cmd) {
09070                cmd = ast_play_and_wait(chan, vm_pls_try_again);
09071             }
09072             break;
09073          }
09074          if (pwdchange & PWDCHANGE_INTERNAL)
09075             vm_change_password(vmu, newpassword);
09076          if ((pwdchange & PWDCHANGE_EXTERNAL) && !ast_strlen_zero(ext_pass_cmd))
09077             vm_change_password_shell(vmu, newpassword);
09078 
09079          ast_debug(1, "User %s set password to %s of length %d\n",
09080             vms->username, newpassword, (int) strlen(newpassword));
09081          cmd = ast_play_and_wait(chan, vm_passchanged);
09082          break;
09083       case '*': 
09084          cmd = 't';
09085          break;
09086       default: 
09087          cmd = 0;
09088          snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
09089          RETRIEVE(prefile, -1, vmu->mailbox, vmu->context);
09090          if (ast_fileexists(prefile, NULL, NULL)) {
09091             cmd = ast_play_and_wait(chan, "vm-tmpexists");
09092          }
09093          DISPOSE(prefile, -1);
09094          if (!cmd) {
09095             cmd = ast_play_and_wait(chan, "vm-options");
09096          }
09097          if (!cmd) {
09098             cmd = ast_waitfordigit(chan, 6000);
09099          }
09100          if (!cmd) {
09101             retries++;
09102          }
09103          if (retries > 3) {
09104             cmd = 't';
09105          }
09106       }
09107    }
09108    if (cmd == 't')
09109       cmd = 0;
09110    return cmd;
09111 }
09112 
09113 /*!
09114  * \brief The handler for 'record a temporary greeting'. 
09115  * \param chan
09116  * \param vmu
09117  * \param vms
09118  * \param fmtc
09119  * \param record_gain
09120  *
09121  * This is option 4 from the mailbox options menu.
09122  * This function manages the following promptings:
09123  * 1: play / record / review the temporary greeting. : invokes play_record_review().
09124  * 2: remove (delete) the temporary greeting.
09125  * *: return to the main menu.
09126  *
09127  * \return zero on success, -1 on error.
09128  */
09129 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
09130 {
09131    int cmd = 0;
09132    int retries = 0;
09133    int duration = 0;
09134    char prefile[PATH_MAX] = "";
09135    unsigned char buf[256];
09136    int bytes = 0;
09137 
09138    if (ast_adsi_available(chan)) {
09139       bytes += adsi_logo(buf + bytes);
09140       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Temp Greeting Menu", "");
09141       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
09142       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
09143       bytes += ast_adsi_voice_mode(buf + bytes, 0);
09144       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
09145    }
09146 
09147    snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
09148    while ((cmd >= 0) && (cmd != 't')) {
09149       if (cmd)
09150          retries = 0;
09151       RETRIEVE(prefile, -1, vmu->mailbox, vmu->context);
09152       if (ast_fileexists(prefile, NULL, NULL) <= 0) {
09153          play_record_review(chan, "vm-rec-temp", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
09154          cmd = 't';  
09155       } else {
09156          switch (cmd) {
09157          case '1':
09158             cmd = play_record_review(chan, "vm-rec-temp", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms, NULL);
09159             break;
09160          case '2':
09161             DELETE(prefile, -1, prefile, vmu);
09162             ast_play_and_wait(chan, "vm-tempremoved");
09163             cmd = 't';  
09164             break;
09165          case '*': 
09166             cmd = 't';
09167             break;
09168          default:
09169             cmd = ast_play_and_wait(chan,
09170                ast_fileexists(prefile, NULL, NULL) > 0 ? /* XXX always true ? */
09171                   "vm-tempgreeting2" : "vm-tempgreeting");
09172             if (!cmd)
09173                cmd = ast_waitfordigit(chan, 6000);
09174             if (!cmd)
09175                retries++;
09176             if (retries > 3)
09177                cmd = 't';
09178          }
09179       }
09180       DISPOSE(prefile, -1);
09181    }
09182    if (cmd == 't')
09183       cmd = 0;
09184    return cmd;
09185 }
09186 
09187 /*!
09188  * \brief Greek syntax for 'You have N messages' greeting.
09189  * \param chan
09190  * \param vms
09191  * \param vmu
09192  *
09193  * \return zero on success, -1 on error.
09194  */   
09195 static int vm_browse_messages_gr(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09196 {
09197    int cmd = 0;
09198 
09199    if (vms->lastmsg > -1) {
09200       cmd = play_message(chan, vmu, vms);
09201    } else {
09202       cmd = ast_play_and_wait(chan, "vm-youhaveno");
09203       if (!strcasecmp(vms->vmbox, "vm-INBOX") ||!strcasecmp(vms->vmbox, "vm-Old")){
09204          if (!cmd) {
09205             snprintf(vms->fn, sizeof(vms->fn), "vm-%ss", vms->curbox);
09206             cmd = ast_play_and_wait(chan, vms->fn);
09207          }
09208          if (!cmd)
09209             cmd = ast_play_and_wait(chan, "vm-messages");
09210       } else {
09211          if (!cmd)
09212             cmd = ast_play_and_wait(chan, "vm-messages");
09213          if (!cmd) {
09214             snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09215             cmd = ast_play_and_wait(chan, vms->fn);
09216          }
09217       }
09218    } 
09219    return cmd;
09220 }
09221 
09222 /* Hebrew Syntax */
09223 static int vm_browse_messages_he(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09224 {
09225    int cmd = 0;
09226 
09227    if (vms->lastmsg > -1) {
09228       cmd = play_message(chan, vmu, vms);
09229    } else {
09230       if (!strcasecmp(vms->fn, "INBOX")) {
09231          cmd = ast_play_and_wait(chan, "vm-nonewmessages");
09232       } else {
09233          cmd = ast_play_and_wait(chan, "vm-nomessages");
09234       }
09235    }
09236    return cmd;
09237 }
09238 
09239 /*! 
09240  * \brief Default English syntax for 'You have N messages' greeting.
09241  * \param chan
09242  * \param vms
09243  * \param vmu
09244  *
09245  * \return zero on success, -1 on error.
09246  */
09247 static int vm_browse_messages_en(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09248 {
09249    int cmd = 0;
09250 
09251    if (vms->lastmsg > -1) {
09252       cmd = play_message(chan, vmu, vms);
09253    } else {
09254       cmd = ast_play_and_wait(chan, "vm-youhave");
09255       if (!cmd) 
09256          cmd = ast_play_and_wait(chan, "vm-no");
09257       if (!cmd) {
09258          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09259          cmd = ast_play_and_wait(chan, vms->fn);
09260       }
09261       if (!cmd)
09262          cmd = ast_play_and_wait(chan, "vm-messages");
09263    }
09264    return cmd;
09265 }
09266 
09267 /*! 
09268  *\brief Italian syntax for 'You have N messages' greeting.
09269  * \param chan
09270  * \param vms
09271  * \param vmu
09272  *
09273  * \return zero on success, -1 on error.
09274  */
09275 static int vm_browse_messages_it(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09276 {
09277    int cmd;
09278 
09279    if (vms->lastmsg > -1) {
09280       cmd = play_message(chan, vmu, vms);
09281    } else {
09282       cmd = ast_play_and_wait(chan, "vm-no");
09283       if (!cmd)
09284          cmd = ast_play_and_wait(chan, "vm-message");
09285       if (!cmd) {
09286          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09287          cmd = ast_play_and_wait(chan, vms->fn);
09288       }
09289    }
09290    return cmd;
09291 }
09292 
09293 /*! 
09294  * \brief Spanish syntax for 'You have N messages' greeting.
09295  * \param chan
09296  * \param vms
09297  * \param vmu
09298  *
09299  * \return zero on success, -1 on error.
09300  */
09301 static int vm_browse_messages_es(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09302 {
09303    int cmd;
09304 
09305    if (vms->lastmsg > -1) {
09306       cmd = play_message(chan, vmu, vms);
09307    } else {
09308       cmd = ast_play_and_wait(chan, "vm-youhaveno");
09309       if (!cmd)
09310          cmd = ast_play_and_wait(chan, "vm-messages");
09311       if (!cmd) {
09312          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09313          cmd = ast_play_and_wait(chan, vms->fn);
09314       }
09315    }
09316    return cmd;
09317 }
09318 
09319 /*! 
09320  * \brief Portuguese syntax for 'You have N messages' greeting.
09321  * \param chan
09322  * \param vms
09323  * \param vmu
09324  *
09325  * \return zero on success, -1 on error.
09326  */
09327 static int vm_browse_messages_pt(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09328 {
09329    int cmd;
09330 
09331    if (vms->lastmsg > -1) {
09332       cmd = play_message(chan, vmu, vms);
09333    } else {
09334       cmd = ast_play_and_wait(chan, "vm-no");
09335       if (!cmd) {
09336          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09337          cmd = ast_play_and_wait(chan, vms->fn);
09338       }
09339       if (!cmd)
09340          cmd = ast_play_and_wait(chan, "vm-messages");
09341    }
09342    return cmd;
09343 }
09344 
09345 /*! 
09346  * \brief Chinese (Taiwan)syntax for 'You have N messages' greeting.
09347  * \param chan
09348  * \param vms
09349  * \param vmu
09350  *
09351  * \return zero on success, -1 on error.
09352  */
09353 static int vm_browse_messages_zh(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09354 {
09355    int cmd;
09356 
09357    if (vms->lastmsg > -1) {
09358       cmd = play_message(chan, vmu, vms);
09359    } else {
09360       cmd = ast_play_and_wait(chan, "vm-you");
09361       if (!cmd) 
09362          cmd = ast_play_and_wait(chan, "vm-haveno");
09363       if (!cmd)
09364          cmd = ast_play_and_wait(chan, "vm-messages");
09365       if (!cmd) {
09366          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09367          cmd = ast_play_and_wait(chan, vms->fn);
09368       }
09369    }
09370    return cmd;
09371 }
09372 
09373 /*! 
09374  * \brief Vietnamese syntax for 'You have N messages' greeting.
09375  * \param chan
09376  * \param vms
09377  * \param vmu
09378  *
09379  * \return zero on success, -1 on error.
09380  */
09381 static int vm_browse_messages_vi(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09382 {
09383    int cmd = 0;
09384 
09385    if (vms->lastmsg > -1) {
09386       cmd = play_message(chan, vmu, vms);
09387    } else {
09388       cmd = ast_play_and_wait(chan, "vm-no");
09389       if (!cmd) {
09390          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
09391          cmd = ast_play_and_wait(chan, vms->fn);
09392       }
09393    }
09394    return cmd;
09395 }
09396 
09397 /*!
09398  * \brief Top level method to invoke the language variant vm_browse_messages_XX function.
09399  * \param chan The channel for the current user. We read the language property from this.
09400  * \param vms passed into the language-specific vm_browse_messages function.
09401  * \param vmu passed into the language-specific vm_browse_messages function.
09402  * 
09403  * The method to be invoked is determined by the value of language code property in the user's channel.
09404  * The default (when unable to match) is to use english.
09405  *
09406  * \return zero on success, -1 on error.
09407  */
09408 static int vm_browse_messages(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
09409 {
09410    if (!strncasecmp(chan->language, "es", 2)) {         /* SPANISH */
09411       return vm_browse_messages_es(chan, vms, vmu);
09412    } else if (!strncasecmp(chan->language, "gr", 2)) {  /* GREEK */
09413       return vm_browse_messages_gr(chan, vms, vmu);
09414    } else if (!strncasecmp(chan->language, "he", 2)) {  /* HEBREW */
09415       return vm_browse_messages_he(chan, vms, vmu);
09416    } else if (!strncasecmp(chan->language, "it", 2)) {  /* ITALIAN */
09417       return vm_browse_messages_it(chan, vms, vmu);
09418    } else if (!strncasecmp(chan->language, "pt", 2)) {  /* PORTUGUESE */
09419       return vm_browse_messages_pt(chan, vms, vmu);
09420    } else if (!strncasecmp(chan->language, "vi", 2)) {  /* VIETNAMESE */
09421       return vm_browse_messages_vi(chan, vms, vmu);
09422    } else if (!strncasecmp(chan->language, "zh", 2)) {  /* CHINESE (Taiwan) */
09423       return vm_browse_messages_zh(chan, vms, vmu);
09424    } else {                                             /* Default to English syntax */
09425       return vm_browse_messages_en(chan, vms, vmu);
09426    }
09427 }
09428 
09429 static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_size,
09430          struct ast_vm_user *res_vmu, const char *context, const char *prefix,
09431          int skipuser, int max_logins, int silent)
09432 {
09433    int useadsi = 0, valid = 0, logretries = 0;
09434    char password[AST_MAX_EXTENSION]="", *passptr;
09435    struct ast_vm_user vmus, *vmu = NULL;
09436 
09437    /* If ADSI is supported, setup login screen */
09438    adsi_begin(chan, &useadsi);
09439    if (!skipuser && useadsi)
09440       adsi_login(chan);
09441    if (!silent && !skipuser && ast_streamfile(chan, "vm-login", chan->language)) {
09442       ast_log(AST_LOG_WARNING, "Couldn't stream login file\n");
09443       return -1;
09444    }
09445    
09446    /* Authenticate them and get their mailbox/password */
09447    
09448    while (!valid && (logretries < max_logins)) {
09449       /* Prompt for, and read in the username */
09450       if (!skipuser && ast_readstring(chan, mailbox, mailbox_size - 1, 2000, 10000, "#") < 0) {
09451          ast_log(AST_LOG_WARNING, "Couldn't read username\n");
09452          return -1;
09453       }
09454       if (ast_strlen_zero(mailbox)) {
09455          if (chan->caller.id.number.valid && chan->caller.id.number.str) {
09456             ast_copy_string(mailbox, chan->caller.id.number.str, mailbox_size);
09457          } else {
09458             ast_verb(3, "Username not entered\n"); 
09459             return -1;
09460          }
09461       } else if (mailbox[0] == '*') {
09462          /* user entered '*' */
09463          if (ast_exists_extension(chan, chan->context, "a", 1,
09464             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
09465             return -1;
09466          }
09467          mailbox[0] = '\0';
09468       }
09469 
09470       if (useadsi)
09471          adsi_password(chan);
09472 
09473       if (!ast_strlen_zero(prefix)) {
09474          char fullusername[80] = "";
09475          ast_copy_string(fullusername, prefix, sizeof(fullusername));
09476          strncat(fullusername, mailbox, sizeof(fullusername) - 1 - strlen(fullusername));
09477          ast_copy_string(mailbox, fullusername, mailbox_size);
09478       }
09479 
09480       ast_debug(1, "Before find user for mailbox %s\n", mailbox);
09481       vmu = find_user(&vmus, context, mailbox);
09482       if (vmu && (vmu->password[0] == '\0' || (vmu->password[0] == '-' && vmu->password[1] == '\0'))) {
09483          /* saved password is blank, so don't bother asking */
09484          password[0] = '\0';
09485       } else {
09486          if (ast_streamfile(chan, vm_password, chan->language)) {
09487             ast_log(AST_LOG_WARNING, "Unable to stream password file\n");
09488             return -1;
09489          }
09490          if (ast_readstring(chan, password, sizeof(password) - 1, 2000, 10000, "#") < 0) {
09491             ast_log(AST_LOG_WARNING, "Unable to read password\n");
09492             return -1;
09493          } else if (password[0] == '*') {
09494             /* user entered '*' */
09495             if (ast_exists_extension(chan, chan->context, "a", 1,
09496                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
09497                mailbox[0] = '*';
09498                return -1;
09499             }
09500             mailbox[0] = '\0';
09501          }
09502       }
09503 
09504       if (vmu) {
09505          passptr = vmu->password;
09506          if (passptr[0] == '-') passptr++;
09507       }
09508       if (vmu && !strcmp(passptr, password))
09509          valid++;
09510       else {
09511          ast_verb(3, "Incorrect password '%s' for user '%s' (context = %s)\n", password, mailbox, context ? context : "default");
09512          if (!ast_strlen_zero(prefix))
09513             mailbox[0] = '\0';
09514       }
09515       logretries++;
09516       if (!valid) {
09517          if (skipuser || logretries >= max_logins) {
09518             if (ast_streamfile(chan, "vm-incorrect", chan->language)) {
09519                ast_log(AST_LOG_WARNING, "Unable to stream incorrect message\n");
09520                return -1;
09521             }
09522          } else {
09523             if (useadsi)
09524                adsi_login(chan);
09525             if (ast_streamfile(chan, "vm-incorrect-mailbox", chan->language)) {
09526                ast_log(AST_LOG_WARNING, "Unable to stream incorrect mailbox message\n");
09527                return -1;
09528             }
09529          }
09530          if (ast_waitstream(chan, "")) /* Channel is hung up */
09531             return -1;
09532       }
09533    }
09534    if (!valid && (logretries >= max_logins)) {
09535       ast_stopstream(chan);
09536       ast_play_and_wait(chan, "vm-goodbye");
09537       return -1;
09538    }
09539    if (vmu && !skipuser) {
09540       memcpy(res_vmu, vmu, sizeof(struct ast_vm_user));
09541    }
09542    return 0;
09543 }
09544 
09545 static int vm_execmain(struct ast_channel *chan, const char *data)
09546 {
09547    /* XXX This is, admittedly, some pretty horrendous code.  For some
09548       reason it just seemed a lot easier to do with GOTO's.  I feel
09549       like I'm back in my GWBASIC days. XXX */
09550    int res = -1;
09551    int cmd = 0;
09552    int valid = 0;
09553    char prefixstr[80] ="";
09554    char ext_context[256]="";
09555    int box;
09556    int useadsi = 0;
09557    int skipuser = 0;
09558    struct vm_state vms;
09559    struct ast_vm_user *vmu = NULL, vmus;
09560    char *context = NULL;
09561    int silentexit = 0;
09562    struct ast_flags flags = { 0 };
09563    signed char record_gain = 0;
09564    int play_auto = 0;
09565    int play_folder = 0;
09566    int in_urgent = 0;
09567 #ifdef IMAP_STORAGE
09568    int deleted = 0;
09569 #endif
09570 
09571    /* Add the vm_state to the active list and keep it active */
09572    memset(&vms, 0, sizeof(vms));
09573 
09574    vms.lastmsg = -1;
09575 
09576    memset(&vmus, 0, sizeof(vmus));
09577 
09578    if (chan->_state != AST_STATE_UP) {
09579       ast_debug(1, "Before ast_answer\n");
09580       ast_answer(chan);
09581    }
09582 
09583    if (!ast_strlen_zero(data)) {
09584       char *opts[OPT_ARG_ARRAY_SIZE];
09585       char *parse;
09586       AST_DECLARE_APP_ARGS(args,
09587          AST_APP_ARG(argv0);
09588          AST_APP_ARG(argv1);
09589       );
09590 
09591       parse = ast_strdupa(data);
09592 
09593       AST_STANDARD_APP_ARGS(args, parse);
09594 
09595       if (args.argc == 2) {
09596          if (ast_app_parse_options(vm_app_options, &flags, opts, args.argv1))
09597             return -1;
09598          if (ast_test_flag(&flags, OPT_RECORDGAIN)) {
09599             int gain;
09600             if (!ast_strlen_zero(opts[OPT_ARG_RECORDGAIN])) {
09601                if (sscanf(opts[OPT_ARG_RECORDGAIN], "%30d", &gain) != 1) {
09602                   ast_log(AST_LOG_WARNING, "Invalid value '%s' provided for record gain option\n", opts[OPT_ARG_RECORDGAIN]);
09603                   return -1;
09604                } else {
09605                   record_gain = (signed char) gain;
09606                }
09607             } else {
09608                ast_log(AST_LOG_WARNING, "Invalid Gain level set with option g\n");
09609             }
09610          }
09611          if (ast_test_flag(&flags, OPT_AUTOPLAY) ) {
09612             play_auto = 1;
09613             if (!ast_strlen_zero(opts[OPT_ARG_PLAYFOLDER])) {
09614                /* See if it is a folder name first */
09615                if (isdigit(opts[OPT_ARG_PLAYFOLDER][0])) {
09616                   if (sscanf(opts[OPT_ARG_PLAYFOLDER], "%30d", &play_folder) != 1) {
09617                      play_folder = -1;
09618                   }
09619                } else {
09620                   play_folder = get_folder_by_name(opts[OPT_ARG_PLAYFOLDER]);
09621                }
09622             } else {
09623                ast_log(AST_LOG_WARNING, "Invalid folder set with option a\n");
09624             }
09625             if (play_folder > 9 || play_folder < 0) {
09626                ast_log(AST_LOG_WARNING,
09627                   "Invalid value '%s' provided for folder autoplay option. Defaulting to 'INBOX'\n",
09628                   opts[OPT_ARG_PLAYFOLDER]);
09629                play_folder = 0;
09630             }
09631          }
09632       } else {
09633          /* old style options parsing */
09634          while (*(args.argv0)) {
09635             if (*(args.argv0) == 's')
09636                ast_set_flag(&flags, OPT_SILENT);
09637             else if (*(args.argv0) == 'p')
09638                ast_set_flag(&flags, OPT_PREPEND_MAILBOX);
09639             else 
09640                break;
09641             (args.argv0)++;
09642          }
09643 
09644       }
09645 
09646       valid = ast_test_flag(&flags, OPT_SILENT);
09647 
09648       if ((context = strchr(args.argv0, '@')))
09649          *context++ = '\0';
09650 
09651       if (ast_test_flag(&flags, OPT_PREPEND_MAILBOX))
09652          ast_copy_string(prefixstr, args.argv0, sizeof(prefixstr));
09653       else
09654          ast_copy_string(vms.username, args.argv0, sizeof(vms.username));
09655 
09656       if (!ast_strlen_zero(vms.username) && (vmu = find_user(&vmus, context ,vms.username)))
09657          skipuser++;
09658       else
09659          valid = 0;
09660    }
09661 
09662    if (!valid)
09663       res = vm_authenticate(chan, vms.username, sizeof(vms.username), &vmus, context, prefixstr, skipuser, maxlogins, 0);
09664 
09665    ast_debug(1, "After vm_authenticate\n");
09666 
09667    if (vms.username[0] == '*') {
09668       ast_debug(1, "user pressed * in context '%s'\n", chan->context);
09669 
09670       /* user entered '*' */
09671       if (!ast_goto_if_exists(chan, chan->context, "a", 1)) {
09672          res = 0; /* prevent hangup */
09673          goto out;
09674       }
09675    }
09676 
09677    if (!res) {
09678       valid = 1;
09679       if (!skipuser)
09680          vmu = &vmus;
09681    } else {
09682       res = 0;
09683    }
09684 
09685    /* If ADSI is supported, setup login screen */
09686    adsi_begin(chan, &useadsi);
09687 
09688    if (!valid) {
09689       goto out;
09690    }
09691 
09692 #ifdef IMAP_STORAGE
09693    pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
09694    pthread_setspecific(ts_vmstate.key, &vms);
09695 
09696    vms.interactive = 1;
09697    vms.updated = 1;
09698    if (vmu)
09699       ast_copy_string(vms.context, vmu->context, sizeof(vms.context));
09700    vmstate_insert(&vms);
09701    init_vm_state(&vms);
09702 #endif
09703    /* Avoid allocating a buffer of 0 bytes, because some platforms really don't like that. */
09704    if (!(vms.deleted = ast_calloc(vmu->maxmsg ? vmu->maxmsg : 1, sizeof(int)))) {
09705       ast_log(AST_LOG_ERROR, "Could not allocate memory for deleted message storage!\n");
09706       cmd = ast_play_and_wait(chan, "an-error-has-occured");
09707       return -1;
09708    }
09709    if (!(vms.heard = ast_calloc(vmu->maxmsg ? vmu->maxmsg : 1, sizeof(int)))) {
09710       ast_log(AST_LOG_ERROR, "Could not allocate memory for heard message storage!\n");
09711       cmd = ast_play_and_wait(chan, "an-error-has-occured");
09712       return -1;
09713    }
09714    
09715    /* Set language from config to override channel language */
09716    if (!ast_strlen_zero(vmu->language))
09717       ast_string_field_set(chan, language, vmu->language);
09718 
09719    /* Retrieve urgent, old and new message counts */
09720    ast_debug(1, "Before open_mailbox\n");
09721    res = open_mailbox(&vms, vmu, OLD_FOLDER); /* Count all messages, even Urgent */
09722    if (res == ERROR_LOCK_PATH)
09723       goto out;
09724    vms.oldmessages = vms.lastmsg + 1;
09725    ast_debug(1, "Number of old messages: %d\n", vms.oldmessages);
09726    /* check INBOX */
09727    res = open_mailbox(&vms, vmu, NEW_FOLDER);
09728    if (res == ERROR_LOCK_PATH)
09729       goto out;
09730    vms.newmessages = vms.lastmsg + 1;
09731    ast_debug(1, "Number of new messages: %d\n", vms.newmessages);
09732    /* Start in Urgent */
09733    in_urgent = 1;
09734    res = open_mailbox(&vms, vmu, 11); /*11 is the Urgent folder */
09735    if (res == ERROR_LOCK_PATH)
09736       goto out;
09737    vms.urgentmessages = vms.lastmsg + 1;
09738    ast_debug(1, "Number of urgent messages: %d\n", vms.urgentmessages);
09739 
09740    /* Select proper mailbox FIRST!! */
09741    if (play_auto) {
09742       if (vms.urgentmessages) {
09743          in_urgent = 1;
09744          res = open_mailbox(&vms, vmu, 11);
09745       } else {
09746          in_urgent = 0;
09747          res = open_mailbox(&vms, vmu, play_folder);
09748       }
09749       if (res == ERROR_LOCK_PATH)
09750          goto out;
09751 
09752       /* If there are no new messages, inform the user and hangup */
09753       if (vms.lastmsg == -1) {
09754          in_urgent = 0;
09755          cmd = vm_browse_messages(chan, &vms, vmu);
09756          res = 0;
09757          goto out;
09758       }
09759    } else {
09760       if (!vms.newmessages && !vms.urgentmessages && vms.oldmessages) {
09761          /* If we only have old messages start here */
09762          res = open_mailbox(&vms, vmu, OLD_FOLDER); /* Count all messages, even Urgent */
09763          in_urgent = 0;
09764          play_folder = 1;
09765          if (res == ERROR_LOCK_PATH)
09766             goto out;
09767       } else if (!vms.urgentmessages && vms.newmessages) {
09768          /* If we have new messages but none are urgent */
09769          in_urgent = 0;
09770          res = open_mailbox(&vms, vmu, NEW_FOLDER);
09771          if (res == ERROR_LOCK_PATH)
09772             goto out;
09773       }
09774    }
09775 
09776    if (useadsi)
09777       adsi_status(chan, &vms);
09778    res = 0;
09779 
09780    /* Check to see if this is a new user */
09781    if (!strcasecmp(vmu->mailbox, vmu->password) && 
09782       (ast_test_flag(vmu, VM_FORCENAME | VM_FORCEGREET))) {
09783       if (ast_play_and_wait(chan, "vm-newuser") == -1)
09784          ast_log(AST_LOG_WARNING, "Couldn't stream new user file\n");
09785       cmd = vm_newuser(chan, vmu, &vms, vmfmts, record_gain);
09786       if ((cmd == 't') || (cmd == '#')) {
09787          /* Timeout */
09788          res = 0;
09789          goto out;
09790       } else if (cmd < 0) {
09791          /* Hangup */
09792          res = -1;
09793          goto out;
09794       }
09795    }
09796 #ifdef IMAP_STORAGE
09797       ast_debug(3, "Checking quotas: comparing %u to %u\n", vms.quota_usage, vms.quota_limit);
09798       if (vms.quota_limit && vms.quota_usage >= vms.quota_limit) {
09799          ast_debug(1, "*** QUOTA EXCEEDED!!\n");
09800          cmd = ast_play_and_wait(chan, "vm-mailboxfull");
09801       }
09802       ast_debug(3, "Checking quotas: User has %d messages and limit is %d.\n", (vms.newmessages + vms.oldmessages), vmu->maxmsg);
09803       if ((vms.newmessages + vms.oldmessages) >= vmu->maxmsg) {
09804          ast_log(AST_LOG_WARNING, "No more messages possible.  User has %d messages and limit is %d.\n", (vms.newmessages + vms.oldmessages), vmu->maxmsg);
09805          cmd = ast_play_and_wait(chan, "vm-mailboxfull");
09806       }
09807 #endif
09808    if (play_auto) {
09809       cmd = '1';
09810    } else {
09811       cmd = vm_intro(chan, vmu, &vms);
09812    }
09813 
09814    vms.repeats = 0;
09815    vms.starting = 1;
09816    while ((cmd > -1) && (cmd != 't') && (cmd != '#')) {
09817       /* Run main menu */
09818       switch (cmd) {
09819       case '1': /* First message */
09820          vms.curmsg = 0;
09821          /* Fall through */
09822       case '5': /* Play current message */
09823          cmd = vm_browse_messages(chan, &vms, vmu);
09824          break;
09825       case '2': /* Change folders */
09826          if (useadsi)
09827             adsi_folders(chan, 0, "Change to folder...");
09828          cmd = get_folder2(chan, "vm-changeto", 0);
09829          if (cmd == '#') {
09830             cmd = 0;
09831          } else if (cmd > 0) {
09832             cmd = cmd - '0';
09833             res = close_mailbox(&vms, vmu);
09834             if (res == ERROR_LOCK_PATH)
09835                goto out;
09836             /* If folder is not urgent, set in_urgent to zero! */
09837             if (cmd != 11) in_urgent = 0;
09838             res = open_mailbox(&vms, vmu, cmd);
09839             if (res == ERROR_LOCK_PATH)
09840                goto out;
09841             play_folder = cmd;
09842             cmd = 0;
09843          }
09844          if (useadsi)
09845             adsi_status2(chan, &vms);
09846             
09847          if (!cmd)
09848             cmd = vm_play_folder_name(chan, vms.vmbox);
09849 
09850          vms.starting = 1;
09851          break;
09852       case '3': /* Advanced options */
09853          cmd = 0;
09854          vms.repeats = 0;
09855          while ((cmd > -1) && (cmd != 't') && (cmd != '#')) {
09856             switch (cmd) {
09857             case '1': /* Reply */
09858                if (vms.lastmsg > -1 && !vms.starting) {
09859                   cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 1, record_gain);
09860                   if (cmd == ERROR_LOCK_PATH || cmd == OPERATOR_EXIT) {
09861                      res = cmd;
09862                      goto out;
09863                   }
09864                } else
09865                   cmd = ast_play_and_wait(chan, "vm-sorry");
09866                cmd = 't';
09867                break;
09868             case '2': /* Callback */
09869                if (!vms.starting)
09870                   ast_verb(3, "Callback Requested\n");
09871                if (!ast_strlen_zero(vmu->callback) && vms.lastmsg > -1 && !vms.starting) {
09872                   cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 2, record_gain);
09873                   if (cmd == 9) {
09874                      silentexit = 1;
09875                      goto out;
09876                   } else if (cmd == ERROR_LOCK_PATH) {
09877                      res = cmd;
09878                      goto out;
09879                   }
09880                } else 
09881                   cmd = ast_play_and_wait(chan, "vm-sorry");
09882                cmd = 't';
09883                break;
09884             case '3': /* Envelope */
09885                if (vms.lastmsg > -1 && !vms.starting) {
09886                   cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 3, record_gain);
09887                   if (cmd == ERROR_LOCK_PATH) {
09888                      res = cmd;
09889                      goto out;
09890                   }
09891                } else
09892                   cmd = ast_play_and_wait(chan, "vm-sorry");
09893                cmd = 't';
09894                break;
09895             case '4': /* Dialout */
09896                if (!ast_strlen_zero(vmu->dialout)) {
09897                   cmd = dialout(chan, vmu, NULL, vmu->dialout);
09898                   if (cmd == 9) {
09899                      silentexit = 1;
09900                      goto out;
09901                   }
09902                } else 
09903                   cmd = ast_play_and_wait(chan, "vm-sorry");
09904                cmd = 't';
09905                break;
09906 
09907             case '5': /* Leave VoiceMail */
09908                if (ast_test_flag(vmu, VM_SVMAIL)) {
09909                   cmd = forward_message(chan, context, &vms, vmu, vmfmts, 1, record_gain, 0);
09910                   if (cmd == ERROR_LOCK_PATH || cmd == OPERATOR_EXIT) {
09911                      res = cmd;
09912                      goto out;
09913                   }
09914                } else
09915                   cmd = ast_play_and_wait(chan, "vm-sorry");
09916                cmd = 't';
09917                break;
09918                
09919             case '*': /* Return to main menu */
09920                cmd = 't';
09921                break;
09922 
09923             default:
09924                cmd = 0;
09925                if (!vms.starting) {
09926                   cmd = ast_play_and_wait(chan, "vm-toreply");
09927                }
09928                if (!ast_strlen_zero(vmu->callback) && !vms.starting && !cmd) {
09929                   cmd = ast_play_and_wait(chan, "vm-tocallback");
09930                }
09931                if (!cmd && !vms.starting) {
09932                   cmd = ast_play_and_wait(chan, "vm-tohearenv");
09933                }
09934                if (!ast_strlen_zero(vmu->dialout) && !cmd) {
09935                   cmd = ast_play_and_wait(chan, "vm-tomakecall");
09936                }
09937                if (ast_test_flag(vmu, VM_SVMAIL) && !cmd)
09938                   cmd = ast_play_and_wait(chan, "vm-leavemsg");
09939                if (!cmd)
09940                   cmd = ast_play_and_wait(chan, "vm-starmain");
09941                if (!cmd)
09942                   cmd = ast_waitfordigit(chan, 6000);
09943                if (!cmd)
09944                   vms.repeats++;
09945                if (vms.repeats > 3)
09946                   cmd = 't';
09947             }
09948          }
09949          if (cmd == 't') {
09950             cmd = 0;
09951             vms.repeats = 0;
09952          }
09953          break;
09954       case '4': /* Go to the previous message */
09955          if (vms.curmsg > 0) {
09956             vms.curmsg--;
09957             cmd = play_message(chan, vmu, &vms);
09958          } else {
09959             /* Check if we were listening to new
09960                messages.  If so, go to Urgent messages
09961                instead of saying "no more messages"
09962             */
09963             if (in_urgent == 0 && vms.urgentmessages > 0) {
09964                /* Check for Urgent messages */
09965                in_urgent = 1;
09966                res = close_mailbox(&vms, vmu);
09967                if (res == ERROR_LOCK_PATH)
09968                   goto out;
09969                res = open_mailbox(&vms, vmu, 11);  /* Open Urgent folder */
09970                if (res == ERROR_LOCK_PATH)
09971                   goto out;
09972                ast_debug(1, "No more new messages, opened INBOX and got %d Urgent messages\n", vms.lastmsg + 1);
09973                vms.curmsg = vms.lastmsg;
09974                if (vms.lastmsg < 0)
09975                   cmd = ast_play_and_wait(chan, "vm-nomore");
09976             } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
09977                vms.curmsg = vms.lastmsg;
09978                cmd = play_message(chan, vmu, &vms);
09979             } else {
09980                cmd = ast_play_and_wait(chan, "vm-nomore");
09981             }
09982          }
09983          break;
09984       case '6': /* Go to the next message */
09985          if (vms.curmsg < vms.lastmsg) {
09986             vms.curmsg++;
09987             cmd = play_message(chan, vmu, &vms);
09988          } else {
09989             if (in_urgent && vms.newmessages > 0) {
09990                /* Check if we were listening to urgent
09991                 * messages.  If so, go to regular new messages
09992                 * instead of saying "no more messages"
09993                 */
09994                in_urgent = 0;
09995                res = close_mailbox(&vms, vmu);
09996                if (res == ERROR_LOCK_PATH)
09997                   goto out;
09998                res = open_mailbox(&vms, vmu, NEW_FOLDER);
09999                if (res == ERROR_LOCK_PATH)
10000                   goto out;
10001                ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
10002                vms.curmsg = -1;
10003                if (vms.lastmsg < 0) {
10004                   cmd = ast_play_and_wait(chan, "vm-nomore");
10005                }
10006             } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
10007                vms.curmsg = 0;
10008                cmd = play_message(chan, vmu, &vms);
10009             } else {
10010                cmd = ast_play_and_wait(chan, "vm-nomore");
10011             }
10012          }
10013          break;
10014       case '7': /* Delete the current message */
10015          if (vms.curmsg >= 0 && vms.curmsg <= vms.lastmsg) {
10016             vms.deleted[vms.curmsg] = !vms.deleted[vms.curmsg];
10017             if (useadsi)
10018                adsi_delete(chan, &vms);
10019             if (vms.deleted[vms.curmsg]) {
10020                if (play_folder == 0) {
10021                   if (in_urgent) {
10022                      vms.urgentmessages--;
10023                   } else {
10024                      vms.newmessages--;
10025                   }
10026                }
10027                else if (play_folder == 1)
10028                   vms.oldmessages--;
10029                cmd = ast_play_and_wait(chan, "vm-deleted");
10030             } else {
10031                if (play_folder == 0) {
10032                   if (in_urgent) {
10033                      vms.urgentmessages++;
10034                   } else {
10035                      vms.newmessages++;
10036                   }
10037                }
10038                else if (play_folder == 1)
10039                   vms.oldmessages++;
10040                cmd = ast_play_and_wait(chan, "vm-undeleted");
10041             }
10042             if (ast_test_flag(vmu, VM_SKIPAFTERCMD)) {
10043                if (vms.curmsg < vms.lastmsg) {
10044                   vms.curmsg++;
10045                   cmd = play_message(chan, vmu, &vms);
10046                } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
10047                   vms.curmsg = 0;
10048                   cmd = play_message(chan, vmu, &vms);
10049                } else {
10050                   /* Check if we were listening to urgent
10051                      messages.  If so, go to regular new messages
10052                      instead of saying "no more messages"
10053                   */
10054                   if (in_urgent == 1) {
10055                      /* Check for new messages */
10056                      in_urgent = 0;
10057                      res = close_mailbox(&vms, vmu);
10058                      if (res == ERROR_LOCK_PATH)
10059                         goto out;
10060                      res = open_mailbox(&vms, vmu, NEW_FOLDER);
10061                      if (res == ERROR_LOCK_PATH)
10062                         goto out;
10063                      ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
10064                      vms.curmsg = -1;
10065                      if (vms.lastmsg < 0)
10066                         cmd = ast_play_and_wait(chan, "vm-nomore");
10067                   } else {
10068                      cmd = ast_play_and_wait(chan, "vm-nomore");
10069                   }
10070                }
10071             }
10072          } else /* Delete not valid if we haven't selected a message */
10073             cmd = 0;
10074 #ifdef IMAP_STORAGE
10075          deleted = 1;
10076 #endif
10077          break;
10078    
10079       case '8': /* Forward the current messgae */
10080          if (vms.lastmsg > -1) {
10081             cmd = forward_message(chan, context, &vms, vmu, vmfmts, 0, record_gain, in_urgent);
10082             if (cmd == ERROR_LOCK_PATH) {
10083                res = cmd;
10084                goto out;
10085             }
10086          } else {
10087             /* Check if we were listening to urgent
10088                messages.  If so, go to regular new messages
10089                instead of saying "no more messages"
10090             */
10091             if (in_urgent == 1 && vms.newmessages > 0) {
10092                /* Check for new messages */
10093                in_urgent = 0;
10094                res = close_mailbox(&vms, vmu);
10095                if (res == ERROR_LOCK_PATH)
10096                   goto out;
10097                res = open_mailbox(&vms, vmu, NEW_FOLDER);
10098                if (res == ERROR_LOCK_PATH)
10099                   goto out;
10100                ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
10101                vms.curmsg = -1;
10102                if (vms.lastmsg < 0)
10103                   cmd = ast_play_and_wait(chan, "vm-nomore");
10104             } else {
10105                cmd = ast_play_and_wait(chan, "vm-nomore");
10106             }
10107          }
10108          break;
10109       case '9': /* Save message to folder */
10110          if (vms.curmsg < 0 || vms.curmsg > vms.lastmsg) {
10111             /* No message selected */
10112             cmd = 0;
10113             break;
10114          }
10115          if (useadsi)
10116             adsi_folders(chan, 1, "Save to folder...");
10117          cmd = get_folder2(chan, "vm-savefolder", 1);
10118          box = 0; /* Shut up compiler */
10119          if (cmd == '#') {
10120             cmd = 0;
10121             break;
10122          } else if (cmd > 0) {
10123             box = cmd = cmd - '0';
10124             cmd = save_to_folder(vmu, &vms, vms.curmsg, cmd);
10125             if (cmd == ERROR_LOCK_PATH) {
10126                res = cmd;
10127                goto out;
10128 #ifndef IMAP_STORAGE
10129             } else if (!cmd) {
10130                vms.deleted[vms.curmsg] = 1;
10131 #endif
10132             } else {
10133                vms.deleted[vms.curmsg] = 0;
10134                vms.heard[vms.curmsg] = 0;
10135             }
10136          }
10137          make_file(vms.fn, sizeof(vms.fn), vms.curdir, vms.curmsg);
10138          if (useadsi)
10139             adsi_message(chan, &vms);
10140          snprintf(vms.fn, sizeof(vms.fn), "vm-%s", mbox(vmu, box));
10141          if (!cmd) {
10142             cmd = ast_play_and_wait(chan, "vm-message");
10143             if (!cmd) 
10144                cmd = say_and_wait(chan, vms.curmsg + 1, chan->language);
10145             if (!cmd)
10146                cmd = ast_play_and_wait(chan, "vm-savedto");
10147             if (!cmd)
10148                cmd = vm_play_folder_name(chan, vms.fn);
10149          } else {
10150             cmd = ast_play_and_wait(chan, "vm-mailboxfull");
10151          }
10152          if (ast_test_flag((&globalflags), VM_SKIPAFTERCMD)) {
10153             if (vms.curmsg < vms.lastmsg) {
10154                vms.curmsg++;
10155                cmd = play_message(chan, vmu, &vms);
10156             } else if (ast_test_flag(vmu, VM_MESSAGEWRAP) && vms.lastmsg > 0) {
10157                vms.curmsg = 0;
10158                cmd = play_message(chan, vmu, &vms);
10159             } else {
10160                /* Check if we were listening to urgent
10161                   messages.  If so, go to regular new messages
10162                   instead of saying "no more messages"
10163                */
10164                if (in_urgent == 1 && vms.newmessages > 0) {
10165                   /* Check for new messages */
10166                   in_urgent = 0;
10167                   res = close_mailbox(&vms, vmu);
10168                   if (res == ERROR_LOCK_PATH)
10169                      goto out;
10170                   res = open_mailbox(&vms, vmu, NEW_FOLDER);
10171                   if (res == ERROR_LOCK_PATH)
10172                      goto out;
10173                   ast_debug(1, "No more urgent messages, opened INBOX and got %d new messages\n", vms.lastmsg + 1);
10174                   vms.curmsg = -1;
10175                   if (vms.lastmsg < 0)
10176                      cmd = ast_play_and_wait(chan, "vm-nomore");
10177                } else {
10178                   cmd = ast_play_and_wait(chan, "vm-nomore");
10179                }
10180             }
10181          }
10182          break;
10183       case '*': /* Help */
10184          if (!vms.starting) {
10185             cmd = ast_play_and_wait(chan, "vm-onefor");
10186             if (!strncasecmp(chan->language, "he", 2)) {
10187                cmd = ast_play_and_wait(chan, "vm-for");
10188             }
10189             if (!cmd)
10190                cmd = vm_play_folder_name(chan, vms.vmbox);
10191             if (!cmd)
10192                cmd = ast_play_and_wait(chan, "vm-opts");
10193             if (!cmd)
10194                cmd = vm_instructions(chan, vmu, &vms, 1, in_urgent);
10195          } else
10196             cmd = 0;
10197          break;
10198       case '0': /* Mailbox options */
10199          cmd = vm_options(chan, vmu, &vms, vmfmts, record_gain);
10200          if (useadsi)
10201             adsi_status(chan, &vms);
10202          break;
10203       default: /* Nothing */
10204          cmd = vm_instructions(chan, vmu, &vms, 0, in_urgent);
10205          break;
10206       }
10207    }
10208    if ((cmd == 't') || (cmd == '#')) {
10209       /* Timeout */
10210       res = 0;
10211    } else {
10212       /* Hangup */
10213       res = -1;
10214    }
10215 
10216 out:
10217    if (res > -1) {
10218       ast_stopstream(chan);
10219       adsi_goodbye(chan);
10220       if (valid && res != OPERATOR_EXIT) {
10221          if (silentexit)
10222             res = ast_play_and_wait(chan, "vm-dialout");
10223          else 
10224             res = ast_play_and_wait(chan, "vm-goodbye");
10225       }
10226       if ((valid && res > 0) || res == OPERATOR_EXIT) {
10227          res = 0;
10228       }
10229       if (useadsi)
10230          ast_adsi_unload_session(chan);
10231    }
10232    if (vmu)
10233       close_mailbox(&vms, vmu);
10234    if (valid) {
10235       int new = 0, old = 0, urgent = 0;
10236       snprintf(ext_context, sizeof(ext_context), "%s@%s", vms.username, vmu->context);
10237       ast_manager_event(chan, EVENT_FLAG_CALL, "MessageWaiting", "Mailbox: %s\r\nWaiting: %d\r\n", ext_context, has_voicemail(ext_context, NULL));
10238       /* Urgent flag not passwd to externnotify here */
10239       run_externnotify(vmu->context, vmu->mailbox, NULL);
10240       ast_app_inboxcount2(ext_context, &urgent, &new, &old);
10241       queue_mwi_event(ext_context, urgent, new, old);
10242    }
10243 #ifdef IMAP_STORAGE
10244    /* expunge message - use UID Expunge if supported on IMAP server*/
10245    ast_debug(3, "*** Checking if we can expunge, deleted set to %d, expungeonhangup set to %d\n", deleted, expungeonhangup);
10246    if (vmu && deleted == 1 && expungeonhangup == 1 && vms.mailstream != NULL) {
10247       ast_mutex_lock(&vms.lock);
10248 #ifdef HAVE_IMAP_TK2006
10249       if (LEVELUIDPLUS (vms.mailstream)) {
10250          mail_expunge_full(vms.mailstream, NIL, EX_UID);
10251       } else 
10252 #endif
10253          mail_expunge(vms.mailstream);
10254       ast_mutex_unlock(&vms.lock);
10255    }
10256    /*  before we delete the state, we should copy pertinent info
10257     *  back to the persistent model */
10258    if (vmu) {
10259       vmstate_delete(&vms);
10260    }
10261 #endif
10262    if (vmu)
10263       free_user(vmu);
10264    if (vms.deleted)
10265       ast_free(vms.deleted);
10266    if (vms.heard)
10267       ast_free(vms.heard);
10268 
10269 #ifdef IMAP_STORAGE
10270    pthread_setspecific(ts_vmstate.key, NULL);
10271 #endif
10272    return res;
10273 }
10274 
10275 static int vm_exec(struct ast_channel *chan, const char *data)
10276 {
10277    int res = 0;
10278    char *tmp;
10279    struct leave_vm_options leave_options;
10280    struct ast_flags flags = { 0 };
10281    char *opts[OPT_ARG_ARRAY_SIZE];
10282    AST_DECLARE_APP_ARGS(args,
10283       AST_APP_ARG(argv0);
10284       AST_APP_ARG(argv1);
10285    );
10286    
10287    memset(&leave_options, 0, sizeof(leave_options));
10288 
10289    if (chan->_state != AST_STATE_UP)
10290       ast_answer(chan);
10291 
10292    if (!ast_strlen_zero(data)) {
10293       tmp = ast_strdupa(data);
10294       AST_STANDARD_APP_ARGS(args, tmp);
10295       if (args.argc == 2) {
10296          if (ast_app_parse_options(vm_app_options, &flags, opts, args.argv1))
10297             return -1;
10298          ast_copy_flags(&leave_options, &flags, OPT_SILENT | OPT_BUSY_GREETING | OPT_UNAVAIL_GREETING | OPT_MESSAGE_Urgent | OPT_MESSAGE_PRIORITY | OPT_DTMFEXIT);
10299          if (ast_test_flag(&flags, OPT_RECORDGAIN)) {
10300             int gain;
10301 
10302             if (sscanf(opts[OPT_ARG_RECORDGAIN], "%30d", &gain) != 1) {
10303                ast_log(AST_LOG_WARNING, "Invalid value '%s' provided for record gain option\n", opts[OPT_ARG_RECORDGAIN]);
10304                return -1;
10305             } else {
10306                leave_options.record_gain = (signed char) gain;
10307             }
10308          }
10309          if (ast_test_flag(&flags, OPT_DTMFEXIT)) {
10310             if (!ast_strlen_zero(opts[OPT_ARG_DTMFEXIT]))
10311                leave_options.exitcontext = opts[OPT_ARG_DTMFEXIT];
10312          }
10313       }
10314    } else {
10315       char temp[256];
10316       res = ast_app_getdata(chan, "vm-whichbox", temp, sizeof(temp) - 1, 0);
10317       if (res < 0)
10318          return res;
10319       if (ast_strlen_zero(temp))
10320          return 0;
10321       args.argv0 = ast_strdupa(temp);
10322    }
10323 
10324    res = leave_voicemail(chan, args.argv0, &leave_options);
10325    if (res == OPERATOR_EXIT) {
10326       res = 0;
10327    }
10328 
10329    if (res == ERROR_LOCK_PATH) {
10330       ast_log(AST_LOG_ERROR, "Could not leave voicemail. The path is already locked.\n");
10331       pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
10332       res = 0;
10333    }
10334 
10335    return res;
10336 }
10337 
10338 static struct ast_vm_user *find_or_create(const char *context, const char *box)
10339 {
10340    struct ast_vm_user *vmu;
10341 
10342    AST_LIST_TRAVERSE(&users, vmu, list) {
10343       if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(box, vmu->mailbox)) {
10344          if (strcasecmp(vmu->context, context)) {
10345             ast_log(LOG_WARNING, "\nIt has been detected that you have defined mailbox '%s' in separate\
10346                   \n\tcontexts and that you have the 'searchcontexts' option on. This type of\
10347                   \n\tconfiguration creates an ambiguity that you likely do not want. Please\
10348                   \n\tamend your voicemail.conf file to avoid this situation.\n", box);
10349          }
10350          ast_log(LOG_WARNING, "Ignoring duplicated mailbox %s\n", box);
10351          return NULL;
10352       }
10353       if (!strcasecmp(context, vmu->context) && !strcasecmp(box, vmu->mailbox)) {
10354          ast_log(LOG_WARNING, "Ignoring duplicated mailbox %s in context %s\n", box, context);
10355          return NULL;
10356       }
10357    }
10358    
10359    if (!(vmu = ast_calloc(1, sizeof(*vmu))))
10360       return NULL;
10361    
10362    ast_copy_string(vmu->context, context, sizeof(vmu->context));
10363    ast_copy_string(vmu->mailbox, box, sizeof(vmu->mailbox));
10364 
10365    AST_LIST_INSERT_TAIL(&users, vmu, list);
10366    
10367    return vmu;
10368 }
10369 
10370 static int append_mailbox(const char *context, const char *box, const char *data)
10371 {
10372    /* Assumes lock is already held */
10373    char *tmp;
10374    char *stringp;
10375    char *s;
10376    struct ast_vm_user *vmu;
10377    char *mailbox_full;
10378    int new = 0, old = 0, urgent = 0;
10379    char secretfn[PATH_MAX] = "";
10380 
10381    tmp = ast_strdupa(data);
10382 
10383    if (!(vmu = find_or_create(context, box)))
10384       return -1;
10385 
10386    populate_defaults(vmu);
10387 
10388    stringp = tmp;
10389    if ((s = strsep(&stringp, ","))) {
10390       ast_copy_string(vmu->password, s, sizeof(vmu->password));
10391    }
10392    if (stringp && (s = strsep(&stringp, ","))) {
10393       ast_copy_string(vmu->fullname, s, sizeof(vmu->fullname));
10394    }
10395    if (stringp && (s = strsep(&stringp, ","))) {
10396       ast_copy_string(vmu->email, s, sizeof(vmu->email));
10397    }
10398    if (stringp && (s = strsep(&stringp, ","))) {
10399       ast_copy_string(vmu->pager, s, sizeof(vmu->pager));
10400    }
10401    if (stringp && (s = strsep(&stringp, ","))) {
10402       apply_options(vmu, s);
10403    }
10404 
10405    switch (vmu->passwordlocation) {
10406    case OPT_PWLOC_SPOOLDIR:
10407       snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
10408       read_password_from_file(secretfn, vmu->password, sizeof(vmu->password));
10409    }
10410 
10411    mailbox_full = alloca(strlen(box) + strlen(context) + 1);
10412    strcpy(mailbox_full, box);
10413    strcat(mailbox_full, "@");
10414    strcat(mailbox_full, context);
10415 
10416    inboxcount2(mailbox_full, &urgent, &new, &old);
10417    queue_mwi_event(mailbox_full, urgent, new, old);
10418 
10419    return 0;
10420 }
10421 
10422 AST_TEST_DEFINE(test_voicemail_vmuser)
10423 {
10424    int res = 0;
10425    struct ast_vm_user *vmu;
10426    /* language parameter seems to only be used for display in manager action */
10427    static const char options_string[] = "attach=yes|attachfmt=wav49|"
10428       "serveremail=someguy@digium.com|tz=central|delete=yes|saycid=yes|"
10429       "sendvoicemail=yes|review=yes|tempgreetwarn=yes|messagewrap=yes|operator=yes|"
10430       "envelope=yes|moveheard=yes|sayduration=yes|saydurationm=5|forcename=yes|"
10431       "forcegreetings=yes|callback=somecontext|dialout=somecontext2|"
10432       "exitcontext=somecontext3|minsecs=10|maxsecs=100|nextaftercmd=yes|"
10433       "backupdeleted=50|volgain=1.3|passwordlocation=spooldir";
10434 #ifdef IMAP_STORAGE
10435    static const char option_string2[] = "imapuser=imapuser|imappassword=imappasswd|"
10436       "imapfolder=INBOX|imapvmshareid=6000";
10437 #endif
10438 
10439    switch (cmd) {
10440    case TEST_INIT:
10441       info->name = "vmuser";
10442       info->category = "/apps/app_voicemail/";
10443       info->summary = "Vmuser unit test";
10444       info->description =
10445          "This tests passing all supported parameters to apply_options, the voicemail user config parser";
10446       return AST_TEST_NOT_RUN;
10447    case TEST_EXECUTE:
10448       break;
10449    }
10450 
10451    if (!(vmu = ast_calloc(1, sizeof(*vmu)))) {
10452       return AST_TEST_NOT_RUN;
10453    }
10454    ast_set_flag(vmu, VM_ALLOCED);
10455 
10456    apply_options(vmu, options_string);
10457 
10458    if (!ast_test_flag(vmu, VM_ATTACH)) {
10459       ast_test_status_update(test, "Parse failure for attach option\n");
10460       res = 1;
10461    }
10462    if (strcasecmp(vmu->attachfmt, "wav49")) {
10463       ast_test_status_update(test, "Parse failure for attachftm option\n");
10464       res = 1;
10465    }
10466    if (strcasecmp(vmu->serveremail, "someguy@digium.com")) {
10467       ast_test_status_update(test, "Parse failure for serveremail option\n");
10468       res = 1;
10469    }
10470    if (strcasecmp(vmu->zonetag, "central")) {
10471       ast_test_status_update(test, "Parse failure for tz option\n");
10472       res = 1;
10473    }
10474    if (!ast_test_flag(vmu, VM_DELETE)) {
10475       ast_test_status_update(test, "Parse failure for delete option\n");
10476       res = 1;
10477    }
10478    if (!ast_test_flag(vmu, VM_SAYCID)) {
10479       ast_test_status_update(test, "Parse failure for saycid option\n");
10480       res = 1;
10481    }
10482    if (!ast_test_flag(vmu, VM_SVMAIL)) {
10483       ast_test_status_update(test, "Parse failure for sendvoicemail option\n");
10484       res = 1;
10485    }
10486    if (!ast_test_flag(vmu, VM_REVIEW)) {
10487       ast_test_status_update(test, "Parse failure for review option\n");
10488       res = 1;
10489    }
10490    if (!ast_test_flag(vmu, VM_TEMPGREETWARN)) {
10491       ast_test_status_update(test, "Parse failure for tempgreetwarm option\n");
10492       res = 1;
10493    }
10494    if (!ast_test_flag(vmu, VM_MESSAGEWRAP)) {
10495       ast_test_status_update(test, "Parse failure for messagewrap option\n");
10496       res = 1;
10497    }
10498    if (!ast_test_flag(vmu, VM_OPERATOR)) {
10499       ast_test_status_update(test, "Parse failure for operator option\n");
10500       res = 1;
10501    }
10502    if (!ast_test_flag(vmu, VM_ENVELOPE)) {
10503       ast_test_status_update(test, "Parse failure for envelope option\n");
10504       res = 1;
10505    }
10506    if (!ast_test_flag(vmu, VM_MOVEHEARD)) {
10507       ast_test_status_update(test, "Parse failure for moveheard option\n");
10508       res = 1;
10509    }
10510    if (!ast_test_flag(vmu, VM_SAYDURATION)) {
10511       ast_test_status_update(test, "Parse failure for sayduration option\n");
10512       res = 1;
10513    }
10514    if (vmu->saydurationm != 5) {
10515       ast_test_status_update(test, "Parse failure for saydurationm option\n");
10516       res = 1;
10517    }
10518    if (!ast_test_flag(vmu, VM_FORCENAME)) {
10519       ast_test_status_update(test, "Parse failure for forcename option\n");
10520       res = 1;
10521    }
10522    if (!ast_test_flag(vmu, VM_FORCEGREET)) {
10523       ast_test_status_update(test, "Parse failure for forcegreetings option\n");
10524       res = 1;
10525    }
10526    if (strcasecmp(vmu->callback, "somecontext")) {
10527       ast_test_status_update(test, "Parse failure for callbacks option\n");
10528       res = 1;
10529    }
10530    if (strcasecmp(vmu->dialout, "somecontext2")) {
10531       ast_test_status_update(test, "Parse failure for dialout option\n");
10532       res = 1;
10533    }
10534    if (strcasecmp(vmu->exit, "somecontext3")) {
10535       ast_test_status_update(test, "Parse failure for exitcontext option\n");
10536       res = 1;
10537    }
10538    if (vmu->minsecs != 10) {
10539       ast_test_status_update(test, "Parse failure for minsecs option\n");
10540       res = 1;
10541    }
10542    if (vmu->maxsecs != 100) {
10543       ast_test_status_update(test, "Parse failure for maxsecs option\n");
10544       res = 1;
10545    }
10546    if (!ast_test_flag(vmu, VM_SKIPAFTERCMD)) {
10547       ast_test_status_update(test, "Parse failure for nextaftercmd option\n");
10548       res = 1;
10549    }
10550    if (vmu->maxdeletedmsg != 50) {
10551       ast_test_status_update(test, "Parse failure for backupdeleted option\n");
10552       res = 1;
10553    }
10554    if (vmu->volgain != 1.3) {
10555       ast_test_status_update(test, "Parse failure for volgain option\n");
10556       res = 1;
10557    }
10558    if (vmu->passwordlocation != OPT_PWLOC_SPOOLDIR) {
10559       ast_test_status_update(test, "Parse failure for passwordlocation option\n");
10560       res = 1;
10561    }
10562 #ifdef IMAP_STORAGE
10563    apply_options(vmu, option_string2);
10564 
10565    if (strcasecmp(vmu->imapuser, "imapuser")) {
10566       ast_test_status_update(test, "Parse failure for imapuser option\n");
10567       res = 1;
10568    }
10569    if (strcasecmp(vmu->imappassword, "imappasswd")) {
10570       ast_test_status_update(test, "Parse failure for imappasswd option\n");
10571       res = 1;
10572    }
10573    if (strcasecmp(vmu->imapfolder, "INBOX")) {
10574       ast_test_status_update(test, "Parse failure for imappasswd option\n");
10575       res = 1;
10576    }
10577    if (strcasecmp(vmu->imapvmshareid, "6000")) {
10578       ast_test_status_update(test, "Parse failure for imapvmshareid option\n");
10579       res = 1;
10580    }
10581 #endif
10582 
10583    free_user(vmu);
10584    return res ? AST_TEST_FAIL : AST_TEST_PASS;
10585 }
10586 
10587 static int vm_box_exists(struct ast_channel *chan, const char *data) 
10588 {
10589    struct ast_vm_user svm;
10590    char *context, *box;
10591    AST_DECLARE_APP_ARGS(args,
10592       AST_APP_ARG(mbox);
10593       AST_APP_ARG(options);
10594    );
10595    static int dep_warning = 0;
10596 
10597    if (ast_strlen_zero(data)) {
10598       ast_log(AST_LOG_ERROR, "MailboxExists requires an argument: (vmbox[@context][|options])\n");
10599       return -1;
10600    }
10601 
10602    if (!dep_warning) {
10603       dep_warning = 1;
10604       ast_log(AST_LOG_WARNING, "MailboxExists is deprecated.  Please use ${MAILBOX_EXISTS(%s)} instead.\n", (char *) data);
10605    }
10606 
10607    box = ast_strdupa(data);
10608 
10609    AST_STANDARD_APP_ARGS(args, box);
10610 
10611    if (args.options) {
10612    }
10613 
10614    if ((context = strchr(args.mbox, '@'))) {
10615       *context = '\0';
10616       context++;
10617    }
10618 
10619    if (find_user(&svm, context, args.mbox)) {
10620       pbx_builtin_setvar_helper(chan, "VMBOXEXISTSSTATUS", "SUCCESS");
10621    } else
10622       pbx_builtin_setvar_helper(chan, "VMBOXEXISTSSTATUS", "FAILED");
10623 
10624    return 0;
10625 }
10626 
10627 static int acf_mailbox_exists(struct ast_channel *chan, const char *cmd, char *args, char *buf, size_t len)
10628 {
10629    struct ast_vm_user svm;
10630    AST_DECLARE_APP_ARGS(arg,
10631       AST_APP_ARG(mbox);
10632       AST_APP_ARG(context);
10633    );
10634 
10635    AST_NONSTANDARD_APP_ARGS(arg, args, '@');
10636 
10637    if (ast_strlen_zero(arg.mbox)) {
10638       ast_log(LOG_ERROR, "MAILBOX_EXISTS requires an argument (<mailbox>[@<context>])\n");
10639       return -1;
10640    }
10641 
10642    ast_copy_string(buf, find_user(&svm, ast_strlen_zero(arg.context) ? "default" : arg.context, arg.mbox) ? "1" : "0", len);
10643    return 0;
10644 }
10645 
10646 static struct ast_custom_function mailbox_exists_acf = {
10647    .name = "MAILBOX_EXISTS",
10648    .read = acf_mailbox_exists,
10649 };
10650 
10651 static int vmauthenticate(struct ast_channel *chan, const char *data)
10652 {
10653    char *s, *user = NULL, *context = NULL, mailbox[AST_MAX_EXTENSION] = "";
10654    struct ast_vm_user vmus;
10655    char *options = NULL;
10656    int silent = 0, skipuser = 0;
10657    int res = -1;
10658    
10659    if (data) {
10660       s = ast_strdupa(data);
10661       user = strsep(&s, ",");
10662       options = strsep(&s, ",");
10663       if (user) {
10664          s = user;
10665          user = strsep(&s, "@");
10666          context = strsep(&s, "");
10667          if (!ast_strlen_zero(user))
10668             skipuser++;
10669          ast_copy_string(mailbox, user, sizeof(mailbox));
10670       }
10671    }
10672 
10673    if (options) {
10674       silent = (strchr(options, 's')) != NULL;
10675    }
10676 
10677    if (!vm_authenticate(chan, mailbox, sizeof(mailbox), &vmus, context, NULL, skipuser, 3, silent)) {
10678       pbx_builtin_setvar_helper(chan, "AUTH_MAILBOX", mailbox);
10679       pbx_builtin_setvar_helper(chan, "AUTH_CONTEXT", vmus.context);
10680       ast_play_and_wait(chan, "auth-thankyou");
10681       res = 0;
10682    } else if (mailbox[0] == '*') {
10683       /* user entered '*' */
10684       if (!ast_goto_if_exists(chan, chan->context, "a", 1)) {
10685          res = 0; /* prevent hangup */
10686       }
10687    }
10688 
10689    return res;
10690 }
10691 
10692 static char *show_users_realtime(int fd, const char *context)
10693 {
10694    struct ast_config *cfg;
10695    const char *cat = NULL;
10696 
10697    if (!(cfg = ast_load_realtime_multientry("voicemail", 
10698       "context", context, SENTINEL))) {
10699       return CLI_FAILURE;
10700    }
10701 
10702    ast_cli(fd,
10703       "\n"
10704       "=============================================================\n"
10705       "=== Configured Voicemail Users ==============================\n"
10706       "=============================================================\n"
10707       "===\n");
10708 
10709    while ((cat = ast_category_browse(cfg, cat))) {
10710       struct ast_variable *var = NULL;
10711       ast_cli(fd,
10712          "=== Mailbox ...\n"
10713          "===\n");
10714       for (var = ast_variable_browse(cfg, cat); var; var = var->next)
10715          ast_cli(fd, "=== ==> %s: %s\n", var->name, var->value);
10716       ast_cli(fd,
10717          "===\n"
10718          "=== ---------------------------------------------------------\n"
10719          "===\n");
10720    }
10721 
10722    ast_cli(fd,
10723       "=============================================================\n"
10724       "\n");
10725 
10726    ast_config_destroy(cfg);
10727 
10728    return CLI_SUCCESS;
10729 }
10730 
10731 static char *complete_voicemail_show_users(const char *line, const char *word, int pos, int state)
10732 {
10733    int which = 0;
10734    int wordlen;
10735    struct ast_vm_user *vmu;
10736    const char *context = "";
10737 
10738    /* 0 - show; 1 - voicemail; 2 - users; 3 - for; 4 - <context> */
10739    if (pos > 4)
10740       return NULL;
10741    if (pos == 3)
10742       return (state == 0) ? ast_strdup("for") : NULL;
10743    wordlen = strlen(word);
10744    AST_LIST_TRAVERSE(&users, vmu, list) {
10745       if (!strncasecmp(word, vmu->context, wordlen)) {
10746          if (context && strcmp(context, vmu->context) && ++which > state)
10747             return ast_strdup(vmu->context);
10748          /* ignore repeated contexts ? */
10749          context = vmu->context;
10750       }
10751    }
10752    return NULL;
10753 }
10754 
10755 /*! \brief Show a list of voicemail users in the CLI */
10756 static char *handle_voicemail_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
10757 {
10758    struct ast_vm_user *vmu;
10759 #define HVSU_OUTPUT_FORMAT "%-10s %-5s %-25s %-10s %6s\n"
10760    const char *context = NULL;
10761    int users_counter = 0;
10762 
10763    switch (cmd) {
10764    case CLI_INIT:
10765       e->command = "voicemail show users";
10766       e->usage =
10767          "Usage: voicemail show users [for <context>]\n"
10768          "       Lists all mailboxes currently set up\n";
10769       return NULL;
10770    case CLI_GENERATE:
10771       return complete_voicemail_show_users(a->line, a->word, a->pos, a->n);
10772    }  
10773 
10774    if ((a->argc < 3) || (a->argc > 5) || (a->argc == 4))
10775       return CLI_SHOWUSAGE;
10776    if (a->argc == 5) {
10777       if (strcmp(a->argv[3],"for"))
10778          return CLI_SHOWUSAGE;
10779       context = a->argv[4];
10780    }
10781 
10782    if (ast_check_realtime("voicemail")) {
10783       if (!context) {
10784          ast_cli(a->fd, "You must specify a specific context to show users from realtime!\n");
10785          return CLI_SHOWUSAGE;
10786       }
10787       return show_users_realtime(a->fd, context);
10788    }
10789 
10790    AST_LIST_LOCK(&users);
10791    if (AST_LIST_EMPTY(&users)) {
10792       ast_cli(a->fd, "There are no voicemail users currently defined\n");
10793       AST_LIST_UNLOCK(&users);
10794       return CLI_FAILURE;
10795    }
10796    if (a->argc == 3)
10797       ast_cli(a->fd, HVSU_OUTPUT_FORMAT, "Context", "Mbox", "User", "Zone", "NewMsg");
10798    else {
10799       int count = 0;
10800       AST_LIST_TRAVERSE(&users, vmu, list) {
10801          if (!strcmp(context, vmu->context))
10802             count++;
10803       }
10804       if (count) {
10805          ast_cli(a->fd, HVSU_OUTPUT_FORMAT, "Context", "Mbox", "User", "Zone", "NewMsg");
10806       } else {
10807          ast_cli(a->fd, "No such voicemail context \"%s\"\n", context);
10808          AST_LIST_UNLOCK(&users);
10809          return CLI_FAILURE;
10810       }
10811    }
10812    AST_LIST_TRAVERSE(&users, vmu, list) {
10813       int newmsgs = 0, oldmsgs = 0;
10814       char count[12], tmp[256] = "";
10815 
10816       if ((a->argc == 3) || ((a->argc == 5) && !strcmp(context, vmu->context))) {
10817          snprintf(tmp, sizeof(tmp), "%s@%s", vmu->mailbox, ast_strlen_zero(vmu->context) ? "default" : vmu->context);
10818          inboxcount(tmp, &newmsgs, &oldmsgs);
10819          snprintf(count, sizeof(count), "%d", newmsgs);
10820          ast_cli(a->fd, HVSU_OUTPUT_FORMAT, vmu->context, vmu->mailbox, vmu->fullname, vmu->zonetag, count);
10821          users_counter++;
10822       }
10823    }
10824    AST_LIST_UNLOCK(&users);
10825    ast_cli(a->fd, "%d voicemail users configured.\n", users_counter);
10826    return CLI_SUCCESS;
10827 }
10828 
10829 /*! \brief Show a list of voicemail zones in the CLI */
10830 static char *handle_voicemail_show_zones(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
10831 {
10832    struct vm_zone *zone;
10833 #define HVSZ_OUTPUT_FORMAT "%-15s %-20s %-45s\n"
10834    char *res = CLI_SUCCESS;
10835 
10836    switch (cmd) {
10837    case CLI_INIT:
10838       e->command = "voicemail show zones";
10839       e->usage =
10840          "Usage: voicemail show zones\n"
10841          "       Lists zone message formats\n";
10842       return NULL;
10843    case CLI_GENERATE:
10844       return NULL;
10845    }
10846 
10847    if (a->argc != 3)
10848       return CLI_SHOWUSAGE;
10849 
10850    AST_LIST_LOCK(&zones);
10851    if (!AST_LIST_EMPTY(&zones)) {
10852       ast_cli(a->fd, HVSZ_OUTPUT_FORMAT, "Zone", "Timezone", "Message Format");
10853       AST_LIST_TRAVERSE(&zones, zone, list) {
10854          ast_cli(a->fd, HVSZ_OUTPUT_FORMAT, zone->name, zone->timezone, zone->msg_format);
10855       }
10856    } else {
10857       ast_cli(a->fd, "There are no voicemail zones currently defined\n");
10858       res = CLI_FAILURE;
10859    }
10860    AST_LIST_UNLOCK(&zones);
10861 
10862    return res;
10863 }
10864 
10865 /*! \brief Reload voicemail configuration from the CLI */
10866 static char *handle_voicemail_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
10867 {
10868    switch (cmd) {
10869    case CLI_INIT:
10870       e->command = "voicemail reload";
10871       e->usage =
10872          "Usage: voicemail reload\n"
10873          "       Reload voicemail configuration\n";
10874       return NULL;
10875    case CLI_GENERATE:
10876       return NULL;
10877    }
10878 
10879    if (a->argc != 2)
10880       return CLI_SHOWUSAGE;
10881 
10882    ast_cli(a->fd, "Reloading voicemail configuration...\n");   
10883    load_config(1);
10884    
10885    return CLI_SUCCESS;
10886 }
10887 
10888 static struct ast_cli_entry cli_voicemail[] = {
10889    AST_CLI_DEFINE(handle_voicemail_show_users, "List defined voicemail boxes"),
10890    AST_CLI_DEFINE(handle_voicemail_show_zones, "List zone message formats"),
10891    AST_CLI_DEFINE(handle_voicemail_reload, "Reload voicemail configuration"),
10892 };
10893 
10894 #ifdef IMAP_STORAGE
10895    #define DATA_EXPORT_VM_USERS(USER)              \
10896       USER(ast_vm_user, context, AST_DATA_STRING)        \
10897       USER(ast_vm_user, mailbox, AST_DATA_STRING)        \
10898       USER(ast_vm_user, password, AST_DATA_PASSWORD)        \
10899       USER(ast_vm_user, fullname, AST_DATA_STRING)       \
10900       USER(ast_vm_user, email, AST_DATA_STRING)       \
10901       USER(ast_vm_user, emailsubject, AST_DATA_STRING)      \
10902       USER(ast_vm_user, emailbody, AST_DATA_STRING)         \
10903       USER(ast_vm_user, pager, AST_DATA_STRING)       \
10904       USER(ast_vm_user, serveremail, AST_DATA_STRING)       \
10905       USER(ast_vm_user, mailcmd, AST_DATA_STRING)        \
10906       USER(ast_vm_user, language, AST_DATA_STRING)       \
10907       USER(ast_vm_user, zonetag, AST_DATA_STRING)        \
10908       USER(ast_vm_user, callback, AST_DATA_STRING)       \
10909       USER(ast_vm_user, dialout, AST_DATA_STRING)        \
10910       USER(ast_vm_user, uniqueid, AST_DATA_STRING)       \
10911       USER(ast_vm_user, exit, AST_DATA_STRING)        \
10912       USER(ast_vm_user, attachfmt, AST_DATA_STRING)         \
10913       USER(ast_vm_user, flags, AST_DATA_UNSIGNED_INTEGER)      \
10914       USER(ast_vm_user, saydurationm, AST_DATA_INTEGER)     \
10915       USER(ast_vm_user, maxmsg, AST_DATA_INTEGER)        \
10916       USER(ast_vm_user, maxdeletedmsg, AST_DATA_INTEGER)    \
10917       USER(ast_vm_user, maxsecs, AST_DATA_INTEGER)       \
10918       USER(ast_vm_user, imapuser, AST_DATA_STRING)       \
10919       USER(ast_vm_user, imappassword, AST_DATA_STRING)      \
10920       USER(ast_vm_user, imapvmshareid, AST_DATA_STRING)     \
10921       USER(ast_vm_user, volgain, AST_DATA_DOUBLE)
10922 #else
10923    #define DATA_EXPORT_VM_USERS(USER)              \
10924       USER(ast_vm_user, context, AST_DATA_STRING)        \
10925       USER(ast_vm_user, mailbox, AST_DATA_STRING)        \
10926       USER(ast_vm_user, password, AST_DATA_PASSWORD)        \
10927       USER(ast_vm_user, fullname, AST_DATA_STRING)       \
10928       USER(ast_vm_user, email, AST_DATA_STRING)       \
10929       USER(ast_vm_user, emailsubject, AST_DATA_STRING)      \
10930       USER(ast_vm_user, emailbody, AST_DATA_STRING)         \
10931       USER(ast_vm_user, pager, AST_DATA_STRING)       \
10932       USER(ast_vm_user, serveremail, AST_DATA_STRING)       \
10933       USER(ast_vm_user, mailcmd, AST_DATA_STRING)        \
10934       USER(ast_vm_user, language, AST_DATA_STRING)       \
10935       USER(ast_vm_user, zonetag, AST_DATA_STRING)        \
10936       USER(ast_vm_user, callback, AST_DATA_STRING)       \
10937       USER(ast_vm_user, dialout, AST_DATA_STRING)        \
10938       USER(ast_vm_user, uniqueid, AST_DATA_STRING)       \
10939       USER(ast_vm_user, exit, AST_DATA_STRING)        \
10940       USER(ast_vm_user, attachfmt, AST_DATA_STRING)         \
10941       USER(ast_vm_user, flags, AST_DATA_UNSIGNED_INTEGER)      \
10942       USER(ast_vm_user, saydurationm, AST_DATA_INTEGER)     \
10943       USER(ast_vm_user, maxmsg, AST_DATA_INTEGER)        \
10944       USER(ast_vm_user, maxdeletedmsg, AST_DATA_INTEGER)    \
10945       USER(ast_vm_user, maxsecs, AST_DATA_INTEGER)       \
10946       USER(ast_vm_user, volgain, AST_DATA_DOUBLE)
10947 #endif
10948 
10949 AST_DATA_STRUCTURE(ast_vm_user, DATA_EXPORT_VM_USERS);
10950 
10951 #define DATA_EXPORT_VM_ZONES(ZONE)        \
10952    ZONE(vm_zone, name, AST_DATA_STRING)      \
10953    ZONE(vm_zone, timezone, AST_DATA_STRING)  \
10954    ZONE(vm_zone, msg_format, AST_DATA_STRING)
10955 
10956 AST_DATA_STRUCTURE(vm_zone, DATA_EXPORT_VM_ZONES);
10957 
10958 /*!
10959  * \internal
10960  * \brief Add voicemail user to the data_root.
10961  * \param[in] search The search tree.
10962  * \param[in] data_root The main result node.
10963  * \param[in] user The voicemail user.
10964  */
10965 static int vm_users_data_provider_get_helper(const struct ast_data_search *search,
10966     struct ast_data *data_root, struct ast_vm_user *user)
10967 {
10968    struct ast_data *data_user, *data_zone;
10969    struct ast_data *data_state;
10970    struct vm_zone *zone = NULL;
10971    int urgentmsg = 0, newmsg = 0, oldmsg = 0;
10972    char ext_context[256] = "";
10973 
10974    data_user = ast_data_add_node(data_root, "user");
10975    if (!data_user) {
10976       return -1;
10977    }
10978 
10979    ast_data_add_structure(ast_vm_user, data_user, user);
10980 
10981    AST_LIST_LOCK(&zones);
10982    AST_LIST_TRAVERSE(&zones, zone, list) {
10983       if (!strcmp(zone->name, user->zonetag)) {
10984          break;
10985       }
10986    }
10987    AST_LIST_UNLOCK(&zones);
10988 
10989    /* state */
10990    data_state = ast_data_add_node(data_user, "state");
10991    if (!data_state) {
10992       return -1;
10993    }
10994    snprintf(ext_context, sizeof(ext_context), "%s@%s", user->mailbox, user->context);
10995    inboxcount2(ext_context, &urgentmsg, &newmsg, &oldmsg);
10996    ast_data_add_int(data_state, "urgentmsg", urgentmsg);
10997    ast_data_add_int(data_state, "newmsg", newmsg);
10998    ast_data_add_int(data_state, "oldmsg", oldmsg);
10999 
11000    if (zone) {
11001       data_zone = ast_data_add_node(data_user, "zone");
11002       ast_data_add_structure(vm_zone, data_zone, zone);
11003    }
11004 
11005    if (!ast_data_search_match(search, data_user)) {
11006       ast_data_remove_node(data_root, data_user);
11007    }
11008 
11009    return 0;
11010 }
11011 
11012 static int vm_users_data_provider_get(const struct ast_data_search *search,
11013    struct ast_data *data_root)
11014 {
11015    struct ast_vm_user *user;
11016 
11017    AST_LIST_LOCK(&users);
11018    AST_LIST_TRAVERSE(&users, user, list) {
11019       vm_users_data_provider_get_helper(search, data_root, user);
11020    }
11021    AST_LIST_UNLOCK(&users);
11022 
11023    return 0;
11024 }
11025 
11026 static const struct ast_data_handler vm_users_data_provider = {
11027    .version = AST_DATA_HANDLER_VERSION,
11028    .get = vm_users_data_provider_get
11029 };
11030 
11031 static const struct ast_data_entry vm_data_providers[] = {
11032    AST_DATA_ENTRY("asterisk/application/voicemail/list", &vm_users_data_provider)
11033 };
11034 
11035 static void poll_subscribed_mailbox(struct mwi_sub *mwi_sub)
11036 {
11037    int new = 0, old = 0, urgent = 0;
11038 
11039    inboxcount2(mwi_sub->mailbox, &urgent, &new, &old);
11040 
11041    if (urgent != mwi_sub->old_urgent || new != mwi_sub->old_new || old != mwi_sub->old_old) {
11042       mwi_sub->old_urgent = urgent;
11043       mwi_sub->old_new = new;
11044       mwi_sub->old_old = old;
11045       queue_mwi_event(mwi_sub->mailbox, urgent, new, old);
11046       run_externnotify(NULL, mwi_sub->mailbox, NULL);
11047    }
11048 }
11049 
11050 static void poll_subscribed_mailboxes(void)
11051 {
11052    struct mwi_sub *mwi_sub;
11053 
11054    AST_RWLIST_RDLOCK(&mwi_subs);
11055    AST_RWLIST_TRAVERSE(&mwi_subs, mwi_sub, entry) {
11056       if (!ast_strlen_zero(mwi_sub->mailbox)) {
11057          poll_subscribed_mailbox(mwi_sub);
11058       }
11059    }
11060    AST_RWLIST_UNLOCK(&mwi_subs);
11061 }
11062 
11063 static void *mb_poll_thread(void *data)
11064 {
11065    while (poll_thread_run) {
11066       struct timespec ts = { 0, };
11067       struct timeval wait;
11068 
11069       wait = ast_tvadd(ast_tvnow(), ast_samp2tv(poll_freq, 1));
11070       ts.tv_sec = wait.tv_sec;
11071       ts.tv_nsec = wait.tv_usec * 1000;
11072 
11073       ast_mutex_lock(&poll_lock);
11074       ast_cond_timedwait(&poll_cond, &poll_lock, &ts);
11075       ast_mutex_unlock(&poll_lock);
11076 
11077       if (!poll_thread_run)
11078          break;
11079 
11080       poll_subscribed_mailboxes();
11081    }
11082 
11083    return NULL;
11084 }
11085 
11086 static void mwi_sub_destroy(struct mwi_sub *mwi_sub)
11087 {
11088    ast_free(mwi_sub);
11089 }
11090 
11091 static int handle_unsubscribe(void *datap)
11092 {
11093    struct mwi_sub *mwi_sub;
11094    uint32_t *uniqueid = datap;
11095    
11096    AST_RWLIST_WRLOCK(&mwi_subs);
11097    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&mwi_subs, mwi_sub, entry) {
11098       if (mwi_sub->uniqueid == *uniqueid) {
11099          AST_LIST_REMOVE_CURRENT(entry);
11100          break;
11101       }
11102    }
11103    AST_RWLIST_TRAVERSE_SAFE_END
11104    AST_RWLIST_UNLOCK(&mwi_subs);
11105 
11106    if (mwi_sub)
11107       mwi_sub_destroy(mwi_sub);
11108 
11109    ast_free(uniqueid);  
11110    return 0;
11111 }
11112 
11113 static int handle_subscribe(void *datap)
11114 {
11115    unsigned int len;
11116    struct mwi_sub *mwi_sub;
11117    struct mwi_sub_task *p = datap;
11118 
11119    len = sizeof(*mwi_sub);
11120    if (!ast_strlen_zero(p->mailbox))
11121       len += strlen(p->mailbox);
11122 
11123    if (!ast_strlen_zero(p->context))
11124       len += strlen(p->context) + 1; /* Allow for seperator */
11125 
11126    if (!(mwi_sub = ast_calloc(1, len)))
11127       return -1;
11128 
11129    mwi_sub->uniqueid = p->uniqueid;
11130    if (!ast_strlen_zero(p->mailbox))
11131       strcpy(mwi_sub->mailbox, p->mailbox);
11132 
11133    if (!ast_strlen_zero(p->context)) {
11134       strcat(mwi_sub->mailbox, "@");
11135       strcat(mwi_sub->mailbox, p->context);
11136    }
11137 
11138    AST_RWLIST_WRLOCK(&mwi_subs);
11139    AST_RWLIST_INSERT_TAIL(&mwi_subs, mwi_sub, entry);
11140    AST_RWLIST_UNLOCK(&mwi_subs);
11141    ast_free((void *) p->mailbox);
11142    ast_free((void *) p->context);
11143    ast_free(p);
11144    poll_subscribed_mailbox(mwi_sub);
11145    return 0;
11146 }
11147 
11148 static void mwi_unsub_event_cb(const struct ast_event *event, void *userdata)
11149 {
11150    uint32_t u, *uniqueid = ast_calloc(1, sizeof(*uniqueid));
11151    if (ast_event_get_type(event) != AST_EVENT_UNSUB)
11152       return;
11153 
11154    if (ast_event_get_ie_uint(event, AST_EVENT_IE_EVENTTYPE) != AST_EVENT_MWI)
11155       return;
11156 
11157    u = ast_event_get_ie_uint(event, AST_EVENT_IE_UNIQUEID);
11158    *uniqueid = u;
11159    if (ast_taskprocessor_push(mwi_subscription_tps, handle_unsubscribe, uniqueid) < 0) {
11160       ast_free(uniqueid);
11161    }
11162 }
11163 
11164 static void mwi_sub_event_cb(const struct ast_event *event, void *userdata)
11165 {
11166    struct mwi_sub_task *mwist;
11167    
11168    if (ast_event_get_type(event) != AST_EVENT_SUB)
11169       return;
11170 
11171    if (ast_event_get_ie_uint(event, AST_EVENT_IE_EVENTTYPE) != AST_EVENT_MWI)
11172       return;
11173 
11174    if ((mwist = ast_calloc(1, (sizeof(*mwist)))) == NULL) {
11175       ast_log(LOG_ERROR, "could not allocate a mwi_sub_task\n");
11176       return;
11177    }
11178    mwist->mailbox = ast_strdup(ast_event_get_ie_str(event, AST_EVENT_IE_MAILBOX));
11179    mwist->context = ast_strdup(ast_event_get_ie_str(event, AST_EVENT_IE_CONTEXT));
11180    mwist->uniqueid = ast_event_get_ie_uint(event, AST_EVENT_IE_UNIQUEID);
11181    
11182    if (ast_taskprocessor_push(mwi_subscription_tps, handle_subscribe, mwist) < 0) {
11183       ast_free(mwist);
11184    }
11185 }
11186 
11187 static void start_poll_thread(void)
11188 {
11189    mwi_sub_sub = ast_event_subscribe(AST_EVENT_SUB, mwi_sub_event_cb, "Voicemail MWI subscription", NULL,
11190       AST_EVENT_IE_EVENTTYPE, AST_EVENT_IE_PLTYPE_UINT, AST_EVENT_MWI,
11191       AST_EVENT_IE_END);
11192 
11193    mwi_unsub_sub = ast_event_subscribe(AST_EVENT_UNSUB, mwi_unsub_event_cb, "Voicemail MWI subscription", NULL,
11194       AST_EVENT_IE_EVENTTYPE, AST_EVENT_IE_PLTYPE_UINT, AST_EVENT_MWI,
11195       AST_EVENT_IE_END);
11196 
11197    if (mwi_sub_sub)
11198       ast_event_report_subs(mwi_sub_sub);
11199 
11200    poll_thread_run = 1;
11201 
11202    ast_pthread_create(&poll_thread, NULL, mb_poll_thread, NULL);
11203 }
11204 
11205 static void stop_poll_thread(void)
11206 {
11207    poll_thread_run = 0;
11208 
11209    if (mwi_sub_sub) {
11210       ast_event_unsubscribe(mwi_sub_sub);
11211       mwi_sub_sub = NULL;
11212    }
11213 
11214    if (mwi_unsub_sub) {
11215       ast_event_unsubscribe(mwi_unsub_sub);
11216       mwi_unsub_sub = NULL;
11217    }
11218 
11219    ast_mutex_lock(&poll_lock);
11220    ast_cond_signal(&poll_cond);
11221    ast_mutex_unlock(&poll_lock);
11222 
11223    pthread_join(poll_thread, NULL);
11224 
11225    poll_thread = AST_PTHREADT_NULL;
11226 }
11227 
11228 /*! \brief Manager list voicemail users command */
11229 static int manager_list_voicemail_users(struct mansession *s, const struct message *m)
11230 {
11231    struct ast_vm_user *vmu = NULL;
11232    const char *id = astman_get_header(m, "ActionID");
11233    char actionid[128] = "";
11234 
11235    if (!ast_strlen_zero(id))
11236       snprintf(actionid, sizeof(actionid), "ActionID: %s\r\n", id);
11237 
11238    AST_LIST_LOCK(&users);
11239 
11240    if (AST_LIST_EMPTY(&users)) {
11241       astman_send_ack(s, m, "There are no voicemail users currently defined.");
11242       AST_LIST_UNLOCK(&users);
11243       return RESULT_SUCCESS;
11244    }
11245    
11246    astman_send_ack(s, m, "Voicemail user list will follow");
11247    
11248    AST_LIST_TRAVERSE(&users, vmu, list) {
11249       char dirname[256];
11250 
11251 #ifdef IMAP_STORAGE
11252       int new, old;
11253       inboxcount(vmu->mailbox, &new, &old);
11254 #endif
11255       
11256       make_dir(dirname, sizeof(dirname), vmu->context, vmu->mailbox, "INBOX");
11257       astman_append(s,
11258          "%s"
11259          "Event: VoicemailUserEntry\r\n"
11260          "VMContext: %s\r\n"
11261          "VoiceMailbox: %s\r\n"
11262          "Fullname: %s\r\n"
11263          "Email: %s\r\n"
11264          "Pager: %s\r\n"
11265          "ServerEmail: %s\r\n"
11266          "MailCommand: %s\r\n"
11267          "Language: %s\r\n"
11268          "TimeZone: %s\r\n"
11269          "Callback: %s\r\n"
11270          "Dialout: %s\r\n"
11271          "UniqueID: %s\r\n"
11272          "ExitContext: %s\r\n"
11273          "SayDurationMinimum: %d\r\n"
11274          "SayEnvelope: %s\r\n"
11275          "SayCID: %s\r\n"
11276          "AttachMessage: %s\r\n"
11277          "AttachmentFormat: %s\r\n"
11278          "DeleteMessage: %s\r\n"
11279          "VolumeGain: %.2f\r\n"
11280          "CanReview: %s\r\n"
11281          "CallOperator: %s\r\n"
11282          "MaxMessageCount: %d\r\n"
11283          "MaxMessageLength: %d\r\n"
11284          "NewMessageCount: %d\r\n"
11285 #ifdef IMAP_STORAGE
11286          "OldMessageCount: %d\r\n"
11287          "IMAPUser: %s\r\n"
11288 #endif
11289          "\r\n",
11290          actionid,
11291          vmu->context,
11292          vmu->mailbox,
11293          vmu->fullname,
11294          vmu->email,
11295          vmu->pager,
11296          vmu->serveremail,
11297          vmu->mailcmd,
11298          vmu->language,
11299          vmu->zonetag,
11300          vmu->callback,
11301          vmu->dialout,
11302          vmu->uniqueid,
11303          vmu->exit,
11304          vmu->saydurationm,
11305          ast_test_flag(vmu, VM_ENVELOPE) ? "Yes" : "No",
11306          ast_test_flag(vmu, VM_SAYCID) ? "Yes" : "No",
11307          ast_test_flag(vmu, VM_ATTACH) ? "Yes" : "No",
11308          vmu->attachfmt,
11309          ast_test_flag(vmu, VM_DELETE) ? "Yes" : "No",
11310          vmu->volgain,
11311          ast_test_flag(vmu, VM_REVIEW) ? "Yes" : "No",
11312          ast_test_flag(vmu, VM_OPERATOR) ? "Yes" : "No",
11313          vmu->maxmsg,
11314          vmu->maxsecs,
11315 #ifdef IMAP_STORAGE
11316          new, old, vmu->imapuser
11317 #else
11318          count_messages(vmu, dirname)
11319 #endif
11320          );
11321    }     
11322    astman_append(s, "Event: VoicemailUserEntryComplete\r\n%s\r\n", actionid);
11323 
11324    AST_LIST_UNLOCK(&users);
11325 
11326    return RESULT_SUCCESS;
11327 }
11328 
11329 /*! \brief Free the users structure. */
11330 static void free_vm_users(void) 
11331 {
11332    struct ast_vm_user *current;
11333    AST_LIST_LOCK(&users);
11334    while ((current = AST_LIST_REMOVE_HEAD(&users, list))) {
11335       ast_set_flag(current, VM_ALLOCED);
11336       free_user(current);
11337    }
11338    AST_LIST_UNLOCK(&users);
11339 }
11340 
11341 /*! \brief Free the zones structure. */
11342 static void free_vm_zones(void)
11343 {
11344    struct vm_zone *zcur;
11345    AST_LIST_LOCK(&zones);
11346    while ((zcur = AST_LIST_REMOVE_HEAD(&zones, list)))
11347       free_zone(zcur);
11348    AST_LIST_UNLOCK(&zones);
11349 }
11350 
11351 static const char *substitute_escapes(const char *value)
11352 {
11353    char *current;
11354 
11355    /* Add 16 for fudge factor */
11356    struct ast_str *str = ast_str_thread_get(&ast_str_thread_global_buf, strlen(value) + 16);
11357 
11358    ast_str_reset(str);
11359    
11360    /* Substitute strings \r, \n, and \t into the appropriate characters */
11361    for (current = (char *) value; *current; current++) {
11362       if (*current == '\\') {
11363          current++;
11364          if (!*current) {
11365             ast_log(AST_LOG_NOTICE, "Incomplete escape at end of value.\n");
11366             break;
11367          }
11368          switch (*current) {
11369          case 'r':
11370             ast_str_append(&str, 0, "\r");
11371             break;
11372          case 'n':
11373 #ifdef IMAP_STORAGE
11374             if (!str->used || str->str[str->used - 1] != '\r') {
11375                ast_str_append(&str, 0, "\r");
11376             }
11377 #endif
11378             ast_str_append(&str, 0, "\n");
11379             break;
11380          case 't':
11381             ast_str_append(&str, 0, "\t");
11382             break;
11383          default:
11384             ast_log(AST_LOG_NOTICE, "Substitution routine does not support this character: \\%c\n", *current);
11385             break;
11386          }
11387       } else {
11388          ast_str_append(&str, 0, "%c", *current);
11389       }
11390    }
11391 
11392    return ast_str_buffer(str);
11393 }
11394 
11395 static int load_config(int reload)
11396 {
11397    struct ast_vm_user *current;
11398    struct ast_config *cfg, *ucfg;
11399    char *cat;
11400    struct ast_variable *var;
11401    const char *val;
11402    char *q, *stringp, *tmp;
11403    int x;
11404    int tmpadsi[4];
11405    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
11406    char secretfn[PATH_MAX] = "";
11407 
11408    ast_unload_realtime("voicemail");
11409    ast_unload_realtime("voicemail_data");
11410 
11411    if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
11412       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
11413          return 0;
11414       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
11415          ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Avoiding.\n");
11416          ucfg = NULL;
11417       }
11418       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
11419       if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) == CONFIG_STATUS_FILEINVALID) {
11420          ast_config_destroy(ucfg);
11421          ast_log(LOG_ERROR, "Config file " VOICEMAIL_CONFIG " is in an invalid format.  Aborting.\n");
11422          return 0;
11423       }
11424    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
11425       ast_log(LOG_ERROR, "Config file " VOICEMAIL_CONFIG " is in an invalid format.  Aborting.\n");
11426       return 0;
11427    } else {
11428       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
11429       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
11430          ast_log(LOG_ERROR, "Config file users.conf is in an invalid format.  Avoiding.\n");
11431          ucfg = NULL;
11432       }
11433    }
11434 #ifdef IMAP_STORAGE
11435    ast_copy_string(imapparentfolder, "\0", sizeof(imapparentfolder));
11436 #endif
11437    /* set audio control prompts */
11438    strcpy(listen_control_forward_key, DEFAULT_LISTEN_CONTROL_FORWARD_KEY);
11439    strcpy(listen_control_reverse_key, DEFAULT_LISTEN_CONTROL_REVERSE_KEY);
11440    strcpy(listen_control_pause_key, DEFAULT_LISTEN_CONTROL_PAUSE_KEY);
11441    strcpy(listen_control_restart_key, DEFAULT_LISTEN_CONTROL_RESTART_KEY);
11442    strcpy(listen_control_stop_key, DEFAULT_LISTEN_CONTROL_STOP_KEY);
11443 
11444    /* Free all the users structure */  
11445    free_vm_users();
11446 
11447    /* Free all the zones structure */
11448    free_vm_zones();
11449 
11450    AST_LIST_LOCK(&users);  
11451 
11452    memset(ext_pass_cmd, 0, sizeof(ext_pass_cmd));
11453    memset(ext_pass_check_cmd, 0, sizeof(ext_pass_check_cmd));
11454 
11455    if (cfg) {
11456       /* General settings */
11457 
11458       if (!(val = ast_variable_retrieve(cfg, "general", "userscontext")))
11459          val = "default";
11460       ast_copy_string(userscontext, val, sizeof(userscontext));
11461       /* Attach voice message to mail message ? */
11462       if (!(val = ast_variable_retrieve(cfg, "general", "attach"))) 
11463          val = "yes";
11464       ast_set2_flag((&globalflags), ast_true(val), VM_ATTACH); 
11465 
11466       if (!(val = ast_variable_retrieve(cfg, "general", "searchcontexts")))
11467          val = "no";
11468       ast_set2_flag((&globalflags), ast_true(val), VM_SEARCH);
11469 
11470       volgain = 0.0;
11471       if ((val = ast_variable_retrieve(cfg, "general", "volgain")))
11472          sscanf(val, "%30lf", &volgain);
11473 
11474 #ifdef ODBC_STORAGE
11475       strcpy(odbc_database, "asterisk");
11476       if ((val = ast_variable_retrieve(cfg, "general", "odbcstorage"))) {
11477          ast_copy_string(odbc_database, val, sizeof(odbc_database));
11478       }
11479       strcpy(odbc_table, "voicemessages");
11480       if ((val = ast_variable_retrieve(cfg, "general", "odbctable"))) {
11481          ast_copy_string(odbc_table, val, sizeof(odbc_table));
11482       }
11483 #endif      
11484       /* Mail command */
11485       strcpy(mailcmd, SENDMAIL);
11486       if ((val = ast_variable_retrieve(cfg, "general", "mailcmd")))
11487          ast_copy_string(mailcmd, val, sizeof(mailcmd)); /* User setting */
11488 
11489       maxsilence = 0;
11490       if ((val = ast_variable_retrieve(cfg, "general", "maxsilence"))) {
11491          maxsilence = atoi(val);
11492          if (maxsilence > 0)
11493             maxsilence *= 1000;
11494       }
11495       
11496       if (!(val = ast_variable_retrieve(cfg, "general", "maxmsg"))) {
11497          maxmsg = MAXMSG;
11498       } else {
11499          maxmsg = atoi(val);
11500          if (maxmsg < 0) {
11501             ast_log(AST_LOG_WARNING, "Invalid number of messages per folder '%s'. Using default value %i\n", val, MAXMSG);
11502             maxmsg = MAXMSG;
11503          } else if (maxmsg > MAXMSGLIMIT) {
11504             ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %i. Cannot accept value '%s'\n", MAXMSGLIMIT, val);
11505             maxmsg = MAXMSGLIMIT;
11506          }
11507       }
11508 
11509       if (!(val = ast_variable_retrieve(cfg, "general", "backupdeleted"))) {
11510          maxdeletedmsg = 0;
11511       } else {
11512          if (sscanf(val, "%30d", &x) == 1)
11513             maxdeletedmsg = x;
11514          else if (ast_true(val))
11515             maxdeletedmsg = MAXMSG;
11516          else
11517             maxdeletedmsg = 0;
11518 
11519          if (maxdeletedmsg < 0) {
11520             ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox '%s'. Using default value %i\n", val, MAXMSG);
11521             maxdeletedmsg = MAXMSG;
11522          } else if (maxdeletedmsg > MAXMSGLIMIT) {
11523             ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %i. Cannot accept value '%s'\n", MAXMSGLIMIT, val);
11524             maxdeletedmsg = MAXMSGLIMIT;
11525          }
11526       }
11527 
11528       /* Load date format config for voicemail mail */
11529       if ((val = ast_variable_retrieve(cfg, "general", "emaildateformat"))) {
11530          ast_copy_string(emaildateformat, val, sizeof(emaildateformat));
11531       }
11532 
11533       /* Load date format config for voicemail pager mail */
11534       if ((val = ast_variable_retrieve(cfg, "general", "pagerdateformat"))) {
11535          ast_copy_string(pagerdateformat, val, sizeof(pagerdateformat));
11536       }
11537 
11538       /* External password changing command */
11539       if ((val = ast_variable_retrieve(cfg, "general", "externpass"))) {
11540          ast_copy_string(ext_pass_cmd, val, sizeof(ext_pass_cmd));
11541          pwdchange = PWDCHANGE_EXTERNAL;
11542       } else if ((val = ast_variable_retrieve(cfg, "general", "externpassnotify"))) {
11543          ast_copy_string(ext_pass_cmd, val, sizeof(ext_pass_cmd));
11544          pwdchange = PWDCHANGE_EXTERNAL | PWDCHANGE_INTERNAL;
11545       }
11546  
11547       /* External password validation command */
11548       if ((val = ast_variable_retrieve(cfg, "general", "externpasscheck"))) {
11549          ast_copy_string(ext_pass_check_cmd, val, sizeof(ext_pass_check_cmd));
11550          ast_log(AST_LOG_DEBUG, "found externpasscheck: %s\n", ext_pass_check_cmd);
11551       }
11552 
11553 #ifdef IMAP_STORAGE
11554       /* IMAP server address */
11555       if ((val = ast_variable_retrieve(cfg, "general", "imapserver"))) {
11556          ast_copy_string(imapserver, val, sizeof(imapserver));
11557       } else {
11558          ast_copy_string(imapserver, "localhost", sizeof(imapserver));
11559       }
11560       /* IMAP server port */
11561       if ((val = ast_variable_retrieve(cfg, "general", "imapport"))) {
11562          ast_copy_string(imapport, val, sizeof(imapport));
11563       } else {
11564          ast_copy_string(imapport, "143", sizeof(imapport));
11565       }
11566       /* IMAP server flags */
11567       if ((val = ast_variable_retrieve(cfg, "general", "imapflags"))) {
11568          ast_copy_string(imapflags, val, sizeof(imapflags));
11569       }
11570       /* IMAP server master username */
11571       if ((val = ast_variable_retrieve(cfg, "general", "authuser"))) {
11572          ast_copy_string(authuser, val, sizeof(authuser));
11573       }
11574       /* IMAP server master password */
11575       if ((val = ast_variable_retrieve(cfg, "general", "authpassword"))) {
11576          ast_copy_string(authpassword, val, sizeof(authpassword));
11577       }
11578       /* Expunge on exit */
11579       if ((val = ast_variable_retrieve(cfg, "general", "expungeonhangup"))) {
11580          if (ast_false(val))
11581             expungeonhangup = 0;
11582          else
11583             expungeonhangup = 1;
11584       } else {
11585          expungeonhangup = 1;
11586       }
11587       /* IMAP voicemail folder */
11588       if ((val = ast_variable_retrieve(cfg, "general", "imapfolder"))) {
11589          ast_copy_string(imapfolder, val, sizeof(imapfolder));
11590       } else {
11591          ast_copy_string(imapfolder, "INBOX", sizeof(imapfolder));
11592       }
11593       if ((val = ast_variable_retrieve(cfg, "general", "imapparentfolder"))) {
11594          ast_copy_string(imapparentfolder, val, sizeof(imapparentfolder));
11595       }
11596       if ((val = ast_variable_retrieve(cfg, "general", "imapgreetings"))) {
11597          imapgreetings = ast_true(val);
11598       } else {
11599          imapgreetings = 0;
11600       }
11601       if ((val = ast_variable_retrieve(cfg, "general", "greetingfolder"))) {
11602          ast_copy_string(greetingfolder, val, sizeof(greetingfolder));
11603       } else {
11604          ast_copy_string(greetingfolder, imapfolder, sizeof(greetingfolder));
11605       }
11606 
11607       /* There is some very unorthodox casting done here. This is due
11608        * to the way c-client handles the argument passed in. It expects a 
11609        * void pointer and casts the pointer directly to a long without
11610        * first dereferencing it. */
11611       if ((val = ast_variable_retrieve(cfg, "general", "imapreadtimeout"))) {
11612          mail_parameters(NIL, SET_READTIMEOUT, (void *) (atol(val)));
11613       } else {
11614          mail_parameters(NIL, SET_READTIMEOUT, (void *) 60L);
11615       }
11616 
11617       if ((val = ast_variable_retrieve(cfg, "general", "imapwritetimeout"))) {
11618          mail_parameters(NIL, SET_WRITETIMEOUT, (void *) (atol(val)));
11619       } else {
11620          mail_parameters(NIL, SET_WRITETIMEOUT, (void *) 60L);
11621       }
11622 
11623       if ((val = ast_variable_retrieve(cfg, "general", "imapopentimeout"))) {
11624          mail_parameters(NIL, SET_OPENTIMEOUT, (void *) (atol(val)));
11625       } else {
11626          mail_parameters(NIL, SET_OPENTIMEOUT, (void *) 60L);
11627       }
11628 
11629       if ((val = ast_variable_retrieve(cfg, "general", "imapclosetimeout"))) {
11630          mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) (atol(val)));
11631       } else {
11632          mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) 60L);
11633       }
11634 
11635       /* Increment configuration version */
11636       imapversion++;
11637 #endif
11638       /* External voicemail notify application */
11639       if ((val = ast_variable_retrieve(cfg, "general", "externnotify"))) {
11640          ast_copy_string(externnotify, val, sizeof(externnotify));
11641          ast_debug(1, "found externnotify: %s\n", externnotify);
11642       } else {
11643          externnotify[0] = '\0';
11644       }
11645 
11646       /* SMDI voicemail notification */
11647       if ((val = ast_variable_retrieve(cfg, "general", "smdienable")) && ast_true(val)) {
11648          ast_debug(1, "Enabled SMDI voicemail notification\n");
11649          if ((val = ast_variable_retrieve(cfg, "general", "smdiport"))) {
11650             smdi_iface = ast_smdi_interface_find(val);
11651          } else {
11652             ast_debug(1, "No SMDI interface set, trying default (/dev/ttyS0)\n");
11653             smdi_iface = ast_smdi_interface_find("/dev/ttyS0");
11654          }
11655          if (!smdi_iface) {
11656             ast_log(AST_LOG_ERROR, "No valid SMDI interface specfied, disabling SMDI voicemail notification\n");
11657          } 
11658       }
11659 
11660       /* Silence treshold */
11661       silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
11662       if ((val = ast_variable_retrieve(cfg, "general", "silencethreshold")))
11663          silencethreshold = atoi(val);
11664       
11665       if (!(val = ast_variable_retrieve(cfg, "general", "serveremail"))) 
11666          val = ASTERISK_USERNAME;
11667       ast_copy_string(serveremail, val, sizeof(serveremail));
11668       
11669       vmmaxsecs = 0;
11670       if ((val = ast_variable_retrieve(cfg, "general", "maxsecs"))) {
11671          if (sscanf(val, "%30d", &x) == 1) {
11672             vmmaxsecs = x;
11673          } else {
11674             ast_log(AST_LOG_WARNING, "Invalid max message time length\n");
11675          }
11676       } else if ((val = ast_variable_retrieve(cfg, "general", "maxmessage"))) {
11677          static int maxmessage_deprecate = 0;
11678          if (maxmessage_deprecate == 0) {
11679             maxmessage_deprecate = 1;
11680             ast_log(AST_LOG_WARNING, "Setting 'maxmessage' has been deprecated in favor of 'maxsecs'.\n");
11681          }
11682          if (sscanf(val, "%30d", &x) == 1) {
11683             vmmaxsecs = x;
11684          } else {
11685             ast_log(AST_LOG_WARNING, "Invalid max message time length\n");
11686          }
11687       }
11688 
11689       vmminsecs = 0;
11690       if ((val = ast_variable_retrieve(cfg, "general", "minsecs"))) {
11691          if (sscanf(val, "%30d", &x) == 1) {
11692             vmminsecs = x;
11693             if (maxsilence / 1000 >= vmminsecs) {
11694                ast_log(AST_LOG_WARNING, "maxsilence should be less than minsecs or you may get empty messages\n");
11695             }
11696          } else {
11697             ast_log(AST_LOG_WARNING, "Invalid min message time length\n");
11698          }
11699       } else if ((val = ast_variable_retrieve(cfg, "general", "minmessage"))) {
11700          static int maxmessage_deprecate = 0;
11701          if (maxmessage_deprecate == 0) {
11702             maxmessage_deprecate = 1;
11703             ast_log(AST_LOG_WARNING, "Setting 'minmessage' has been deprecated in favor of 'minsecs'.\n");
11704          }
11705          if (sscanf(val, "%30d", &x) == 1) {
11706             vmminsecs = x;
11707             if (maxsilence / 1000 >= vmminsecs) {
11708                ast_log(AST_LOG_WARNING, "maxsilence should be less than minmessage or you may get empty messages\n");
11709             }
11710          } else {
11711             ast_log(AST_LOG_WARNING, "Invalid min message time length\n");
11712          }
11713       }
11714 
11715       val = ast_variable_retrieve(cfg, "general", "format");
11716       if (!val) {
11717          val = "wav";   
11718       } else {
11719          tmp = ast_strdupa(val);
11720          val = ast_format_str_reduce(tmp);
11721          if (!val) {
11722             ast_log(LOG_ERROR, "Error processing format string, defaulting to format 'wav'\n");
11723             val = "wav";
11724          }
11725       }
11726       ast_copy_string(vmfmts, val, sizeof(vmfmts));
11727 
11728       skipms = 3000;
11729       if ((val = ast_variable_retrieve(cfg, "general", "maxgreet"))) {
11730          if (sscanf(val, "%30d", &x) == 1) {
11731             maxgreet = x;
11732          } else {
11733             ast_log(AST_LOG_WARNING, "Invalid max message greeting length\n");
11734          }
11735       }
11736 
11737       if ((val = ast_variable_retrieve(cfg, "general", "skipms"))) {
11738          if (sscanf(val, "%30d", &x) == 1) {
11739             skipms = x;
11740          } else {
11741             ast_log(AST_LOG_WARNING, "Invalid skipms value\n");
11742          }
11743       }
11744 
11745       maxlogins = 3;
11746       if ((val = ast_variable_retrieve(cfg, "general", "maxlogins"))) {
11747          if (sscanf(val, "%30d", &x) == 1) {
11748             maxlogins = x;
11749          } else {
11750             ast_log(AST_LOG_WARNING, "Invalid max failed login attempts\n");
11751          }
11752       }
11753 
11754       minpassword = MINPASSWORD;
11755       if ((val = ast_variable_retrieve(cfg, "general", "minpassword"))) {
11756          if (sscanf(val, "%30d", &x) == 1) {
11757             minpassword = x;
11758          } else {
11759             ast_log(AST_LOG_WARNING, "Invalid minimum password length.  Default to %d\n", minpassword);
11760          }
11761       }
11762 
11763       /* Force new user to record name ? */
11764       if (!(val = ast_variable_retrieve(cfg, "general", "forcename"))) 
11765          val = "no";
11766       ast_set2_flag((&globalflags), ast_true(val), VM_FORCENAME);
11767 
11768       /* Force new user to record greetings ? */
11769       if (!(val = ast_variable_retrieve(cfg, "general", "forcegreetings"))) 
11770          val = "no";
11771       ast_set2_flag((&globalflags), ast_true(val), VM_FORCEGREET);
11772 
11773       if ((val = ast_variable_retrieve(cfg, "general", "cidinternalcontexts"))) {
11774          ast_debug(1, "VM_CID Internal context string: %s\n", val);
11775          stringp = ast_strdupa(val);
11776          for (x = 0 ; x < MAX_NUM_CID_CONTEXTS ; x++){
11777             if (!ast_strlen_zero(stringp)) {
11778                q = strsep(&stringp, ",");
11779                while ((*q == ' ')||(*q == '\t')) /* Eat white space between contexts */
11780                   q++;
11781                ast_copy_string(cidinternalcontexts[x], q, sizeof(cidinternalcontexts[x]));
11782                ast_debug(1, "VM_CID Internal context %d: %s\n", x, cidinternalcontexts[x]);
11783             } else {
11784                cidinternalcontexts[x][0] = '\0';
11785             }
11786          }
11787       }
11788       if (!(val = ast_variable_retrieve(cfg, "general", "review"))){
11789          ast_debug(1, "VM Review Option disabled globally\n");
11790          val = "no";
11791       }
11792       ast_set2_flag((&globalflags), ast_true(val), VM_REVIEW); 
11793 
11794       /* Temporary greeting reminder */
11795       if (!(val = ast_variable_retrieve(cfg, "general", "tempgreetwarn"))) {
11796          ast_debug(1, "VM Temporary Greeting Reminder Option disabled globally\n");
11797          val = "no";
11798       } else {
11799          ast_debug(1, "VM Temporary Greeting Reminder Option enabled globally\n");
11800       }
11801       ast_set2_flag((&globalflags), ast_true(val), VM_TEMPGREETWARN);
11802       if (!(val = ast_variable_retrieve(cfg, "general", "messagewrap"))){
11803          ast_debug(1, "VM next message wrap disabled globally\n");
11804          val = "no";
11805       }
11806       ast_set2_flag((&globalflags), ast_true(val), VM_MESSAGEWRAP);  
11807 
11808       if (!(val = ast_variable_retrieve(cfg, "general", "operator"))){
11809          ast_debug(1, "VM Operator break disabled globally\n");
11810          val = "no";
11811       }
11812       ast_set2_flag((&globalflags), ast_true(val), VM_OPERATOR);  
11813 
11814       if (!(val = ast_variable_retrieve(cfg, "general", "saycid"))) {
11815          ast_debug(1, "VM CID Info before msg disabled globally\n");
11816          val = "no";
11817       } 
11818       ast_set2_flag((&globalflags), ast_true(val), VM_SAYCID); 
11819 
11820       if (!(val = ast_variable_retrieve(cfg, "general", "sendvoicemail"))){
11821          ast_debug(1, "Send Voicemail msg disabled globally\n");
11822          val = "no";
11823       }
11824       ast_set2_flag((&globalflags), ast_true(val), VM_SVMAIL);
11825    
11826       if (!(val = ast_variable_retrieve(cfg, "general", "envelope"))) {
11827          ast_debug(1, "ENVELOPE before msg enabled globally\n");
11828          val = "yes";
11829       }
11830       ast_set2_flag((&globalflags), ast_true(val), VM_ENVELOPE);  
11831 
11832       if (!(val = ast_variable_retrieve(cfg, "general", "moveheard"))) {
11833          ast_debug(1, "Move Heard enabled globally\n");
11834          val = "yes";
11835       }
11836       ast_set2_flag((&globalflags), ast_true(val), VM_MOVEHEARD); 
11837 
11838       if (!(val = ast_variable_retrieve(cfg, "general", "forward_urgent_auto"))) {
11839          ast_debug(1, "Autoset of Urgent flag on forwarded Urgent messages disabled globally\n");
11840          val = "no";
11841       }
11842       ast_set2_flag((&globalflags), ast_true(val), VM_FWDURGAUTO);   
11843 
11844       if (!(val = ast_variable_retrieve(cfg, "general", "sayduration"))) {
11845          ast_debug(1, "Duration info before msg enabled globally\n");
11846          val = "yes";
11847       }
11848       ast_set2_flag((&globalflags), ast_true(val), VM_SAYDURATION);  
11849 
11850       saydurationminfo = 2;
11851       if ((val = ast_variable_retrieve(cfg, "general", "saydurationm"))) {
11852          if (sscanf(val, "%30d", &x) == 1) {
11853             saydurationminfo = x;
11854          } else {
11855             ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
11856          }
11857       }
11858 
11859       if (!(val = ast_variable_retrieve(cfg, "general", "nextaftercmd"))) {
11860          ast_debug(1, "We are not going to skip to the next msg after save/delete\n");
11861          val = "no";
11862       }
11863       ast_set2_flag((&globalflags), ast_true(val), VM_SKIPAFTERCMD);
11864 
11865       if ((val = ast_variable_retrieve(cfg, "general", "dialout"))) {
11866          ast_copy_string(dialcontext, val, sizeof(dialcontext));
11867          ast_debug(1, "found dialout context: %s\n", dialcontext);
11868       } else {
11869          dialcontext[0] = '\0';  
11870       }
11871       
11872       if ((val = ast_variable_retrieve(cfg, "general", "callback"))) {
11873          ast_copy_string(callcontext, val, sizeof(callcontext));
11874          ast_debug(1, "found callback context: %s\n", callcontext);
11875       } else {
11876          callcontext[0] = '\0';
11877       }
11878 
11879       if ((val = ast_variable_retrieve(cfg, "general", "exitcontext"))) {
11880          ast_copy_string(exitcontext, val, sizeof(exitcontext));
11881          ast_debug(1, "found operator context: %s\n", exitcontext);
11882       } else {
11883          exitcontext[0] = '\0';
11884       }
11885       
11886       /* load password sounds configuration */
11887       if ((val = ast_variable_retrieve(cfg, "general", "vm-password")))
11888          ast_copy_string(vm_password, val, sizeof(vm_password));
11889       if ((val = ast_variable_retrieve(cfg, "general", "vm-newpassword")))
11890          ast_copy_string(vm_newpassword, val, sizeof(vm_newpassword));
11891       if ((val = ast_variable_retrieve(cfg, "general", "vm-invalid-password")))
11892          ast_copy_string(vm_invalid_password, val, sizeof(vm_invalid_password));
11893       if ((val = ast_variable_retrieve(cfg, "general", "vm-passchanged")))
11894          ast_copy_string(vm_passchanged, val, sizeof(vm_passchanged));
11895       if ((val = ast_variable_retrieve(cfg, "general", "vm-reenterpassword")))
11896          ast_copy_string(vm_reenterpassword, val, sizeof(vm_reenterpassword));
11897       if ((val = ast_variable_retrieve(cfg, "general", "vm-mismatch")))
11898          ast_copy_string(vm_mismatch, val, sizeof(vm_mismatch));
11899       if ((val = ast_variable_retrieve(cfg, "general", "vm-pls-try-again"))) {
11900          ast_copy_string(vm_pls_try_again, val, sizeof(vm_pls_try_again));
11901       }
11902       /* load configurable audio prompts */
11903       if ((val = ast_variable_retrieve(cfg, "general", "listen-control-forward-key")) && is_valid_dtmf(val))
11904          ast_copy_string(listen_control_forward_key, val, sizeof(listen_control_forward_key));
11905       if ((val = ast_variable_retrieve(cfg, "general", "listen-control-reverse-key")) && is_valid_dtmf(val))
11906          ast_copy_string(listen_control_reverse_key, val, sizeof(listen_control_reverse_key));
11907       if ((val = ast_variable_retrieve(cfg, "general", "listen-control-pause-key")) && is_valid_dtmf(val))
11908          ast_copy_string(listen_control_pause_key, val, sizeof(listen_control_pause_key));
11909       if ((val = ast_variable_retrieve(cfg, "general", "listen-control-restart-key")) && is_valid_dtmf(val))
11910          ast_copy_string(listen_control_restart_key, val, sizeof(listen_control_restart_key));
11911       if ((val = ast_variable_retrieve(cfg, "general", "listen-control-stop-key")) && is_valid_dtmf(val))
11912          ast_copy_string(listen_control_stop_key, val, sizeof(listen_control_stop_key));
11913 
11914       if (!(val = ast_variable_retrieve(cfg, "general", "usedirectory"))) 
11915          val = "no";
11916       ast_set2_flag((&globalflags), ast_true(val), VM_DIRECFORWARD); 
11917 
11918       if (!(val = ast_variable_retrieve(cfg, "general", "passwordlocation"))) {
11919          val = "voicemail.conf";
11920       }
11921       if (!(strcmp(val, "spooldir"))) {
11922          passwordlocation = OPT_PWLOC_SPOOLDIR;
11923       } else {
11924          passwordlocation = OPT_PWLOC_VOICEMAILCONF;
11925       }
11926 
11927       poll_freq = DEFAULT_POLL_FREQ;
11928       if ((val = ast_variable_retrieve(cfg, "general", "pollfreq"))) {
11929          if (sscanf(val, "%30u", &poll_freq) != 1) {
11930             poll_freq = DEFAULT_POLL_FREQ;
11931             ast_log(AST_LOG_ERROR, "'%s' is not a valid value for the pollfreq option!\n", val);
11932          }
11933       }
11934 
11935       poll_mailboxes = 0;
11936       if ((val = ast_variable_retrieve(cfg, "general", "pollmailboxes")))
11937          poll_mailboxes = ast_true(val);
11938 
11939       if (ucfg) { 
11940          for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
11941             if (!ast_true(ast_config_option(ucfg, cat, "hasvoicemail")))
11942                continue;
11943             if ((current = find_or_create(userscontext, cat))) {
11944                populate_defaults(current);
11945                apply_options_full(current, ast_variable_browse(ucfg, cat));
11946                ast_copy_string(current->context, userscontext, sizeof(current->context));
11947                if (!ast_strlen_zero(current->password) && current->passwordlocation == OPT_PWLOC_VOICEMAILCONF) {
11948                   current->passwordlocation = OPT_PWLOC_USERSCONF;
11949                }
11950 
11951                switch (current->passwordlocation) {
11952                case OPT_PWLOC_SPOOLDIR:
11953                   snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, current->context, current->mailbox);
11954                   read_password_from_file(secretfn, current->password, sizeof(current->password));
11955                }
11956             }
11957          }
11958          ast_config_destroy(ucfg);
11959       }
11960       cat = ast_category_browse(cfg, NULL);
11961       while (cat) {
11962          if (strcasecmp(cat, "general")) {
11963             var = ast_variable_browse(cfg, cat);
11964             if (strcasecmp(cat, "zonemessages")) {
11965                /* Process mailboxes in this context */
11966                while (var) {
11967                   append_mailbox(cat, var->name, var->value);
11968                   var = var->next;
11969                }
11970             } else {
11971                /* Timezones in this context */
11972                while (var) {
11973                   struct vm_zone *z;
11974                   if ((z = ast_malloc(sizeof(*z)))) {
11975                      char *msg_format, *tzone;
11976                      msg_format = ast_strdupa(var->value);
11977                      tzone = strsep(&msg_format, "|,");
11978                      if (msg_format) {
11979                         ast_copy_string(z->name, var->name, sizeof(z->name));
11980                         ast_copy_string(z->timezone, tzone, sizeof(z->timezone));
11981                         ast_copy_string(z->msg_format, msg_format, sizeof(z->msg_format));
11982                         AST_LIST_LOCK(&zones);
11983                         AST_LIST_INSERT_HEAD(&zones, z, list);
11984                         AST_LIST_UNLOCK(&zones);
11985                      } else {
11986                         ast_log(AST_LOG_WARNING, "Invalid timezone definition at line %d\n", var->lineno);
11987                         ast_free(z);
11988                      }
11989                   } else {
11990                      AST_LIST_UNLOCK(&users);
11991                      ast_config_destroy(cfg);
11992                      return -1;
11993                   }
11994                   var = var->next;
11995                }
11996             }
11997          }
11998          cat = ast_category_browse(cfg, cat);
11999       }
12000       memset(fromstring, 0, sizeof(fromstring));
12001       memset(pagerfromstring, 0, sizeof(pagerfromstring));
12002       strcpy(charset, "ISO-8859-1");
12003       if (emailbody) {
12004          ast_free(emailbody);
12005          emailbody = NULL;
12006       }
12007       if (emailsubject) {
12008          ast_free(emailsubject);
12009          emailsubject = NULL;
12010       }
12011       if (pagerbody) {
12012          ast_free(pagerbody);
12013          pagerbody = NULL;
12014       }
12015       if (pagersubject) {
12016          ast_free(pagersubject);
12017          pagersubject = NULL;
12018       }
12019       if ((val = ast_variable_retrieve(cfg, "general", "pbxskip")))
12020          ast_set2_flag((&globalflags), ast_true(val), VM_PBXSKIP);
12021       if ((val = ast_variable_retrieve(cfg, "general", "fromstring")))
12022          ast_copy_string(fromstring, val, sizeof(fromstring));
12023       if ((val = ast_variable_retrieve(cfg, "general", "pagerfromstring")))
12024          ast_copy_string(pagerfromstring, val, sizeof(pagerfromstring));
12025       if ((val = ast_variable_retrieve(cfg, "general", "charset")))
12026          ast_copy_string(charset, val, sizeof(charset));
12027       if ((val = ast_variable_retrieve(cfg, "general", "adsifdn"))) {
12028          sscanf(val, "%2x%2x%2x%2x", &tmpadsi[0], &tmpadsi[1], &tmpadsi[2], &tmpadsi[3]);
12029          for (x = 0; x < 4; x++) {
12030             memcpy(&adsifdn[x], &tmpadsi[x], 1);
12031          }
12032       }
12033       if ((val = ast_variable_retrieve(cfg, "general", "adsisec"))) {
12034          sscanf(val, "%2x%2x%2x%2x", &tmpadsi[0], &tmpadsi[1], &tmpadsi[2], &tmpadsi[3]);
12035          for (x = 0; x < 4; x++) {
12036             memcpy(&adsisec[x], &tmpadsi[x], 1);
12037          }
12038       }
12039       if ((val = ast_variable_retrieve(cfg, "general", "adsiver"))) {
12040          if (atoi(val)) {
12041             adsiver = atoi(val);
12042          }
12043       }
12044       if ((val = ast_variable_retrieve(cfg, "general", "tz"))) {
12045          ast_copy_string(zonetag, val, sizeof(zonetag));
12046       }
12047       if ((val = ast_variable_retrieve(cfg, "general", "locale"))) {
12048          ast_copy_string(locale, val, sizeof(locale));
12049       }
12050       if ((val = ast_variable_retrieve(cfg, "general", "emailsubject"))) {
12051          emailsubject = ast_strdup(val);
12052       }
12053       if ((val = ast_variable_retrieve(cfg, "general", "emailbody"))) {
12054          emailbody = ast_strdup(substitute_escapes(val));
12055       }
12056       if ((val = ast_variable_retrieve(cfg, "general", "pagersubject"))) {
12057          pagersubject = ast_strdup(val);
12058       }
12059       if ((val = ast_variable_retrieve(cfg, "general", "pagerbody"))) {
12060          pagerbody = ast_strdup(substitute_escapes(val));
12061       }
12062       AST_LIST_UNLOCK(&users);
12063       ast_config_destroy(cfg);
12064 
12065       if (poll_mailboxes && poll_thread == AST_PTHREADT_NULL)
12066          start_poll_thread();
12067       if (!poll_mailboxes && poll_thread != AST_PTHREADT_NULL)
12068          stop_poll_thread();;
12069 
12070       return 0;
12071    } else {
12072       AST_LIST_UNLOCK(&users);
12073       ast_log(AST_LOG_WARNING, "Failed to load configuration file.\n");
12074       if (ucfg)
12075          ast_config_destroy(ucfg);
12076       return 0;
12077    }
12078 }
12079 
12080 static int sayname(struct ast_channel *chan, const char *mailbox, const char *context)
12081 {
12082    int res = -1;
12083    char dir[PATH_MAX];
12084    snprintf(dir, sizeof(dir), "%s%s/%s/greet", VM_SPOOL_DIR, context, mailbox);
12085    ast_debug(2, "About to try retrieving name file %s\n", dir);
12086    RETRIEVE(dir, -1, mailbox, context);
12087    if (ast_fileexists(dir, NULL, NULL)) {
12088       res = ast_stream_and_wait(chan, dir, AST_DIGIT_ANY);
12089    }
12090    DISPOSE(dir, -1);
12091    return res;
12092 }
12093 
12094 static void read_password_from_file(const char *secretfn, char *password, int passwordlen) {
12095    struct ast_config *pwconf;
12096    struct ast_flags config_flags = { 0 };
12097 
12098    pwconf = ast_config_load(secretfn, config_flags);
12099    if (pwconf) {
12100       const char *val = ast_variable_retrieve(pwconf, "general", "password");
12101       if (val) {
12102          ast_copy_string(password, val, passwordlen);
12103          return;
12104       }
12105    }
12106    ast_log(LOG_NOTICE, "Failed reading voicemail password from %s, using secret from config file\n", secretfn);
12107 }
12108 
12109 static int write_password_to_file(const char *secretfn, const char *password) {
12110    struct ast_config *conf;
12111    struct ast_category *cat;
12112    struct ast_variable *var;
12113 
12114    if (!(conf=ast_config_new())) {
12115       ast_log(LOG_ERROR, "Error creating new config structure\n");
12116       return -1;
12117    }
12118    if (!(cat=ast_category_new("general","",1))) {
12119       ast_log(LOG_ERROR, "Error creating new category structure\n");
12120       return -1;
12121    }
12122    if (!(var=ast_variable_new("password",password,""))) {
12123       ast_log(LOG_ERROR, "Error creating new variable structure\n");
12124       return -1;
12125    }
12126    ast_category_append(conf,cat);
12127    ast_variable_append(cat,var);
12128    if (ast_config_text_file_save(secretfn, conf, "app_voicemail")) {
12129       ast_log(LOG_ERROR, "Error writing voicemail password to %s\n", secretfn);
12130       return -1;
12131    }
12132    return 0;
12133 }
12134 
12135 static int vmsayname_exec(struct ast_channel *chan, const char *data)
12136 {
12137    char *context;
12138    char *args_copy;
12139    int res;
12140 
12141    if (ast_strlen_zero(data)) {
12142       ast_log(LOG_WARNING, "VMSayName requires argument mailbox@context");
12143       return -1;
12144    }
12145 
12146    args_copy = ast_strdupa(data);
12147    if ((context = strchr(args_copy, '@'))) {
12148       *context++ = '\0';
12149    } else {
12150       context = "default";
12151    }
12152 
12153    if ((res = sayname(chan, args_copy, context) < 0)) {
12154       ast_debug(3, "Greeting not found for '%s@%s', falling back to mailbox number.\n", args_copy, context);
12155       res = ast_stream_and_wait(chan, "vm-extension", AST_DIGIT_ANY);
12156       if (!res) {
12157          res = ast_say_character_str(chan, args_copy, AST_DIGIT_ANY, chan->language);
12158       }
12159    }
12160 
12161    return res;
12162 }
12163 
12164 #ifdef TEST_FRAMEWORK
12165 static int fake_write(struct ast_channel *ast, struct ast_frame *frame)
12166 {
12167    return 0;
12168 }
12169 
12170 static struct ast_frame *fake_read(struct ast_channel *ast)
12171 {
12172    return &ast_null_frame;
12173 }
12174 
12175 AST_TEST_DEFINE(test_voicemail_vmsayname)
12176 {
12177    char dir[PATH_MAX];
12178    char dir2[PATH_MAX];
12179    static const char TEST_CONTEXT[] = "very_long_unique_context_so_that_nobody_will_ever_have_the_same_one_configured_3141592653";
12180    static const char TEST_EXTENSION[] = "1234";
12181 
12182    struct ast_channel *test_channel1 = NULL;
12183    int res = -1;
12184 
12185    static const struct ast_channel_tech fake_tech = {
12186       .write = fake_write,
12187       .read = fake_read,
12188    };
12189 
12190    switch (cmd) {
12191    case TEST_INIT:
12192       info->name = "vmsayname_exec";
12193       info->category = "/apps/app_voicemail/";
12194       info->summary = "Vmsayname unit test";
12195       info->description =
12196          "This tests passing various parameters to vmsayname";
12197       return AST_TEST_NOT_RUN;
12198    case TEST_EXECUTE:
12199       break;
12200    }
12201 
12202    if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL,
12203         NULL, NULL, 0, 0, "TestChannel1"))) {
12204       goto exit_vmsayname_test;
12205    }
12206 
12207    /* normally this is done in the channel driver */
12208    test_channel1->nativeformats = AST_FORMAT_GSM;
12209    test_channel1->writeformat = AST_FORMAT_GSM;
12210    test_channel1->rawwriteformat = AST_FORMAT_GSM;
12211    test_channel1->readformat = AST_FORMAT_GSM;
12212    test_channel1->rawreadformat = AST_FORMAT_GSM;
12213    test_channel1->tech = &fake_tech;
12214 
12215    ast_test_status_update(test, "Test playing of extension when greeting is not available...\n");
12216    snprintf(dir, sizeof(dir), "%s@%s", TEST_EXTENSION, TEST_CONTEXT); /* not a dir, don't get confused */
12217    if (!(res = vmsayname_exec(test_channel1, dir))) {
12218       snprintf(dir, sizeof(dir), "%s%s/%s/greet", VM_SPOOL_DIR, TEST_CONTEXT, TEST_EXTENSION);
12219       if (ast_fileexists(dir, NULL, NULL)) {
12220          ast_test_status_update(test, "This should not happen, most likely means clean up from previous test failed\n");
12221          res = -1;
12222          goto exit_vmsayname_test;
12223       } else {
12224          /* no greeting already exists as expected, let's create one to fully test sayname */
12225          if ((res = create_dirpath(dir, sizeof(dir), TEST_CONTEXT, TEST_EXTENSION, ""))) {
12226             ast_log(AST_LOG_WARNING, "Failed to make test directory\n");
12227             goto exit_vmsayname_test;
12228          }
12229          snprintf(dir, sizeof(dir), "%s/sounds/beep.gsm", ast_config_AST_VAR_DIR);
12230          snprintf(dir2, sizeof(dir2), "%s%s/%s/greet.gsm", VM_SPOOL_DIR, TEST_CONTEXT, TEST_EXTENSION);
12231          /* we're not going to hear the sound anyway, just use a valid gsm audio file */
12232          if ((res = symlink(dir, dir2))) {
12233             ast_log(LOG_WARNING, "Symlink reported %s\n", strerror(errno));
12234             goto exit_vmsayname_test;
12235          }
12236          ast_test_status_update(test, "Test playing created mailbox greeting...\n");
12237          snprintf(dir, sizeof(dir), "%s@%s", TEST_EXTENSION, TEST_CONTEXT); /* not a dir, don't get confused */
12238          res = vmsayname_exec(test_channel1, dir);
12239 
12240          /* TODO: there may be a better way to do this */
12241          unlink(dir2);
12242          snprintf(dir2, sizeof(dir2), "%s%s/%s", VM_SPOOL_DIR, TEST_CONTEXT, TEST_EXTENSION);
12243          rmdir(dir2);
12244          snprintf(dir2, sizeof(dir2), "%s%s", VM_SPOOL_DIR, TEST_CONTEXT);
12245          rmdir(dir2);
12246       }
12247    }
12248 
12249 exit_vmsayname_test:
12250 
12251    if (test_channel1) {
12252       ast_hangup(test_channel1);
12253    }
12254 
12255    return res ? AST_TEST_FAIL : AST_TEST_PASS;
12256 }
12257 
12258 AST_TEST_DEFINE(test_voicemail_msgcount)
12259 {
12260    int i, j, res = AST_TEST_PASS, syserr;
12261    struct ast_vm_user *vmu;
12262    struct vm_state vms;
12263 #ifdef IMAP_STORAGE
12264    struct ast_channel *chan = NULL;
12265 #endif
12266    struct {
12267       char dir[256];
12268       char file[256];
12269       char txtfile[256];
12270    } tmp[3];
12271    char syscmd[256];
12272    const char origweasels[] = "tt-weasels";
12273    const char testcontext[] = "test";
12274    const char testmailbox[] = "00000000";
12275    const char testspec[] = "00000000@test";
12276    FILE *txt;
12277    int new, old, urgent;
12278    const char *folders[3] = { "Old", "Urgent", "INBOX" };
12279    const int folder2mbox[3] = { 1, 11, 0 };
12280    const int expected_results[3][12] = {
12281       /* hasvm-old, hasvm-urgent, hasvm-new, ic-old, ic-urgent, ic-new, ic2-old, ic2-urgent, ic2-new, mc-old, mc-urgent, mc-new */
12282       {          1,            0,         0,      1,         0,      0,       1,          0,       0,      1,         0,      0 },
12283       {          1,            1,         1,      1,         0,      1,       1,          1,       0,      1,         1,      1 },
12284       {          1,            1,         1,      1,         0,      2,       1,          1,       1,      1,         1,      2 },
12285    };
12286 
12287    switch (cmd) {
12288    case TEST_INIT:
12289       info->name = "test_voicemail_msgcount";
12290       info->category = "/apps/app_voicemail/";
12291       info->summary = "Test Voicemail status checks";
12292       info->description =
12293          "Verify that message counts are correct when retrieved through the public API";
12294       return AST_TEST_NOT_RUN;
12295    case TEST_EXECUTE:
12296       break;
12297    }
12298 
12299    /* Make sure the original path was completely empty */
12300    snprintf(syscmd, sizeof(syscmd), "rm -rf %s%s/%s", VM_SPOOL_DIR, testcontext, testmailbox);
12301    if ((syserr = ast_safe_system(syscmd))) {
12302       ast_test_status_update(test, "Unable to clear test directory: %s\n",
12303          syserr > 0 ? strerror(syserr) : "unable to fork()");
12304       return AST_TEST_FAIL;
12305    }
12306 
12307 #ifdef IMAP_STORAGE
12308    if (!(chan = ast_dummy_channel_alloc())) {
12309       ast_test_status_update(test, "Unable to create dummy channel\n");
12310       return AST_TEST_FAIL;
12311    }
12312 #endif
12313 
12314    if (!(vmu = find_user(NULL, testcontext, testmailbox)) &&
12315       !(vmu = find_or_create(testcontext, testmailbox))) {
12316       ast_test_status_update(test, "Cannot create vmu structure\n");
12317       ast_unreplace_sigchld();
12318       return AST_TEST_FAIL;
12319    }
12320 
12321    populate_defaults(vmu);
12322    memset(&vms, 0, sizeof(vms));
12323 
12324    /* Create temporary voicemail */
12325    for (i = 0; i < 3; i++) {
12326       create_dirpath(tmp[i].dir, sizeof(tmp[i].dir), testcontext, testmailbox, folders[i]);
12327       make_file(tmp[i].file, sizeof(tmp[i].file), tmp[i].dir, 0);
12328       snprintf(tmp[i].txtfile, sizeof(tmp[i].txtfile), "%s.txt", tmp[i].file);
12329 
12330       if (ast_fileexists(origweasels, "gsm", "en") > 0) {
12331          snprintf(syscmd, sizeof(syscmd), "cp %s/sounds/en/%s.gsm %s/%s/%s/%s/msg0000.gsm", ast_config_AST_DATA_DIR, origweasels,
12332             VM_SPOOL_DIR, testcontext, testmailbox, folders[i]);
12333          if ((syserr = ast_safe_system(syscmd))) {
12334             ast_test_status_update(test, "Unable to create test voicemail: %s\n",
12335                syserr > 0 ? strerror(syserr) : "unable to fork()");
12336             ast_unreplace_sigchld();
12337             return AST_TEST_FAIL;
12338          }
12339       }
12340 
12341       if ((txt = fopen(tmp[i].txtfile, "w+"))) {
12342          fprintf(txt, "; just a stub\n[message]\nflag=%s\n", strcmp(folders[i], "Urgent") ? "" : "Urgent");
12343          fclose(txt);
12344       } else {
12345          ast_test_status_update(test, "Unable to write message file '%s'\n", tmp[i].txtfile);
12346          res = AST_TEST_FAIL;
12347          break;
12348       }
12349       open_mailbox(&vms, vmu, folder2mbox[i]);
12350       STORE(tmp[i].dir, testmailbox, testcontext, 0, chan, vmu, "gsm", 600, &vms, strcmp(folders[i], "Urgent") ? "" : "Urgent");
12351 
12352       /* hasvm-old, hasvm-urgent, hasvm-new, ic-old, ic-urgent, ic-new, ic2-old, ic2-urgent, ic2-new, mc-old, mc-urgent, mc-new */
12353       for (j = 0; j < 3; j++) {
12354          /* folder[2] is INBOX, __has_voicemail will default back to INBOX */ 
12355          if (ast_app_has_voicemail(testspec, (j==2 ? NULL : folders[j])) != expected_results[i][0 + j]) {
12356             ast_test_status_update(test, "has_voicemail(%s, %s) returned %d and we expected %d\n",
12357                testspec, folders[j], ast_app_has_voicemail(testspec, folders[j]), expected_results[i][0 + j]);
12358             res = AST_TEST_FAIL;
12359          }
12360       }
12361 
12362       new = old = urgent = 0;
12363       if (ast_app_inboxcount(testspec, &new, &old)) {
12364          ast_test_status_update(test, "inboxcount returned failure\n");
12365          res = AST_TEST_FAIL;
12366       } else if (old != expected_results[i][3 + 0] || new != expected_results[i][3 + 2]) {
12367          ast_test_status_update(test, "inboxcount(%s) returned old=%d (expected %d) and new=%d (expected %d)\n",
12368             testspec, old, expected_results[i][3 + 0], new, expected_results[i][3 + 2]);
12369          res = AST_TEST_FAIL;
12370       }
12371 
12372       new = old = urgent = 0;
12373       if (ast_app_inboxcount2(testspec, &urgent, &new, &old)) {
12374          ast_test_status_update(test, "inboxcount2 returned failure\n");
12375          res = AST_TEST_FAIL;
12376       } else if (old != expected_results[i][6 + 0] ||
12377             urgent != expected_results[i][6 + 1] ||
12378                new != expected_results[i][6 + 2]    ) {
12379          ast_test_status_update(test, "inboxcount2(%s) returned old=%d (expected %d), urgent=%d (expected %d), and new=%d (expected %d)\n",
12380             testspec, old, expected_results[i][6 + 0], urgent, expected_results[i][6 + 1], new, expected_results[i][6 + 2]);
12381          res = AST_TEST_FAIL;
12382       }
12383 
12384       new = old = urgent = 0;
12385       for (j = 0; j < 3; j++) {
12386          if (ast_app_messagecount(testcontext, testmailbox, folders[j]) != expected_results[i][9 + j]) {
12387             ast_test_status_update(test, "messagecount(%s, %s) returned %d and we expected %d\n",
12388                testspec, folders[j], ast_app_messagecount(testcontext, testmailbox, folders[j]), expected_results[i][9 + j]);
12389             res = AST_TEST_FAIL;
12390          }
12391       }
12392    }
12393 
12394    for (i = 0; i < 3; i++) {
12395       /* This is necessary if the voicemails are stored on an ODBC/IMAP
12396        * server, in which case, the rm below will not affect the
12397        * voicemails. */
12398       DELETE(tmp[i].dir, 0, tmp[i].file, vmu);
12399       DISPOSE(tmp[i].dir, 0);
12400    }
12401 
12402    if (vms.deleted) {
12403       ast_free(vms.deleted);
12404    }
12405    if (vms.heard) {
12406       ast_free(vms.heard);
12407    }
12408 
12409 #ifdef IMAP_STORAGE
12410    chan = ast_channel_release(chan);
12411 #endif
12412 
12413    /* And remove test directory */
12414    snprintf(syscmd, sizeof(syscmd), "rm -rf %s%s/%s", VM_SPOOL_DIR, testcontext, testmailbox);
12415    if ((syserr = ast_safe_system(syscmd))) {
12416       ast_test_status_update(test, "Unable to clear test directory: %s\n",
12417          syserr > 0 ? strerror(syserr) : "unable to fork()");
12418    }
12419 
12420    return res;
12421 }
12422 
12423 AST_TEST_DEFINE(test_voicemail_notify_endl)
12424 {
12425    int res = AST_TEST_PASS;
12426    char testcontext[] = "test";
12427    char testmailbox[] = "00000000";
12428    char from[] = "test@example.net", cidnum[] = "1234", cidname[] = "Mark Spencer", format[] = "gsm";
12429    char attach[256], attach2[256];
12430    char buf[256] = ""; /* No line should actually be longer than 80 */
12431    struct ast_channel *chan = NULL;
12432    struct ast_vm_user *vmu, vmus = {
12433       .flags = 0,
12434    };
12435    FILE *file;
12436    struct {
12437       char *name;
12438       enum { INT, FLAGVAL, STATIC, STRPTR } type;
12439       void *location;
12440       union {
12441          int intval;
12442          char *strval;
12443       } u;
12444    } test_items[] = {
12445       { "plain jane config", STATIC, vmus.password, .u.strval = "1234" }, /* No, this doesn't change this test any. */
12446       { "emailsubject", STRPTR, vmus.emailsubject, .u.strval = "Oogly boogly\xf8koogly with what appears to be UTF-8" },
12447       { "emailbody", STRPTR, vmus.emailbody, .u.strval = "This is a test\n\twith multiple\nlines\nwithin\n" },
12448       { "serveremail", STATIC, vmus.serveremail, .u.strval = "\"\xf8Something\xe8that\xd8seems to have UTF-8 chars\" <test@example.net>" },
12449       { "attachment flag", FLAGVAL, &vmus.flags, .u.intval = VM_ATTACH },
12450       { "attach2", STRPTR, attach2, .u.strval = "" },
12451       { "attach", STRPTR, attach, .u.strval = "" },
12452    };
12453    int which;
12454 
12455    switch (cmd) {
12456    case TEST_INIT:
12457       info->name = "test_voicemail_notify_endl";
12458       info->category = "/apps/app_voicemail/";
12459       info->summary = "Test Voicemail notification end-of-line";
12460       info->description =
12461          "Verify that notification emails use a consistent end-of-line character";
12462       return AST_TEST_NOT_RUN;
12463    case TEST_EXECUTE:
12464       break;
12465    }
12466 
12467    snprintf(attach, sizeof(attach), "%s/sounds/en/tt-weasels", ast_config_AST_VAR_DIR);
12468    snprintf(attach2, sizeof(attach2), "%s/sounds/en/tt-somethingwrong", ast_config_AST_VAR_DIR);
12469 
12470    if (!(vmu = find_user(&vmus, testcontext, testmailbox)) &&
12471       !(vmu = find_or_create(testcontext, testmailbox))) {
12472       ast_test_status_update(test, "Cannot create vmu structure\n");
12473       return AST_TEST_NOT_RUN;
12474    }
12475 
12476    if (vmu != &vmus && !(vmu = find_user(&vmus, testcontext, testmailbox))) {
12477       ast_test_status_update(test, "Cannot find vmu structure?!!\n");
12478       return AST_TEST_NOT_RUN;
12479    }
12480 
12481    populate_defaults(vmu);
12482    ast_copy_string(vmu->email, "test2@example.net", sizeof(vmu->email));
12483 #ifdef IMAP_STORAGE
12484    /* TODO When we set up the IMAP server test, we'll need to have credentials for the VMU structure added here */
12485 #endif
12486 
12487    file = tmpfile();
12488    for (which = 0; which < ARRAY_LEN(test_items); which++) {
12489       /* Kill previous test, if any */
12490       rewind(file);
12491       if (ftruncate(fileno(file), 0)) {
12492          ast_test_status_update(test, "Cannot truncate test output file: %s\n", strerror(errno));
12493          res = AST_TEST_FAIL;
12494          break;
12495       }
12496 
12497       /* Make each change, in order, to the test mailbox */
12498       if (test_items[which].type == INT) {
12499          *((int *) test_items[which].location) = test_items[which].u.intval;
12500       } else if (test_items[which].type == FLAGVAL) {
12501          if (ast_test_flag(vmu, test_items[which].u.intval)) {
12502             ast_clear_flag(vmu, test_items[which].u.intval);
12503          } else {
12504             ast_set_flag(vmu, test_items[which].u.intval);
12505          }
12506       } else if (test_items[which].type == STATIC) {
12507          strcpy(test_items[which].location, test_items[which].u.strval);
12508       } else if (test_items[which].type == STRPTR) {
12509          test_items[which].location = test_items[which].u.strval;
12510       }
12511 
12512       make_email_file(file, from, vmu, 0, testcontext, testmailbox, "INBOX", cidnum, cidname, attach, attach2, format, 999, 1, chan, NULL, 0, NULL);
12513       rewind(file);
12514       while (fgets(buf, sizeof(buf), file)) {
12515          if (
12516 #ifdef IMAP_STORAGE
12517          buf[strlen(buf) - 2] != '\r'
12518 #else
12519          buf[strlen(buf) - 2] == '\r'
12520 #endif
12521          || buf[strlen(buf) - 1] != '\n') {
12522             res = AST_TEST_FAIL;
12523          }
12524       }
12525    }
12526    fclose(file);
12527    return res;
12528 }
12529 #endif /* defined(TEST_FRAMEWORK) */
12530 
12531 static int reload(void)
12532 {
12533    return load_config(1);
12534 }
12535 
12536 static int unload_module(void)
12537 {
12538    int res;
12539 
12540    res = ast_unregister_application(app);
12541    res |= ast_unregister_application(app2);
12542    res |= ast_unregister_application(app3);
12543    res |= ast_unregister_application(app4);
12544    res |= ast_custom_function_unregister(&mailbox_exists_acf);
12545    res |= ast_manager_unregister("VoicemailUsersList");
12546    res |= ast_data_unregister(NULL);
12547 #ifdef TEST_FRAMEWORK
12548    res |= AST_TEST_UNREGISTER(test_voicemail_vmsayname);
12549    res |= AST_TEST_UNREGISTER(test_voicemail_msgcount);
12550    res |= AST_TEST_UNREGISTER(test_voicemail_vmuser);
12551    res |= AST_TEST_UNREGISTER(test_voicemail_notify_endl);
12552 #endif
12553    ast_cli_unregister_multiple(cli_voicemail, ARRAY_LEN(cli_voicemail));
12554    ast_uninstall_vm_functions();
12555    ao2_ref(inprocess_container, -1);
12556 
12557    if (poll_thread != AST_PTHREADT_NULL)
12558       stop_poll_thread();
12559 
12560    mwi_subscription_tps = ast_taskprocessor_unreference(mwi_subscription_tps);
12561    ast_unload_realtime("voicemail");
12562    ast_unload_realtime("voicemail_data");
12563 
12564    free_vm_users();
12565    free_vm_zones();
12566    return res;
12567 }
12568 
12569 static int load_module(void)
12570 {
12571    int res;
12572    my_umask = umask(0);
12573    umask(my_umask);
12574 
12575    if (!(inprocess_container = ao2_container_alloc(573, inprocess_hash_fn, inprocess_cmp_fn))) {
12576       return AST_MODULE_LOAD_DECLINE;
12577    }
12578 
12579    /* compute the location of the voicemail spool directory */
12580    snprintf(VM_SPOOL_DIR, sizeof(VM_SPOOL_DIR), "%s/voicemail/", ast_config_AST_SPOOL_DIR);
12581    
12582    if (!(mwi_subscription_tps = ast_taskprocessor_get("app_voicemail", 0))) {
12583       ast_log(AST_LOG_WARNING, "failed to reference mwi subscription taskprocessor.  MWI will not work\n");
12584    }
12585 
12586    if ((res = load_config(0)))
12587       return res;
12588 
12589    res = ast_register_application_xml(app, vm_exec);
12590    res |= ast_register_application_xml(app2, vm_execmain);
12591    res |= ast_register_application_xml(app3, vm_box_exists);
12592    res |= ast_register_application_xml(app4, vmauthenticate);
12593    res |= ast_register_application_xml(sayname_app, vmsayname_exec);
12594    res |= ast_custom_function_register(&mailbox_exists_acf);
12595    res |= ast_manager_register_xml("VoicemailUsersList", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, manager_list_voicemail_users);
12596 #ifdef TEST_FRAMEWORK
12597    res |= AST_TEST_REGISTER(test_voicemail_vmsayname);
12598    res |= AST_TEST_REGISTER(test_voicemail_msgcount);
12599    res |= AST_TEST_REGISTER(test_voicemail_vmuser);
12600    res |= AST_TEST_REGISTER(test_voicemail_notify_endl);
12601 #endif
12602 
12603    if (res)
12604       return res;
12605 
12606    ast_cli_register_multiple(cli_voicemail, ARRAY_LEN(cli_voicemail));
12607    ast_data_register_multiple(vm_data_providers, ARRAY_LEN(vm_data_providers));
12608 
12609    ast_install_vm_functions(has_voicemail, inboxcount, inboxcount2, messagecount, sayname);
12610    ast_realtime_require_field("voicemail", "uniqueid", RQ_UINTEGER3, 11, "password", RQ_CHAR, 10, SENTINEL);
12611    ast_realtime_require_field("voicemail_data", "filename", RQ_CHAR, 30, "duration", RQ_UINTEGER3, 5, SENTINEL);
12612 
12613    return res;
12614 }
12615 
12616 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context) 
12617 {
12618    int cmd = 0;
12619    char destination[80] = "";
12620    int retries = 0;
12621 
12622    if (!num) {
12623       ast_verb(3, "Destination number will be entered manually\n");
12624       while (retries < 3 && cmd != 't') {
12625          destination[1] = '\0';
12626          destination[0] = cmd = ast_play_and_wait(chan, "vm-enter-num-to-call");
12627          if (!cmd)
12628             destination[0] = cmd = ast_play_and_wait(chan, "vm-then-pound");
12629          if (!cmd)
12630             destination[0] = cmd = ast_play_and_wait(chan, "vm-star-cancel");
12631          if (!cmd) {
12632             cmd = ast_waitfordigit(chan, 6000);
12633             if (cmd)
12634                destination[0] = cmd;
12635          }
12636          if (!cmd) {
12637             retries++;
12638          } else {
12639 
12640             if (cmd < 0)
12641                return 0;
12642             if (cmd == '*') {
12643                ast_verb(3, "User hit '*' to cancel outgoing call\n");
12644                return 0;
12645             }
12646             if ((cmd = ast_readstring(chan, destination + strlen(destination), sizeof(destination) - 1, 6000, 10000, "#")) < 0) 
12647                retries++;
12648             else
12649                cmd = 't';
12650          }
12651       }
12652       if (retries >= 3) {
12653          return 0;
12654       }
12655       
12656    } else {
12657       if (option_verbose > 2)
12658          ast_verbose( VERBOSE_PREFIX_3 "Destination number is CID number '%s'\n", num);
12659       ast_copy_string(destination, num, sizeof(destination));
12660    }
12661 
12662    if (!ast_strlen_zero(destination)) {
12663       if (destination[strlen(destination) -1 ] == '*')
12664          return 0; 
12665       if (option_verbose > 2)
12666          ast_verbose( VERBOSE_PREFIX_3 "Placing outgoing call to extension '%s' in context '%s' from context '%s'\n", destination, outgoing_context, chan->context);
12667       ast_copy_string(chan->exten, destination, sizeof(chan->exten));
12668       ast_copy_string(chan->context, outgoing_context, sizeof(chan->context));
12669       chan->priority = 0;
12670       return 9;
12671    }
12672    return 0;
12673 }
12674 
12675 /*!
12676  * \brief The advanced options within a message.
12677  * \param chan
12678  * \param vmu 
12679  * \param vms
12680  * \param msg
12681  * \param option
12682  * \param record_gain
12683  *
12684  * Provides handling for the play message envelope, call the person back, or reply to message. 
12685  *
12686  * \return zero on success, -1 on error.
12687  */
12688 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)
12689 {
12690    int res = 0;
12691    char filename[PATH_MAX];
12692    struct ast_config *msg_cfg = NULL;
12693    const char *origtime, *context;
12694    char *name, *num;
12695    int retries = 0;
12696    char *cid;
12697    struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE, };
12698 
12699    vms->starting = 0; 
12700 
12701    make_file(vms->fn, sizeof(vms->fn), vms->curdir, msg);
12702 
12703    /* Retrieve info from VM attribute file */
12704    snprintf(filename, sizeof(filename), "%s.txt", vms->fn);
12705    RETRIEVE(vms->curdir, vms->curmsg, vmu->mailbox, vmu->context);
12706    msg_cfg = ast_config_load(filename, config_flags);
12707    DISPOSE(vms->curdir, vms->curmsg);
12708    if (!msg_cfg || msg_cfg == CONFIG_STATUS_FILEINVALID) {
12709       ast_log(AST_LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
12710       return 0;
12711    }
12712 
12713    if (!(origtime = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
12714       ast_config_destroy(msg_cfg);
12715       return 0;
12716    }
12717 
12718    cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
12719 
12720    context = ast_variable_retrieve(msg_cfg, "message", "context");
12721    if (!strncasecmp("macro", context, 5)) /* Macro names in contexts are useless for our needs */
12722       context = ast_variable_retrieve(msg_cfg, "message", "macrocontext");
12723    switch (option) {
12724    case 3: /* Play message envelope */
12725       if (!res)
12726          res = play_message_datetime(chan, vmu, origtime, filename);
12727       if (!res)
12728          res = play_message_callerid(chan, vms, cid, context, 0);
12729 
12730       res = 't';
12731       break;
12732 
12733    case 2:  /* Call back */
12734 
12735       if (ast_strlen_zero(cid))
12736          break;
12737 
12738       ast_callerid_parse(cid, &name, &num);
12739       while ((res > -1) && (res != 't')) {
12740          switch (res) {
12741          case '1':
12742             if (num) {
12743                /* Dial the CID number */
12744                res = dialout(chan, vmu, num, vmu->callback);
12745                if (res) {
12746                   ast_config_destroy(msg_cfg);
12747                   return 9;
12748                }
12749             } else {
12750                res = '2';
12751             }
12752             break;
12753 
12754          case '2':
12755             /* Want to enter a different number, can only do this if there's a dialout context for this user */
12756             if (!ast_strlen_zero(vmu->dialout)) {
12757                res = dialout(chan, vmu, NULL, vmu->dialout);
12758                if (res) {
12759                   ast_config_destroy(msg_cfg);
12760                   return 9;
12761                }
12762             } else {
12763                ast_verb(3, "Caller can not specify callback number - no dialout context available\n");
12764                res = ast_play_and_wait(chan, "vm-sorry");
12765             }
12766             ast_config_destroy(msg_cfg);
12767             return res;
12768          case '*':
12769             res = 't';
12770             break;
12771          case '3':
12772          case '4':
12773          case '5':
12774          case '6':
12775          case '7':
12776          case '8':
12777          case '9':
12778          case '0':
12779 
12780             res = ast_play_and_wait(chan, "vm-sorry");
12781             retries++;
12782             break;
12783          default:
12784             if (num) {
12785                ast_verb(3, "Confirm CID number '%s' is number to use for callback\n", num);
12786                res = ast_play_and_wait(chan, "vm-num-i-have");
12787                if (!res)
12788                   res = play_message_callerid(chan, vms, num, vmu->context, 1);
12789                if (!res)
12790                   res = ast_play_and_wait(chan, "vm-tocallnum");
12791                /* Only prompt for a caller-specified number if there is a dialout context specified */
12792                if (!ast_strlen_zero(vmu->dialout)) {
12793                   if (!res)
12794                      res = ast_play_and_wait(chan, "vm-calldiffnum");
12795                }
12796             } else {
12797                res = ast_play_and_wait(chan, "vm-nonumber");
12798                if (!ast_strlen_zero(vmu->dialout)) {
12799                   if (!res)
12800                      res = ast_play_and_wait(chan, "vm-toenternumber");
12801                }
12802             }
12803             if (!res)
12804                res = ast_play_and_wait(chan, "vm-star-cancel");
12805             if (!res)
12806                res = ast_waitfordigit(chan, 6000);
12807             if (!res) {
12808                retries++;
12809                if (retries > 3)
12810                   res = 't';
12811             }
12812             break; 
12813             
12814          }
12815          if (res == 't')
12816             res = 0;
12817          else if (res == '*')
12818             res = -1;
12819       }
12820       break;
12821       
12822    case 1:  /* Reply */
12823       /* Send reply directly to sender */
12824       if (ast_strlen_zero(cid))
12825          break;
12826 
12827       ast_callerid_parse(cid, &name, &num);
12828       if (!num) {
12829          ast_verb(3, "No CID number available, no reply sent\n");
12830          if (!res)
12831             res = ast_play_and_wait(chan, "vm-nonumber");
12832          ast_config_destroy(msg_cfg);
12833          return res;
12834       } else {
12835          struct ast_vm_user vmu2;
12836          if (find_user(&vmu2, vmu->context, num)) {
12837             struct leave_vm_options leave_options;
12838             char mailbox[AST_MAX_EXTENSION * 2 + 2];
12839             snprintf(mailbox, sizeof(mailbox), "%s@%s", num, vmu->context);
12840 
12841             ast_verb(3, "Leaving voicemail for '%s' in context '%s'\n", num, vmu->context);
12842             
12843             memset(&leave_options, 0, sizeof(leave_options));
12844             leave_options.record_gain = record_gain;
12845             res = leave_voicemail(chan, mailbox, &leave_options);
12846             if (!res)
12847                res = 't';
12848             ast_config_destroy(msg_cfg);
12849             return res;
12850          } else {
12851             /* Sender has no mailbox, can't reply */
12852             ast_verb(3, "No mailbox number '%s' in context '%s', no reply sent\n", num, vmu->context);
12853             ast_play_and_wait(chan, "vm-nobox");
12854             res = 't';
12855             ast_config_destroy(msg_cfg);
12856             return res;
12857          }
12858       } 
12859       res = 0;
12860 
12861       break;
12862    }
12863 
12864 #ifndef IMAP_STORAGE
12865    ast_config_destroy(msg_cfg);
12866 
12867    if (!res) {
12868       make_file(vms->fn, sizeof(vms->fn), vms->curdir, msg);
12869       vms->heard[msg] = 1;
12870       res = wait_file(chan, vms, vms->fn);
12871    }
12872 #endif
12873    return res;
12874 }
12875 
12876 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt,
12877          int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
12878          signed char record_gain, struct vm_state *vms, char *flag)
12879 {
12880    /* Record message & let caller review or re-record it, or set options if applicable */
12881    int res = 0;
12882    int cmd = 0;
12883    int max_attempts = 3;
12884    int attempts = 0;
12885    int recorded = 0;
12886    int msg_exists = 0;
12887    signed char zero_gain = 0;
12888    char tempfile[PATH_MAX];
12889    char *acceptdtmf = "#";
12890    char *canceldtmf = "";
12891    int canceleddtmf = 0;
12892 
12893    /* Note that urgent and private are for flagging messages as such in the future */
12894 
12895    /* barf if no pointer passed to store duration in */
12896    if (duration == NULL) {
12897       ast_log(AST_LOG_WARNING, "Error play_record_review called without duration pointer\n");
12898       return -1;
12899    }
12900 
12901    if (!outsidecaller)
12902       snprintf(tempfile, sizeof(tempfile), "%s.tmp", recordfile);
12903    else
12904       ast_copy_string(tempfile, recordfile, sizeof(tempfile));
12905 
12906    cmd = '3';  /* Want to start by recording */
12907 
12908    while ((cmd >= 0) && (cmd != 't')) {
12909       switch (cmd) {
12910       case '1':
12911          if (!msg_exists) {
12912             /* In this case, 1 is to record a message */
12913             cmd = '3';
12914             break;
12915          } else {
12916             /* Otherwise 1 is to save the existing message */
12917             ast_verb(3, "Saving message as is\n");
12918             if (!outsidecaller) 
12919                ast_filerename(tempfile, recordfile, NULL);
12920             ast_stream_and_wait(chan, "vm-msgsaved", "");
12921             if (!outsidecaller) {
12922                /* Saves to IMAP server only if imapgreeting=yes */
12923                STORE(recordfile, vmu->mailbox, vmu->context, -1, chan, vmu, fmt, *duration, vms, flag);
12924                DISPOSE(recordfile, -1);
12925             }
12926             cmd = 't';
12927             return res;
12928          }
12929       case '2':
12930          /* Review */
12931          ast_verb(3, "Reviewing the message\n");
12932          cmd = ast_stream_and_wait(chan, tempfile, AST_DIGIT_ANY);
12933          break;
12934       case '3':
12935          msg_exists = 0;
12936          /* Record */
12937          if (recorded == 1) 
12938             ast_verb(3, "Re-recording the message\n");
12939          else  
12940             ast_verb(3, "Recording the message\n");
12941          
12942          if (recorded && outsidecaller) {
12943             cmd = ast_play_and_wait(chan, INTRO);
12944             cmd = ast_play_and_wait(chan, "beep");
12945          }
12946          recorded = 1;
12947          /* After an attempt has been made to record message, we have to take care of INTRO and beep for incoming messages, but not for greetings */
12948          if (record_gain)
12949             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &record_gain, sizeof(record_gain), 0);
12950          if (ast_test_flag(vmu, VM_OPERATOR))
12951             canceldtmf = "0";
12952          cmd = ast_play_and_record_full(chan, playfile, tempfile, maxtime, fmt, duration, silencethreshold, maxsilence, unlockdir, acceptdtmf, canceldtmf);
12953          if (strchr(canceldtmf, cmd)) {
12954          /* need this flag here to distinguish between pressing '0' during message recording or after */
12955             canceleddtmf = 1;
12956          }
12957          if (record_gain)
12958             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &zero_gain, sizeof(zero_gain), 0);
12959          if (cmd == -1) {
12960             /* User has hung up, no options to give */
12961             if (!outsidecaller) {
12962                /* user was recording a greeting and they hung up, so let's delete the recording. */
12963                ast_filedelete(tempfile, NULL);
12964             }     
12965             return cmd;
12966          }
12967          if (cmd == '0') {
12968             break;
12969          } else if (cmd == '*') {
12970             break;
12971 #if 0
12972          } else if (vmu->review && (*duration < 5)) {
12973             /* Message is too short */
12974             ast_verb(3, "Message too short\n");
12975             cmd = ast_play_and_wait(chan, "vm-tooshort");
12976             cmd = ast_filedelete(tempfile, NULL);
12977             break;
12978          } else if (vmu->review && (cmd == 2 && *duration < (maxsilence + 3))) {
12979             /* Message is all silence */
12980             ast_verb(3, "Nothing recorded\n");
12981             cmd = ast_filedelete(tempfile, NULL);
12982             cmd = ast_play_and_wait(chan, "vm-nothingrecorded");
12983             if (!cmd)
12984                cmd = ast_play_and_wait(chan, "vm-speakup");
12985             break;
12986 #endif
12987          } else {
12988             /* If all is well, a message exists */
12989             msg_exists = 1;
12990             cmd = 0;
12991          }
12992          break;
12993       case '4':
12994          if (outsidecaller) {  /* only mark vm messages */
12995             /* Mark Urgent */
12996             if ((flag && ast_strlen_zero(flag)) || (!ast_strlen_zero(flag) && strcmp(flag, "Urgent"))) {
12997                ast_verbose(VERBOSE_PREFIX_3 "marking message as Urgent\n");
12998                res = ast_play_and_wait(chan, "vm-marked-urgent");
12999                strcpy(flag, "Urgent");
13000             } else if (flag) {
13001                ast_verbose(VERBOSE_PREFIX_3 "UNmarking message as Urgent\n");
13002                res = ast_play_and_wait(chan, "vm-urgent-removed");
13003                strcpy(flag, "");
13004             } else {
13005                ast_play_and_wait(chan, "vm-sorry");
13006             }
13007             cmd = 0;
13008          } else {
13009             cmd = ast_play_and_wait(chan, "vm-sorry");
13010          }
13011          break;
13012       case '5':
13013       case '6':
13014       case '7':
13015       case '8':
13016       case '9':
13017       case '*':
13018       case '#':
13019          cmd = ast_play_and_wait(chan, "vm-sorry");
13020          break;
13021 #if 0 
13022 /*  XXX Commented out for the moment because of the dangers of deleting
13023     a message while recording (can put the message numbers out of sync) */
13024       case '*':
13025          /* Cancel recording, delete message, offer to take another message*/
13026          cmd = ast_play_and_wait(chan, "vm-deleted");
13027          cmd = ast_filedelete(tempfile, NULL);
13028          if (outsidecaller) {
13029             res = vm_exec(chan, NULL);
13030             return res;
13031          }
13032          else
13033             return 1;
13034 #endif
13035       case '0':
13036          if (!ast_test_flag(vmu, VM_OPERATOR) || (!canceleddtmf && !outsidecaller)) {
13037             cmd = ast_play_and_wait(chan, "vm-sorry");
13038             break;
13039          }
13040          if (msg_exists || recorded) {
13041             cmd = ast_play_and_wait(chan, "vm-saveoper");
13042             if (!cmd)
13043                cmd = ast_waitfordigit(chan, 3000);
13044             if (cmd == '1') {
13045                ast_filerename(tempfile, recordfile, NULL);
13046                ast_play_and_wait(chan, "vm-msgsaved");
13047                cmd = '0';
13048             } else if (cmd == '4') {
13049                if (flag) {
13050                   ast_play_and_wait(chan, "vm-marked-urgent");
13051                   strcpy(flag, "Urgent");
13052                }
13053                ast_play_and_wait(chan, "vm-msgsaved");
13054                cmd = '0';
13055             } else {
13056                ast_play_and_wait(chan, "vm-deleted");
13057                DELETE(tempfile, -1, tempfile, vmu);
13058                cmd = '0';
13059             }
13060          }
13061          return cmd;
13062       default:
13063          /* If the caller is an ouside caller, and the review option is enabled,
13064             allow them to review the message, but let the owner of the box review
13065             their OGM's */
13066          if (outsidecaller && !ast_test_flag(vmu, VM_REVIEW))
13067             return cmd;
13068          if (msg_exists) {
13069             cmd = ast_play_and_wait(chan, "vm-review");
13070             if (!cmd && outsidecaller) {
13071                if ((flag && ast_strlen_zero(flag)) || (!ast_strlen_zero(flag) && strcmp(flag, "Urgent"))) {
13072                   cmd = ast_play_and_wait(chan, "vm-review-urgent");
13073                } else if (flag) {
13074                   cmd = ast_play_and_wait(chan, "vm-review-nonurgent");
13075                }
13076             }
13077          } else {
13078             cmd = ast_play_and_wait(chan, "vm-torerecord");
13079             if (!cmd)
13080                cmd = ast_waitfordigit(chan, 600);
13081          }
13082          
13083          if (!cmd && outsidecaller && ast_test_flag(vmu, VM_OPERATOR)) {
13084             cmd = ast_play_and_wait(chan, "vm-reachoper");
13085             if (!cmd)
13086                cmd = ast_waitfordigit(chan, 600);
13087          }
13088 #if 0
13089          if (!cmd)
13090             cmd = ast_play_and_wait(chan, "vm-tocancelmsg");
13091 #endif
13092          if (!cmd)
13093             cmd = ast_waitfordigit(chan, 6000);
13094          if (!cmd) {
13095             attempts++;
13096          }
13097          if (attempts > max_attempts) {
13098             cmd = 't';
13099          }
13100       }
13101    }
13102    if (!outsidecaller && (cmd == -1 || cmd == 't')) {
13103       /* Hang up or timeout, so delete the recording. */
13104       ast_filedelete(tempfile, NULL);
13105    }
13106    if (cmd == 't')
13107       cmd = 0;
13108    else if (outsidecaller) /* won't play if time out occurs */
13109       ast_play_and_wait(chan, "vm-goodbye");
13110    return cmd;
13111 }
13112 
13113 /* This is a workaround so that menuselect displays a proper description
13114  * AST_MODULE_INFO(, , "Comedian Mail (Voicemail System)"
13115  */
13116 
13117 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
13118       .load = load_module,
13119       .unload = unload_module,
13120       .reload = reload,
13121       .nonoptreq = "res_adsi,res_smdi",
13122       );

Generated on Sat Mar 26 11:06:42 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9