2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \author Mark Spencer <markster@digium.com>
22 * \brief Comedian Mail - Voicemail System
24 * \extref unixODBC (http://www.unixodbc.org/)
25 * \extref A source distribution of University of Washington's IMAP c-client
26 * (http://www.washington.edu/imap/)
30 * \note For information about voicemail IMAP storage, https://wiki.asterisk.org/wiki/display/AST/IMAP+Voicemail+Storage
31 * \ingroup applications
32 * \note This module requires res_adsi to load. This needs to be optional
35 * \note This file is now almost impossible to work with, due to all \#ifdefs.
36 * Feels like the database code before realtime. Someone - please come up
37 * with a plan to clean this up.
46 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" touch_on_change="apps/app_voicemail.c apps/app_directory.c">
47 <member name="FILE_STORAGE" displayname="Storage of Voicemail using filesystem">
48 <conflict>ODBC_STORAGE</conflict>
49 <conflict>IMAP_STORAGE</conflict>
50 <defaultenabled>yes</defaultenabled>
52 <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
53 <depend>generic_odbc</depend>
55 <conflict>IMAP_STORAGE</conflict>
56 <conflict>FILE_STORAGE</conflict>
57 <defaultenabled>no</defaultenabled>
59 <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
60 <depend>imap_tk</depend>
61 <conflict>ODBC_STORAGE</conflict>
62 <conflict>FILE_STORAGE</conflict>
64 <defaultenabled>no</defaultenabled>
75 #ifdef USE_SYSTEM_IMAP
76 #include <imap/c-client.h>
77 #include <imap/imap4r1.h>
78 #include <imap/linkage.h>
79 #elif defined (USE_SYSTEM_CCLIENT)
80 #include <c-client/c-client.h>
81 #include <c-client/imap4r1.h>
82 #include <c-client/linkage.h>
90 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
92 #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR */
98 #if defined(__FreeBSD__) || defined(__OpenBSD__)
102 #include "asterisk/logger.h"
103 #include "asterisk/lock.h"
104 #include "asterisk/file.h"
105 #include "asterisk/channel.h"
106 #include "asterisk/pbx.h"
107 #include "asterisk/config.h"
108 #include "asterisk/say.h"
109 #include "asterisk/module.h"
110 #include "asterisk/adsi.h"
111 #include "asterisk/app.h"
112 #include "asterisk/manager.h"
113 #include "asterisk/dsp.h"
114 #include "asterisk/localtime.h"
115 #include "asterisk/cli.h"
116 #include "asterisk/utils.h"
117 #include "asterisk/stringfields.h"
118 #include "asterisk/smdi.h"
119 #include "asterisk/astobj2.h"
120 #include "asterisk/event.h"
121 #include "asterisk/taskprocessor.h"
122 #include "asterisk/test.h"
125 #include "asterisk/res_odbc.h"
129 #include "asterisk/threadstorage.h"
133 <application name="VoiceMail" language="en_US">
135 Leave a Voicemail message.
138 <parameter name="mailboxs" argsep="&" required="true">
139 <argument name="mailbox1" argsep="@" required="true">
140 <argument name="mailbox" required="true" />
141 <argument name="context" />
143 <argument name="mailbox2" argsep="@" multiple="true">
144 <argument name="mailbox" required="true" />
145 <argument name="context" />
148 <parameter name="options">
151 <para>Play the <literal>busy</literal> greeting to the calling party.</para>
154 <argument name="c" />
155 <para>Accept digits for a new extension in context <replaceable>c</replaceable>,
156 if played during the greeting. Context defaults to the current context.</para>
159 <argument name="#" required="true" />
160 <para>Use the specified amount of gain when recording the voicemail
161 message. The units are whole-number decibels (dB). Only works on supported
162 technologies, which is DAHDI only.</para>
165 <para>Skip the playback of instructions for leaving a message to the
166 calling party.</para>
169 <para>Play the <literal>unavailable</literal> greeting.</para>
172 <para>Mark message as <literal>URGENT</literal>.</para>
175 <para>Mark message as <literal>PRIORITY</literal>.</para>
181 <para>This application allows the calling party to leave a message for the specified
182 list of mailboxes. When multiple mailboxes are specified, the greeting will be taken from
183 the first mailbox specified. Dialplan execution will stop if the specified mailbox does not
185 <para>The Voicemail application will exit if any of the following DTMF digits are received:</para>
188 <para>Jump to the <literal>o</literal> extension in the current dialplan context.</para>
191 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
194 <para>This application will set the following channel variable upon completion:</para>
196 <variable name="VMSTATUS">
197 <para>This indicates the status of the execution of the VoiceMail application.</para>
198 <value name="SUCCESS" />
199 <value name="USEREXIT" />
200 <value name="FAILED" />
205 <ref type="application">VoiceMailMain</ref>
208 <application name="VoiceMailMain" language="en_US">
210 Check Voicemail messages.
213 <parameter name="mailbox" required="true" argsep="@">
214 <argument name="mailbox" />
215 <argument name="context" />
217 <parameter name="options">
220 <para>Consider the <replaceable>mailbox</replaceable> parameter as a prefix to
221 the mailbox that is entered by the caller.</para>
224 <argument name="#" required="true" />
225 <para>Use the specified amount of gain when recording a voicemail message.
226 The units are whole-number decibels (dB).</para>
229 <para>Skip checking the passcode for the mailbox.</para>
232 <argument name="folder" required="true" />
233 <para>Skip folder prompt and go directly to <replaceable>folder</replaceable> specified.
234 Defaults to <literal>INBOX</literal> (or <literal>0</literal>).</para>
236 <enum name="0"><para>INBOX</para></enum>
237 <enum name="1"><para>Old</para></enum>
238 <enum name="2"><para>Work</para></enum>
239 <enum name="3"><para>Family</para></enum>
240 <enum name="4"><para>Friends</para></enum>
241 <enum name="5"><para>Cust1</para></enum>
242 <enum name="6"><para>Cust2</para></enum>
243 <enum name="7"><para>Cust3</para></enum>
244 <enum name="8"><para>Cust4</para></enum>
245 <enum name="9"><para>Cust5</para></enum>
252 <para>This application allows the calling party to check voicemail messages. A specific
253 <replaceable>mailbox</replaceable>, and optional corresponding <replaceable>context</replaceable>,
254 may be specified. If a <replaceable>mailbox</replaceable> is not provided, the calling party will
255 be prompted to enter one. If a <replaceable>context</replaceable> is not specified, the
256 <literal>default</literal> context will be used.</para>
257 <para>The VoiceMailMain application will exit if the following DTMF digit is entered as Mailbox
258 or Password, and the extension exists:</para>
261 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
266 <ref type="application">VoiceMail</ref>
269 <application name="MailboxExists" language="en_US">
271 Check to see if Voicemail mailbox exists.
274 <parameter name="mailbox" required="true" argsep="@">
275 <argument name="mailbox" required="true" />
276 <argument name="context" />
278 <parameter name="options">
279 <para>None options.</para>
283 <para>Check to see if the specified <replaceable>mailbox</replaceable> exists. If no voicemail
284 <replaceable>context</replaceable> is specified, the <literal>default</literal> context
286 <para>This application will set the following channel variable upon completion:</para>
288 <variable name="VMBOXEXISTSSTATUS">
289 <para>This will contain the status of the execution of the MailboxExists application.
290 Possible values include:</para>
291 <value name="SUCCESS" />
292 <value name="FAILED" />
297 <application name="VMAuthenticate" language="en_US">
299 Authenticate with Voicemail passwords.
302 <parameter name="mailbox" required="true" argsep="@">
303 <argument name="mailbox" />
304 <argument name="context" />
306 <parameter name="options">
309 <para>Skip playing the initial prompts.</para>
315 <para>This application behaves the same way as the Authenticate application, but the passwords
316 are taken from <filename>voicemail.conf</filename>. If the <replaceable>mailbox</replaceable> is
317 specified, only that mailbox's password will be considered valid. If the <replaceable>mailbox</replaceable>
318 is not specified, the channel variable <variable>AUTH_MAILBOX</variable> will be set with the authenticated
320 <para>The VMAuthenticate application will exit if the following DTMF digit is entered as Mailbox
321 or Password, and the extension exists:</para>
324 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
329 <application name="VMSayName" language="en_US">
331 Play the name of a voicemail user
334 <parameter name="mailbox" required="true" argsep="@">
335 <argument name="mailbox" />
336 <argument name="context" />
340 <para>This application will say the recorded name of the voicemail user specified as the
341 argument to this application. If no context is provided, <literal>default</literal> is assumed.</para>
344 <function name="MAILBOX_EXISTS" language="en_US">
346 Tell if a mailbox is configured.
349 <parameter name="mailbox" required="true" />
350 <parameter name="context" />
353 <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.
354 If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
358 <manager name="VoicemailUsersList" language="en_US">
360 List All Voicemail User Information.
363 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
371 static char imapserver[48];
372 static char imapport[8];
373 static char imapflags[128];
374 static char imapfolder[64];
375 static char imapparentfolder[64] = "\0";
376 static char greetingfolder[64];
377 static char authuser[32];
378 static char authpassword[42];
379 static int imapversion = 1;
381 static int expungeonhangup = 1;
382 static int imapgreetings = 0;
383 static char delimiter = '\0';
388 AST_THREADSTORAGE(ts_vmstate);
390 /* Forward declarations for IMAP */
391 static int init_mailstream(struct vm_state *vms, int box);
392 static void write_file(char *filename, char *buffer, unsigned long len);
393 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
394 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu);
395 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
396 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive);
397 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
398 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
399 static void vmstate_insert(struct vm_state *vms);
400 static void vmstate_delete(struct vm_state *vms);
401 static void set_update(MAILSTREAM * stream);
402 static void init_vm_state(struct vm_state *vms);
403 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
404 static void get_mailbox_delimiter(MAILSTREAM *stream);
405 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
406 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
407 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);
408 static void update_messages_by_imapuser(const char *user, unsigned long number);
409 static int vm_delete(char *file);
411 static int imap_remove_file (char *dir, int msgnum);
412 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
413 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
414 static void check_quota(struct vm_state *vms, char *mailbox);
415 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
417 struct vm_state *vms;
418 AST_LIST_ENTRY(vmstate) list;
421 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
425 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
427 #define COMMAND_TIMEOUT 5000
428 /* Don't modify these here; set your umask at runtime instead */
429 #define VOICEMAIL_DIR_MODE 0777
430 #define VOICEMAIL_FILE_MODE 0666
431 #define CHUNKSIZE 65536
433 #define VOICEMAIL_CONFIG "voicemail.conf"
434 #define ASTERISK_USERNAME "asterisk"
436 /* Define fast-forward, pause, restart, and reverse keys
437 while listening to a voicemail message - these are
438 strings, not characters */
439 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
440 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
441 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
442 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
443 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
444 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
446 /* Default mail command to mail voicemail. Change it with the
447 mailcmd= command in voicemail.conf */
448 #define SENDMAIL "/usr/sbin/sendmail -t"
450 #define INTRO "vm-intro"
453 #define MAXMSGLIMIT 9999
455 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
457 #define BASELINELEN 72
458 #define BASEMAXINLINE 256
465 #define MAX_DATETIME_FORMAT 512
466 #define MAX_NUM_CID_CONTEXTS 10
468 #define VM_REVIEW (1 << 0) /*!< After recording, permit the caller to review the recording before saving */
469 #define VM_OPERATOR (1 << 1) /*!< Allow 0 to be pressed to go to 'o' extension */
470 #define VM_SAYCID (1 << 2) /*!< Repeat the CallerID info during envelope playback */
471 #define VM_SVMAIL (1 << 3) /*!< Allow the user to compose a new VM from within VoicemailMain */
472 #define VM_ENVELOPE (1 << 4) /*!< Play the envelope information (who-from, time received, etc.) */
473 #define VM_SAYDURATION (1 << 5) /*!< Play the length of the message during envelope playback */
474 #define VM_SKIPAFTERCMD (1 << 6) /*!< After deletion, assume caller wants to go to the next message */
475 #define VM_FORCENAME (1 << 7) /*!< Have new users record their name */
476 #define VM_FORCEGREET (1 << 8) /*!< Have new users record their greetings */
477 #define VM_PBXSKIP (1 << 9) /*!< Skip the [PBX] preamble in the Subject line of emails */
478 #define VM_DIRECFORWARD (1 << 10) /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
479 #define VM_ATTACH (1 << 11) /*!< Attach message to voicemail notifications? */
480 #define VM_DELETE (1 << 12) /*!< Delete message after sending notification */
481 #define VM_ALLOCED (1 << 13) /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
482 #define VM_SEARCH (1 << 14) /*!< Search all contexts for a matching mailbox */
483 #define VM_TEMPGREETWARN (1 << 15) /*!< Remind user tempgreeting is set */
484 #define VM_MOVEHEARD (1 << 16) /*!< Move a "heard" message to Old after listening to it */
485 #define VM_MESSAGEWRAP (1 << 17) /*!< Wrap around from the last message to the first, and vice-versa */
486 #define VM_FWDURGAUTO (1 << 18) /*!< Autoset of Urgent flag on forwarded Urgent messages set globally */
487 #define ERROR_LOCK_PATH -100
488 #define OPERATOR_EXIT 300
500 enum vm_option_flags {
501 OPT_SILENT = (1 << 0),
502 OPT_BUSY_GREETING = (1 << 1),
503 OPT_UNAVAIL_GREETING = (1 << 2),
504 OPT_RECORDGAIN = (1 << 3),
505 OPT_PREPEND_MAILBOX = (1 << 4),
506 OPT_AUTOPLAY = (1 << 6),
507 OPT_DTMFEXIT = (1 << 7),
508 OPT_MESSAGE_Urgent = (1 << 8),
509 OPT_MESSAGE_PRIORITY = (1 << 9)
512 enum vm_option_args {
513 OPT_ARG_RECORDGAIN = 0,
514 OPT_ARG_PLAYFOLDER = 1,
515 OPT_ARG_DTMFEXIT = 2,
516 /* This *must* be the last value in this enum! */
517 OPT_ARG_ARRAY_SIZE = 3,
520 enum vm_passwordlocation {
521 OPT_PWLOC_VOICEMAILCONF = 0,
522 OPT_PWLOC_SPOOLDIR = 1,
523 OPT_PWLOC_USERSCONF = 2,
526 AST_APP_OPTIONS(vm_app_options, {
527 AST_APP_OPTION('s', OPT_SILENT),
528 AST_APP_OPTION('b', OPT_BUSY_GREETING),
529 AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
530 AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
531 AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
532 AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
533 AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
534 AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
535 AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY)
538 static int load_config(int reload);
540 /*! \page vmlang Voicemail Language Syntaxes Supported
542 \par Syntaxes supported, not really language codes.
549 \arg \b pt - Portuguese
550 \arg \b pt_BR - Portuguese (Brazil)
552 \arg \b no - Norwegian
554 \arg \b tw - Chinese (Taiwan)
555 \arg \b ua - Ukrainian
557 German requires the following additional soundfile:
558 \arg \b 1F einE (feminine)
560 Spanish requires the following additional soundfile:
561 \arg \b 1M un (masculine)
563 Dutch, Portuguese & Spanish require the following additional soundfiles:
564 \arg \b vm-INBOXs singular of 'new'
565 \arg \b vm-Olds singular of 'old/heard/read'
568 \arg \b vm-INBOX nieuwe (nl)
569 \arg \b vm-Old oude (nl)
572 \arg \b vm-new-a 'new', feminine singular accusative
573 \arg \b vm-new-e 'new', feminine plural accusative
574 \arg \b vm-new-ych 'new', feminine plural genitive
575 \arg \b vm-old-a 'old', feminine singular accusative
576 \arg \b vm-old-e 'old', feminine plural accusative
577 \arg \b vm-old-ych 'old', feminine plural genitive
578 \arg \b digits/1-a 'one', not always same as 'digits/1'
579 \arg \b digits/2-ie 'two', not always same as 'digits/2'
582 \arg \b vm-nytt singular of 'new'
583 \arg \b vm-nya plural of 'new'
584 \arg \b vm-gammalt singular of 'old'
585 \arg \b vm-gamla plural of 'old'
586 \arg \b digits/ett 'one', not always same as 'digits/1'
589 \arg \b vm-ny singular of 'new'
590 \arg \b vm-nye plural of 'new'
591 \arg \b vm-gammel singular of 'old'
592 \arg \b vm-gamle plural of 'old'
600 Italian requires the following additional soundfile:
604 \arg \b vm-nuovi new plural
605 \arg \b vm-vecchio old
606 \arg \b vm-vecchi old plural
608 Chinese (Taiwan) requires the following additional soundfile:
609 \arg \b vm-tong A class-word for call (tong1)
610 \arg \b vm-ri A class-word for day (ri4)
611 \arg \b vm-you You (ni3)
612 \arg \b vm-haveno Have no (mei2 you3)
613 \arg \b vm-have Have (you3)
614 \arg \b vm-listen To listen (yao4 ting1)
617 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
618 spelled among others when you have to change folder. For the above reasons, vm-INBOX
619 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
628 unsigned char iobuf[BASEMAXINLINE];
631 /*! Structure for linked list of users
632 * Use ast_vm_user_destroy() to free one of these structures. */
634 char context[AST_MAX_CONTEXT]; /*!< Voicemail context */
635 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
636 char password[80]; /*!< Secret pin code, numbers only */
637 char fullname[80]; /*!< Full name, for directory app */
638 char email[80]; /*!< E-mail address */
639 char *emailsubject; /*!< E-mail subject */
640 char *emailbody; /*!< E-mail body */
641 char pager[80]; /*!< E-mail address to pager (no attachment) */
642 char serveremail[80]; /*!< From: Mail address */
643 char mailcmd[160]; /*!< Configurable mail command */
644 char language[MAX_LANGUAGE]; /*!< Config: Language setting */
645 char zonetag[80]; /*!< Time zone */
646 char locale[20]; /*!< The locale (for presentation of date/time) */
649 char uniqueid[80]; /*!< Unique integer identifier */
651 char attachfmt[20]; /*!< Attachment format */
652 unsigned int flags; /*!< VM_ flags */
654 int minsecs; /*!< Minimum number of seconds per message for this mailbox */
655 int maxmsg; /*!< Maximum number of msgs per folder for this mailbox */
656 int maxdeletedmsg; /*!< Maximum number of deleted msgs saved for this mailbox */
657 int maxsecs; /*!< Maximum number of seconds per message for this mailbox */
658 int passwordlocation; /*!< Storage location of the password */
660 char imapuser[80]; /*!< IMAP server login */
661 char imappassword[80]; /*!< IMAP server password if authpassword not defined */
662 char imapfolder[64]; /*!< IMAP voicemail folder */
663 char imapvmshareid[80]; /*!< Shared mailbox ID to use rather than the dialed one */
664 int imapversion; /*!< If configuration changes, use the new values */
666 double volgain; /*!< Volume gain for voicemails sent via email */
667 AST_LIST_ENTRY(ast_vm_user) list;
670 /*! Voicemail time zones */
672 AST_LIST_ENTRY(vm_zone) list;
675 char msg_format[512];
678 #define VMSTATE_MAX_MSG_ARRAY 256
680 /*! Voicemail mailbox state */
685 char curdir[PATH_MAX];
686 char vmbox[PATH_MAX];
688 char intro[PATH_MAX];
691 int dh_arraysize; /* used for deleted / heard allocation */
701 int updated; /*!< decremented on each mail check until 1 -allows delay */
702 long msgArray[VMSTATE_MAX_MSG_ARRAY];
703 MAILSTREAM *mailstream;
705 char imapuser[80]; /*!< IMAP server login */
706 char imapfolder[64]; /*!< IMAP voicemail folder */
709 char introfn[PATH_MAX]; /*!< Name of prepended file */
710 unsigned int quota_limit;
711 unsigned int quota_usage;
712 struct vm_state *persist_vms;
717 static char odbc_database[80];
718 static char odbc_table[80];
719 #define RETRIEVE(a,b,c,d) retrieve_file(a,b)
720 #define DISPOSE(a,b) remove_file(a,b)
721 #define STORE(a,b,c,d,e,f,g,h,i,j) store_file(a,b,c,d)
722 #define EXISTS(a,b,c,d) (message_exists(a,b))
723 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
724 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
725 #define DELETE(a,b,c,d) (delete_file(a,b))
728 #define DISPOSE(a,b) (imap_remove_file(a,b))
729 #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))
730 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
731 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
732 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
733 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
734 #define DELETE(a,b,c,d) (vm_imap_delete(a,b,d))
736 #define RETRIEVE(a,b,c,d)
738 #define STORE(a,b,c,d,e,f,g,h,i,j)
739 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
740 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
741 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
742 #define DELETE(a,b,c,d) (vm_delete(c))
746 static char VM_SPOOL_DIR[PATH_MAX];
748 static char ext_pass_cmd[128];
749 static char ext_pass_check_cmd[128];
753 #define PWDCHANGE_INTERNAL (1 << 1)
754 #define PWDCHANGE_EXTERNAL (1 << 2)
755 static int pwdchange = PWDCHANGE_INTERNAL;
758 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
761 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
763 # define tdesc "Comedian Mail (Voicemail System)"
767 static char userscontext[AST_MAX_EXTENSION] = "default";
769 static char *addesc = "Comedian Mail";
771 /* Leave a message */
772 static char *app = "VoiceMail";
774 /* Check mail, control, etc */
775 static char *app2 = "VoiceMailMain";
777 static char *app3 = "MailboxExists";
778 static char *app4 = "VMAuthenticate";
780 static char *sayname_app = "VMSayName";
782 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
783 static AST_LIST_HEAD_STATIC(zones, vm_zone);
784 static char zonetag[80];
785 static char locale[20];
786 static int maxsilence;
788 static int maxdeletedmsg;
789 static int silencethreshold = 128;
790 static char serveremail[80];
791 static char mailcmd[160]; /* Configurable mail cmd */
792 static char externnotify[160];
793 static struct ast_smdi_interface *smdi_iface = NULL;
794 static char vmfmts[80];
795 static double volgain;
796 static int vmminsecs;
797 static int vmmaxsecs;
800 static int maxlogins;
801 static int minpassword;
802 static int passwordlocation;
804 /*! Poll mailboxes for changes since there is something external to
805 * app_voicemail that may change them. */
806 static unsigned int poll_mailboxes;
808 /*! Polling frequency */
809 static unsigned int poll_freq;
810 /*! By default, poll every 30 seconds */
811 #define DEFAULT_POLL_FREQ 30
813 AST_MUTEX_DEFINE_STATIC(poll_lock);
814 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
815 static pthread_t poll_thread = AST_PTHREADT_NULL;
816 static unsigned char poll_thread_run;
818 /*! Subscription to ... MWI event subscriptions */
819 static struct ast_event_sub *mwi_sub_sub;
820 /*! Subscription to ... MWI event un-subscriptions */
821 static struct ast_event_sub *mwi_unsub_sub;
824 * \brief An MWI subscription
826 * This is so we can keep track of which mailboxes are subscribed to.
827 * This way, we know which mailboxes to poll when the pollmailboxes
828 * option is being used.
831 AST_RWLIST_ENTRY(mwi_sub) entry;
839 struct mwi_sub_task {
845 static struct ast_taskprocessor *mwi_subscription_tps;
847 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
849 /* custom audio control prompts for voicemail playback */
850 static char listen_control_forward_key[12];
851 static char listen_control_reverse_key[12];
852 static char listen_control_pause_key[12];
853 static char listen_control_restart_key[12];
854 static char listen_control_stop_key[12];
856 /* custom password sounds */
857 static char vm_password[80] = "vm-password";
858 static char vm_newpassword[80] = "vm-newpassword";
859 static char vm_passchanged[80] = "vm-passchanged";
860 static char vm_reenterpassword[80] = "vm-reenterpassword";
861 static char vm_mismatch[80] = "vm-mismatch";
862 static char vm_invalid_password[80] = "vm-invalid-password";
863 static char vm_pls_try_again[80] = "vm-pls-try-again";
865 static struct ast_flags globalflags = {0};
867 static int saydurationminfo;
869 static char dialcontext[AST_MAX_CONTEXT] = "";
870 static char callcontext[AST_MAX_CONTEXT] = "";
871 static char exitcontext[AST_MAX_CONTEXT] = "";
873 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
876 static char *emailbody = NULL;
877 static char *emailsubject = NULL;
878 static char *pagerbody = NULL;
879 static char *pagersubject = NULL;
880 static char fromstring[100];
881 static char pagerfromstring[100];
882 static char charset[32] = "ISO-8859-1";
884 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
885 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
886 static int adsiver = 1;
887 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
888 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
890 /* Forward declarations - generic */
891 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
892 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);
893 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
894 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
895 char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
896 signed char record_gain, struct vm_state *vms, char *flag);
897 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
898 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
899 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);
900 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);
901 static void apply_options(struct ast_vm_user *vmu, const char *options);
902 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);
903 static int is_valid_dtmf(const char *key);
904 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
905 static int write_password_to_file(const char *secretfn, const char *password);
907 struct ao2_container *inprocess_container;
915 static int inprocess_hash_fn(const void *obj, const int flags)
917 const struct inprocess *i = obj;
918 return atoi(i->mailbox);
921 static int inprocess_cmp_fn(void *obj, void *arg, int flags)
923 struct inprocess *i = obj, *j = arg;
924 if (strcmp(i->mailbox, j->mailbox)) {
927 return !strcmp(i->context, j->context) ? CMP_MATCH : 0;
930 static int inprocess_count(const char *context, const char *mailbox, int delta)
932 struct inprocess *i, *arg = alloca(sizeof(*arg) + strlen(context) + strlen(mailbox) + 2);
933 arg->context = arg->mailbox + strlen(mailbox) + 1;
934 strcpy(arg->mailbox, mailbox); /* SAFE */
935 strcpy(arg->context, context); /* SAFE */
936 ao2_lock(inprocess_container);
937 if ((i = ao2_find(inprocess_container, arg, 0))) {
938 int ret = ast_atomic_fetchadd_int(&i->count, delta);
939 ao2_unlock(inprocess_container);
944 ast_log(LOG_WARNING, "BUG: ref count decrement on non-existing object???\n");
946 if (!(i = ao2_alloc(sizeof(*i) + strlen(context) + strlen(mailbox) + 2, NULL))) {
947 ao2_unlock(inprocess_container);
950 i->context = i->mailbox + strlen(mailbox) + 1;
951 strcpy(i->mailbox, mailbox); /* SAFE */
952 strcpy(i->context, context); /* SAFE */
954 ao2_link(inprocess_container, i);
955 ao2_unlock(inprocess_container);
960 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
961 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
965 * \brief Strips control and non 7-bit clean characters from input string.
967 * \note To map control and none 7-bit characters to a 7-bit clean characters
968 * please use ast_str_encode_mine().
970 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
973 for (; *input; input++) {
978 if (bufptr == buf + buflen - 1) {
988 * \brief Sets default voicemail system options to a voicemail user.
990 * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
991 * - all the globalflags
992 * - the saydurationminfo
996 * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
999 static void populate_defaults(struct ast_vm_user *vmu)
1001 ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);
1002 vmu->passwordlocation = passwordlocation;
1003 if (saydurationminfo) {
1004 vmu->saydurationm = saydurationminfo;
1006 ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
1007 ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
1008 ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
1009 ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
1010 ast_copy_string(vmu->locale, locale, sizeof(vmu->locale));
1012 vmu->minsecs = vmminsecs;
1015 vmu->maxsecs = vmmaxsecs;
1018 vmu->maxmsg = maxmsg;
1020 if (maxdeletedmsg) {
1021 vmu->maxdeletedmsg = maxdeletedmsg;
1023 vmu->volgain = volgain;
1024 vmu->emailsubject = NULL;
1025 vmu->emailbody = NULL;
1027 ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
1032 * \brief Sets a a specific property value.
1033 * \param vmu The voicemail user object to work with.
1034 * \param var The name of the property to be set.
1035 * \param value The value to be set to the property.
1037 * The property name must be one of the understood properties. See the source for details.
1039 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
1042 if (!strcasecmp(var, "attach")) {
1043 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
1044 } else if (!strcasecmp(var, "attachfmt")) {
1045 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
1046 } else if (!strcasecmp(var, "serveremail")) {
1047 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
1048 } else if (!strcasecmp(var, "language")) {
1049 ast_copy_string(vmu->language, value, sizeof(vmu->language));
1050 } else if (!strcasecmp(var, "tz")) {
1051 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
1052 } else if (!strcasecmp(var, "locale")) {
1053 ast_copy_string(vmu->locale, value, sizeof(vmu->locale));
1055 } else if (!strcasecmp(var, "imapuser")) {
1056 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
1057 vmu->imapversion = imapversion;
1058 } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
1059 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
1060 vmu->imapversion = imapversion;
1061 } else if (!strcasecmp(var, "imapfolder")) {
1062 ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
1063 } else if (!strcasecmp(var, "imapvmshareid")) {
1064 ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
1065 vmu->imapversion = imapversion;
1067 } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
1068 ast_set2_flag(vmu, ast_true(value), VM_DELETE);
1069 } else if (!strcasecmp(var, "saycid")){
1070 ast_set2_flag(vmu, ast_true(value), VM_SAYCID);
1071 } else if (!strcasecmp(var, "sendvoicemail")){
1072 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);
1073 } else if (!strcasecmp(var, "review")){
1074 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
1075 } else if (!strcasecmp(var, "tempgreetwarn")){
1076 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);
1077 } else if (!strcasecmp(var, "messagewrap")){
1078 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);
1079 } else if (!strcasecmp(var, "operator")) {
1080 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);
1081 } else if (!strcasecmp(var, "envelope")){
1082 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);
1083 } else if (!strcasecmp(var, "moveheard")){
1084 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
1085 } else if (!strcasecmp(var, "sayduration")){
1086 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);
1087 } else if (!strcasecmp(var, "saydurationm")){
1088 if (sscanf(value, "%30d", &x) == 1) {
1089 vmu->saydurationm = x;
1091 ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
1093 } else if (!strcasecmp(var, "forcename")){
1094 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);
1095 } else if (!strcasecmp(var, "forcegreetings")){
1096 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);
1097 } else if (!strcasecmp(var, "callback")) {
1098 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
1099 } else if (!strcasecmp(var, "dialout")) {
1100 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
1101 } else if (!strcasecmp(var, "exitcontext")) {
1102 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
1103 } else if (!strcasecmp(var, "minsecs")) {
1104 if (sscanf(value, "%30d", &x) == 1 && x >= 0) {
1107 ast_log(LOG_WARNING, "Invalid min message length of %s. Using global value %d\n", value, vmminsecs);
1108 vmu->minsecs = vmminsecs;
1110 } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
1111 vmu->maxsecs = atoi(value);
1112 if (vmu->maxsecs <= 0) {
1113 ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
1114 vmu->maxsecs = vmmaxsecs;
1116 vmu->maxsecs = atoi(value);
1118 if (!strcasecmp(var, "maxmessage"))
1119 ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'. Please make that change in your voicemail config.\n");
1120 } else if (!strcasecmp(var, "maxmsg")) {
1121 vmu->maxmsg = atoi(value);
1122 /* Accept maxmsg=0 (Greetings only voicemail) */
1123 if (vmu->maxmsg < 0) {
1124 ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
1125 vmu->maxmsg = MAXMSG;
1126 } else if (vmu->maxmsg > MAXMSGLIMIT) {
1127 ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
1128 vmu->maxmsg = MAXMSGLIMIT;
1130 } else if (!strcasecmp(var, "nextaftercmd")) {
1131 ast_set2_flag(vmu, ast_true(value), VM_SKIPAFTERCMD);
1132 } else if (!strcasecmp(var, "backupdeleted")) {
1133 if (sscanf(value, "%30d", &x) == 1)
1134 vmu->maxdeletedmsg = x;
1135 else if (ast_true(value))
1136 vmu->maxdeletedmsg = MAXMSG;
1138 vmu->maxdeletedmsg = 0;
1140 if (vmu->maxdeletedmsg < 0) {
1141 ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
1142 vmu->maxdeletedmsg = MAXMSG;
1143 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
1144 ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
1145 vmu->maxdeletedmsg = MAXMSGLIMIT;
1147 } else if (!strcasecmp(var, "volgain")) {
1148 sscanf(value, "%30lf", &vmu->volgain);
1149 } else if (!strcasecmp(var, "passwordlocation")) {
1150 if (!strcasecmp(value, "spooldir")) {
1151 vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
1153 vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
1155 } else if (!strcasecmp(var, "options")) {
1156 apply_options(vmu, value);
1160 static char *vm_check_password_shell(char *command, char *buf, size_t len)
1162 int fds[2], pid = 0;
1164 memset(buf, 0, len);
1167 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
1170 pid = ast_safe_fork(0);
1176 snprintf(buf, len, "FAILURE: Fork failed");
1180 if (read(fds[0], buf, len) < 0) {
1181 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
1186 AST_DECLARE_APP_ARGS(arg,
1189 char *mycmd = ast_strdupa(command);
1192 dup2(fds[1], STDOUT_FILENO);
1194 ast_close_fds_above_n(STDOUT_FILENO);
1196 AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
1198 execv(arg.v[0], arg.v);
1199 printf("FAILURE: %s", strerror(errno));
1207 * \brief Check that password meets minimum required length
1208 * \param vmu The voicemail user to change the password for.
1209 * \param password The password string to check
1211 * \return zero on ok, 1 on not ok.
1213 static int check_password(struct ast_vm_user *vmu, char *password)
1215 /* check minimum length */
1216 if (strlen(password) < minpassword)
1218 if (!ast_strlen_zero(ext_pass_check_cmd)) {
1219 char cmd[255], buf[255];
1221 ast_debug(1, "Verify password policies for %s\n", password);
1223 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
1224 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
1225 ast_debug(5, "Result: %s\n", buf);
1226 if (!strncasecmp(buf, "VALID", 5)) {
1227 ast_debug(3, "Passed password check: '%s'\n", buf);
1229 } else if (!strncasecmp(buf, "FAILURE", 7)) {
1230 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
1233 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
1242 * \brief Performs a change of the voicemail passowrd in the realtime engine.
1243 * \param vmu The voicemail user to change the password for.
1244 * \param password The new value to be set to the password for this user.
1246 * This only works if there is a realtime engine configured.
1247 * This is called from the (top level) vm_change_password.
1249 * \return zero on success, -1 on error.
1251 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
1254 if (!strcmp(vmu->password, password)) {
1255 /* No change (but an update would return 0 rows updated, so we opt out here) */
1259 if (strlen(password) > 10) {
1260 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
1262 if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
1263 ast_copy_string(vmu->password, password, sizeof(vmu->password));
1270 * \brief Destructively Parse options and apply.
1272 static void apply_options(struct ast_vm_user *vmu, const char *options)
1277 stringp = ast_strdupa(options);
1278 while ((s = strsep(&stringp, "|"))) {
1280 if ((var = strsep(&value, "=")) && value) {
1281 apply_option(vmu, var, value);
1287 * \brief Loads the options specific to a voicemail user.
1289 * This is called when a vm_user structure is being set up, such as from load_options.
1291 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
1293 for (; var; var = var->next) {
1294 if (!strcasecmp(var->name, "vmsecret")) {
1295 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1296 } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
1297 if (ast_strlen_zero(retval->password))
1298 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1299 } else if (!strcasecmp(var->name, "uniqueid")) {
1300 ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
1301 } else if (!strcasecmp(var->name, "pager")) {
1302 ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
1303 } else if (!strcasecmp(var->name, "email")) {
1304 ast_copy_string(retval->email, var->value, sizeof(retval->email));
1305 } else if (!strcasecmp(var->name, "fullname")) {
1306 ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
1307 } else if (!strcasecmp(var->name, "context")) {
1308 ast_copy_string(retval->context, var->value, sizeof(retval->context));
1309 } else if (!strcasecmp(var->name, "emailsubject")) {
1310 retval->emailsubject = ast_strdup(var->value);
1311 } else if (!strcasecmp(var->name, "emailbody")) {
1312 retval->emailbody = ast_strdup(var->value);
1314 } else if (!strcasecmp(var->name, "imapuser")) {
1315 ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
1316 retval->imapversion = imapversion;
1317 } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
1318 ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
1319 retval->imapversion = imapversion;
1320 } else if (!strcasecmp(var->name, "imapfolder")) {
1321 ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
1322 } else if (!strcasecmp(var->name, "imapvmshareid")) {
1323 ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
1324 retval->imapversion = imapversion;
1327 apply_option(retval, var->name, var->value);
1332 * \brief Determines if a DTMF key entered is valid.
1333 * \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.
1335 * Tests the character entered against the set of valid DTMF characters.
1336 * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1338 static int is_valid_dtmf(const char *key)
1341 char *local_key = ast_strdupa(key);
1343 for (i = 0; i < strlen(key); ++i) {
1344 if (!strchr(VALID_DTMF, *local_key)) {
1345 ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1354 * \brief Finds a voicemail user from the realtime engine.
1359 * 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.
1361 * \return The ast_vm_user structure for the user that was found.
1363 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1365 struct ast_variable *var;
1366 struct ast_vm_user *retval;
1368 if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1370 ast_set_flag(retval, VM_ALLOCED);
1372 memset(retval, 0, sizeof(*retval));
1374 ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1375 populate_defaults(retval);
1376 if (!context && ast_test_flag((&globalflags), VM_SEARCH))
1377 var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1379 var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1381 apply_options_full(retval, var);
1382 ast_variables_destroy(var);
1393 * \brief Finds a voicemail user from the users file or the realtime engine.
1398 * \return The ast_vm_user structure for the user that was found.
1400 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1402 /* This function could be made to generate one from a database, too */
1403 struct ast_vm_user *vmu = NULL, *cur;
1404 AST_LIST_LOCK(&users);
1406 if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1407 context = "default";
1409 AST_LIST_TRAVERSE(&users, cur, list) {
1411 if (cur->imapversion != imapversion) {
1415 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1417 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
1421 /* Make a copy, so that on a reload, we have no race */
1422 if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
1423 memcpy(vmu, cur, sizeof(*vmu));
1424 ast_set2_flag(vmu, !ivm, VM_ALLOCED);
1425 AST_LIST_NEXT(vmu, list) = NULL;
1428 vmu = find_user_realtime(ivm, context, mailbox);
1429 AST_LIST_UNLOCK(&users);
1434 * \brief Resets a user password to a specified password.
1439 * This does the actual change password work, called by the vm_change_password() function.
1441 * \return zero on success, -1 on error.
1443 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
1445 /* This function could be made to generate one from a database, too */
1446 struct ast_vm_user *cur;
1448 AST_LIST_LOCK(&users);
1449 AST_LIST_TRAVERSE(&users, cur, list) {
1450 if ((!context || !strcasecmp(context, cur->context)) &&
1451 (!strcasecmp(mailbox, cur->mailbox)))
1455 ast_copy_string(cur->password, newpass, sizeof(cur->password));
1458 AST_LIST_UNLOCK(&users);
1463 * \brief The handler for the change password option.
1464 * \param vmu The voicemail user to work with.
1465 * \param newpassword The new password (that has been gathered from the appropriate prompting).
1466 * 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.
1467 * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
1469 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
1471 struct ast_config *cfg = NULL;
1472 struct ast_variable *var = NULL;
1473 struct ast_category *cat = NULL;
1474 char *category = NULL, *value = NULL, *new = NULL;
1475 const char *tmp = NULL;
1476 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
1477 char secretfn[PATH_MAX] = "";
1480 if (!change_password_realtime(vmu, newpassword))
1483 /* check if we should store the secret in the spool directory next to the messages */
1484 switch (vmu->passwordlocation) {
1485 case OPT_PWLOC_SPOOLDIR:
1486 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
1487 if (write_password_to_file(secretfn, newpassword) == 0) {
1488 ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
1489 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1490 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1493 ast_verb(4, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
1496 case OPT_PWLOC_VOICEMAILCONF:
1497 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1498 while ((category = ast_category_browse(cfg, category))) {
1499 if (!strcasecmp(category, vmu->context)) {
1500 if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
1501 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
1504 value = strstr(tmp, ",");
1506 new = alloca(strlen(newpassword)+1);
1507 sprintf(new, "%s", newpassword);
1509 new = alloca((strlen(value) + strlen(newpassword) + 1));
1510 sprintf(new, "%s%s", newpassword, value);
1512 if (!(cat = ast_category_get(cfg, category))) {
1513 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
1516 ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
1520 /* save the results */
1522 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1523 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1524 ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
1529 case OPT_PWLOC_USERSCONF:
1530 /* check users.conf and update the password stored for the mailbox */
1531 /* if no vmsecret entry exists create one. */
1532 if ((cfg = ast_config_load("users.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1533 ast_debug(4, "we are looking for %s\n", vmu->mailbox);
1534 for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
1535 ast_debug(4, "users.conf: %s\n", category);
1536 if (!strcasecmp(category, vmu->mailbox)) {
1537 if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
1538 ast_debug(3, "looks like we need to make vmsecret!\n");
1539 var = ast_variable_new("vmsecret", newpassword, "");
1543 new = alloca(strlen(newpassword) + 1);
1544 sprintf(new, "%s", newpassword);
1545 if (!(cat = ast_category_get(cfg, category))) {
1546 ast_debug(4, "failed to get category!\n");
1551 ast_variable_update(cat, "vmsecret", new, NULL, 0);
1553 ast_variable_append(cat, var);
1559 /* save the results and clean things up */
1561 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1562 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1563 ast_config_text_file_save("users.conf", cfg, "AppVoicemail");
1569 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
1572 snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
1573 if (!ast_safe_system(buf)) {
1574 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1575 /* Reset the password in memory, too */
1576 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1581 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1582 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1583 * \param len The length of the path string that was written out.
1588 * The path is constructed as
1589 * VM_SPOOL_DIRcontext/ext/folder
1591 * \return zero on success, -1 on error.
1593 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
1595 return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
1599 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1600 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1601 * \param len The length of the path string that was written out.
1605 * The path is constructed as
1606 * VM_SPOOL_DIRcontext/ext/folder
1608 * \return zero on success, -1 on error.
1610 static int make_file(char *dest, const int len, const char *dir, const int num)
1612 return snprintf(dest, len, "%s/msg%04d", dir, num);
1615 /* same as mkstemp, but return a FILE * */
1616 static FILE *vm_mkftemp(char *template)
1619 int pfd = mkstemp(template);
1620 chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
1622 p = fdopen(pfd, "w+");
1631 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
1632 * \param dest String. base directory.
1633 * \param len Length of dest.
1634 * \param context String. Ignored if is null or empty string.
1635 * \param ext String. Ignored if is null or empty string.
1636 * \param folder String. Ignored if is null or empty string.
1637 * \return -1 on failure, 0 on success.
1639 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
1641 mode_t mode = VOICEMAIL_DIR_MODE;
1644 make_dir(dest, len, context, ext, folder);
1645 if ((res = ast_mkdir(dest, mode))) {
1646 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
1652 static const char * const mailbox_folders[] = {
1671 static const char *mbox(struct ast_vm_user *vmu, int id)
1674 if (vmu && id == 0) {
1675 return vmu->imapfolder;
1678 return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
1681 static int get_folder_by_name(const char *name)
1685 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
1686 if (strcasecmp(name, mailbox_folders[i]) == 0) {
1694 static void free_user(struct ast_vm_user *vmu)
1696 if (ast_test_flag(vmu, VM_ALLOCED)) {
1697 if (vmu->emailbody != NULL) {
1698 ast_free(vmu->emailbody);
1699 vmu->emailbody = NULL;
1701 if (vmu->emailsubject != NULL) {
1702 ast_free(vmu->emailsubject);
1703 vmu->emailsubject = NULL;
1709 static int vm_allocate_dh(struct vm_state *vms, struct ast_vm_user *vmu, int count_msg) {
1711 int arraysize = (vmu->maxmsg > count_msg ? vmu->maxmsg : count_msg);
1712 if (!vms->dh_arraysize) {
1713 /* initial allocation */
1714 if (!(vms->deleted = ast_calloc(arraysize, sizeof(int)))) {
1717 if (!(vms->heard = ast_calloc(arraysize, sizeof(int)))) {
1720 vms->dh_arraysize = arraysize;
1721 } else if (vms->dh_arraysize < arraysize) {
1722 if (!(vms->deleted = ast_realloc(vms->deleted, arraysize * sizeof(int)))) {
1725 if (!(vms->heard = ast_realloc(vms->heard, arraysize * sizeof(int)))) {
1728 memset(vms->deleted, 0, arraysize * sizeof(int));
1729 memset(vms->heard, 0, arraysize * sizeof(int));
1730 vms->dh_arraysize = arraysize;
1736 /* All IMAP-specific functions should go in this block. This
1737 * keeps them from being spread out all over the code */
1739 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
1742 struct vm_state *vms;
1743 unsigned long messageNum;
1745 /* If greetings aren't stored in IMAP, just delete the file */
1746 if (msgnum < 0 && !imapgreetings) {
1747 ast_filedelete(file, NULL);
1751 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1752 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);
1756 /* find real message number based on msgnum */
1757 /* this may be an index into vms->msgArray based on the msgnum. */
1758 messageNum = vms->msgArray[msgnum];
1759 if (messageNum == 0) {
1760 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
1763 ast_debug(3, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
1764 /* delete message */
1765 snprintf (arg, sizeof(arg), "%lu", messageNum);
1766 ast_mutex_lock(&vms->lock);
1767 mail_setflag (vms->mailstream, arg, "\\DELETED");
1768 mail_expunge(vms->mailstream);
1769 ast_mutex_unlock(&vms->lock);
1772 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
1774 struct vm_state *vms_p;
1775 char *file, *filename;
1780 /* This function is only used for retrieval of IMAP greetings
1781 * regular messages are not retrieved this way, nor are greetings
1782 * if they are stored locally*/
1783 if (msgnum > -1 || !imapgreetings) {
1786 file = strrchr(ast_strdupa(dir), '/');
1790 ast_debug(1, "Failed to procure file name from directory passed.\n");
1795 /* check if someone is accessing this box right now... */
1796 if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) &&
1797 !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1798 /* Unlike when retrieving a message, it is reasonable not to be able to find a
1799 * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
1800 * that's all we need to do.
1802 if (!(vms_p = create_vm_state_from_user(vmu))) {
1803 ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
1808 /* Greetings will never have a prepended message */
1809 *vms_p->introfn = '\0';
1811 ast_mutex_lock(&vms_p->lock);
1812 ret = init_mailstream(vms_p, GREETINGS_FOLDER);
1813 if (!vms_p->mailstream) {
1814 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL\n");
1815 ast_mutex_unlock(&vms_p->lock);
1819 /*XXX Yuck, this could probably be done a lot better */
1820 for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
1821 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
1822 /* We have the body, now we extract the file name of the first attachment. */
1823 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1824 attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
1826 ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
1827 ast_mutex_unlock(&vms_p->lock);
1830 filename = strsep(&attachment, ".");
1831 if (!strcmp(filename, file)) {
1832 ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
1833 vms_p->msgArray[vms_p->curmsg] = i + 1;
1834 save_body(body, vms_p, "2", attachment, 0);
1835 ast_mutex_unlock(&vms_p->lock);
1839 ast_mutex_unlock(&vms_p->lock);
1844 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
1847 char *header_content;
1848 char *attachedfilefmt;
1850 struct vm_state *vms;
1851 char text_file[PATH_MAX];
1852 FILE *text_file_ptr;
1854 struct ast_vm_user *vmu;
1856 if (!(vmu = find_user(NULL, context, mailbox))) {
1857 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
1862 if (imapgreetings) {
1863 res = imap_retrieve_greeting(dir, msgnum, vmu);
1871 /* Before anything can happen, we need a vm_state so that we can
1872 * actually access the imap server through the vms->mailstream
1874 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1875 /* This should not happen. If it does, then I guess we'd
1876 * need to create the vm_state, extract which mailbox to
1877 * open, and then set up the msgArray so that the correct
1878 * IMAP message could be accessed. If I have seen correctly
1879 * though, the vms should be obtainable from the vmstates list
1880 * and should have its msgArray properly set up.
1882 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
1887 make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
1888 snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
1890 /* Don't try to retrieve a message from IMAP if it already is on the file system */
1891 if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
1896 ast_debug(3, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
1897 if (vms->msgArray[msgnum] == 0) {
1898 ast_log(LOG_WARNING, "Trying to access unknown message\n");
1903 /* This will only work for new messages... */
1904 ast_mutex_lock(&vms->lock);
1905 header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
1906 ast_mutex_unlock(&vms->lock);
1907 /* empty string means no valid header */
1908 if (ast_strlen_zero(header_content)) {
1909 ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
1914 ast_mutex_lock(&vms->lock);
1915 mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
1916 ast_mutex_unlock(&vms->lock);
1918 /* We have the body, now we extract the file name of the first attachment. */
1919 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1920 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
1922 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
1927 /* Find the format of the attached file */
1929 strsep(&attachedfilefmt, ".");
1930 if (!attachedfilefmt) {
1931 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
1936 save_body(body, vms, "2", attachedfilefmt, 0);
1937 if (save_body(body, vms, "3", attachedfilefmt, 1)) {
1938 *vms->introfn = '\0';
1941 /* Get info from headers!! */
1942 snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
1944 if (!(text_file_ptr = fopen(text_file, "w"))) {
1945 ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
1948 fprintf(text_file_ptr, "%s\n", "[message]");
1950 get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf));
1951 fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
1952 get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf));
1953 fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
1954 get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf));
1955 fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
1956 get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf));
1957 fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
1958 get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf));
1959 fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
1960 get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf));
1961 fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
1962 get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf));
1963 fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
1964 fclose(text_file_ptr);
1971 static int folder_int(const char *folder)
1973 /*assume a NULL folder means INBOX*/
1977 if (!strcasecmp(folder, imapfolder)) {
1979 } else if (!strcasecmp(folder, "Old")) {
1981 } else if (!strcasecmp(folder, "Work")) {
1983 } else if (!strcasecmp(folder, "Family")) {
1985 } else if (!strcasecmp(folder, "Friends")) {
1987 } else if (!strcasecmp(folder, "Cust1")) {
1989 } else if (!strcasecmp(folder, "Cust2")) {
1991 } else if (!strcasecmp(folder, "Cust3")) {
1993 } else if (!strcasecmp(folder, "Cust4")) {
1995 } else if (!strcasecmp(folder, "Cust5")) {
1997 } else if (!strcasecmp(folder, "Urgent")) {
1999 } else { /*assume they meant INBOX if folder is not found otherwise*/
2004 static int __messagecount(const char *context, const char *mailbox, const char *folder)
2009 struct ast_vm_user *vmu, vmus;
2010 struct vm_state *vms_p;
2012 int fold = folder_int(folder);
2015 /* If URGENT, then look at INBOX */
2021 if (ast_strlen_zero(mailbox))
2024 /* We have to get the user before we can open the stream! */
2025 vmu = find_user(&vmus, context, mailbox);
2027 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailbox, context);
2030 /* No IMAP account available */
2031 if (vmu->imapuser[0] == '\0') {
2032 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2037 /* No IMAP account available */
2038 if (vmu->imapuser[0] == '\0') {
2039 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2044 /* check if someone is accessing this box right now... */
2045 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
2047 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
2050 ast_debug(3, "Returning before search - user is logged in\n");
2051 if (fold == 0) { /* INBOX */
2052 return urgent ? vms_p->urgentmessages : vms_p->newmessages;
2054 if (fold == 1) { /* Old messages */
2055 return vms_p->oldmessages;
2059 /* add one if not there... */
2060 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
2062 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
2066 vms_p = create_vm_state_from_user(vmu);
2068 ret = init_mailstream(vms_p, fold);
2069 if (!vms_p->mailstream) {
2070 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
2074 ast_mutex_lock(&vms_p->lock);
2075 pgm = mail_newsearchpgm ();
2076 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
2077 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
2079 if (fold != OLD_FOLDER) {
2083 /* In the special case where fold is 1 (old messages) we have to do things a bit
2084 * differently. Old messages are stored in the INBOX but are marked as "seen"
2090 /* look for urgent messages */
2091 if (fold == NEW_FOLDER) {
2103 vms_p->vmArrayIndex = 0;
2104 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
2105 if (fold == 0 && urgent == 0)
2106 vms_p->newmessages = vms_p->vmArrayIndex;
2108 vms_p->oldmessages = vms_p->vmArrayIndex;
2109 if (fold == 0 && urgent == 1)
2110 vms_p->urgentmessages = vms_p->vmArrayIndex;
2111 /*Freeing the searchpgm also frees the searchhdr*/
2112 mail_free_searchpgm(&pgm);
2113 ast_mutex_unlock(&vms_p->lock);
2115 return vms_p->vmArrayIndex;
2117 ast_mutex_lock(&vms_p->lock);
2118 mail_ping(vms_p->mailstream);
2119 ast_mutex_unlock(&vms_p->lock);
2124 static int imap_check_limits(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu, int msgnum)
2126 /* Check if mailbox is full */
2127 check_quota(vms, vmu->imapfolder);
2128 if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
2129 ast_debug(1, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
2130 ast_play_and_wait(chan, "vm-mailboxfull");
2134 /* Check if we have exceeded maxmsg */
2135 ast_debug(3, "Checking message number quota: mailbox has %d messages, maximum is set to %d, current messages %d\n", msgnum, vmu->maxmsg, inprocess_count(vmu->mailbox, vmu->context, 0));
2136 if (msgnum >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
2137 ast_log(LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u >= %u)\n", msgnum, vmu->maxmsg);
2138 ast_play_and_wait(chan, "vm-mailboxfull");
2139 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
2147 * \brief Gets the number of messages that exist in a mailbox folder.
2152 * This method is used when IMAP backend is used.
2153 * \return The number of messages in this mailbox folder (zero or more).
2155 static int messagecount(const char *context, const char *mailbox, const char *folder)
2157 if (ast_strlen_zero(folder) || !strcmp(folder, "INBOX")) {
2158 return __messagecount(context, mailbox, "INBOX") + __messagecount(context, mailbox, "Urgent");
2160 return __messagecount(context, mailbox, folder);
2164 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)
2166 char *myserveremail = serveremail;
2168 char introfn[PATH_MAX];
2172 char tmp[80] = "/tmp/astmail-XXXXXX";
2177 int ret; /* for better error checking */
2178 char *imap_flags = NIL;
2179 int msgcount = (messagecount(vmu->context, vmu->mailbox, "INBOX") + messagecount(vmu->context, vmu->mailbox, "Old"));
2181 /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
2182 if (msgnum < 0 && !imapgreetings) {
2186 if (imap_check_limits(chan, vms, vmu, msgcount)) {
2190 /* Set urgent flag for IMAP message */
2191 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
2192 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
2193 imap_flags = "\\FLAGGED";
2196 /* Attach only the first format */
2197 fmt = ast_strdupa(fmt);
2199 strsep(&stringp, "|");
2201 if (!ast_strlen_zero(vmu->serveremail))
2202 myserveremail = vmu->serveremail;
2205 make_file(fn, sizeof(fn), dir, msgnum);
2207 ast_copy_string (fn, dir, sizeof(fn));
2209 snprintf(introfn, sizeof(introfn), "%sintro", fn);
2210 if (ast_fileexists(introfn, NULL, NULL) <= 0) {
2214 if (ast_strlen_zero(vmu->email)) {
2215 /* We need the vmu->email to be set when we call make_email_file, but
2216 * if we keep it set, a duplicate e-mail will be created. So at the end
2217 * of this function, we will revert back to an empty string if tempcopy
2220 ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
2224 if (!strcmp(fmt, "wav49"))
2226 ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
2228 /* Make a temporary file instead of piping directly to sendmail, in case the mail
2230 if (!(p = vm_mkftemp(tmp))) {
2231 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
2233 *(vmu->email) = '\0';
2237 if (msgnum < 0 && imapgreetings) {
2238 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
2239 ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
2242 imap_delete_old_greeting(fn, vms);
2245 make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, "INBOX",
2246 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
2247 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
2248 fn, introfn, fmt, duration, 1, chan, NULL, 1, flag);
2249 /* read mail file to memory */
2252 if (!(buf = ast_malloc(len + 1))) {
2253 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
2256 *(vmu->email) = '\0';
2259 if (fread(buf, len, 1, p) < len) {
2261 ast_log(LOG_ERROR, "Short read while reading in mail file.\n");
2265 ((char *) buf)[len] = '\0';
2266 INIT(&str, mail_string, buf, len);
2267 ret = init_mailstream(vms, NEW_FOLDER);
2269 imap_mailbox_name(mailbox, sizeof(mailbox), vms, NEW_FOLDER, 1);
2270 ast_mutex_lock(&vms->lock);
2271 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
2272 ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
2273 ast_mutex_unlock(&vms->lock);
2278 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
2284 ast_debug(3, "%s stored\n", fn);
2287 *(vmu->email) = '\0';
2288 inprocess_count(vmu->mailbox, vmu->context, -1);
2294 * \brief Gets the number of messages that exist in the inbox folder.
2295 * \param mailbox_context
2296 * \param newmsgs The variable that is updated with the count of new messages within this inbox.
2297 * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
2298 * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
2300 * This method is used when IMAP backend is used.
2301 * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
2303 * \return zero on success, -1 on error.
2306 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
2308 char tmp[PATH_MAX] = "";
2320 ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
2321 /* If no mailbox, return immediately */
2322 if (ast_strlen_zero(mailbox_context))
2325 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2326 context = strchr(tmp, '@');
2327 if (strchr(mailbox_context, ',')) {
2328 int tmpnew, tmpold, tmpurgent;
2329 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2331 while ((cur = strsep(&mb, ", "))) {
2332 if (!ast_strlen_zero(cur)) {
2333 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2341 *urgentmsgs += tmpurgent;
2352 context = "default";
2353 mailboxnc = (char *) mailbox_context;
2357 struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
2359 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
2362 if ((*newmsgs = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
2367 if ((*oldmsgs = __messagecount(context, mailboxnc, "Old")) < 0) {
2372 if ((*urgentmsgs = __messagecount(context, mailboxnc, "Urgent")) < 0) {
2380 * \brief Determines if the given folder has messages.
2381 * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
2382 * \param folder the folder to look in
2384 * This function is used when the mailbox is stored in an IMAP back end.
2385 * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
2386 * \return 1 if the folder has one or more messages. zero otherwise.
2389 static int has_voicemail(const char *mailbox, const char *folder)
2391 char tmp[256], *tmp2, *box, *context;
2392 ast_copy_string(tmp, mailbox, sizeof(tmp));
2394 if (strchr(tmp2, ',') || strchr(tmp2, '&')) {
2395 while ((box = strsep(&tmp2, ",&"))) {
2396 if (!ast_strlen_zero(box)) {
2397 if (has_voicemail(box, folder)) {
2403 if ((context = strchr(tmp, '@'))) {
2406 context = "default";
2408 return __messagecount(context, tmp, folder) ? 1 : 0;
2412 * \brief Copies a message from one mailbox to another.
2422 * This works with IMAP storage based mailboxes.
2424 * \return zero on success, -1 on error.
2426 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)
2428 struct vm_state *sendvms = NULL, *destvms = NULL;
2429 char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
2430 if (msgnum >= recip->maxmsg) {
2431 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
2434 if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
2435 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
2438 if (!(destvms = get_vm_state_by_imapuser(recip->imapuser, 0))) {
2439 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
2442 snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
2443 ast_mutex_lock(&sendvms->lock);
2444 if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
2445 ast_mutex_unlock(&sendvms->lock);
2448 ast_mutex_unlock(&sendvms->lock);
2449 ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
2453 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
2455 char tmp[256], *t = tmp;
2456 size_t left = sizeof(tmp);
2458 if (box == OLD_FOLDER) {
2459 ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
2461 ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
2464 if (box == NEW_FOLDER) {
2465 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
2467 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
2470 /* Build up server information */
2471 ast_build_string(&t, &left, "{%s:%s/imap", imapserver, imapport);
2473 /* Add authentication user if present */
2474 if (!ast_strlen_zero(authuser))
2475 ast_build_string(&t, &left, "/authuser=%s", authuser);
2477 /* Add flags if present */
2478 if (!ast_strlen_zero(imapflags))
2479 ast_build_string(&t, &left, "/%s", imapflags);
2481 /* End with username */
2483 ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
2485 ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
2487 if (box == NEW_FOLDER || box == OLD_FOLDER)
2488 snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
2489 else if (box == GREETINGS_FOLDER)
2490 snprintf(spec, len, "%s%s", tmp, greetingfolder);
2491 else { /* Other folders such as Friends, Family, etc... */
2492 if (!ast_strlen_zero(imapparentfolder)) {
2493 /* imapparentfolder would typically be set to INBOX */
2494 snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
2496 snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
2501 static int init_mailstream(struct vm_state *vms, int box)
2503 MAILSTREAM *stream = NIL;
2508 ast_log(LOG_ERROR, "vm_state is NULL!\n");
2511 ast_debug(3, "vm_state user is:%s\n", vms->imapuser);
2512 if (vms->mailstream == NIL || !vms->mailstream) {
2513 ast_debug(1, "mailstream not set.\n");
2515 stream = vms->mailstream;
2517 /* debug = T; user wants protocol telemetry? */
2518 debug = NIL; /* NO protocol telemetry? */
2520 if (delimiter == '\0') { /* did not probe the server yet */
2522 #ifdef USE_SYSTEM_IMAP
2523 #include <imap/linkage.c>
2524 #elif defined(USE_SYSTEM_CCLIENT)
2525 #include <c-client/linkage.c>
2527 #include "linkage.c"
2529 /* Connect to INBOX first to get folders delimiter */
2530 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
2531 ast_mutex_lock(&vms->lock);
2532 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2533 ast_mutex_unlock(&vms->lock);
2534 if (stream == NIL) {
2535 ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
2538 get_mailbox_delimiter(stream);
2539 /* update delimiter in imapfolder */
2540 for (cp = vms->imapfolder; *cp; cp++)
2544 /* Now connect to the target folder */
2545 imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
2546 ast_debug(3, "Before mail_open, server: %s, box:%d\n", tmp, box);
2547 ast_mutex_lock(&vms->lock);
2548 vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2549 ast_mutex_unlock(&vms->lock);
2550 if (vms->mailstream == NIL) {
2557 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
2561 int ret, urgent = 0;
2563 /* If Urgent, then look at INBOX */
2569 ast_copy_string(vms->imapuser, vmu->imapuser, sizeof(vms->imapuser));
2570 ast_copy_string(vms->imapfolder, vmu->imapfolder, sizeof(vms->imapfolder));
2571 vms->imapversion = vmu->imapversion;
2572 ast_debug(3, "Before init_mailstream, user is %s\n", vmu->imapuser);
2574 if ((ret = init_mailstream(vms, box)) || !vms->mailstream) {
2575 ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
2579 create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
2583 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(vmu, box));
2584 check_quota(vms, (char *) mbox(vmu, box));
2587 ast_mutex_lock(&vms->lock);
2588 pgm = mail_newsearchpgm();
2590 /* Check IMAP folder for Asterisk messages only... */
2591 hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : vmu->mailbox));
2592 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", vmu->context);
2597 /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
2598 if (box == NEW_FOLDER && urgent == 1) {
2603 } else if (box == NEW_FOLDER && urgent == 0) {
2608 } else if (box == OLD_FOLDER) {
2613 ast_debug(3, "Before mail_search_full, user is %s\n", vmu->imapuser);
2615 vms->vmArrayIndex = 0;
2616 mail_search_full (vms->mailstream, NULL, pgm, NIL);
2617 vms->lastmsg = vms->vmArrayIndex - 1;
2618 mail_free_searchpgm(&pgm);
2619 /* Since IMAP storage actually stores both old and new messages in the same IMAP folder,
2620 * ensure to allocate enough space to account for all of them. Warn if old messages
2621 * have not been checked first as that is required.
2623 if (box == 0 && !vms->dh_arraysize) {
2624 ast_log(LOG_WARNING, "The code expects the old messages to be checked first, fix the code.\n");
2626 if (vm_allocate_dh(vms, vmu, box == 0 ? vms->vmArrayIndex + vms->oldmessages : vms->lastmsg)) {
2627 ast_mutex_unlock(&vms->lock);
2631 ast_mutex_unlock(&vms->lock);
2635 static void write_file(char *filename, char *buffer, unsigned long len)
2639 output = fopen (filename, "w");
2640 if (fwrite(buffer, len, 1, output) != 1) {
2641 if (ferror(output)) {
2642 ast_log(LOG_ERROR, "Short write while writing e-mail body: %s.\n", strerror(errno));
2648 static void update_messages_by_imapuser(const char *user, unsigned long number)
2650 struct vm_state *vms = get_vm_state_by_imapuser(user, 1);
2652 if (!vms && !(vms = get_vm_state_by_imapuser(user, 0))) {
2656 ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vms->vmArrayIndex, vms->interactive);
2657 vms->msgArray[vms->vmArrayIndex++] = number;
2660 void mm_searched(MAILSTREAM *stream, unsigned long number)
2662 char *mailbox = stream->mailbox, buf[1024] = "", *user;
2664 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
2667 update_messages_by_imapuser(user, number);
2670 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
2672 struct ast_variable *var;
2673 struct ast_vm_user *vmu;
2675 vmu = ast_calloc(1, sizeof *vmu);
2678 ast_set_flag(vmu, VM_ALLOCED);
2679 populate_defaults(vmu);
2681 var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
2683 apply_options_full(vmu, var);
2684 ast_variables_destroy(var);
2692 /* Interfaces to C-client */
2694 void mm_exists(MAILSTREAM * stream, unsigned long number)
2696 /* mail_ping will callback here if new mail! */
2697 ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
2698 if (number == 0) return;
2703 void mm_expunged(MAILSTREAM * stream, unsigned long number)
2705 /* mail_ping will callback here if expunged mail! */
2706 ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
2707 if (number == 0) return;
2712 void mm_flags(MAILSTREAM * stream, unsigned long number)
2714 /* mail_ping will callback here if read mail! */
2715 ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
2716 if (number == 0) return;
2721 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
2723 ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
2724 mm_log (string, errflg);
2728 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2730 if (delimiter == '\0') {
2734 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
2735 if (attributes & LATT_NOINFERIORS)
2736 ast_debug(5, "no inferiors\n");
2737 if (attributes & LATT_NOSELECT)
2738 ast_debug(5, "no select\n");
2739 if (attributes & LATT_MARKED)
2740 ast_debug(5, "marked\n");
2741 if (attributes & LATT_UNMARKED)
2742 ast_debug(5, "unmarked\n");
2746 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2748 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
2749 if (attributes & LATT_NOINFERIORS)
2750 ast_debug(5, "no inferiors\n");
2751 if (attributes & LATT_NOSELECT)
2752 ast_debug(5, "no select\n");
2753 if (attributes & LATT_MARKED)
2754 ast_debug(5, "marked\n");
2755 if (attributes & LATT_UNMARKED)
2756 ast_debug(5, "unmarked\n");
2760 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
2762 ast_log(AST_LOG_NOTICE, " Mailbox %s", mailbox);
2763 if (status->flags & SA_MESSAGES)
2764 ast_log(AST_LOG_NOTICE, ", %lu messages", status->messages);
2765 if (status->flags & SA_RECENT)
2766 ast_log(AST_LOG_NOTICE, ", %lu recent", status->recent);
2767 if (status->flags & SA_UNSEEN)
2768 ast_log(AST_LOG_NOTICE, ", %lu unseen", status->unseen);
2769 if (status->flags & SA_UIDVALIDITY)
2770 ast_log(AST_LOG_NOTICE, ", %lu UID validity", status->uidvalidity);
2771 if (status->flags & SA_UIDNEXT)
2772 ast_log(AST_LOG_NOTICE, ", %lu next UID", status->uidnext);
2773 ast_log(AST_LOG_NOTICE, "\n");
2777 void mm_log(char *string, long errflg)
2779 switch ((short) errflg) {
2781 ast_debug(1, "IMAP Info: %s\n", string);
2785 ast_log(AST_LOG_WARNING, "IMAP Warning: %s\n", string);
2788 ast_log(AST_LOG_ERROR, "IMAP Error: %s\n", string);
2794 void mm_dlog(char *string)
2796 ast_log(AST_LOG_NOTICE, "%s\n", string);
2800 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
2802 struct ast_vm_user *vmu;
2804 ast_debug(4, "Entering callback mm_login\n");
2806 ast_copy_string(user, mb->user, MAILTMPLEN);
2808 /* We should only do this when necessary */
2809 if (!ast_strlen_zero(authpassword)) {
2810 ast_copy_string(pwd, authpassword, MAILTMPLEN);
2812 AST_LIST_TRAVERSE(&users, vmu, list) {
2813 if (!strcasecmp(mb->user, vmu->imapuser)) {
2814 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2819 if ((vmu = find_user_realtime_imapuser(mb->user))) {
2820 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2828 void mm_critical(MAILSTREAM * stream)
2833 void mm_nocritical(MAILSTREAM * stream)
2838 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
2840 kill (getpid (), SIGSTOP);
2845 void mm_fatal(char *string)
2847 ast_log(AST_LOG_ERROR, "IMAP access FATAL error: %s\n", string);
2850 /* C-client callback to handle quota */
2851 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
2853 struct vm_state *vms;
2854 char *mailbox = stream->mailbox, *user;
2855 char buf[1024] = "";
2856 unsigned long usage = 0, limit = 0;
2859 usage = pquota->usage;
2860 limit = pquota->limit;
2861 pquota = pquota->next;
2864 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)))) {
2865 ast_log(AST_LOG_ERROR, "No state found.\n");
2869 ast_debug(3, "User %s usage is %lu, limit is %lu\n", user, usage, limit);
2871 vms->quota_usage = usage;
2872 vms->quota_limit = limit;
2875 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len)
2877 char *start, *eol_pnt;
2880 if (ast_strlen_zero(header) || ast_strlen_zero(tag))
2883 taglen = strlen(tag) + 1;
2887 if (!(start = strstr(header, tag)))
2890 /* Since we can be called multiple times we should clear our buffer */
2891 memset(buf, 0, len);
2893 ast_copy_string(buf, start+taglen, len);
2894 if ((eol_pnt = strchr(buf,'\r')) || (eol_pnt = strchr(buf,'\n')))
2899 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len)
2901 char *start, *quote, *eol_pnt;
2903 if (ast_strlen_zero(mailbox))
2906 if (!(start = strstr(mailbox, "/user=")))
2909 ast_copy_string(buf, start+6, len);
2911 if (!(quote = strchr(buf, '\"'))) {
2912 if (!(eol_pnt = strchr(buf, '/')))
2913 eol_pnt = strchr(buf,'}');
2917 eol_pnt = strchr(buf+1,'\"');
2923 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
2925 struct vm_state *vms_p;
2927 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2928 if ((vms_p = pthread_getspecific(ts_vmstate.key)) && !strcmp(vms_p->imapuser, vmu->imapuser) && !strcmp(vms_p->username, vmu->mailbox)) {
2931 ast_debug(5, "Adding new vmstate for %s\n", vmu->imapuser);
2932 if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
2934 ast_copy_string(vms_p->imapuser, vmu->imapuser, sizeof(vms_p->imapuser));
2935 ast_copy_string(vms_p->imapfolder, vmu->imapfolder, sizeof(vms_p->imapfolder));
2936 ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
2937 ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
2938 vms_p->mailstream = NIL; /* save for access from interactive entry point */
2939 vms_p->imapversion = vmu->imapversion;
2940 ast_debug(5, "Copied %s to %s\n", vmu->imapuser, vms_p->imapuser);
2942 /* set mailbox to INBOX! */
2943 ast_copy_string(vms_p->curbox, mbox(vmu, 0), sizeof(vms_p->curbox));
2944 init_vm_state(vms_p);
2945 vmstate_insert(vms_p);
2949 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive)
2951 struct vmstate *vlist = NULL;
2954 struct vm_state *vms;
2955 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2956 vms = pthread_getspecific(ts_vmstate.key);
2960 AST_LIST_LOCK(&vmstates);
2961 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
2963 ast_debug(3, "error: vms is NULL for %s\n", user);
2966 if (vlist->vms->imapversion != imapversion) {
2969 if (!vlist->vms->imapuser) {
2970 ast_debug(3, "error: imapuser is NULL for %s\n", user);
2974 if (!strcmp(vlist->vms->imapuser, user) && (interactive == 2 || vlist->vms->interactive == interactive)) {
2975 AST_LIST_UNLOCK(&vmstates);
2979 AST_LIST_UNLOCK(&vmstates);
2981 ast_debug(3, "%s not found in vmstates\n", user);
2986 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
2989 struct vmstate *vlist = NULL;
2990 const char *local_context = S_OR(context, "default");
2993 struct vm_state *vms;
2994 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2995 vms = pthread_getspecific(ts_vmstate.key);
2999 AST_LIST_LOCK(&vmstates);
3000 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
3002 ast_debug(3, "error: vms is NULL for %s\n", mailbox);
3005 if (vlist->vms->imapversion != imapversion) {
3008 if (!vlist->vms->username || !vlist->vms->context) {
3009 ast_debug(3, "error: username is NULL for %s\n", mailbox);
3013 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);
3015 if (!strcmp(vlist->vms->username, mailbox) && !strcmp(vlist->vms->context, local_context) && vlist->vms->interactive == interactive) {
3016 ast_debug(3, "Found it!\n");
3017 AST_LIST_UNLOCK(&vmstates);
3021 AST_LIST_UNLOCK(&vmstates);
3023 ast_debug(3, "%s not found in vmstates\n", mailbox);
3028 static void vmstate_insert(struct vm_state *vms)
3031 struct vm_state *altvms;
3033 /* If interactive, it probably already exists, and we should
3034 use the one we already have since it is more up to date.
3035 We can compare the username to find the duplicate */
3036 if (vms->interactive == 1) {
3037 altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
3039 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
3040 vms->newmessages = altvms->newmessages;
3041 vms->oldmessages = altvms->oldmessages;
3042 vms->vmArrayIndex = altvms->vmArrayIndex;
3043 vms->lastmsg = altvms->lastmsg;
3044 vms->curmsg = altvms->curmsg;
3045 /* get a pointer to the persistent store */
3046 vms->persist_vms = altvms;
3047 /* Reuse the mailstream? */
3048 #ifdef REALLY_FAST_EVEN_IF_IT_MEANS_RESOURCE_LEAKS
3049 vms->mailstream = altvms->mailstream;
3051 vms->mailstream = NIL;
3057 if (!(v = ast_calloc(1, sizeof(*v))))
3062 ast_debug(3, "Inserting vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3064 AST_LIST_LOCK(&vmstates);
3065 AST_LIST_INSERT_TAIL(&vmstates, v, list);
3066 AST_LIST_UNLOCK(&vmstates);
3069 static void vmstate_delete(struct vm_state *vms)
3071 struct vmstate *vc = NULL;
3072 struct vm_state *altvms = NULL;
3074 /* If interactive, we should copy pertinent info
3075 back to the persistent state (to make update immediate) */
3076 if (vms->interactive == 1 && (altvms = vms->persist_vms)) {
3077 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
3078 altvms->newmessages = vms->newmessages;
3079 altvms->oldmessages = vms->oldmessages;
3080 altvms->updated = 1;
3081 vms->mailstream = mail_close(vms->mailstream);
3083 /* Interactive states are not stored within the persistent list */
3087 ast_debug(3, "Removing vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3089 AST_LIST_LOCK(&vmstates);
3090 AST_LIST_TRAVERSE_SAFE_BEGIN(&vmstates, vc, list) {
3091 if (vc->vms == vms) {
3092 AST_LIST_REMOVE_CURRENT(list);
3096 AST_LIST_TRAVERSE_SAFE_END
3097 AST_LIST_UNLOCK(&vmstates);
3100 ast_mutex_destroy(&vc->vms->lock);
3104 ast_log(AST_LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3107 static void set_update(MAILSTREAM * stream)
3109 struct vm_state *vms;
3110 char *mailbox = stream->mailbox, *user;
3111 char buf[1024] = "";
3113 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || !(vms = get_vm_state_by_imapuser(user, 0))) {
3114 if (user && option_debug > 2)
3115 ast_log(AST_LOG_WARNING, "User %s mailbox not found for update.\n", user);
3119 ast_debug(3, "User %s mailbox set for update.\n", user);
3121 vms->updated = 1; /* Set updated flag since mailbox changed */
3124 static void init_vm_state(struct vm_state *vms)
3127 vms->vmArrayIndex = 0;
3128 for (x = 0; x < VMSTATE_MAX_MSG_ARRAY; x++) {
3129 vms->msgArray[x] = 0;
3131 ast_mutex_init(&vms->lock);
3134 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro)
3138 char *fn = is_intro ? vms->introfn : vms->fn;
3140 unsigned long newlen;
3143 if (!body || body == NIL)
3146 ast_mutex_lock(&vms->lock);
3147 body_content = mail_fetchbody(vms->mailstream, vms->msgArray[vms->curmsg], section, &len);
3148 ast_mutex_unlock(&vms->lock);
3149 if (body_content != NIL) {
3150 snprintf(filename, sizeof(filename), "%s.%s", fn, format);
3151 /* ast_debug(1, body_content); */
3152 body_decoded = rfc822_base64((unsigned char *) body_content, len, &newlen);
3153 /* If the body of the file is empty, return an error */
3157 write_file(filename, (char *) body_decoded, newlen);
3159 ast_debug(5, "Body of message is NULL.\n");
3166 * \brief Get delimiter via mm_list callback
3169 * Determines the delimiter character that is used by the underlying IMAP based mail store.
3171 /* MUTEX should already be held */
3172 static void get_mailbox_delimiter(MAILSTREAM *stream) {
3174 snprintf(tmp, sizeof(tmp), "{%s}", imapserver);
3175 mail_list(stream, tmp, "*");
3179 * \brief Check Quota for user
3180 * \param vms a pointer to a vm_state struct, will use the mailstream property of this.
3181 * \param mailbox the mailbox to check the quota for.
3183 * Calls imap_getquotaroot, which will populate its results into the vm_state vms input structure.
3185 static void check_quota(struct vm_state *vms, char *mailbox) {
3186 ast_mutex_lock(&vms->lock);
3187 mail_parameters(NULL, SET_QUOTA, (void *) mm_parsequota);
3188 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mailbox);
3189 if (vms && vms->mailstream != NULL) {
3190 imap_getquotaroot(vms->mailstream, mailbox);
3192 ast_log(AST_LOG_WARNING, "Mailstream not available for mailbox: %s\n", mailbox);
3194 ast_mutex_unlock(&vms->lock);
3197 #endif /* IMAP_STORAGE */
3199 /*! \brief Lock file path
3200 only return failure if ast_lock_path returns 'timeout',
3201 not if the path does not exist or any other reason
3203 static int vm_lock_path(const char *path)
3205 switch (ast_lock_path(path)) {
3206 case AST_LOCK_TIMEOUT:
3215 struct generic_prepare_struct {
3221 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
3223 struct generic_prepare_struct *gps = data;
3227 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
3228 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3229 ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
3232 res = SQLPrepare(stmt, (unsigned char *) gps->sql, SQL_NTS);
3233 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3234 ast_log(AST_LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
3235 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3238 for (i = 0; i < gps->argc; i++)
3239 SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
3245 * \brief Retrieves a file from an ODBC data store.
3246 * \param dir the path to the file to be retreived.
3247 * \param msgnum the message number, such as within a mailbox folder.
3249 * This method is used by the RETRIEVE macro when mailboxes are stored in an ODBC back end.
3250 * 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.
3252 * The file is looked up by invoking a SQL on the odbc_table (default 'voicemessages') using the dir and msgnum input parameters.
3253 * The output is the message information file with the name msgnum and the extension .txt
3254 * and the message file with the extension of its format, in the directory with base file name of the msgnum.
3256 * \return 0 on success, -1 on error.
3258 static int retrieve_file(char *dir, int msgnum)
3264 void *fdm = MAP_FAILED;
3265 SQLSMALLINT colcount = 0;
3272 SQLSMALLINT datatype;
3273 SQLSMALLINT decimaldigits;
3274 SQLSMALLINT nullable;
3280 char full_fn[PATH_MAX];
3282 char *argv[] = { dir, msgnums };
3283 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
3285 struct odbc_obj *obj;
3286 obj = ast_odbc_request_obj(odbc_database, 0);
3288 ast_copy_string(fmt, vmfmts, sizeof(fmt));
3289 c = strchr(fmt, '|');
3292 if (!strcasecmp(fmt, "wav49"))
3294 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
3296 make_file(fn, sizeof(fn), dir, msgnum);
3298 ast_copy_string(fn, dir, sizeof(fn));
3300 /* Create the information file */
3301 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
3303 if (!(f = fopen(full_fn, "w+"))) {
3304 ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
3308 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
3309 snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?", odbc_table);
3310 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3312 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3313 ast_odbc_release_obj(obj);
3316 res = SQLFetch(stmt);
3317 if (res == SQL_NO_DATA) {
3318 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3319 ast_odbc_release_obj(obj);
3321 } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3322 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3323 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3324 ast_odbc_release_obj(obj);
3327 fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
3329 ast_log(AST_LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
3330 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3331 ast_odbc_release_obj(obj);
3334 res = SQLNumResultCols(stmt, &colcount);
3335 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3336 ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
3337 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3338 ast_odbc_release_obj(obj);
3342 fprintf(f, "[message]\n");
3343 for (x = 0; x < colcount; x++) {
3346 collen = sizeof(coltitle);
3347 res = SQLDescribeCol(stmt, x + 1, (unsigned char *) coltitle, sizeof(coltitle), &collen,
3348 &datatype, &colsize, &decimaldigits, &nullable);
3349 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3350 ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
3351 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3352 ast_odbc_release_obj(obj);
3355 if (!strcasecmp(coltitle, "recording")) {
3357 res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
3361 lseek(fd, fdlen - 1, SEEK_SET);
3362 if (write(fd, tmp, 1) != 1) {
3367 /* Read out in small chunks */
3368 for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
3369 if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
3370 ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
3371 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3372 ast_odbc_release_obj(obj);
3375 res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
3376 munmap(fdm, CHUNKSIZE);
3377 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3378 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
3380 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3381 ast_odbc_release_obj(obj);
3386 if (truncate(full_fn, fdlen) < 0) {
3387 ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
3391 res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3392 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3393 ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
3394 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3395 ast_odbc_release_obj(obj);
3398 if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
3399 fprintf(f, "%s=%s\n", coltitle, rowdata);
3402 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3403 ast_odbc_release_obj(obj);
3405 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3415 * \brief Determines the highest message number in use for a given user and mailbox folder.
3417 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
3419 * This method is used when mailboxes are stored in an ODBC back end.
3420 * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
3422 * \return the value of zero or greater to indicate the last message index in use, -1 to indicate none.
3425 static int last_message_index(struct ast_vm_user *vmu, char *dir)
3432 char *argv[] = { dir };
3433 struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
3435 struct odbc_obj *obj;
3436 obj = ast_odbc_request_obj(odbc_database, 0);
3438 snprintf(sql, sizeof(sql), "SELECT msgnum FROM %s WHERE dir=? order by msgnum desc limit 1", odbc_table);
3440 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3442 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3443 ast_odbc_release_obj(obj);
3446 res = SQLFetch(stmt);
3447 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3448 if (res == SQL_NO_DATA) {
3449 ast_log(AST_LOG_DEBUG, "Directory '%s' has no messages and therefore no index was retrieved.\n", dir);
3451 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3454 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3455 ast_odbc_release_obj(obj);
3458 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3459 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3460 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
3461 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3462 ast_odbc_release_obj(obj);
3465 if (sscanf(rowdata, "%30d", &x) != 1)
3466 ast_log(AST_LOG_WARNING, "Failed to read message index!\n");
3467 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3468 ast_odbc_release_obj(obj);
3471 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3477 * \brief Determines if the specified message exists.
3478 * \param dir the folder the mailbox folder to look for messages.
3479 * \param msgnum the message index to query for.
3481 * This method is used when mailboxes are stored in an ODBC back end.
3483 * \return greater than zero if the message exists, zero when the message does not exist or on error.
3485 static int message_exists(char *dir, int msgnum)
3493 char *argv[] = { dir, msgnums };
3494 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
3496 struct odbc_obj *obj;
3497 obj = ast_odbc_request_obj(odbc_database, 0);
3499 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
3500 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?", odbc_table);
3501 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3503 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3504 ast_odbc_release_obj(obj);
3507 res = SQLFetch(stmt);
3508 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3509 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3510 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3511 ast_odbc_release_obj(obj);
3514 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3515 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3516 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
3517 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3518 ast_odbc_release_obj(obj);
3521 if (sscanf(rowdata, "%30d", &x) != 1)
3522 ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
3523 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3524 ast_odbc_release_obj(obj);
3526 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3532 * \brief returns the number of messages found.
3534 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
3536 * This method is used when mailboxes are stored in an ODBC back end.
3538 * \return The count of messages being zero or more, less than zero on error.
3540 static int count_messages(struct ast_vm_user *vmu, char *dir)
3547 char *argv[] = { dir };
3548 struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
3550 struct odbc_obj *obj;
3551 obj = ast_odbc_request_obj(odbc_database, 0);
3553 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?", odbc_table);
3554 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3556 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3557 ast_odbc_release_obj(obj);
3560 res = SQLFetch(stmt);
3561 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3562 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
3563 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3564 ast_odbc_release_obj(obj);
3567 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
3568 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO))