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.
41 <use type="module">res_adsi</use>
42 <use type="module">res_smdi</use>
43 <support_level>core</support_level>
47 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" touch_on_change="apps/app_voicemail.c apps/app_directory.c">
48 <member name="FILE_STORAGE" displayname="Storage of Voicemail using filesystem">
49 <conflict>ODBC_STORAGE</conflict>
50 <conflict>IMAP_STORAGE</conflict>
51 <defaultenabled>yes</defaultenabled>
52 <support_level>core</support_level>
54 <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
55 <depend>generic_odbc</depend>
57 <conflict>IMAP_STORAGE</conflict>
58 <conflict>FILE_STORAGE</conflict>
59 <defaultenabled>no</defaultenabled>
60 <support_level>core</support_level>
62 <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
63 <depend>imap_tk</depend>
64 <conflict>ODBC_STORAGE</conflict>
65 <conflict>FILE_STORAGE</conflict>
66 <use type="external">openssl</use>
67 <defaultenabled>no</defaultenabled>
68 <support_level>core</support_level>
79 #ifdef USE_SYSTEM_IMAP
80 #include <imap/c-client.h>
81 #include <imap/imap4r1.h>
82 #include <imap/linkage.h>
83 #elif defined (USE_SYSTEM_CCLIENT)
84 #include <c-client/c-client.h>
85 #include <c-client/imap4r1.h>
86 #include <c-client/linkage.h>
94 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
96 #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR */
102 #if defined(__FreeBSD__) || defined(__OpenBSD__)
103 #include <sys/wait.h>
106 #include "asterisk/logger.h"
107 #include "asterisk/lock.h"
108 #include "asterisk/file.h"
109 #include "asterisk/channel.h"
110 #include "asterisk/pbx.h"
111 #include "asterisk/config.h"
112 #include "asterisk/say.h"
113 #include "asterisk/module.h"
114 #include "asterisk/adsi.h"
115 #include "asterisk/app.h"
116 #include "asterisk/app_voicemail.h"
117 #include "asterisk/manager.h"
118 #include "asterisk/dsp.h"
119 #include "asterisk/localtime.h"
120 #include "asterisk/cli.h"
121 #include "asterisk/utils.h"
122 #include "asterisk/stringfields.h"
123 #include "asterisk/strings.h"
124 #include "asterisk/smdi.h"
125 #include "asterisk/astobj2.h"
126 #include "asterisk/event.h"
127 #include "asterisk/taskprocessor.h"
128 #include "asterisk/test.h"
131 #include "asterisk/res_odbc.h"
135 #include "asterisk/threadstorage.h"
139 <application name="VoiceMail" language="en_US">
141 Leave a Voicemail message.
144 <parameter name="mailboxs" argsep="&" required="true">
145 <argument name="mailbox1" argsep="@" required="true">
146 <argument name="mailbox" required="true" />
147 <argument name="context" />
149 <argument name="mailbox2" argsep="@" multiple="true">
150 <argument name="mailbox" required="true" />
151 <argument name="context" />
154 <parameter name="options">
157 <para>Play the <literal>busy</literal> greeting to the calling party.</para>
160 <argument name="c" />
161 <para>Accept digits for a new extension in context <replaceable>c</replaceable>,
162 if played during the greeting. Context defaults to the current context.</para>
165 <argument name="#" required="true" />
166 <para>Use the specified amount of gain when recording the voicemail
167 message. The units are whole-number decibels (dB). Only works on supported
168 technologies, which is DAHDI only.</para>
171 <para>Skip the playback of instructions for leaving a message to the
172 calling party.</para>
175 <para>Play the <literal>unavailable</literal> greeting.</para>
178 <para>Mark message as <literal>URGENT</literal>.</para>
181 <para>Mark message as <literal>PRIORITY</literal>.</para>
187 <para>This application allows the calling party to leave a message for the specified
188 list of mailboxes. When multiple mailboxes are specified, the greeting will be taken from
189 the first mailbox specified. Dialplan execution will stop if the specified mailbox does not
191 <para>The Voicemail application will exit if any of the following DTMF digits are received:</para>
194 <para>Jump to the <literal>o</literal> extension in the current dialplan context.</para>
197 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
200 <para>This application will set the following channel variable upon completion:</para>
202 <variable name="VMSTATUS">
203 <para>This indicates the status of the execution of the VoiceMail application.</para>
204 <value name="SUCCESS" />
205 <value name="USEREXIT" />
206 <value name="FAILED" />
211 <ref type="application">VoiceMailMain</ref>
214 <application name="VoiceMailMain" language="en_US">
216 Check Voicemail messages.
219 <parameter name="mailbox" required="true" argsep="@">
220 <argument name="mailbox" />
221 <argument name="context" />
223 <parameter name="options">
226 <para>Consider the <replaceable>mailbox</replaceable> parameter as a prefix to
227 the mailbox that is entered by the caller.</para>
230 <argument name="#" required="true" />
231 <para>Use the specified amount of gain when recording a voicemail message.
232 The units are whole-number decibels (dB).</para>
235 <para>Skip checking the passcode for the mailbox.</para>
238 <argument name="folder" required="true" />
239 <para>Skip folder prompt and go directly to <replaceable>folder</replaceable> specified.
240 Defaults to <literal>INBOX</literal> (or <literal>0</literal>).</para>
242 <enum name="0"><para>INBOX</para></enum>
243 <enum name="1"><para>Old</para></enum>
244 <enum name="2"><para>Work</para></enum>
245 <enum name="3"><para>Family</para></enum>
246 <enum name="4"><para>Friends</para></enum>
247 <enum name="5"><para>Cust1</para></enum>
248 <enum name="6"><para>Cust2</para></enum>
249 <enum name="7"><para>Cust3</para></enum>
250 <enum name="8"><para>Cust4</para></enum>
251 <enum name="9"><para>Cust5</para></enum>
258 <para>This application allows the calling party to check voicemail messages. A specific
259 <replaceable>mailbox</replaceable>, and optional corresponding <replaceable>context</replaceable>,
260 may be specified. If a <replaceable>mailbox</replaceable> is not provided, the calling party will
261 be prompted to enter one. If a <replaceable>context</replaceable> is not specified, the
262 <literal>default</literal> context will be used.</para>
263 <para>The VoiceMailMain application will exit if the following DTMF digit is entered as Mailbox
264 or Password, and the extension exists:</para>
267 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
272 <ref type="application">VoiceMail</ref>
275 <application name="MailboxExists" language="en_US">
277 Check to see if Voicemail mailbox exists.
280 <parameter name="mailbox" required="true" argsep="@">
281 <argument name="mailbox" required="true" />
282 <argument name="context" />
284 <parameter name="options">
285 <para>None options.</para>
289 <note><para>DEPRECATED. Use VM_INFO(mailbox[@context],exists) instead.</para></note>
290 <para>Check to see if the specified <replaceable>mailbox</replaceable> exists. If no voicemail
291 <replaceable>context</replaceable> is specified, the <literal>default</literal> context
293 <para>This application will set the following channel variable upon completion:</para>
295 <variable name="VMBOXEXISTSSTATUS">
296 <para>This will contain the status of the execution of the MailboxExists application.
297 Possible values include:</para>
298 <value name="SUCCESS" />
299 <value name="FAILED" />
304 <ref type="function">VM_INFO</ref>
307 <application name="VMAuthenticate" language="en_US">
309 Authenticate with Voicemail passwords.
312 <parameter name="mailbox" required="true" argsep="@">
313 <argument name="mailbox" />
314 <argument name="context" />
316 <parameter name="options">
319 <para>Skip playing the initial prompts.</para>
325 <para>This application behaves the same way as the Authenticate application, but the passwords
326 are taken from <filename>voicemail.conf</filename>. If the <replaceable>mailbox</replaceable> is
327 specified, only that mailbox's password will be considered valid. If the <replaceable>mailbox</replaceable>
328 is not specified, the channel variable <variable>AUTH_MAILBOX</variable> will be set with the authenticated
330 <para>The VMAuthenticate application will exit if the following DTMF digit is entered as Mailbox
331 or Password, and the extension exists:</para>
334 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
339 <application name="VoiceMailPlayMsg" language="en_US">
341 Play a single voice mail msg from a mailbox by msg id.
344 <parameter name="mailbox" required="true" argsep="@">
345 <argument name="mailbox" />
346 <argument name="context" />
348 <parameter name="msg_id" required="true">
349 <para>The msg id of the msg to play back. </para>
353 <para>This application sets the following channel variable upon completion:</para>
355 <variable name="VOICEMAIL_PLAYBACKSTATUS">
356 <para>The status of the playback attempt as a text string.</para>
357 <value name="SUCCESS"/>
358 <value name="FAILED"/>
363 <application name="VMSayName" language="en_US">
365 Play the name of a voicemail user
368 <parameter name="mailbox" required="true" argsep="@">
369 <argument name="mailbox" />
370 <argument name="context" />
374 <para>This application will say the recorded name of the voicemail user specified as the
375 argument to this application. If no context is provided, <literal>default</literal> is assumed.</para>
378 <function name="MAILBOX_EXISTS" language="en_US">
380 Tell if a mailbox is configured.
383 <parameter name="mailbox" required="true" />
384 <parameter name="context" />
387 <note><para>DEPRECATED. Use VM_INFO(mailbox[@context],exists) instead.</para></note>
388 <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.
389 If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
393 <ref type="function">VM_INFO</ref>
396 <function name="VM_INFO" language="en_US">
398 Returns the selected attribute from a mailbox.
401 <parameter name="mailbox" argsep="@" required="true">
402 <argument name="mailbox" required="true" />
403 <argument name="context" />
405 <parameter name="attribute" required="true">
407 <option name="count">
408 <para>Count of messages in specified <replaceable>folder</replaceable>.
409 If <replaceable>folder</replaceable> is not specified, defaults to <literal>INBOX</literal>.</para>
411 <option name="email">
412 <para>E-mail address associated with the mailbox.</para>
414 <option name="exists">
415 <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.</para>
417 <option name="fullname">
418 <para>Full name associated with the mailbox.</para>
420 <option name="language">
421 <para>Mailbox language if overridden, otherwise the language of the channel.</para>
423 <option name="locale">
424 <para>Mailbox locale if overridden, otherwise global locale.</para>
426 <option name="pager">
427 <para>Pager e-mail address associated with the mailbox.</para>
429 <option name="password">
430 <para>Mailbox access password.</para>
433 <para>Mailbox timezone if overridden, otherwise global timezone</para>
437 <parameter name="folder" required="false">
438 <para>If not specified, <literal>INBOX</literal> is assumed.</para>
442 <para>Returns the selected attribute from the specified <replaceable>mailbox</replaceable>.
443 If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
444 context. Where the <replaceable>folder</replaceable> can be specified, common folders
445 include <literal>INBOX</literal>, <literal>Old</literal>, <literal>Work</literal>,
446 <literal>Family</literal> and <literal>Friends</literal>.</para>
449 <manager name="VoicemailUsersList" language="en_US">
451 List All Voicemail User Information.
454 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
462 static char imapserver[48];
463 static char imapport[8];
464 static char imapflags[128];
465 static char imapfolder[64];
466 static char imapparentfolder[64] = "\0";
467 static char greetingfolder[64];
468 static char authuser[32];
469 static char authpassword[42];
470 static int imapversion = 1;
472 static int expungeonhangup = 1;
473 static int imapgreetings = 0;
474 static char delimiter = '\0';
479 AST_THREADSTORAGE(ts_vmstate);
481 /* Forward declarations for IMAP */
482 static int init_mailstream(struct vm_state *vms, int box);
483 static void write_file(char *filename, char *buffer, unsigned long len);
484 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
485 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu);
486 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
487 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive);
488 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
489 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
490 static void vmstate_insert(struct vm_state *vms);
491 static void vmstate_delete(struct vm_state *vms);
492 static void set_update(MAILSTREAM * stream);
493 static void init_vm_state(struct vm_state *vms);
494 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
495 static void get_mailbox_delimiter(struct vm_state *vms, MAILSTREAM *stream);
496 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
497 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
498 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, const char *msg_id);
499 static void vm_imap_update_msg_id(char *dir, int msgnum, const char *msg_id, struct ast_vm_user *vmu, struct ast_config *msg_cfg, int folder);
500 static void update_messages_by_imapuser(const char *user, unsigned long number);
501 static int vm_delete(char *file);
503 static int imap_remove_file (char *dir, int msgnum);
504 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
505 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
506 static void check_quota(struct vm_state *vms, char *mailbox);
507 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
509 struct vm_state *vms;
510 AST_LIST_ENTRY(vmstate) list;
513 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
517 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
519 #define COMMAND_TIMEOUT 5000
520 /* Don't modify these here; set your umask at runtime instead */
521 #define VOICEMAIL_DIR_MODE 0777
522 #define VOICEMAIL_FILE_MODE 0666
523 #define CHUNKSIZE 65536
525 #define VOICEMAIL_CONFIG "voicemail.conf"
526 #define ASTERISK_USERNAME "asterisk"
528 /* Define fast-forward, pause, restart, and reverse keys
529 * while listening to a voicemail message - these are
530 * strings, not characters */
531 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
532 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
533 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
534 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
535 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
536 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
538 /* Default mail command to mail voicemail. Change it with the
539 * mailcmd= command in voicemail.conf */
540 #define SENDMAIL "/usr/sbin/sendmail -t"
542 #define INTRO "vm-intro"
545 #define MAXMSGLIMIT 9999
547 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
549 #define BASELINELEN 72
550 #define BASEMAXINLINE 256
557 #define MAX_DATETIME_FORMAT 512
558 #define MAX_NUM_CID_CONTEXTS 10
560 #define VM_REVIEW (1 << 0) /*!< After recording, permit the caller to review the recording before saving */
561 #define VM_OPERATOR (1 << 1) /*!< Allow 0 to be pressed to go to 'o' extension */
562 #define VM_SAYCID (1 << 2) /*!< Repeat the CallerID info during envelope playback */
563 #define VM_SVMAIL (1 << 3) /*!< Allow the user to compose a new VM from within VoicemailMain */
564 #define VM_ENVELOPE (1 << 4) /*!< Play the envelope information (who-from, time received, etc.) */
565 #define VM_SAYDURATION (1 << 5) /*!< Play the length of the message during envelope playback */
566 #define VM_SKIPAFTERCMD (1 << 6) /*!< After deletion, assume caller wants to go to the next message */
567 #define VM_FORCENAME (1 << 7) /*!< Have new users record their name */
568 #define VM_FORCEGREET (1 << 8) /*!< Have new users record their greetings */
569 #define VM_PBXSKIP (1 << 9) /*!< Skip the [PBX] preamble in the Subject line of emails */
570 #define VM_DIRECFORWARD (1 << 10) /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
571 #define VM_ATTACH (1 << 11) /*!< Attach message to voicemail notifications? */
572 #define VM_DELETE (1 << 12) /*!< Delete message after sending notification */
573 #define VM_ALLOCED (1 << 13) /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
574 #define VM_SEARCH (1 << 14) /*!< Search all contexts for a matching mailbox */
575 #define VM_TEMPGREETWARN (1 << 15) /*!< Remind user tempgreeting is set */
576 #define VM_MOVEHEARD (1 << 16) /*!< Move a "heard" message to Old after listening to it */
577 #define VM_MESSAGEWRAP (1 << 17) /*!< Wrap around from the last message to the first, and vice-versa */
578 #define VM_FWDURGAUTO (1 << 18) /*!< Autoset of Urgent flag on forwarded Urgent messages set globally */
579 #define ERROR_LOCK_PATH -100
580 #define OPERATOR_EXIT 300
591 enum vm_option_flags {
592 OPT_SILENT = (1 << 0),
593 OPT_BUSY_GREETING = (1 << 1),
594 OPT_UNAVAIL_GREETING = (1 << 2),
595 OPT_RECORDGAIN = (1 << 3),
596 OPT_PREPEND_MAILBOX = (1 << 4),
597 OPT_AUTOPLAY = (1 << 6),
598 OPT_DTMFEXIT = (1 << 7),
599 OPT_MESSAGE_Urgent = (1 << 8),
600 OPT_MESSAGE_PRIORITY = (1 << 9)
603 enum vm_option_args {
604 OPT_ARG_RECORDGAIN = 0,
605 OPT_ARG_PLAYFOLDER = 1,
606 OPT_ARG_DTMFEXIT = 2,
607 /* This *must* be the last value in this enum! */
608 OPT_ARG_ARRAY_SIZE = 3,
611 enum vm_passwordlocation {
612 OPT_PWLOC_VOICEMAILCONF = 0,
613 OPT_PWLOC_SPOOLDIR = 1,
614 OPT_PWLOC_USERSCONF = 2,
617 AST_APP_OPTIONS(vm_app_options, {
618 AST_APP_OPTION('s', OPT_SILENT),
619 AST_APP_OPTION('b', OPT_BUSY_GREETING),
620 AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
621 AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
622 AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
623 AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
624 AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
625 AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
626 AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY)
629 static const char * const mailbox_folders[] = {
648 static int load_config(int reload);
649 #ifdef TEST_FRAMEWORK
650 static int load_config_from_memory(int reload, struct ast_config *cfg, struct ast_config *ucfg);
652 static int actual_load_config(int reload, struct ast_config *cfg, struct ast_config *ucfg);
654 /*! \page vmlang Voicemail Language Syntaxes Supported
656 \par Syntaxes supported, not really language codes.
663 \arg \b pt - Portuguese
664 \arg \b pt_BR - Portuguese (Brazil)
666 \arg \b no - Norwegian
668 \arg \b tw - Chinese (Taiwan)
669 \arg \b ua - Ukrainian
671 German requires the following additional soundfile:
672 \arg \b 1F einE (feminine)
674 Spanish requires the following additional soundfile:
675 \arg \b 1M un (masculine)
677 Dutch, Portuguese & Spanish require the following additional soundfiles:
678 \arg \b vm-INBOXs singular of 'new'
679 \arg \b vm-Olds singular of 'old/heard/read'
682 \arg \b vm-INBOX nieuwe (nl)
683 \arg \b vm-Old oude (nl)
686 \arg \b vm-new-a 'new', feminine singular accusative
687 \arg \b vm-new-e 'new', feminine plural accusative
688 \arg \b vm-new-ych 'new', feminine plural genitive
689 \arg \b vm-old-a 'old', feminine singular accusative
690 \arg \b vm-old-e 'old', feminine plural accusative
691 \arg \b vm-old-ych 'old', feminine plural genitive
692 \arg \b digits/1-a 'one', not always same as 'digits/1'
693 \arg \b digits/2-ie 'two', not always same as 'digits/2'
696 \arg \b vm-nytt singular of 'new'
697 \arg \b vm-nya plural of 'new'
698 \arg \b vm-gammalt singular of 'old'
699 \arg \b vm-gamla plural of 'old'
700 \arg \b digits/ett 'one', not always same as 'digits/1'
703 \arg \b vm-ny singular of 'new'
704 \arg \b vm-nye plural of 'new'
705 \arg \b vm-gammel singular of 'old'
706 \arg \b vm-gamle plural of 'old'
714 Italian requires the following additional soundfile:
718 \arg \b vm-nuovi new plural
719 \arg \b vm-vecchio old
720 \arg \b vm-vecchi old plural
722 Chinese (Taiwan) requires the following additional soundfile:
723 \arg \b vm-tong A class-word for call (tong1)
724 \arg \b vm-ri A class-word for day (ri4)
725 \arg \b vm-you You (ni3)
726 \arg \b vm-haveno Have no (mei2 you3)
727 \arg \b vm-have Have (you3)
728 \arg \b vm-listen To listen (yao4 ting1)
731 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
732 spelled among others when you have to change folder. For the above reasons, vm-INBOX
733 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
742 unsigned char iobuf[BASEMAXINLINE];
745 /*! Structure for linked list of users
746 * Use ast_vm_user_destroy() to free one of these structures. */
748 char context[AST_MAX_CONTEXT]; /*!< Voicemail context */
749 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
750 char password[80]; /*!< Secret pin code, numbers only */
751 char fullname[80]; /*!< Full name, for directory app */
752 char email[80]; /*!< E-mail address */
753 char *emailsubject; /*!< E-mail subject */
754 char *emailbody; /*!< E-mail body */
755 char pager[80]; /*!< E-mail address to pager (no attachment) */
756 char serveremail[80]; /*!< From: Mail address */
757 char mailcmd[160]; /*!< Configurable mail command */
758 char language[MAX_LANGUAGE]; /*!< Config: Language setting */
759 char zonetag[80]; /*!< Time zone */
760 char locale[20]; /*!< The locale (for presentation of date/time) */
763 char uniqueid[80]; /*!< Unique integer identifier */
765 char attachfmt[20]; /*!< Attachment format */
766 unsigned int flags; /*!< VM_ flags */
768 int minsecs; /*!< Minimum number of seconds per message for this mailbox */
769 int maxmsg; /*!< Maximum number of msgs per folder for this mailbox */
770 int maxdeletedmsg; /*!< Maximum number of deleted msgs saved for this mailbox */
771 int maxsecs; /*!< Maximum number of seconds per message for this mailbox */
772 int passwordlocation; /*!< Storage location of the password */
774 char imapserver[48]; /*!< IMAP server address */
775 char imapport[8]; /*!< IMAP server port */
776 char imapflags[128]; /*!< IMAP optional flags */
777 char imapuser[80]; /*!< IMAP server login */
778 char imappassword[80]; /*!< IMAP server password if authpassword not defined */
779 char imapfolder[64]; /*!< IMAP voicemail folder */
780 char imapvmshareid[80]; /*!< Shared mailbox ID to use rather than the dialed one */
781 int imapversion; /*!< If configuration changes, use the new values */
783 double volgain; /*!< Volume gain for voicemails sent via email */
784 AST_LIST_ENTRY(ast_vm_user) list;
787 /*! Voicemail time zones */
789 AST_LIST_ENTRY(vm_zone) list;
792 char msg_format[512];
795 #define VMSTATE_MAX_MSG_ARRAY 256
797 /*! Voicemail mailbox state */
802 char curdir[PATH_MAX];
803 char vmbox[PATH_MAX];
805 char intro[PATH_MAX];
808 int dh_arraysize; /* used for deleted / heard allocation */
818 int updated; /*!< decremented on each mail check until 1 -allows delay */
819 long msgArray[VMSTATE_MAX_MSG_ARRAY];
820 MAILSTREAM *mailstream;
822 char imapuser[80]; /*!< IMAP server login */
823 char imapfolder[64]; /*!< IMAP voicemail folder */
824 char imapserver[48]; /*!< IMAP server address */
825 char imapport[8]; /*!< IMAP server port */
826 char imapflags[128]; /*!< IMAP optional flags */
829 char introfn[PATH_MAX]; /*!< Name of prepended file */
830 unsigned int quota_limit;
831 unsigned int quota_usage;
832 struct vm_state *persist_vms;
837 static char odbc_database[80];
838 static char odbc_table[80];
839 #define RETRIEVE(a,b,c,d) retrieve_file(a,b)
840 #define DISPOSE(a,b) remove_file(a,b)
841 #define STORE(a,b,c,d,e,f,g,h,i,j,k) store_file(a,b,c,d)
842 #define EXISTS(a,b,c,d) (message_exists(a,b))
843 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
844 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
845 #define DELETE(a,b,c,d) (delete_file(a,b))
846 #define UPDATE_MSG_ID(a, b, c, d, e, f) (odbc_update_msg_id((a), (b), (c)))
849 #define DISPOSE(a,b) (imap_remove_file(a,b))
850 #define STORE(a,b,c,d,e,f,g,h,i,j,k) (imap_store_file(a,b,c,d,e,f,g,h,i,j,k))
851 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
852 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
853 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
854 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
855 #define DELETE(a,b,c,d) (vm_imap_delete(a,b,d))
856 #define UPDATE_MSG_ID(a, b, c, d, e, f) (vm_imap_update_msg_id((a), (b), (c), (d), (e), (f)))
858 #define RETRIEVE(a,b,c,d)
860 #define STORE(a,b,c,d,e,f,g,h,i,j,k)
861 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
862 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
863 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
864 #define DELETE(a,b,c,d) (vm_delete(c))
865 #define UPDATE_MSG_ID(a, b, c, d, e, f)
869 static char VM_SPOOL_DIR[PATH_MAX];
871 static char ext_pass_cmd[128];
872 static char ext_pass_check_cmd[128];
876 #define PWDCHANGE_INTERNAL (1 << 1)
877 #define PWDCHANGE_EXTERNAL (1 << 2)
878 static int pwdchange = PWDCHANGE_INTERNAL;
881 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
884 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
886 # define tdesc "Comedian Mail (Voicemail System)"
890 static char userscontext[AST_MAX_EXTENSION] = "default";
892 static char *addesc = "Comedian Mail";
894 /* Leave a message */
895 static char *app = "VoiceMail";
897 /* Check mail, control, etc */
898 static char *app2 = "VoiceMailMain";
900 static char *app3 = "MailboxExists";
901 static char *app4 = "VMAuthenticate";
903 static char *playmsg_app = "VoiceMailPlayMsg";
905 static char *sayname_app = "VMSayName";
907 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
908 static AST_LIST_HEAD_STATIC(zones, vm_zone);
909 static char zonetag[80];
910 static char locale[20];
911 static int maxsilence;
913 static int maxdeletedmsg;
914 static int silencethreshold = 128;
915 static char serveremail[80];
916 static char mailcmd[160]; /* Configurable mail cmd */
917 static char externnotify[160];
918 static struct ast_smdi_interface *smdi_iface = NULL;
919 static char vmfmts[80];
920 static double volgain;
921 static int vmminsecs;
922 static int vmmaxsecs;
925 static int maxlogins;
926 static int minpassword;
927 static int passwordlocation;
929 /*! Poll mailboxes for changes since there is something external to
930 * app_voicemail that may change them. */
931 static unsigned int poll_mailboxes;
933 /*! Polling frequency */
934 static unsigned int poll_freq;
935 /*! By default, poll every 30 seconds */
936 #define DEFAULT_POLL_FREQ 30
938 AST_MUTEX_DEFINE_STATIC(poll_lock);
939 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
940 static pthread_t poll_thread = AST_PTHREADT_NULL;
941 static unsigned char poll_thread_run;
943 /*! Subscription to ... MWI event subscriptions */
944 static struct ast_event_sub *mwi_sub_sub;
945 /*! Subscription to ... MWI event un-subscriptions */
946 static struct ast_event_sub *mwi_unsub_sub;
949 * \brief An MWI subscription
951 * This is so we can keep track of which mailboxes are subscribed to.
952 * This way, we know which mailboxes to poll when the pollmailboxes
953 * option is being used.
956 AST_RWLIST_ENTRY(mwi_sub) entry;
964 struct mwi_sub_task {
970 static struct ast_taskprocessor *mwi_subscription_tps;
972 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
974 /* custom audio control prompts for voicemail playback */
975 static char listen_control_forward_key[12];
976 static char listen_control_reverse_key[12];
977 static char listen_control_pause_key[12];
978 static char listen_control_restart_key[12];
979 static char listen_control_stop_key[12];
981 /* custom password sounds */
982 static char vm_password[80] = "vm-password";
983 static char vm_newpassword[80] = "vm-newpassword";
984 static char vm_passchanged[80] = "vm-passchanged";
985 static char vm_reenterpassword[80] = "vm-reenterpassword";
986 static char vm_mismatch[80] = "vm-mismatch";
987 static char vm_invalid_password[80] = "vm-invalid-password";
988 static char vm_pls_try_again[80] = "vm-pls-try-again";
991 * XXX If we have the time, motivation, etc. to fix up this prompt, one of the following would be appropriate:
992 * 1. create a sound along the lines of "Please try again. When done, press the pound key" which could be spliced
993 * from existing sound clips. This would require some programming changes in the area of vm_forward options and also
994 * app.c's __ast_play_and_record function
995 * 2. create a sound prompt saying "Please try again. When done recording, press any key to stop and send the prepended
996 * message." At the time of this comment, I think this would require new voice work to be commissioned.
997 * 3. Something way different like providing instructions before a time out or a post-recording menu. This would require
998 * more effort than either of the other two.
1000 static char vm_prepend_timeout[80] = "vm-then-pound";
1002 static struct ast_flags globalflags = {0};
1004 static int saydurationminfo;
1006 static char dialcontext[AST_MAX_CONTEXT] = "";
1007 static char callcontext[AST_MAX_CONTEXT] = "";
1008 static char exitcontext[AST_MAX_CONTEXT] = "";
1010 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
1013 static char *emailbody = NULL;
1014 static char *emailsubject = NULL;
1015 static char *pagerbody = NULL;
1016 static char *pagersubject = NULL;
1017 static char fromstring[100];
1018 static char pagerfromstring[100];
1019 static char charset[32] = "ISO-8859-1";
1021 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
1022 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
1023 static int adsiver = 1;
1024 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
1025 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
1027 /* Forward declarations - generic */
1028 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
1029 static int close_mailbox(struct vm_state *vms, struct ast_vm_user *vmu);
1030 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);
1031 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
1032 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
1033 char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, int *sound_duration, const char *unlockdir,
1034 signed char record_gain, struct vm_state *vms, char *flag, const char *msg_id);
1035 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
1036 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
1037 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);
1038 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, const char *msg_id);
1039 static void apply_options(struct ast_vm_user *vmu, const char *options);
1040 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);
1041 static int is_valid_dtmf(const char *key);
1042 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
1043 static int write_password_to_file(const char *secretfn, const char *password);
1044 struct ast_str *vm_mailbox_snapshot_str(const char *mailbox, const char *context);
1045 static const char *substitute_escapes(const char *value);
1046 static int message_range_and_existence_check(struct vm_state *vms, const char *msg_ids [], size_t num_msgs, int *msg_nums, struct ast_vm_user *vmu);
1048 * Place a message in the indicated folder
1050 * \param vmu Voicemail user
1051 * \param vms Current voicemail state for the user
1052 * \param msg The message number to save
1053 * \param box The folder into which the message should be saved
1054 * \param[out] newmsg The new message number of the saved message
1055 * \param move Tells whether to copy or to move the message
1057 * \note the "move" parameter is only honored for IMAP voicemail presently
1059 * \revval other Failure
1061 static int save_to_folder(struct ast_vm_user *vmu, struct vm_state *vms, int msg, int box, int *newmsg, int move);
1063 struct ao2_container *inprocess_container;
1071 static int inprocess_hash_fn(const void *obj, const int flags)
1073 const struct inprocess *i = obj;
1074 return atoi(i->mailbox);
1077 static int inprocess_cmp_fn(void *obj, void *arg, int flags)
1079 struct inprocess *i = obj, *j = arg;
1080 if (strcmp(i->mailbox, j->mailbox)) {
1083 return !strcmp(i->context, j->context) ? CMP_MATCH : 0;
1086 static int inprocess_count(const char *context, const char *mailbox, int delta)
1088 struct inprocess *i, *arg = alloca(sizeof(*arg) + strlen(context) + strlen(mailbox) + 2);
1089 arg->context = arg->mailbox + strlen(mailbox) + 1;
1090 strcpy(arg->mailbox, mailbox); /* SAFE */
1091 strcpy(arg->context, context); /* SAFE */
1092 ao2_lock(inprocess_container);
1093 if ((i = ao2_find(inprocess_container, arg, 0))) {
1094 int ret = ast_atomic_fetchadd_int(&i->count, delta);
1095 ao2_unlock(inprocess_container);
1100 ast_log(LOG_WARNING, "BUG: ref count decrement on non-existing object???\n");
1102 if (!(i = ao2_alloc(sizeof(*i) + strlen(context) + strlen(mailbox) + 2, NULL))) {
1103 ao2_unlock(inprocess_container);
1106 i->context = i->mailbox + strlen(mailbox) + 1;
1107 strcpy(i->mailbox, mailbox); /* SAFE */
1108 strcpy(i->context, context); /* SAFE */
1110 ao2_link(inprocess_container, i);
1111 ao2_unlock(inprocess_container);
1116 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
1117 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
1121 * \brief Strips control and non 7-bit clean characters from input string.
1123 * \note To map control and none 7-bit characters to a 7-bit clean characters
1124 * please use ast_str_encode_mine().
1126 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
1129 for (; *input; input++) {
1134 if (bufptr == buf + buflen - 1) {
1144 * \brief Sets default voicemail system options to a voicemail user.
1146 * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
1147 * - all the globalflags
1148 * - the saydurationminfo
1152 * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
1154 * - emailsubject, emailbody set to NULL
1156 static void populate_defaults(struct ast_vm_user *vmu)
1158 ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);
1159 vmu->passwordlocation = passwordlocation;
1160 if (saydurationminfo) {
1161 vmu->saydurationm = saydurationminfo;
1163 ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
1164 ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
1165 ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
1166 ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
1167 ast_copy_string(vmu->locale, locale, sizeof(vmu->locale));
1169 vmu->minsecs = vmminsecs;
1172 vmu->maxsecs = vmmaxsecs;
1175 vmu->maxmsg = maxmsg;
1177 if (maxdeletedmsg) {
1178 vmu->maxdeletedmsg = maxdeletedmsg;
1180 vmu->volgain = volgain;
1181 ast_free(vmu->emailsubject);
1182 vmu->emailsubject = NULL;
1183 ast_free(vmu->emailbody);
1184 vmu->emailbody = NULL;
1186 ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
1187 ast_copy_string(vmu->imapserver, imapserver, sizeof(vmu->imapserver));
1188 ast_copy_string(vmu->imapport, imapport, sizeof(vmu->imapport));
1189 ast_copy_string(vmu->imapflags, imapflags, sizeof(vmu->imapflags));
1194 * \brief Sets a a specific property value.
1195 * \param vmu The voicemail user object to work with.
1196 * \param var The name of the property to be set.
1197 * \param value The value to be set to the property.
1199 * The property name must be one of the understood properties. See the source for details.
1201 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
1204 if (!strcasecmp(var, "attach")) {
1205 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
1206 } else if (!strcasecmp(var, "attachfmt")) {
1207 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
1208 } else if (!strcasecmp(var, "serveremail")) {
1209 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
1210 } else if (!strcasecmp(var, "emailbody")) {
1211 ast_free(vmu->emailbody);
1212 vmu->emailbody = ast_strdup(substitute_escapes(value));
1213 } else if (!strcasecmp(var, "emailsubject")) {
1214 ast_free(vmu->emailsubject);
1215 vmu->emailsubject = ast_strdup(substitute_escapes(value));
1216 } else if (!strcasecmp(var, "language")) {
1217 ast_copy_string(vmu->language, value, sizeof(vmu->language));
1218 } else if (!strcasecmp(var, "tz")) {
1219 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
1220 } else if (!strcasecmp(var, "locale")) {
1221 ast_copy_string(vmu->locale, value, sizeof(vmu->locale));
1223 } else if (!strcasecmp(var, "imapuser")) {
1224 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
1225 vmu->imapversion = imapversion;
1226 } else if (!strcasecmp(var, "imapserver")) {
1227 ast_copy_string(vmu->imapserver, value, sizeof(vmu->imapserver));
1228 vmu->imapversion = imapversion;
1229 } else if (!strcasecmp(var, "imapport")) {
1230 ast_copy_string(vmu->imapport, value, sizeof(vmu->imapport));
1231 vmu->imapversion = imapversion;
1232 } else if (!strcasecmp(var, "imapflags")) {
1233 ast_copy_string(vmu->imapflags, value, sizeof(vmu->imapflags));
1234 vmu->imapversion = imapversion;
1235 } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
1236 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
1237 vmu->imapversion = imapversion;
1238 } else if (!strcasecmp(var, "imapfolder")) {
1239 ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
1240 vmu->imapversion = imapversion;
1241 } else if (!strcasecmp(var, "imapvmshareid")) {
1242 ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
1243 vmu->imapversion = imapversion;
1245 } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
1246 ast_set2_flag(vmu, ast_true(value), VM_DELETE);
1247 } else if (!strcasecmp(var, "saycid")){
1248 ast_set2_flag(vmu, ast_true(value), VM_SAYCID);
1249 } else if (!strcasecmp(var, "sendvoicemail")){
1250 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);
1251 } else if (!strcasecmp(var, "review")){
1252 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
1253 } else if (!strcasecmp(var, "tempgreetwarn")){
1254 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);
1255 } else if (!strcasecmp(var, "messagewrap")){
1256 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);
1257 } else if (!strcasecmp(var, "operator")) {
1258 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);
1259 } else if (!strcasecmp(var, "envelope")){
1260 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);
1261 } else if (!strcasecmp(var, "moveheard")){
1262 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
1263 } else if (!strcasecmp(var, "sayduration")){
1264 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);
1265 } else if (!strcasecmp(var, "saydurationm")){
1266 if (sscanf(value, "%30d", &x) == 1) {
1267 vmu->saydurationm = x;
1269 ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
1271 } else if (!strcasecmp(var, "forcename")){
1272 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);
1273 } else if (!strcasecmp(var, "forcegreetings")){
1274 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);
1275 } else if (!strcasecmp(var, "callback")) {
1276 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
1277 } else if (!strcasecmp(var, "dialout")) {
1278 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
1279 } else if (!strcasecmp(var, "exitcontext")) {
1280 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
1281 } else if (!strcasecmp(var, "minsecs")) {
1282 if (sscanf(value, "%30d", &x) == 1 && x >= 0) {
1285 ast_log(LOG_WARNING, "Invalid min message length of %s. Using global value %d\n", value, vmminsecs);
1286 vmu->minsecs = vmminsecs;
1288 } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
1289 vmu->maxsecs = atoi(value);
1290 if (vmu->maxsecs <= 0) {
1291 ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
1292 vmu->maxsecs = vmmaxsecs;
1294 vmu->maxsecs = atoi(value);
1296 if (!strcasecmp(var, "maxmessage"))
1297 ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'. Please make that change in your voicemail config.\n");
1298 } else if (!strcasecmp(var, "maxmsg")) {
1299 vmu->maxmsg = atoi(value);
1300 /* Accept maxmsg=0 (Greetings only voicemail) */
1301 if (vmu->maxmsg < 0) {
1302 ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
1303 vmu->maxmsg = MAXMSG;
1304 } else if (vmu->maxmsg > MAXMSGLIMIT) {
1305 ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
1306 vmu->maxmsg = MAXMSGLIMIT;
1308 } else if (!strcasecmp(var, "nextaftercmd")) {
1309 ast_set2_flag(vmu, ast_true(value), VM_SKIPAFTERCMD);
1310 } else if (!strcasecmp(var, "backupdeleted")) {
1311 if (sscanf(value, "%30d", &x) == 1)
1312 vmu->maxdeletedmsg = x;
1313 else if (ast_true(value))
1314 vmu->maxdeletedmsg = MAXMSG;
1316 vmu->maxdeletedmsg = 0;
1318 if (vmu->maxdeletedmsg < 0) {
1319 ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
1320 vmu->maxdeletedmsg = MAXMSG;
1321 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
1322 ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
1323 vmu->maxdeletedmsg = MAXMSGLIMIT;
1325 } else if (!strcasecmp(var, "volgain")) {
1326 sscanf(value, "%30lf", &vmu->volgain);
1327 } else if (!strcasecmp(var, "passwordlocation")) {
1328 if (!strcasecmp(value, "spooldir")) {
1329 vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
1331 vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
1333 } else if (!strcasecmp(var, "options")) {
1334 apply_options(vmu, value);
1338 static char *vm_check_password_shell(char *command, char *buf, size_t len)
1340 int fds[2], pid = 0;
1342 memset(buf, 0, len);
1345 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
1348 pid = ast_safe_fork(0);
1354 snprintf(buf, len, "FAILURE: Fork failed");
1358 if (read(fds[0], buf, len) < 0) {
1359 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
1364 AST_DECLARE_APP_ARGS(arg,
1367 char *mycmd = ast_strdupa(command);
1370 dup2(fds[1], STDOUT_FILENO);
1372 ast_close_fds_above_n(STDOUT_FILENO);
1374 AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
1376 execv(arg.v[0], arg.v);
1377 printf("FAILURE: %s", strerror(errno));
1385 * \brief Check that password meets minimum required length
1386 * \param vmu The voicemail user to change the password for.
1387 * \param password The password string to check
1389 * \return zero on ok, 1 on not ok.
1391 static int check_password(struct ast_vm_user *vmu, char *password)
1393 /* check minimum length */
1394 if (strlen(password) < minpassword)
1396 /* check that password does not contain '*' character */
1397 if (!ast_strlen_zero(password) && password[0] == '*')
1399 if (!ast_strlen_zero(ext_pass_check_cmd)) {
1400 char cmd[255], buf[255];
1402 ast_debug(1, "Verify password policies for %s\n", password);
1404 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
1405 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
1406 ast_debug(5, "Result: %s\n", buf);
1407 if (!strncasecmp(buf, "VALID", 5)) {
1408 ast_debug(3, "Passed password check: '%s'\n", buf);
1410 } else if (!strncasecmp(buf, "FAILURE", 7)) {
1411 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
1414 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
1423 * \brief Performs a change of the voicemail passowrd in the realtime engine.
1424 * \param vmu The voicemail user to change the password for.
1425 * \param password The new value to be set to the password for this user.
1427 * This only works if there is a realtime engine configured.
1428 * This is called from the (top level) vm_change_password.
1430 * \return zero on success, -1 on error.
1432 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
1435 if (!strcmp(vmu->password, password)) {
1436 /* No change (but an update would return 0 rows updated, so we opt out here) */
1440 if (strlen(password) > 10) {
1441 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
1443 if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
1444 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: realtime engine updated with new password\r\nPasswordSource: realtime");
1445 ast_copy_string(vmu->password, password, sizeof(vmu->password));
1452 * \brief Destructively Parse options and apply.
1454 static void apply_options(struct ast_vm_user *vmu, const char *options)
1459 stringp = ast_strdupa(options);
1460 while ((s = strsep(&stringp, "|"))) {
1462 if ((var = strsep(&value, "=")) && value) {
1463 apply_option(vmu, var, value);
1469 * \brief Loads the options specific to a voicemail user.
1471 * This is called when a vm_user structure is being set up, such as from load_options.
1473 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
1475 for (; var; var = var->next) {
1476 if (!strcasecmp(var->name, "vmsecret")) {
1477 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1478 } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
1479 if (ast_strlen_zero(retval->password)) {
1480 if (!ast_strlen_zero(var->value) && var->value[0] == '*') {
1481 ast_log(LOG_WARNING, "Invalid password detected for mailbox %s. The password"
1482 "\n\tmust be reset in voicemail.conf.\n", retval->mailbox);
1484 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1487 } else if (!strcasecmp(var->name, "uniqueid")) {
1488 ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
1489 } else if (!strcasecmp(var->name, "pager")) {
1490 ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
1491 } else if (!strcasecmp(var->name, "email")) {
1492 ast_copy_string(retval->email, var->value, sizeof(retval->email));
1493 } else if (!strcasecmp(var->name, "fullname")) {
1494 ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
1495 } else if (!strcasecmp(var->name, "context")) {
1496 ast_copy_string(retval->context, var->value, sizeof(retval->context));
1497 } else if (!strcasecmp(var->name, "emailsubject")) {
1498 ast_free(retval->emailsubject);
1499 retval->emailsubject = ast_strdup(substitute_escapes(var->value));
1500 } else if (!strcasecmp(var->name, "emailbody")) {
1501 ast_free(retval->emailbody);
1502 retval->emailbody = ast_strdup(substitute_escapes(var->value));
1504 } else if (!strcasecmp(var->name, "imapuser")) {
1505 ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
1506 retval->imapversion = imapversion;
1507 } else if (!strcasecmp(var->name, "imapserver")) {
1508 ast_copy_string(retval->imapserver, var->value, sizeof(retval->imapserver));
1509 retval->imapversion = imapversion;
1510 } else if (!strcasecmp(var->name, "imapport")) {
1511 ast_copy_string(retval->imapport, var->value, sizeof(retval->imapport));
1512 retval->imapversion = imapversion;
1513 } else if (!strcasecmp(var->name, "imapflags")) {
1514 ast_copy_string(retval->imapflags, var->value, sizeof(retval->imapflags));
1515 retval->imapversion = imapversion;
1516 } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
1517 ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
1518 retval->imapversion = imapversion;
1519 } else if (!strcasecmp(var->name, "imapfolder")) {
1520 ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
1521 retval->imapversion = imapversion;
1522 } else if (!strcasecmp(var->name, "imapvmshareid")) {
1523 ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
1524 retval->imapversion = imapversion;
1527 apply_option(retval, var->name, var->value);
1532 * \brief Determines if a DTMF key entered is valid.
1533 * \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.
1535 * Tests the character entered against the set of valid DTMF characters.
1536 * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1538 static int is_valid_dtmf(const char *key)
1541 char *local_key = ast_strdupa(key);
1543 for (i = 0; i < strlen(key); ++i) {
1544 if (!strchr(VALID_DTMF, *local_key)) {
1545 ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1554 * \brief Finds a voicemail user from the realtime engine.
1559 * 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.
1561 * \return The ast_vm_user structure for the user that was found.
1563 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1565 struct ast_variable *var;
1566 struct ast_vm_user *retval;
1568 if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1570 ast_set_flag(retval, VM_ALLOCED);
1572 memset(retval, 0, sizeof(*retval));
1574 ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1575 populate_defaults(retval);
1576 if (!context && ast_test_flag((&globalflags), VM_SEARCH))
1577 var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1579 var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1581 apply_options_full(retval, var);
1582 ast_variables_destroy(var);
1593 * \brief Finds a voicemail user from the users file or the realtime engine.
1598 * \return The ast_vm_user structure for the user that was found.
1600 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1602 /* This function could be made to generate one from a database, too */
1603 struct ast_vm_user *vmu = NULL, *cur;
1604 AST_LIST_LOCK(&users);
1606 if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1607 context = "default";
1609 AST_LIST_TRAVERSE(&users, cur, list) {
1611 if (cur->imapversion != imapversion) {
1615 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1617 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
1621 /* Make a copy, so that on a reload, we have no race */
1622 if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
1625 vmu->emailbody = ast_strdup(cur->emailbody);
1626 vmu->emailsubject = ast_strdup(cur->emailsubject);
1628 ast_set2_flag(vmu, !ivm, VM_ALLOCED);
1629 AST_LIST_NEXT(vmu, list) = NULL;
1632 vmu = find_user_realtime(ivm, context, mailbox);
1633 AST_LIST_UNLOCK(&users);
1638 * \brief Resets a user password to a specified password.
1643 * This does the actual change password work, called by the vm_change_password() function.
1645 * \return zero on success, -1 on error.
1647 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
1649 /* This function could be made to generate one from a database, too */
1650 struct ast_vm_user *cur;
1652 AST_LIST_LOCK(&users);
1653 AST_LIST_TRAVERSE(&users, cur, list) {
1654 if ((!context || !strcasecmp(context, cur->context)) &&
1655 (!strcasecmp(mailbox, cur->mailbox)))
1659 ast_copy_string(cur->password, newpass, sizeof(cur->password));
1662 AST_LIST_UNLOCK(&users);
1667 * \brief The handler for the change password option.
1668 * \param vmu The voicemail user to work with.
1669 * \param newpassword The new password (that has been gathered from the appropriate prompting).
1670 * 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.
1671 * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
1673 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
1675 struct ast_config *cfg = NULL;
1676 struct ast_variable *var = NULL;
1677 struct ast_category *cat = NULL;
1678 char *category = NULL, *value = NULL, *new = NULL;
1679 const char *tmp = NULL;
1680 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
1681 char secretfn[PATH_MAX] = "";
1684 if (!change_password_realtime(vmu, newpassword))
1687 /* check if we should store the secret in the spool directory next to the messages */
1688 switch (vmu->passwordlocation) {
1689 case OPT_PWLOC_SPOOLDIR:
1690 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
1691 if (write_password_to_file(secretfn, newpassword) == 0) {
1692 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: secret.conf updated with new password\r\nPasswordSource: secret.conf");
1693 ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
1694 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1695 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1698 ast_verb(4, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
1701 case OPT_PWLOC_VOICEMAILCONF:
1702 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1703 while ((category = ast_category_browse(cfg, category))) {
1704 if (!strcasecmp(category, vmu->context)) {
1705 if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
1706 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
1709 value = strstr(tmp, ",");
1711 new = alloca(strlen(newpassword)+1);
1712 sprintf(new, "%s", newpassword);
1714 new = alloca((strlen(value) + strlen(newpassword) + 1));
1715 sprintf(new, "%s%s", newpassword, value);
1717 if (!(cat = ast_category_get(cfg, category))) {
1718 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
1721 ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
1725 /* save the results */
1727 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: voicemail.conf updated with new password\r\nPasswordSource: voicemail.conf");
1728 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1729 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1730 ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
1735 case OPT_PWLOC_USERSCONF:
1736 /* check users.conf and update the password stored for the mailbox */
1737 /* if no vmsecret entry exists create one. */
1738 if ((cfg = ast_config_load("users.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1739 ast_debug(4, "we are looking for %s\n", vmu->mailbox);
1740 for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
1741 ast_debug(4, "users.conf: %s\n", category);
1742 if (!strcasecmp(category, vmu->mailbox)) {
1743 if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
1744 ast_debug(3, "looks like we need to make vmsecret!\n");
1745 var = ast_variable_new("vmsecret", newpassword, "");
1749 new = alloca(strlen(newpassword) + 1);
1750 sprintf(new, "%s", newpassword);
1751 if (!(cat = ast_category_get(cfg, category))) {
1752 ast_debug(4, "failed to get category!\n");
1757 ast_variable_update(cat, "vmsecret", new, NULL, 0);
1759 ast_variable_append(cat, var);
1765 /* save the results and clean things up */
1767 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: users.conf updated with new password\r\nPasswordSource: users.conf");
1768 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1769 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1770 ast_config_text_file_save("users.conf", cfg, "AppVoicemail");
1776 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
1779 snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
1780 ast_debug(1, "External password: %s\n",buf);
1781 if (!ast_safe_system(buf)) {
1782 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: external script updated with new password\r\nPasswordSource: external");
1783 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1784 /* Reset the password in memory, too */
1785 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1790 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1791 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1792 * \param len The length of the path string that was written out.
1797 * The path is constructed as
1798 * VM_SPOOL_DIRcontext/ext/folder
1800 * \return zero on success, -1 on error.
1802 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
1804 return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
1808 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1809 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1810 * \param len The length of the path string that was written out.
1814 * The path is constructed as
1815 * VM_SPOOL_DIRcontext/ext/folder
1817 * \return zero on success, -1 on error.
1819 static int make_file(char *dest, const int len, const char *dir, const int num)
1821 return snprintf(dest, len, "%s/msg%04d", dir, num);
1824 /* same as mkstemp, but return a FILE * */
1825 static FILE *vm_mkftemp(char *template)
1828 int pfd = mkstemp(template);
1829 chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
1831 p = fdopen(pfd, "w+");
1840 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
1841 * \param dest String. base directory.
1842 * \param len Length of dest.
1843 * \param context String. Ignored if is null or empty string.
1844 * \param ext String. Ignored if is null or empty string.
1845 * \param folder String. Ignored if is null or empty string.
1846 * \return -1 on failure, 0 on success.
1848 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
1850 mode_t mode = VOICEMAIL_DIR_MODE;
1853 make_dir(dest, len, context, ext, folder);
1854 if ((res = ast_mkdir(dest, mode))) {
1855 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
1861 static const char *mbox(struct ast_vm_user *vmu, int id)
1864 if (vmu && id == 0) {
1865 return vmu->imapfolder;
1868 return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
1871 static int get_folder_by_name(const char *name)
1875 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
1876 if (strcasecmp(name, mailbox_folders[i]) == 0) {
1884 static void free_user(struct ast_vm_user *vmu)
1886 if (ast_test_flag(vmu, VM_ALLOCED)) {
1888 ast_free(vmu->emailbody);
1889 vmu->emailbody = NULL;
1891 ast_free(vmu->emailsubject);
1892 vmu->emailsubject = NULL;
1898 static int vm_allocate_dh(struct vm_state *vms, struct ast_vm_user *vmu, int count_msg) {
1900 int arraysize = (vmu->maxmsg > count_msg ? vmu->maxmsg : count_msg);
1901 if (!vms->dh_arraysize) {
1902 /* initial allocation */
1903 if (!(vms->deleted = ast_calloc(arraysize, sizeof(int)))) {
1906 if (!(vms->heard = ast_calloc(arraysize, sizeof(int)))) {
1909 vms->dh_arraysize = arraysize;
1910 } else if (vms->dh_arraysize < arraysize) {
1911 if (!(vms->deleted = ast_realloc(vms->deleted, arraysize * sizeof(int)))) {
1914 if (!(vms->heard = ast_realloc(vms->heard, arraysize * sizeof(int)))) {
1917 memset(vms->deleted, 0, arraysize * sizeof(int));
1918 memset(vms->heard, 0, arraysize * sizeof(int));
1919 vms->dh_arraysize = arraysize;
1925 /* All IMAP-specific functions should go in this block. This
1926 * keeps them from being spread out all over the code */
1928 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
1931 struct vm_state *vms;
1932 unsigned long messageNum;
1934 /* If greetings aren't stored in IMAP, just delete the file */
1935 if (msgnum < 0 && !imapgreetings) {
1936 ast_filedelete(file, NULL);
1940 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1941 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);
1945 /* find real message number based on msgnum */
1946 /* this may be an index into vms->msgArray based on the msgnum. */
1947 messageNum = vms->msgArray[msgnum];
1948 if (messageNum == 0) {
1949 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
1952 ast_debug(3, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
1953 /* delete message */
1954 snprintf (arg, sizeof(arg), "%lu", messageNum);
1955 ast_mutex_lock(&vms->lock);
1956 mail_setflag (vms->mailstream, arg, "\\DELETED");
1957 mail_expunge(vms->mailstream);
1958 ast_mutex_unlock(&vms->lock);
1961 static void vm_imap_update_msg_id(char *dir, int msgnum, const char *msg_id, struct ast_vm_user *vmu, struct ast_config *msg_cfg, int folder)
1963 struct ast_channel *chan;
1967 struct vm_state *vms;
1968 const char *duration_str;
1972 * First, get things initially set up. If any of this fails, then
1973 * back out before doing anything substantial
1975 vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0);
1980 if (open_mailbox(vms, vmu, folder)) {
1984 chan = ast_dummy_channel_alloc();
1986 close_mailbox(vms, vmu);
1991 * We need to make sure the new message we save has the same
1992 * callerid, flag, and duration as the original message
1994 cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
1996 if (!ast_strlen_zero(cid)) {
1997 ast_callerid_parse(cid, &cid_name, &cid_num);
1998 ast_party_caller_init(ast_channel_caller(chan));
1999 if (!ast_strlen_zero(cid_name)) {
2000 ast_channel_caller(chan)->id.name.valid = 1;
2001 ast_channel_caller(chan)->id.name.str = ast_strdup(cid_name);
2003 if (!ast_strlen_zero(cid_num)) {
2004 ast_channel_caller(chan)->id.number.valid = 1;
2005 ast_channel_caller(chan)->id.number.str = ast_strdup(cid_num);
2009 duration_str = ast_variable_retrieve(msg_cfg, "message", "duration");
2011 if (!ast_strlen_zero(duration_str)) {
2012 sscanf(duration_str, "%30d", &duration);
2016 * IMAP messages cannot be altered once delivered. So we have to delete the
2017 * current message and then re-add it with the updated message ID.
2019 * Furthermore, there currently is no atomic way to create a new message and to
2020 * store it in an arbitrary folder. So we have to save it to the INBOX and then
2021 * move to the appropriate folder.
2023 if (!imap_store_file(dir, vmu->mailbox, vmu->context, msgnum, chan, vmu, vmfmts,
2024 duration, vms, ast_variable_retrieve(msg_cfg, "message", "flag"), msg_id)) {
2025 if (folder != NEW_FOLDER) {
2026 save_to_folder(vmu, vms, msgnum, folder, NULL, 1);
2028 vm_imap_delete(dir, msgnum, vmu);
2030 close_mailbox(vms, vmu);
2031 ast_channel_unref(chan);
2034 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
2036 struct vm_state *vms_p;
2037 char *file, *filename;
2042 /* This function is only used for retrieval of IMAP greetings
2043 * regular messages are not retrieved this way, nor are greetings
2044 * if they are stored locally*/
2045 if (msgnum > -1 || !imapgreetings) {
2048 file = strrchr(ast_strdupa(dir), '/');
2052 ast_debug(1, "Failed to procure file name from directory passed.\n");
2057 /* check if someone is accessing this box right now... */
2058 if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) &&
2059 !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2060 /* Unlike when retrieving a message, it is reasonable not to be able to find a
2061 * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
2062 * that's all we need to do.
2064 if (!(vms_p = create_vm_state_from_user(vmu))) {
2065 ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
2070 /* Greetings will never have a prepended message */
2071 *vms_p->introfn = '\0';
2073 ast_mutex_lock(&vms_p->lock);
2074 if (init_mailstream(vms_p, GREETINGS_FOLDER) || !vms_p->mailstream) {
2075 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL or can't init_mailstream\n");
2076 ast_mutex_unlock(&vms_p->lock);
2080 /*XXX Yuck, this could probably be done a lot better */
2081 for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
2082 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
2083 /* We have the body, now we extract the file name of the first attachment. */
2084 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
2085 attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
2087 ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
2088 ast_mutex_unlock(&vms_p->lock);
2091 filename = strsep(&attachment, ".");
2092 if (!strcmp(filename, file)) {
2093 ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
2094 vms_p->msgArray[vms_p->curmsg] = i + 1;
2095 save_body(body, vms_p, "2", attachment, 0);
2096 ast_mutex_unlock(&vms_p->lock);
2100 ast_mutex_unlock(&vms_p->lock);
2105 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
2108 char *header_content;
2109 char *attachedfilefmt;
2111 struct vm_state *vms;
2112 char text_file[PATH_MAX];
2113 FILE *text_file_ptr;
2115 struct ast_vm_user *vmu;
2117 if (!(vmu = find_user(NULL, context, mailbox))) {
2118 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
2123 if (imapgreetings) {
2124 res = imap_retrieve_greeting(dir, msgnum, vmu);
2132 /* Before anything can happen, we need a vm_state so that we can
2133 * actually access the imap server through the vms->mailstream
2135 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
2136 /* This should not happen. If it does, then I guess we'd
2137 * need to create the vm_state, extract which mailbox to
2138 * open, and then set up the msgArray so that the correct
2139 * IMAP message could be accessed. If I have seen correctly
2140 * though, the vms should be obtainable from the vmstates list
2141 * and should have its msgArray properly set up.
2143 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
2148 make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
2149 snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
2151 /* Don't try to retrieve a message from IMAP if it already is on the file system */
2152 if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
2157 ast_debug(3, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
2158 if (vms->msgArray[msgnum] == 0) {
2159 ast_log(LOG_WARNING, "Trying to access unknown message\n");
2164 /* This will only work for new messages... */
2165 ast_mutex_lock(&vms->lock);
2166 header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
2167 ast_mutex_unlock(&vms->lock);
2168 /* empty string means no valid header */
2169 if (ast_strlen_zero(header_content)) {
2170 ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
2175 ast_mutex_lock(&vms->lock);
2176 mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
2177 ast_mutex_unlock(&vms->lock);
2179 /* We have the body, now we extract the file name of the first attachment. */
2180 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
2181 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
2183 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
2188 /* Find the format of the attached file */
2190 strsep(&attachedfilefmt, ".");
2191 if (!attachedfilefmt) {
2192 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
2197 save_body(body, vms, "2", attachedfilefmt, 0);
2198 if (save_body(body, vms, "3", attachedfilefmt, 1)) {
2199 *vms->introfn = '\0';
2202 /* Get info from headers!! */
2203 snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
2205 if (!(text_file_ptr = fopen(text_file, "w"))) {
2206 ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
2209 fprintf(text_file_ptr, "%s\n", "[message]");
2211 if (get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf))) {
2212 fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
2214 if (get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf))) {
2215 fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
2217 if (get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf))) {
2218 fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
2220 if (get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf))) {
2221 fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
2223 if (get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf))) {
2224 fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
2226 if (get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf))) {
2227 fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
2229 if (get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf))) {
2230 fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
2232 if (get_header_by_tag(header_content, "X-Asterisk-VM-Message-ID:", buf, sizeof(buf))) {
2233 fprintf(text_file_ptr, "msg_id=%s\n", S_OR(buf, ""));
2235 fclose(text_file_ptr);
2242 static int folder_int(const char *folder)
2244 /*assume a NULL folder means INBOX*/
2248 if (!strcasecmp(folder, imapfolder)) {
2250 } else if (!strcasecmp(folder, "Old")) {
2252 } else if (!strcasecmp(folder, "Work")) {
2254 } else if (!strcasecmp(folder, "Family")) {
2256 } else if (!strcasecmp(folder, "Friends")) {
2258 } else if (!strcasecmp(folder, "Cust1")) {
2260 } else if (!strcasecmp(folder, "Cust2")) {
2262 } else if (!strcasecmp(folder, "Cust3")) {
2264 } else if (!strcasecmp(folder, "Cust4")) {
2266 } else if (!strcasecmp(folder, "Cust5")) {
2268 } else if (!strcasecmp(folder, "Urgent")) {
2270 } else { /*assume they meant INBOX if folder is not found otherwise*/
2275 static int __messagecount(const char *context, const char *mailbox, const char *folder)
2280 struct ast_vm_user *vmu, vmus;
2281 struct vm_state *vms_p;
2283 int fold = folder_int(folder);
2286 /* If URGENT, then look at INBOX */
2292 if (ast_strlen_zero(mailbox))
2295 /* We have to get the user before we can open the stream! */
2296 vmu = find_user(&vmus, context, mailbox);
2298 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailbox, context);
2301 /* No IMAP account available */
2302 if (vmu->imapuser[0] == '\0') {
2303 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2308 /* No IMAP account available */
2309 if (vmu->imapuser[0] == '\0') {
2310 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2315 /* check if someone is accessing this box right now... */
2316 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
2318 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
2321 ast_debug(3, "Returning before search - user is logged in\n");
2322 if (fold == 0) { /* INBOX */
2323 return urgent ? vms_p->urgentmessages : vms_p->newmessages;
2325 if (fold == 1) { /* Old messages */
2326 return vms_p->oldmessages;
2330 /* add one if not there... */
2331 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
2333 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
2337 vms_p = create_vm_state_from_user(vmu);
2339 ret = init_mailstream(vms_p, fold);
2340 if (!vms_p->mailstream) {
2341 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
2345 ast_mutex_lock(&vms_p->lock);
2346 pgm = mail_newsearchpgm ();
2347 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
2348 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
2350 if (fold != OLD_FOLDER) {
2354 /* In the special case where fold is 1 (old messages) we have to do things a bit
2355 * differently. Old messages are stored in the INBOX but are marked as "seen"
2361 /* look for urgent messages */
2362 if (fold == NEW_FOLDER) {
2374 vms_p->vmArrayIndex = 0;
2375 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
2376 if (fold == 0 && urgent == 0)
2377 vms_p->newmessages = vms_p->vmArrayIndex;
2379 vms_p->oldmessages = vms_p->vmArrayIndex;
2380 if (fold == 0 && urgent == 1)
2381 vms_p->urgentmessages = vms_p->vmArrayIndex;
2382 /*Freeing the searchpgm also frees the searchhdr*/
2383 mail_free_searchpgm(&pgm);
2384 ast_mutex_unlock(&vms_p->lock);
2386 return vms_p->vmArrayIndex;
2388 ast_mutex_lock(&vms_p->lock);
2389 mail_ping(vms_p->mailstream);
2390 ast_mutex_unlock(&vms_p->lock);
2395 static int imap_check_limits(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu, int msgnum)
2397 /* Check if mailbox is full */
2398 check_quota(vms, vmu->imapfolder);
2399 if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
2400 ast_debug(1, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
2402 ast_play_and_wait(chan, "vm-mailboxfull");
2407 /* Check if we have exceeded maxmsg */
2408 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));
2409 if (msgnum >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
2410 ast_log(LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u >= %u)\n", msgnum, vmu->maxmsg);
2412 ast_play_and_wait(chan, "vm-mailboxfull");
2413 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
2422 * \brief Gets the number of messages that exist in a mailbox folder.
2427 * This method is used when IMAP backend is used.
2428 * \return The number of messages in this mailbox folder (zero or more).
2430 static int messagecount(const char *context, const char *mailbox, const char *folder)
2432 if (ast_strlen_zero(folder) || !strcmp(folder, "INBOX")) {
2433 return __messagecount(context, mailbox, "INBOX") + __messagecount(context, mailbox, "Urgent");
2435 return __messagecount(context, mailbox, folder);
2439 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, const char *msg_id)
2441 char *myserveremail = serveremail;
2443 char introfn[PATH_MAX];
2447 char tmp[80] = "/tmp/astmail-XXXXXX";
2452 int ret; /* for better error checking */
2453 char *imap_flags = NIL;
2454 int msgcount = (messagecount(vmu->context, vmu->mailbox, "INBOX") + messagecount(vmu->context, vmu->mailbox, "Old"));
2455 int box = NEW_FOLDER;
2457 /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
2459 if(!imapgreetings) {
2462 box = GREETINGS_FOLDER;
2466 if (imap_check_limits(chan, vms, vmu, msgcount)) {
2470 /* Set urgent flag for IMAP message */
2471 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
2472 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
2473 imap_flags = "\\FLAGGED";
2476 /* Attach only the first format */
2477 fmt = ast_strdupa(fmt);
2479 strsep(&stringp, "|");
2481 if (!ast_strlen_zero(vmu->serveremail))
2482 myserveremail = vmu->serveremail;
2485 make_file(fn, sizeof(fn), dir, msgnum);
2487 ast_copy_string (fn, dir, sizeof(fn));
2489 snprintf(introfn, sizeof(introfn), "%sintro", fn);
2490 if (ast_fileexists(introfn, NULL, NULL) <= 0) {
2494 if (ast_strlen_zero(vmu->email)) {
2495 /* We need the vmu->email to be set when we call make_email_file, but
2496 * if we keep it set, a duplicate e-mail will be created. So at the end
2497 * of this function, we will revert back to an empty string if tempcopy
2500 ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
2504 if (!strcmp(fmt, "wav49"))
2506 ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
2508 /* Make a temporary file instead of piping directly to sendmail, in case the mail
2510 if (!(p = vm_mkftemp(tmp))) {
2511 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
2513 *(vmu->email) = '\0';
2517 if (msgnum < 0 && imapgreetings) {
2518 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
2519 ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
2522 imap_delete_old_greeting(fn, vms);
2525 make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, "INBOX",
2526 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL),
2527 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, NULL),
2528 fn, introfn, fmt, duration, 1, chan, NULL, 1, flag, msg_id);
2529 /* read mail file to memory */
2532 if (!(buf = ast_malloc(len + 1))) {
2533 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
2536 *(vmu->email) = '\0';
2539 if (fread(buf, len, 1, p) < len) {
2541 ast_log(LOG_ERROR, "Short read while reading in mail file.\n");
2545 ((char *) buf)[len] = '\0';
2546 INIT(&str, mail_string, buf, len);
2547 ret = init_mailstream(vms, box);
2549 imap_mailbox_name(mailbox, sizeof(mailbox), vms, box, 1);
2550 ast_mutex_lock(&vms->lock);
2551 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
2552 ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
2553 ast_mutex_unlock(&vms->lock);
2558 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
2564 ast_debug(3, "%s stored\n", fn);
2567 *(vmu->email) = '\0';
2568 inprocess_count(vmu->mailbox, vmu->context, -1);
2574 * \brief Gets the number of messages that exist in the inbox folder.
2575 * \param mailbox_context
2576 * \param newmsgs The variable that is updated with the count of new messages within this inbox.
2577 * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
2578 * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
2580 * This method is used when IMAP backend is used.
2581 * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
2583 * \return zero on success, -1 on error.
2586 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
2588 char tmp[PATH_MAX] = "";
2600 ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
2601 /* If no mailbox, return immediately */
2602 if (ast_strlen_zero(mailbox_context))
2605 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2606 context = strchr(tmp, '@');
2607 if (strchr(mailbox_context, ',')) {
2608 int tmpnew, tmpold, tmpurgent;
2609 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2611 while ((cur = strsep(&mb, ", "))) {
2612 if (!ast_strlen_zero(cur)) {
2613 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2621 *urgentmsgs += tmpurgent;
2632 context = "default";
2633 mailboxnc = (char *) mailbox_context;
2637 struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
2639 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
2642 if ((*newmsgs = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
2647 if ((*oldmsgs = __messagecount(context, mailboxnc, "Old")) < 0) {
2652 if ((*urgentmsgs = __messagecount(context, mailboxnc, "Urgent")) < 0) {
2660 * \brief Determines if the given folder has messages.
2661 * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
2662 * \param folder the folder to look in
2664 * This function is used when the mailbox is stored in an IMAP back end.
2665 * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
2666 * \return 1 if the folder has one or more messages. zero otherwise.
2669 static int has_voicemail(const char *mailbox, const char *folder)
2671 char tmp[256], *tmp2, *box, *context;
2672 ast_copy_string(tmp, mailbox, sizeof(tmp));
2674 if (strchr(tmp2, ',') || strchr(tmp2, '&')) {
2675 while ((box = strsep(&tmp2, ",&"))) {
2676 if (!ast_strlen_zero(box)) {
2677 if (has_voicemail(box, folder)) {
2683 if ((context = strchr(tmp, '@'))) {
2686 context = "default";
2688 return __messagecount(context, tmp, folder) ? 1 : 0;
2692 * \brief Copies a message from one mailbox to another.
2702 * This works with IMAP storage based mailboxes.
2704 * \return zero on success, -1 on error.
2706 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, const char *dest_folder)
2708 struct vm_state *sendvms = NULL;
2709 char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
2710 if (msgnum >= recip->maxmsg) {
2711 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
2714 if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
2715 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
2718 if (!get_vm_state_by_imapuser(recip->imapuser, 0)) {
2719 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
2722 snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
2723 ast_mutex_lock(&sendvms->lock);
2724 if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
2725 ast_mutex_unlock(&sendvms->lock);
2728 ast_mutex_unlock(&sendvms->lock);
2729 ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
2733 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
2735 char tmp[256], *t = tmp;
2736 size_t left = sizeof(tmp);
2738 if (box == OLD_FOLDER) {
2739 ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
2741 ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
2744 if (box == NEW_FOLDER) {
2745 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
2747 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
2750 /* Build up server information */
2751 ast_build_string(&t, &left, "{%s:%s/imap", S_OR(vms->imapserver, imapserver), S_OR(vms->imapport, imapport));
2753 /* Add authentication user if present */
2754 if (!ast_strlen_zero(authuser))
2755 ast_build_string(&t, &left, "/authuser=%s", authuser);
2757 /* Add flags if present */
2758 if (!ast_strlen_zero(imapflags) || !(ast_strlen_zero(vms->imapflags))) {
2759 ast_build_string(&t, &left, "/%s", S_OR(vms->imapflags, imapflags));
2762 /* End with username */
2764 ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
2766 ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
2768 if (box == NEW_FOLDER || box == OLD_FOLDER)
2769 snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
2770 else if (box == GREETINGS_FOLDER)
2771 snprintf(spec, len, "%s%s", tmp, greetingfolder);
2772 else { /* Other folders such as Friends, Family, etc... */
2773 if (!ast_strlen_zero(imapparentfolder)) {
2774 /* imapparentfolder would typically be set to INBOX */
2775 snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
2777 snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
2782 static int init_mailstream(struct vm_state *vms, int box)
2784 MAILSTREAM *stream = NIL;
2789 ast_log(LOG_ERROR, "vm_state is NULL!\n");
2792 ast_debug(3, "vm_state user is:%s\n", vms->imapuser);
2793 if (vms->mailstream == NIL || !vms->mailstream) {
2794 ast_debug(1, "mailstream not set.\n");
2796 stream = vms->mailstream;
2798 /* debug = T; user wants protocol telemetry? */
2799 debug = NIL; /* NO protocol telemetry? */
2801 if (delimiter == '\0') { /* did not probe the server yet */
2803 #ifdef USE_SYSTEM_IMAP
2804 #include <imap/linkage.c>
2805 #elif defined(USE_SYSTEM_CCLIENT)
2806 #include <c-client/linkage.c>
2808 #include "linkage.c"
2810 /* Connect to INBOX first to get folders delimiter */
2811 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
2812 ast_mutex_lock(&vms->lock);
2813 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2814 ast_mutex_unlock(&vms->lock);
2815 if (stream == NIL) {
2816 ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
2819 get_mailbox_delimiter(vms, stream);
2820 /* update delimiter in imapfolder */
2821 for (cp = vms->imapfolder; *cp; cp++)
2825 /* Now connect to the target folder */
2826 imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
2827 ast_debug(3, "Before mail_open, server: %s, box:%d\n", tmp, box);
2828 ast_mutex_lock(&vms->lock);
2829 vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2830 ast_mutex_unlock(&vms->lock);
2831 if (vms->mailstream == NIL) {
2838 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
2844 /* If Urgent, then look at INBOX */
2850 ast_copy_string(vms->imapuser, vmu->imapuser, sizeof(vms->imapuser));
2851 ast_copy_string(vms->imapfolder, vmu->imapfolder, sizeof(vms->imapfolder));
2852 ast_copy_string(vms->imapserver, vmu->imapserver, sizeof(vms->imapserver));
2853 ast_copy_string(vms->imapport, vmu->imapport, sizeof(vms->imapport));
2854 ast_copy_string(vms->imapflags, vmu->imapflags, sizeof(vms->imapflags));
2855 vms->imapversion = vmu->imapversion;
2856 ast_debug(3, "Before init_mailstream, user is %s\n", vmu->imapuser);
2858 if (init_mailstream(vms, box) || !vms->mailstream) {
2859 ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
2863 create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
2867 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(vmu, box));
2868 check_quota(vms, (char *) mbox(vmu, box));
2871 ast_mutex_lock(&vms->lock);
2872 pgm = mail_newsearchpgm();
2874 /* Check IMAP folder for Asterisk messages only... */
2875 hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : vmu->mailbox));
2876 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", vmu->context);
2881 /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
2882 if (box == NEW_FOLDER && urgent == 1) {
2887 } else if (box == NEW_FOLDER && urgent == 0) {
2892 } else if (box == OLD_FOLDER) {
2897 ast_debug(3, "Before mail_search_full, user is %s\n", vmu->imapuser);
2899 vms->vmArrayIndex = 0;
2900 mail_search_full (vms->mailstream, NULL, pgm, NIL);
2901 vms->lastmsg = vms->vmArrayIndex - 1;
2902 mail_free_searchpgm(&pgm);
2903 /* Since IMAP storage actually stores both old and new messages in the same IMAP folder,
2904 * ensure to allocate enough space to account for all of them. Warn if old messages
2905 * have not been checked first as that is required.
2907 if (box == 0 && !vms->dh_arraysize) {
2908 ast_log(LOG_WARNING, "The code expects the old messages to be checked first, fix the code.\n");
2910 if (vm_allocate_dh(vms, vmu, box == 0 ? vms->vmArrayIndex + vms->oldmessages : vms->lastmsg)) {
2911 ast_mutex_unlock(&vms->lock);
2915 ast_mutex_unlock(&vms->lock);
2919 static void write_file(char *filename, char *buffer, unsigned long len)
2923 output = fopen (filename, "w");
2924 if (fwrite(buffer, len, 1, output) != 1) {
2925 if (ferror(output)) {
2926 ast_log(LOG_ERROR, "Short write while writing e-mail body: %s.\n", strerror(errno));
2932 static void update_messages_by_imapuser(const char *user, unsigned long number)
2934 struct vm_state *vms = get_vm_state_by_imapuser(user, 1);
2936 if (!vms && !(vms = get_vm_state_by_imapuser(user, 0))) {
2940 ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vms->vmArrayIndex, vms->interactive);
2941 vms->msgArray[vms->vmArrayIndex++] = number;
2944 void mm_searched(MAILSTREAM *stream, unsigned long number)
2946 char *mailbox = stream->mailbox, buf[1024] = "", *user;
2948 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
2951 update_messages_by_imapuser(user, number);
2954 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
2956 struct ast_variable *var;
2957 struct ast_vm_user *vmu;
2959 vmu = ast_calloc(1, sizeof *vmu);
2962 ast_set_flag(vmu, VM_ALLOCED);
2963 populate_defaults(vmu);
2965 var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
2967 apply_options_full(vmu, var);
2968 ast_variables_destroy(var);
2976 /* Interfaces to C-client */
2978 void mm_exists(MAILSTREAM * stream, unsigned long number)
2980 /* mail_ping will callback here if new mail! */
2981 ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
2982 if (number == 0) return;
2987 void mm_expunged(MAILSTREAM * stream, unsigned long number)
2989 /* mail_ping will callback here if expunged mail! */
2990 ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
2991 if (number == 0) return;
2996 void mm_flags(MAILSTREAM * stream, unsigned long number)
2998 /* mail_ping will callback here if read mail! */
2999 ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
3000 if (number == 0) return;
3005 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
3007 ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
3008 mm_log (string, errflg);
3012 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
3014 if (delimiter == '\0') {
3018 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
3019 if (attributes & LATT_NOINFERIORS)
3020 ast_debug(5, "no inferiors\n");
3021 if (attributes & LATT_NOSELECT)
3022 ast_debug(5, "no select\n");
3023 if (attributes & LATT_MARKED)
3024 ast_debug(5, "marked\n");
3025 if (attributes & LATT_UNMARKED)
3026 ast_debug(5, "unmarked\n");
3030 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
3032 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
3033 if (attributes & LATT_NOINFERIORS)
3034 ast_debug(5, "no inferiors\n");
3035 if (attributes & LATT_NOSELECT)
3036 ast_debug(5, "no select\n");
3037 if (attributes & LATT_MARKED)
3038 ast_debug(5, "marked\n");
3039 if (attributes & LATT_UNMARKED)
3040 ast_debug(5, "unmarked\n");
3044 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
3046 ast_log(AST_LOG_NOTICE, " Mailbox %s", mailbox);
3047 if (status->flags & SA_MESSAGES)
3048 ast_log(AST_LOG_NOTICE, ", %lu messages", status->messages);
3049 if (status->flags & SA_RECENT)
3050 ast_log(AST_LOG_NOTICE, ", %lu recent", status->recent);
3051 if (status->flags & SA_UNSEEN)
3052 ast_log(AST_LOG_NOTICE, ", %lu unseen", status->unseen);
3053 if (status->flags & SA_UIDVALIDITY)
3054 ast_log(AST_LOG_NOTICE, ", %lu UID validity", status->uidvalidity);
3055 if (status->flags & SA_UIDNEXT)
3056 ast_log(AST_LOG_NOTICE, ", %lu next UID", status->uidnext);
3057 ast_log(AST_LOG_NOTICE, "\n");
3061 void mm_log(char *string, long errflg)
3063 switch ((short) errflg) {