Skip to content
Snippets Groups Projects
app_voicemail.c 216 KiB
Newer Older
  • Learn to ignore specific revisions
  • Mark Spencer's avatar
    Mark Spencer committed
    /*
    
     * Asterisk -- An open source telephony toolkit.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Copyright (C) 1999 - 2006, Digium, Inc.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Mark Spencer <markster@digium.com>
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * See http://www.asterisk.org for more information about
     * the Asterisk project. Please do not directly contact
     * any of the maintainers of this project for assistance;
     * the project provides a web site, mailing lists and IRC
     * channels for your use.
     *
     * This program is free software, distributed under the terms of
     * the GNU General Public License Version 2. See the LICENSE file
     * at the top of the source tree.
     */
    
    
     * \brief Comedian Mail - Voicemail System
    
     *
     * \author Mark Spencer <markster@digium.com>
    
    Russell Bryant's avatar
    Russell Bryant committed
     * \par See also
     * \arg \ref Config_vm
     * \ingroup applications
    
     * \note This module requires res_adsi to load.
    
    /*
     * 12-16-2004 : Support for Greek added by InAccess Networks (work funded by HOL, www.hol.gr)
     *				 George Konstantoulakis <gkon@inaccessnetworks.com>
     *
     * 05-10-2005 : Support for Swedish and Norwegian added by Daniel Nylander, http://www.danielnylander.se/
     *
     * 05-11-2005 : An option for maximum number of messsages per mailbox added by GDS Partners (www.gdspartners.com)
     * 07-11-2005 : An issue with voicemail synchronization has been fixed by GDS Partners (www.gdspartners.com)
     *				 Stojan Sljivic <stojan.sljivic@gdspartners.com>
     *
    
     * 12-04-2006 : Support for Polish added by DIR (www.dir.pl)
     *				 Bartosz Supczinski <Bartosz.Supczinski@dir.pl>
    
    <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" remove_on_change="apps/app_voicemail.o">
    
    	<member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
    		<depend>unixodbc</depend>
    		<defaultenabled>no</defaultenabled>
    	</member>
    	<member name="EXTENDED_ODBC_STORAGE" displayname="Storage of Voicemail using ODBC (extended)">
    		<depend>unixodbc</depend>
    		<defaultenabled>no</defaultenabled>
    	</member>
    
    	<member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
    		<depend>imap_tk</depend>
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    		<use>ssl</use>
    
    		<defaultenabled>no</defaultenabled>
    	</member>
    
    #include "asterisk.h"
    
    ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
    
    
    #include <stdlib.h>
    #include <errno.h>
    #include <unistd.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <sys/time.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <sys/mman.h>
    #include <time.h>
    #include <dirent.h>
    
    
    #include "asterisk/lock.h"
    #include "asterisk/file.h"
    #include "asterisk/logger.h"
    #include "asterisk/channel.h"
    #include "asterisk/pbx.h"
    #include "asterisk/options.h"
    #include "asterisk/config.h"
    #include "asterisk/say.h"
    #include "asterisk/module.h"
    #include "asterisk/adsi.h"
    #include "asterisk/app.h"
    #include "asterisk/manager.h"
    #include "asterisk/dsp.h"
    #include "asterisk/localtime.h"
    #include "asterisk/cli.h"
    #include "asterisk/utils.h"
    
    #include "asterisk/stringfields.h"
    
    #include "asterisk/smdi.h"
    #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    #define COMMAND_TIMEOUT 5000
    
    #define	VOICEMAIL_DIR_MODE	0770
    #define	VOICEMAIL_FILE_MODE	0660
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    #define VOICEMAIL_CONFIG "voicemail.conf"
    #define ASTERISK_USERNAME "asterisk"
    
    
    /* Default mail command to mail voicemail. Change it with the
        mailcmd= command in voicemail.conf */
    
    Mark Spencer's avatar
    Mark Spencer committed
    #define SENDMAIL "/usr/sbin/sendmail -t"
    
    #define INTRO "vm-intro"
    
    #define MAXMSG 100
    
    Mark Spencer's avatar
    Mark Spencer committed
    #define BASEMAXINLINE 256
    #define BASELINELEN 72
    #define BASEMAXINLINE 256
    #define eol "\r\n"
    
    
    #define MAX_DATETIME_FORMAT	512
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    #define VM_REVIEW        (1 << 0)
    #define VM_OPERATOR      (1 << 1)
    #define VM_SAYCID        (1 << 2)
    #define VM_SVMAIL        (1 << 3)
    #define VM_ENVELOPE      (1 << 4)
    #define VM_SAYDURATION   (1 << 5)
    #define VM_SKIPAFTERCMD  (1 << 6)
    #define VM_FORCENAME     (1 << 7)   /*!< Have new users record their name */
    #define VM_FORCEGREET    (1 << 8)   /*!< Have new users record their greetings */
    #define VM_PBXSKIP       (1 << 9)
    #define VM_DIRECFORWARD  (1 << 10)  /*!< directory_forward */
    #define VM_ATTACH        (1 << 11)
    #define VM_DELETE        (1 << 12)
    #define VM_ALLOCED       (1 << 13)
    #define VM_SEARCH        (1 << 14)
    #define VM_TEMPGREETWARN (1 << 15)  /*!< Remind user tempgreeting is set */
    #define ERROR_LOCK_PATH  -100
    
    	OPT_SILENT =           (1 << 0),
    	OPT_BUSY_GREETING =    (1 << 1),
    
    	OPT_UNAVAIL_GREETING = (1 << 2),
    
    	OPT_RECORDGAIN =       (1 << 3),
    	OPT_PREPEND_MAILBOX =  (1 << 4),
    	OPT_PRIORITY_JUMP =    (1 << 5),
    
    	OPT_AUTOPLAY =         (1 << 6),
    
    } vm_option_flags;
    
    enum {
    	OPT_ARG_RECORDGAIN = 0,
    
    	OPT_ARG_PLAYFOLDER = 1,
    	/* This *must* be the last value in this enum! */
    	OPT_ARG_ARRAY_SIZE = 2,
    
    } vm_option_args;
    
    AST_APP_OPTIONS(vm_app_options, {
    	AST_APP_OPTION('s', OPT_SILENT),
    	AST_APP_OPTION('b', OPT_BUSY_GREETING),
    	AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
    	AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
    	AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    	AST_APP_OPTION('j', OPT_PRIORITY_JUMP),
    
    	AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
    
    Russell Bryant's avatar
    Russell Bryant committed
    /*! \page vmlang Voicemail Language Syntaxes Supported
    
    	\par Syntaxes supported, not really language codes.
    	\arg \b en - English
    	\arg \b de - German
    	\arg \b es - Spanish
    	\arg \b fr - French
    	\arg \b it = Italian
    	\arg \b nl - Dutch
    
    Russell Bryant's avatar
    Russell Bryant committed
    	\arg \b pt - Portuguese
    	\arg \b gr - Greek
    	\arg \b no - Norwegian
    	\arg \b se - Swedish
    
    
    German requires the following additional soundfile:
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b 1F	einE (feminine)
    
    
    Spanish requires the following additional soundfile:
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b 1M      un (masculine)
    
    
    Dutch, Portuguese & Spanish require the following additional soundfiles:
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b vm-INBOXs	singular of 'new'
    \arg \b vm-Olds		singular of 'old/heard/read'
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b vm-INBOX	nieuwe (nl)
    \arg \b vm-Old		oude (nl)
    
    Polish uses:
    \arg \b vm-new-a	'new', feminine singular accusative
    \arg \b vm-new-e	'new', feminine plural accusative
    \arg \b vm-new-ych	'new', feminine plural genitive
    \arg \b vm-old-a	'old', feminine singular accusative
    \arg \b vm-old-e	'old', feminine plural accusative
    \arg \b vm-old-ych	'old', feminine plural genitive
    \arg \b digits/1-a	'one', not always same as 'digits/1'
    \arg \b digits/2-ie	'two', not always same as 'digits/2'
    
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b vm-nytt		singular of 'new'
    \arg \b vm-nya		plural of 'new'
    \arg \b vm-gammalt	singular of 'old'
    \arg \b vm-gamla	plural of 'old'
    \arg \b digits/ett	'one', not always same as 'digits/1'
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b vm-ny		singular of 'new'
    \arg \b vm-nye		plural of 'new'
    \arg \b vm-gammel	singular of 'old'
    \arg \b vm-gamle	plural of 'old'
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b nl-om		'at'?
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b vm-youhaveno
    
    Italian requires the following additional soundfile:
    
    For vm_intro_it:
    
    Russell Bryant's avatar
    Russell Bryant committed
    \arg \b vm-nuovo	new
    \arg \b vm-nuovi	new plural
    \arg \b vm-vecchio	old
    \arg \b vm-vecchi	old plural
    
    \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
    
    spelled among others when you have to change folder. For the above reasons, vm-INBOX
    and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
    
    struct baseio {
    	int iocp;
    	int iolen;
    	int linelength;
    	int ateof;
    	unsigned char iobuf[BASEMAXINLINE];
    };
    
    
    Russell Bryant's avatar
    Russell Bryant committed
    /*! Structure for linked list of users */
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	char context[AST_MAX_CONTEXT];   /*!< Voicemail context */
    	char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
    	char password[80];               /*!< Secret pin code, numbers only */
    	char fullname[80];               /*!< Full name, for directory app */
    	char email[80];                  /*!< E-mail address */
    	char pager[80];                  /*!< E-mail address to pager (no attachment) */
    	char serveremail[80];            /*!< From: Mail address */
    	char mailcmd[160];               /*!< Configurable mail command */
    	char language[MAX_LANGUAGE];     /*!< Config: Language setting */
    	char zonetag[80];                /*!< Time zone */
    
    	char callback[80];
    	char dialout[80];
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	char uniqueid[20];               /*!< Unique integer identifier */
    
    	char exit[80];
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	char attachfmt[20];              /*!< Attachment format */
    	unsigned int flags;              /*!< VM_ flags */	
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    	int maxmsg;                      /*!< Maximum number of msgs per folder for this mailbox */
    
    	AST_LIST_ENTRY(ast_vm_user) list;
    
    	char name[80];
    	char timezone[80];
    	char msg_format[512];
    };
    
    	char curbox[80];
    	char username[80];
    	char curdir[256];
    	char vmbox[256];
    	char fn[256];
    	char fn2[256];
    
    	int curmsg;
    	int lastmsg;
    	int newmessages;
    	int oldmessages;
    	int starting;
    	int repeats;
    };
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    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);
    
    static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
    
    static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
    			signed char record_gain);
    
    static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
    
    static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
    
    static void apply_options(struct ast_vm_user *vmu, const char *options);
    
    
    static char odbc_database[80];
    
    static char odbc_table[80];
    
    #define RETRIEVE(a,b) retrieve_file(a,b)
    #define DISPOSE(a,b) remove_file(a,b)
    
    #define STORE(a,b,c,d) store_file(a,b,c,d)
    
    #define EXISTS(a,b,c,d) (message_exists(a,b))
    
    #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
    #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
    
    #define DELETE(a,b,c) (delete_file(a,b))
    #else
    #define RETRIEVE(a,b)
    #define DISPOSE(a,b)
    
    #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
    
    #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
    #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
    
    #define DELETE(a,b,c) (vm_delete(c))
    #endif
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static char *tdesc = "Comedian Mail (Voicemail System)";
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static char *addesc = "Comedian Mail";
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static char *synopsis_vm =
    
    "Leave a Voicemail message";
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    static char *descrip_vm =
    
    "  VoiceMail(mailbox[@context][&mailbox[@context]][...][|options]): This\n"
    "application allows the calling party to leave a message for the specified\n"
    "list of mailboxes. When multiple mailboxes are specified, the greeting will\n"
    "be taken from the first mailbox specified. Dialplan execution will stop if the\n"
    "specified mailbox does not exist.\n"
    "  The Voicemail application will exit if any of the following DTMF digits are\n"
    "received:\n"
    "    0 - Jump to the 'o' extension in the current dialplan context.\n"
    "    * - Jump to the 'a' extension in the current dialplan context.\n"
    "  This application will set the following channel variable upon completion:\n"
    "    VMSTATUS - This indicates the status of the execution of the VoiceMail\n"
    "               application. The possible values are:\n"
    "               SUCCESS | USEREXIT | FAILED\n\n"
    "  Options:\n"
    "    b    - Play the 'busy' greeting to the calling party.\n"
    "    g(#) - Use the specified amount of gain when recording the voicemail\n"
    "           message. The units are whole-number decibels (dB).\n"
    "    s    - Skip the playback of instructions for leaving a message to the\n"
    "           calling party.\n"
    
    "    u    - Play the 'unavailable greeting.\n"
    
    "    j    - Jump to priority n+101 if the mailbox is not found or some other\n"
    "           error occurs.\n";
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    static char *synopsis_vmain =
    
    "Check Voicemail messages";
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    static char *descrip_vmain =
    
    "  VoiceMailMain([mailbox][@context][|options]): This application allows the\n"
    "calling party to check voicemail messages. A specific mailbox, and optional\n"
    "corresponding context, may be specified. If a mailbox is not provided, the\n"
    "calling party will be prompted to enter one. If a context is not specified,\n"
    "the 'default' context will be used.\n\n"
    "  Options:\n"
    "    p    - Consider the mailbox parameter as a prefix to the mailbox that\n"
    "           is entered by the caller.\n"
    "    g(#) - Use the specified amount of gain when recording a voicemail\n"
    "           message. The units are whole-number decibels (dB).\n"
    
    "    s    - Skip checking the passcode for the mailbox.\n"
    
    "    a(#) - Skip folder prompt and go directly to folder specified.\n"
    
    "           Defaults to INBOX\n";
    
    static char *synopsis_vm_box_exists =
    
    "Check to see if Voicemail mailbox exists";
    
    "  MailboxExists(mailbox[@context][|options]): Check to see if the specified\n"
    "mailbox exists. If no voicemail context is specified, the 'default' context\n"
    "will be used.\n"
    "  This application will set the following channel variable upon completion:\n"
    "    VMBOXEXISTSSTATUS - This will contain the status of the execution of the\n"
    "                        MailboxExists application. Possible values include:\n"
    "                        SUCCESS | FAILED\n\n"
    "  Options:\n"
    "    j - Jump to priority n+101 if the mailbox is found.\n";
    
    static char *synopsis_vmauthenticate =
    
    "Authenticate with Voicemail passwords";
    
    
    static char *descrip_vmauthenticate =
    
    "  VMAuthenticate([mailbox][@context][|options]): This application behaves the\n"
    "same way as the Authenticate application, but the passwords are taken from\n"
    "voicemail.conf.\n"
    
    "  If the mailbox is specified, only that mailbox's password will be considered\n"
    "valid. If the mailbox is not specified, the channel variable AUTH_MAILBOX will\n"
    
    "be set with the authenticated mailbox.\n\n"
    "  Options:\n"
    "    s - Skip playing the initial prompts.\n";
    
    Mark Spencer's avatar
    Mark Spencer committed
    /* Leave a message */
    static char *app = "VoiceMail";
    
    /* Check mail, control, etc */
    static char *app2 = "VoiceMailMain";
    
    
    static char *app4 = "VMAuthenticate";
    
    static AST_LIST_HEAD_STATIC(users, ast_vm_user);
    
    static int silencethreshold = 128;
    static char serveremail[80];
    
    static char mailcmd[160];	/* Configurable mail cmd */
    static char externnotify[160]; 
    
    static struct ast_smdi_interface *smdi_iface = NULL;
    
    static int vmmaxmessage;
    static int maxgreet;
    static int skipms;
    static int maxlogins;
    
    
    static struct ast_flags globalflags = {0};
    
    
    static int saydurationminfo;
    
    static char dialcontext[AST_MAX_CONTEXT];
    static char callcontext[AST_MAX_CONTEXT];
    static char exitcontext[AST_MAX_CONTEXT];
    
    
    static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
    
    
    
    static char *emailsubject = NULL;
    
    static char *pagerbody = NULL;
    static char *pagersubject = NULL;
    
    static char charset[32] = "ISO-8859-1";
    
    static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
    static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
    
    static int adsiver = 1;
    
    static char emaildateformat[32] = "%A, %B %d, %Y at %r";
    
    Mark Spencer's avatar
    Mark Spencer committed
    LOCAL_USER_DECL;
    
    
    static void populate_defaults(struct ast_vm_user *vmu)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);	
    
    		vmu->saydurationm = saydurationminfo;
    
    	if (callcontext)
    
    		ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
    
    	if (dialcontext)
    
    		ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
    
    	if (exitcontext)
    
    		ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
    
    Mark Spencer's avatar
    Mark Spencer committed
    static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (!strcasecmp(var, "attach")) {
    
    		ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
    	} else if (!strcasecmp(var, "attachfmt")) {
    		ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "serveremail")) {
    
    		ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "language")) {
    
    		ast_copy_string(vmu->language, value, sizeof(vmu->language));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "tz")) {
    
    		ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
    
    	} else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
    
    		ast_set2_flag(vmu, ast_true(value), VM_DELETE);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "saycid")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_SAYCID);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var,"sendvoicemail")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "review")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
    	} else if (!strcasecmp(var, "tempgreetwarn")){
    		ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "operator")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "envelope")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);	
    
    	} else if (!strcasecmp(var, "sayduration")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);	
    
    	} else if (!strcasecmp(var, "saydurationm")){
    		if (sscanf(value, "%d", &x) == 1) {
    			vmu->saydurationm = x;
    		} else {
    			ast_log(LOG_WARNING, "Invalid min duration for say duration\n");
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "forcename")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "forcegreetings")){
    
    		ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);	
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "callback")) {
    
    		ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "dialout")) {
    
    		ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else if (!strcasecmp(var, "exitcontext")) {
    
    		ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
    
    	} else if (!strcasecmp(var, "maxmsg")) {
    		vmu->maxmsg = atoi(value);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (vmu->maxmsg <= 0) {
    
    			ast_log(LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %i\n", value, MAXMSG);
    			vmu->maxmsg = MAXMSG;
    		} else if (vmu->maxmsg > MAXMSGLIMIT) {
    			ast_log(LOG_WARNING, "Maximum number of messages per folder is %i. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
    			vmu->maxmsg = MAXMSGLIMIT;
    		}
    
    	} else if (!strcasecmp(var, "options")) {
    		apply_options(vmu, value);
    
    Mark Spencer's avatar
    Mark Spencer committed
    }
    
    Mark Spencer's avatar
    Mark Spencer committed
    static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int res;
    	if (!ast_strlen_zero(vmu->uniqueid)) {
    
    		res = ast_update_realtime("voicemail", "uniqueid", vmu->uniqueid, "password", password, NULL);
    
    			ast_copy_string(vmu->password, password, sizeof(vmu->password));
    
    Mark Spencer's avatar
    Mark Spencer committed
    		return res;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	return -1;
    
    Mark Spencer's avatar
    Mark Spencer committed
    static void apply_options(struct ast_vm_user *vmu, const char *options)
    {	/* Destructively Parse options and apply */
    	char *stringp;
    	char *s;
    	char *var, *value;
    	stringp = ast_strdupa(options);
    	while ((s = strsep(&stringp, "|"))) {
    		value = s;
    		if ((var = strsep(&value, "=")) && value) {
    			apply_option(vmu, var, value);
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct ast_variable *var, *tmp;
    
    	if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if (!ivm)
    
    			ast_set_flag(retval, VM_ALLOCED);	
    
    		else
    			memset(retval, 0, sizeof(*retval));
    
    			ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
    
    		populate_defaults(retval);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (!context && ast_test_flag((&globalflags), VM_SEARCH))
    
    			var = ast_load_realtime("voicemail", "mailbox", mailbox, NULL);
    		else
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, NULL);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if (var) {
    			tmp = var;
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			while (tmp) {
    
    Mark Spencer's avatar
    Mark Spencer committed
    				printf("%s => %s\n", tmp->name, tmp->value);
    				if (!strcasecmp(tmp->name, "password")) {
    
    					ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
    
    Mark Spencer's avatar
    Mark Spencer committed
    				} else if (!strcasecmp(tmp->name, "uniqueid")) {
    
    					ast_copy_string(retval->uniqueid, tmp->value, sizeof(retval->uniqueid));
    
    				} else if (!strcasecmp(tmp->name, "pager")) {
    
    					ast_copy_string(retval->pager, tmp->value, sizeof(retval->pager));
    
    				} else if (!strcasecmp(tmp->name, "email")) {
    
    					ast_copy_string(retval->email, tmp->value, sizeof(retval->email));
    
    				} else if (!strcasecmp(tmp->name, "fullname")) {
    
    					ast_copy_string(retval->fullname, tmp->value, sizeof(retval->fullname));
    
    				} else if (!strcasecmp(tmp->name, "context")) {
    					ast_copy_string(retval->context, tmp->value, sizeof(retval->context));
    
    Mark Spencer's avatar
    Mark Spencer committed
    				} else
    					apply_option(retval, tmp->name, tmp->value);
    				tmp = tmp->next;
    			} 
    
    			ast_variables_destroy(var);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		} else { 
    			if (!ivm) 
    
    Mark Spencer's avatar
    Mark Spencer committed
    			retval = NULL;
    		}	
    	} 
    	return retval;
    
    Mark Spencer's avatar
    Mark Spencer committed
    static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
    
    {
    	/* This function could be made to generate one from a database, too */
    	struct ast_vm_user *vmu=NULL, *cur;
    
    	AST_LIST_LOCK(&users);
    
    Josh Roberson's avatar
    Josh Roberson committed
    
    
    	if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
    
    Josh Roberson's avatar
    Josh Roberson committed
    		context = "default";
    
    
    	AST_LIST_TRAVERSE(&users, cur, list) {
    
    		if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
    			break;
    
    		if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
    
    		/* Make a copy, so that on a reload, we have no race */
    		if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
    
    			memcpy(vmu, cur, sizeof(*vmu));
    
    			ast_set2_flag(vmu, !ivm, VM_ALLOCED);
    			AST_LIST_NEXT(vmu, list) = NULL;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	} else
    		vmu = find_user_realtime(ivm, context, mailbox);
    
    	AST_LIST_UNLOCK(&users);
    
    Mark Spencer's avatar
    Mark Spencer committed
    static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
    
    {
    	/* This function could be made to generate one from a database, too */
    	struct ast_vm_user *cur;
    	int res = -1;
    
    	AST_LIST_LOCK(&users);
    	AST_LIST_TRAVERSE(&users, cur, list) {
    
    		if ((!context || !strcasecmp(context, cur->context)) &&
    			(!strcasecmp(mailbox, cur->mailbox)))
    				break;
    	}
    	if (cur) {
    
    		ast_copy_string(cur->password, newpass, sizeof(cur->password));
    
    	AST_LIST_UNLOCK(&users);
    
    Mark Spencer's avatar
    Mark Spencer committed
    static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
    
    Mark Spencer's avatar
    Mark Spencer committed
    {
    
    	/*  There's probably a better way of doing this. */
    	/*  That's why I've put the password change in a separate function. */
    	/*  This could also be done with a database function */
    
    	FILE *configin;
    	FILE *configout;
    	int linenum=0;
    	char inbuf[256];
    	char orig[256];
    	char currcontext[256] ="";
    
    	char tmpin[PATH_MAX];
    	char tmpout[PATH_MAX];
    
    	struct stat statbuf;
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (!change_password_realtime(vmu, newpassword))
    		return;
    
    
    	snprintf(tmpin, sizeof(tmpin), "%s/voicemail.conf", ast_config_AST_CONFIG_DIR);
    	snprintf(tmpout, sizeof(tmpout), "%s/voicemail.conf.new", ast_config_AST_CONFIG_DIR);
    	configin = fopen(tmpin,"r");
    	if (configin)
    		configout = fopen(tmpout,"w+");
    	else
    		configout = NULL;
    	if (!configin || !configout) {
    
    			fclose(configin);
    
    			ast_log(LOG_WARNING, "Warning: Unable to open '%s' for reading: %s\n", tmpin, strerror(errno));
    		if (configout)
    			fclose(configout);
    		else
    			ast_log(LOG_WARNING, "Warning: Unable to open '%s' for writing: %s\n", tmpout, strerror(errno));
    
    	while (!feof(configin)) {
    
    		char *user = NULL, *pass = NULL, *rest = NULL, *comment = NULL, *tmpctx = NULL, *tmpctxend = NULL;
    
    
    		/* Read in the line */
    
    		if (fgets(inbuf, sizeof(inbuf), configin) == NULL)
    
    
    		/* Make a backup of it */
    		ast_copy_string(orig, inbuf, sizeof(orig));
    
    		/*
    		  Read the file line by line, split each line into a comment and command section
    		  only parse the command portion of the line
    		*/
    		if (inbuf[strlen(inbuf) - 1] == '\n')
    			inbuf[strlen(inbuf) - 1] = '\0';
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    
    
    		if ((comment = strchr(inbuf, ';')))
    			*comment++ = '\0'; /* Now inbuf is terminated just before the comment */
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    
    
    		if (ast_strlen_zero(inbuf)) {
    			fprintf(configout, "%s", orig);
    			continue;
    		}
    
    		/* Check for a context, first '[' to first ']' */
    		if ((tmpctx = strchr(inbuf, '['))) {
    			tmpctxend = strchr(tmpctx, ']');
    			if (tmpctxend) {
    				/* Valid context */
    				ast_copy_string(currcontext, tmpctx + 1, tmpctxend - tmpctx);
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    				fprintf(configout, "%s", orig);
    				continue;
    
    		}
    
    		/* This isn't a context line, check for MBX => PSWD... */
    		user = inbuf;
    		if ((pass = strchr(user, '='))) {
    			/* We have a line in the form of aaaaa=aaaaaa */
    			*pass++ = '\0';
    
    			user = ast_strip(user);
    
    			if (*pass == '>')
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    				*pass++ = '\0';
    
    
    			pass = ast_skip_blanks(pass);
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    
    
    			/* 
    			   Since no whitespace allowed in fields, or more correctly white space
    			   inside the fields is there for a purpose, we can just terminate pass
    			   at the comma or EOL whichever comes first.
    			*/
    			if ((rest = strchr(pass, ',')))
    				*rest++ = '\0';
    		} else {
    			user = NULL;
    		}			
    
    		/* Compare user, pass AND context */
    		if (!ast_strlen_zero(user) && !strcmp(user, vmu->mailbox) &&
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    			!ast_strlen_zero(pass) && !strcmp(pass, vmu->password) &&
    			!strcasecmp(currcontext, vmu->context)) {
    
    			/* This is the line */
    			if (rest) {
    				fprintf(configout, "%s => %s,%s", user, newpassword, rest);
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    			} else {
    
    				fprintf(configout, "%s => %s", user, newpassword);
    			}
    			/* If there was a comment on the line print it out */
    			if (comment) {
    				fprintf(configout, ";%s\n", comment);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			}
    
    		} else {
    			/* Put it back like it was */
    			fprintf(configout, "%s", orig);
    
    		}
    	}
    	fclose(configin);
    	fclose(configout);
    
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    	stat(tmpin, &statbuf);
    	chmod(tmpout, statbuf.st_mode);
    	chown(tmpout, statbuf.st_uid, statbuf.st_gid);
    	unlink(tmpin);
    	rename(tmpout, tmpin);
    
    	reset_user_pw(vmu->context, vmu->mailbox, newpassword);
    
    	ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
    
    static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
    {
    
    	char buf[255];
    	snprintf(buf,255,"%s %s %s %s",ext_pass_cmd,vmu->context,vmu->mailbox,newpassword);
    
    	if (!ast_safe_system(buf)) {
    		reset_user_pw(vmu->context, vmu->mailbox, newpassword);
    
    		ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
    
    static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
    
    	return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
    
    }
    
    static int make_file(char *dest, int len, char *dir, int num)
    {
    	return snprintf(dest, len, "%s/msg%04d", dir, num);
    
    /*! \brief basically mkdir -p $dest/$context/$ext/$folder
    
     * \param dest    String. base directory.
     * \param context String. Ignored if is null or empty string.
     * \param ext     String. Ignored if is null or empty string.
    
     * \param folder  String. Ignored if is null or empty string. 
    
     * \return 0 on failure, 1 on success.
     */
    
    static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
    
    {
    	mode_t	mode = VOICEMAIL_DIR_MODE;
    
    
    		make_dir(dest, len, context, "", "");
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (mkdir(dest, mode) && errno != EEXIST) {
    
    			ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dest, strerror(errno));
    			return 0;
    		}
    	}
    
    		make_dir(dest, len, context, ext, "");
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (mkdir(dest, mode) && errno != EEXIST) {
    
    			ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dest, strerror(errno));
    			return 0;
    		}
    	}
    
    	if (!ast_strlen_zero(folder)) {
    		make_dir(dest, len, context, ext, folder);
    
    Tilghman Lesher's avatar
    Tilghman Lesher committed
    		if (mkdir(dest, mode) && errno != EEXIST) {
    
    			ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dest, strerror(errno));
    			return 0;
    		}
    	}
    	return 1;
    }
    
    
    /* only return failure if ast_lock_path returns 'timeout',
       not if the path does not exist or any other reason
    */
    static int vm_lock_path(const char *path)
    {
    	switch (ast_lock_path(path)) {
    	case AST_LOCK_TIMEOUT:
    		return -1;
    	default:
    		return 0;
    	}
    }
    
    
    static int retrieve_file(char *dir, int msgnum)
    {
    	int x = 0;
    	int res;
    	int fd=-1;
    	size_t fdlen = 0;
    	void *fdm=NULL;
    	SQLSMALLINT colcount=0;
    	SQLHSTMT stmt;
    	char sql[256];
    	char fmt[80]="";
    	char *c;
    	char coltitle[256];
    	SQLSMALLINT collen;
    	SQLSMALLINT datatype;
    	SQLSMALLINT decimaldigits;
    	SQLSMALLINT nullable;
    	SQLULEN colsize;
    	FILE *f=NULL;
    	char rowdata[80];
    
    	char fn[256];
    	char full_fn[256];
    	char msgnums[80];
    
    	struct odbc_obj *obj;
    	obj = odbc_request_obj(odbc_database, 0);
    
    		ast_copy_string(fmt, vmfmts, sizeof(fmt));
    
    		c = strchr(fmt, '|');
    		if (c)
    			*c = '\0';
    		if (!strcasecmp(fmt, "wav49"))
    
    			strcpy(fmt, "WAV");
    
    		snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
    		if (msgnum > -1)
    			make_file(fn, sizeof(fn), dir, msgnum);
    		else
    
    			ast_copy_string(fn, dir, sizeof(fn));
    
    		snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
    		f = fopen(full_fn, "w+");
    		snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
    		res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
    		if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    			ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
    
    		snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?",odbc_table);
    
    		res = SQLPrepare(stmt, sql, SQL_NTS);
    		if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    			ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
    			SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    			goto yuck;
    		}
    		SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dir), 0, (void *)dir, 0, NULL);
    		SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
    
    		res = odbc_smart_execute(obj, stmt);
    
    		if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    			ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
    			SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    		res = SQLFetch(stmt);
    		if (res == SQL_NO_DATA) {
    
    			SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    		else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    			ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
    			SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    		fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, 0770);
    
    		if (fd < 0) {
    			ast_log(LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
    			SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    			goto yuck;
    		}
    		res = SQLNumResultCols(stmt, &colcount);
    		if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {	
    			ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
    			SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    			goto yuck;
    		}
    		if (f) 
    			fprintf(f, "[message]\n");
    		for (x=0;x<colcount;x++) {
    			rowdata[0] = '\0';
    			collen = sizeof(coltitle);
    			res = SQLDescribeCol(stmt, x + 1, coltitle, sizeof(coltitle), &collen, 
    						&datatype, &colsize, &decimaldigits, &nullable);
    
    			if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    
    				ast_log(LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
    
    				SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    			if (!strcasecmp(coltitle, "recording")) {
    				res = SQLGetData(stmt, x + 1, SQL_BINARY, NULL, 0, &colsize);
    				fdlen = colsize;
    				if (fd > -1) {
    					char tmp[1]="";
    					lseek(fd, fdlen - 1, SEEK_SET);
    					if (write(fd, tmp, 1) != 1) {
    						close(fd);
    						fd = -1;
    
    					if (fd > -1)
    						fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    				}
    				if (fdm) {
    					memset(fdm, 0, fdlen);
    					res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, fdlen, &colsize);
    
    					if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    						ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
    						SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    			} else {
    				res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
    				if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
    					ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
    					SQLFreeHandle (SQL_HANDLE_STMT, stmt);
    
    					goto yuck;
    				}
    				if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
    					fprintf(f, "%s=%s\n", coltitle, rowdata);