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>
53 <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
54 <depend>generic_odbc</depend>
56 <conflict>IMAP_STORAGE</conflict>
57 <conflict>FILE_STORAGE</conflict>
58 <defaultenabled>no</defaultenabled>
60 <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
61 <depend>imap_tk</depend>
62 <conflict>ODBC_STORAGE</conflict>
63 <conflict>FILE_STORAGE</conflict>
64 <use type="external">openssl</use>
65 <defaultenabled>no</defaultenabled>
76 #ifdef USE_SYSTEM_IMAP
77 #include <imap/c-client.h>
78 #include <imap/imap4r1.h>
79 #include <imap/linkage.h>
80 #elif defined (USE_SYSTEM_CCLIENT)
81 #include <c-client/c-client.h>
82 #include <c-client/imap4r1.h>
83 #include <c-client/linkage.h>
91 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
93 #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR */
99 #if defined(__FreeBSD__) || defined(__OpenBSD__)
100 #include <sys/wait.h>
103 #include "asterisk/logger.h"
104 #include "asterisk/lock.h"
105 #include "asterisk/file.h"
106 #include "asterisk/channel.h"
107 #include "asterisk/pbx.h"
108 #include "asterisk/config.h"
109 #include "asterisk/say.h"
110 #include "asterisk/module.h"
111 #include "asterisk/adsi.h"
112 #include "asterisk/app.h"
113 #include "asterisk/manager.h"
114 #include "asterisk/dsp.h"
115 #include "asterisk/localtime.h"
116 #include "asterisk/cli.h"
117 #include "asterisk/utils.h"
118 #include "asterisk/stringfields.h"
119 #include "asterisk/smdi.h"
120 #include "asterisk/astobj2.h"
121 #include "asterisk/event.h"
122 #include "asterisk/taskprocessor.h"
123 #include "asterisk/test.h"
126 #include "asterisk/res_odbc.h"
130 #include "asterisk/threadstorage.h"
134 <application name="VoiceMail" language="en_US">
136 Leave a Voicemail message.
139 <parameter name="mailboxs" argsep="&" required="true">
140 <argument name="mailbox1" argsep="@" required="true">
141 <argument name="mailbox" required="true" />
142 <argument name="context" />
144 <argument name="mailbox2" argsep="@" multiple="true">
145 <argument name="mailbox" required="true" />
146 <argument name="context" />
149 <parameter name="options">
152 <para>Play the <literal>busy</literal> greeting to the calling party.</para>
155 <argument name="c" />
156 <para>Accept digits for a new extension in context <replaceable>c</replaceable>,
157 if played during the greeting. Context defaults to the current context.</para>
160 <argument name="#" required="true" />
161 <para>Use the specified amount of gain when recording the voicemail
162 message. The units are whole-number decibels (dB). Only works on supported
163 technologies, which is DAHDI only.</para>
166 <para>Skip the playback of instructions for leaving a message to the
167 calling party.</para>
170 <para>Play the <literal>unavailable</literal> greeting.</para>
173 <para>Mark message as <literal>URGENT</literal>.</para>
176 <para>Mark message as <literal>PRIORITY</literal>.</para>
182 <para>This application allows the calling party to leave a message for the specified
183 list of mailboxes. When multiple mailboxes are specified, the greeting will be taken from
184 the first mailbox specified. Dialplan execution will stop if the specified mailbox does not
186 <para>The Voicemail application will exit if any of the following DTMF digits are received:</para>
189 <para>Jump to the <literal>o</literal> extension in the current dialplan context.</para>
192 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
195 <para>This application will set the following channel variable upon completion:</para>
197 <variable name="VMSTATUS">
198 <para>This indicates the status of the execution of the VoiceMail application.</para>
199 <value name="SUCCESS" />
200 <value name="USEREXIT" />
201 <value name="FAILED" />
206 <ref type="application">VoiceMailMain</ref>
209 <application name="VoiceMailMain" language="en_US">
211 Check Voicemail messages.
214 <parameter name="mailbox" required="true" argsep="@">
215 <argument name="mailbox" />
216 <argument name="context" />
218 <parameter name="options">
221 <para>Consider the <replaceable>mailbox</replaceable> parameter as a prefix to
222 the mailbox that is entered by the caller.</para>
225 <argument name="#" required="true" />
226 <para>Use the specified amount of gain when recording a voicemail message.
227 The units are whole-number decibels (dB).</para>
230 <para>Skip checking the passcode for the mailbox.</para>
233 <argument name="folder" required="true" />
234 <para>Skip folder prompt and go directly to <replaceable>folder</replaceable> specified.
235 Defaults to <literal>INBOX</literal> (or <literal>0</literal>).</para>
237 <enum name="0"><para>INBOX</para></enum>
238 <enum name="1"><para>Old</para></enum>
239 <enum name="2"><para>Work</para></enum>
240 <enum name="3"><para>Family</para></enum>
241 <enum name="4"><para>Friends</para></enum>
242 <enum name="5"><para>Cust1</para></enum>
243 <enum name="6"><para>Cust2</para></enum>
244 <enum name="7"><para>Cust3</para></enum>
245 <enum name="8"><para>Cust4</para></enum>
246 <enum name="9"><para>Cust5</para></enum>
253 <para>This application allows the calling party to check voicemail messages. A specific
254 <replaceable>mailbox</replaceable>, and optional corresponding <replaceable>context</replaceable>,
255 may be specified. If a <replaceable>mailbox</replaceable> is not provided, the calling party will
256 be prompted to enter one. If a <replaceable>context</replaceable> is not specified, the
257 <literal>default</literal> context will be used.</para>
258 <para>The VoiceMailMain application will exit if the following DTMF digit is entered as Mailbox
259 or Password, and the extension exists:</para>
262 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
267 <ref type="application">VoiceMail</ref>
270 <application name="MailboxExists" language="en_US">
272 Check to see if Voicemail mailbox exists.
275 <parameter name="mailbox" required="true" argsep="@">
276 <argument name="mailbox" required="true" />
277 <argument name="context" />
279 <parameter name="options">
280 <para>None options.</para>
284 <para>Check to see if the specified <replaceable>mailbox</replaceable> exists. If no voicemail
285 <replaceable>context</replaceable> is specified, the <literal>default</literal> context
287 <para>This application will set the following channel variable upon completion:</para>
289 <variable name="VMBOXEXISTSSTATUS">
290 <para>This will contain the status of the execution of the MailboxExists application.
291 Possible values include:</para>
292 <value name="SUCCESS" />
293 <value name="FAILED" />
298 <application name="VMAuthenticate" language="en_US">
300 Authenticate with Voicemail passwords.
303 <parameter name="mailbox" required="true" argsep="@">
304 <argument name="mailbox" />
305 <argument name="context" />
307 <parameter name="options">
310 <para>Skip playing the initial prompts.</para>
316 <para>This application behaves the same way as the Authenticate application, but the passwords
317 are taken from <filename>voicemail.conf</filename>. If the <replaceable>mailbox</replaceable> is
318 specified, only that mailbox's password will be considered valid. If the <replaceable>mailbox</replaceable>
319 is not specified, the channel variable <variable>AUTH_MAILBOX</variable> will be set with the authenticated
321 <para>The VMAuthenticate application will exit if the following DTMF digit is entered as Mailbox
322 or Password, and the extension exists:</para>
325 <para>Jump to the <literal>a</literal> extension in the current dialplan context.</para>
330 <application name="VMSayName" language="en_US">
332 Play the name of a voicemail user
335 <parameter name="mailbox" required="true" argsep="@">
336 <argument name="mailbox" />
337 <argument name="context" />
341 <para>This application will say the recorded name of the voicemail user specified as the
342 argument to this application. If no context is provided, <literal>default</literal> is assumed.</para>
345 <function name="MAILBOX_EXISTS" language="en_US">
347 Tell if a mailbox is configured.
350 <parameter name="mailbox" required="true" />
351 <parameter name="context" />
354 <para>Returns a boolean of whether the corresponding <replaceable>mailbox</replaceable> exists.
355 If <replaceable>context</replaceable> is not specified, defaults to the <literal>default</literal>
359 <manager name="VoicemailUsersList" language="en_US">
361 List All Voicemail User Information.
364 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
372 static char imapserver[48];
373 static char imapport[8];
374 static char imapflags[128];
375 static char imapfolder[64];
376 static char imapparentfolder[64] = "\0";
377 static char greetingfolder[64];
378 static char authuser[32];
379 static char authpassword[42];
380 static int imapversion = 1;
382 static int expungeonhangup = 1;
383 static int imapgreetings = 0;
384 static char delimiter = '\0';
389 AST_THREADSTORAGE(ts_vmstate);
391 /* Forward declarations for IMAP */
392 static int init_mailstream(struct vm_state *vms, int box);
393 static void write_file(char *filename, char *buffer, unsigned long len);
394 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
395 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu);
396 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
397 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive);
398 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
399 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
400 static void vmstate_insert(struct vm_state *vms);
401 static void vmstate_delete(struct vm_state *vms);
402 static void set_update(MAILSTREAM * stream);
403 static void init_vm_state(struct vm_state *vms);
404 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
405 static void get_mailbox_delimiter(MAILSTREAM *stream);
406 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
407 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
408 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);
409 static void update_messages_by_imapuser(const char *user, unsigned long number);
410 static int vm_delete(char *file);
412 static int imap_remove_file (char *dir, int msgnum);
413 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
414 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
415 static void check_quota(struct vm_state *vms, char *mailbox);
416 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
418 struct vm_state *vms;
419 AST_LIST_ENTRY(vmstate) list;
422 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
426 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
428 #define COMMAND_TIMEOUT 5000
429 /* Don't modify these here; set your umask at runtime instead */
430 #define VOICEMAIL_DIR_MODE 0777
431 #define VOICEMAIL_FILE_MODE 0666
432 #define CHUNKSIZE 65536
434 #define VOICEMAIL_CONFIG "voicemail.conf"
435 #define ASTERISK_USERNAME "asterisk"
437 /* Define fast-forward, pause, restart, and reverse keys
438 while listening to a voicemail message - these are
439 strings, not characters */
440 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
441 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
442 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
443 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
444 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
445 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
447 /* Default mail command to mail voicemail. Change it with the
448 mailcmd= command in voicemail.conf */
449 #define SENDMAIL "/usr/sbin/sendmail -t"
451 #define INTRO "vm-intro"
454 #define MAXMSGLIMIT 9999
456 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
458 #define BASELINELEN 72
459 #define BASEMAXINLINE 256
466 #define MAX_DATETIME_FORMAT 512
467 #define MAX_NUM_CID_CONTEXTS 10
469 #define VM_REVIEW (1 << 0) /*!< After recording, permit the caller to review the recording before saving */
470 #define VM_OPERATOR (1 << 1) /*!< Allow 0 to be pressed to go to 'o' extension */
471 #define VM_SAYCID (1 << 2) /*!< Repeat the CallerID info during envelope playback */
472 #define VM_SVMAIL (1 << 3) /*!< Allow the user to compose a new VM from within VoicemailMain */
473 #define VM_ENVELOPE (1 << 4) /*!< Play the envelope information (who-from, time received, etc.) */
474 #define VM_SAYDURATION (1 << 5) /*!< Play the length of the message during envelope playback */
475 #define VM_SKIPAFTERCMD (1 << 6) /*!< After deletion, assume caller wants to go to the next message */
476 #define VM_FORCENAME (1 << 7) /*!< Have new users record their name */
477 #define VM_FORCEGREET (1 << 8) /*!< Have new users record their greetings */
478 #define VM_PBXSKIP (1 << 9) /*!< Skip the [PBX] preamble in the Subject line of emails */
479 #define VM_DIRECFORWARD (1 << 10) /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
480 #define VM_ATTACH (1 << 11) /*!< Attach message to voicemail notifications? */
481 #define VM_DELETE (1 << 12) /*!< Delete message after sending notification */
482 #define VM_ALLOCED (1 << 13) /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
483 #define VM_SEARCH (1 << 14) /*!< Search all contexts for a matching mailbox */
484 #define VM_TEMPGREETWARN (1 << 15) /*!< Remind user tempgreeting is set */
485 #define VM_MOVEHEARD (1 << 16) /*!< Move a "heard" message to Old after listening to it */
486 #define VM_MESSAGEWRAP (1 << 17) /*!< Wrap around from the last message to the first, and vice-versa */
487 #define VM_FWDURGAUTO (1 << 18) /*!< Autoset of Urgent flag on forwarded Urgent messages set globally */
488 #define ERROR_LOCK_PATH -100
489 #define OPERATOR_EXIT 300
501 enum vm_option_flags {
502 OPT_SILENT = (1 << 0),
503 OPT_BUSY_GREETING = (1 << 1),
504 OPT_UNAVAIL_GREETING = (1 << 2),
505 OPT_RECORDGAIN = (1 << 3),
506 OPT_PREPEND_MAILBOX = (1 << 4),
507 OPT_AUTOPLAY = (1 << 6),
508 OPT_DTMFEXIT = (1 << 7),
509 OPT_MESSAGE_Urgent = (1 << 8),
510 OPT_MESSAGE_PRIORITY = (1 << 9)
513 enum vm_option_args {
514 OPT_ARG_RECORDGAIN = 0,
515 OPT_ARG_PLAYFOLDER = 1,
516 OPT_ARG_DTMFEXIT = 2,
517 /* This *must* be the last value in this enum! */
518 OPT_ARG_ARRAY_SIZE = 3,
521 enum vm_passwordlocation {
522 OPT_PWLOC_VOICEMAILCONF = 0,
523 OPT_PWLOC_SPOOLDIR = 1,
524 OPT_PWLOC_USERSCONF = 2,
527 AST_APP_OPTIONS(vm_app_options, {
528 AST_APP_OPTION('s', OPT_SILENT),
529 AST_APP_OPTION('b', OPT_BUSY_GREETING),
530 AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
531 AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
532 AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
533 AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
534 AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
535 AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
536 AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY)
539 static int load_config(int reload);
541 /*! \page vmlang Voicemail Language Syntaxes Supported
543 \par Syntaxes supported, not really language codes.
550 \arg \b pt - Portuguese
551 \arg \b pt_BR - Portuguese (Brazil)
553 \arg \b no - Norwegian
555 \arg \b tw - Chinese (Taiwan)
556 \arg \b ua - Ukrainian
558 German requires the following additional soundfile:
559 \arg \b 1F einE (feminine)
561 Spanish requires the following additional soundfile:
562 \arg \b 1M un (masculine)
564 Dutch, Portuguese & Spanish require the following additional soundfiles:
565 \arg \b vm-INBOXs singular of 'new'
566 \arg \b vm-Olds singular of 'old/heard/read'
569 \arg \b vm-INBOX nieuwe (nl)
570 \arg \b vm-Old oude (nl)
573 \arg \b vm-new-a 'new', feminine singular accusative
574 \arg \b vm-new-e 'new', feminine plural accusative
575 \arg \b vm-new-ych 'new', feminine plural genitive
576 \arg \b vm-old-a 'old', feminine singular accusative
577 \arg \b vm-old-e 'old', feminine plural accusative
578 \arg \b vm-old-ych 'old', feminine plural genitive
579 \arg \b digits/1-a 'one', not always same as 'digits/1'
580 \arg \b digits/2-ie 'two', not always same as 'digits/2'
583 \arg \b vm-nytt singular of 'new'
584 \arg \b vm-nya plural of 'new'
585 \arg \b vm-gammalt singular of 'old'
586 \arg \b vm-gamla plural of 'old'
587 \arg \b digits/ett 'one', not always same as 'digits/1'
590 \arg \b vm-ny singular of 'new'
591 \arg \b vm-nye plural of 'new'
592 \arg \b vm-gammel singular of 'old'
593 \arg \b vm-gamle plural of 'old'
601 Italian requires the following additional soundfile:
605 \arg \b vm-nuovi new plural
606 \arg \b vm-vecchio old
607 \arg \b vm-vecchi old plural
609 Chinese (Taiwan) requires the following additional soundfile:
610 \arg \b vm-tong A class-word for call (tong1)
611 \arg \b vm-ri A class-word for day (ri4)
612 \arg \b vm-you You (ni3)
613 \arg \b vm-haveno Have no (mei2 you3)
614 \arg \b vm-have Have (you3)
615 \arg \b vm-listen To listen (yao4 ting1)
618 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
619 spelled among others when you have to change folder. For the above reasons, vm-INBOX
620 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
629 unsigned char iobuf[BASEMAXINLINE];
632 /*! Structure for linked list of users
633 * Use ast_vm_user_destroy() to free one of these structures. */
635 char context[AST_MAX_CONTEXT]; /*!< Voicemail context */
636 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
637 char password[80]; /*!< Secret pin code, numbers only */
638 char fullname[80]; /*!< Full name, for directory app */
639 char email[80]; /*!< E-mail address */
640 char *emailsubject; /*!< E-mail subject */
641 char *emailbody; /*!< E-mail body */
642 char pager[80]; /*!< E-mail address to pager (no attachment) */
643 char serveremail[80]; /*!< From: Mail address */
644 char mailcmd[160]; /*!< Configurable mail command */
645 char language[MAX_LANGUAGE]; /*!< Config: Language setting */
646 char zonetag[80]; /*!< Time zone */
647 char locale[20]; /*!< The locale (for presentation of date/time) */
650 char uniqueid[80]; /*!< Unique integer identifier */
652 char attachfmt[20]; /*!< Attachment format */
653 unsigned int flags; /*!< VM_ flags */
655 int minsecs; /*!< Minimum number of seconds per message for this mailbox */
656 int maxmsg; /*!< Maximum number of msgs per folder for this mailbox */
657 int maxdeletedmsg; /*!< Maximum number of deleted msgs saved for this mailbox */
658 int maxsecs; /*!< Maximum number of seconds per message for this mailbox */
659 int passwordlocation; /*!< Storage location of the password */
661 char imapuser[80]; /*!< IMAP server login */
662 char imappassword[80]; /*!< IMAP server password if authpassword not defined */
663 char imapfolder[64]; /*!< IMAP voicemail folder */
664 char imapvmshareid[80]; /*!< Shared mailbox ID to use rather than the dialed one */
665 int imapversion; /*!< If configuration changes, use the new values */
667 double volgain; /*!< Volume gain for voicemails sent via email */
668 AST_LIST_ENTRY(ast_vm_user) list;
671 /*! Voicemail time zones */
673 AST_LIST_ENTRY(vm_zone) list;
676 char msg_format[512];
679 #define VMSTATE_MAX_MSG_ARRAY 256
681 /*! Voicemail mailbox state */
686 char curdir[PATH_MAX];
687 char vmbox[PATH_MAX];
689 char intro[PATH_MAX];
692 int dh_arraysize; /* used for deleted / heard allocation */
702 int updated; /*!< decremented on each mail check until 1 -allows delay */
703 long msgArray[VMSTATE_MAX_MSG_ARRAY];
704 MAILSTREAM *mailstream;
706 char imapuser[80]; /*!< IMAP server login */
707 char imapfolder[64]; /*!< IMAP voicemail folder */
710 char introfn[PATH_MAX]; /*!< Name of prepended file */
711 unsigned int quota_limit;
712 unsigned int quota_usage;
713 struct vm_state *persist_vms;
718 static char odbc_database[80];
719 static char odbc_table[80];
720 #define RETRIEVE(a,b,c,d) retrieve_file(a,b)
721 #define DISPOSE(a,b) remove_file(a,b)
722 #define STORE(a,b,c,d,e,f,g,h,i,j) store_file(a,b,c,d)
723 #define EXISTS(a,b,c,d) (message_exists(a,b))
724 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
725 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
726 #define DELETE(a,b,c,d) (delete_file(a,b))
729 #define DISPOSE(a,b) (imap_remove_file(a,b))
730 #define STORE(a,b,c,d,e,f,g,h,i,j) (imap_store_file(a,b,c,d,e,f,g,h,i,j))
731 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
732 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
733 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
734 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
735 #define DELETE(a,b,c,d) (vm_imap_delete(a,b,d))
737 #define RETRIEVE(a,b,c,d)
739 #define STORE(a,b,c,d,e,f,g,h,i,j)
740 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
741 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
742 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
743 #define DELETE(a,b,c,d) (vm_delete(c))
747 static char VM_SPOOL_DIR[PATH_MAX];
749 static char ext_pass_cmd[128];
750 static char ext_pass_check_cmd[128];
754 #define PWDCHANGE_INTERNAL (1 << 1)
755 #define PWDCHANGE_EXTERNAL (1 << 2)
756 static int pwdchange = PWDCHANGE_INTERNAL;
759 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
762 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
764 # define tdesc "Comedian Mail (Voicemail System)"
768 static char userscontext[AST_MAX_EXTENSION] = "default";
770 static char *addesc = "Comedian Mail";
772 /* Leave a message */
773 static char *app = "VoiceMail";
775 /* Check mail, control, etc */
776 static char *app2 = "VoiceMailMain";
778 static char *app3 = "MailboxExists";
779 static char *app4 = "VMAuthenticate";
781 static char *sayname_app = "VMSayName";
783 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
784 static AST_LIST_HEAD_STATIC(zones, vm_zone);
785 static char zonetag[80];
786 static char locale[20];
787 static int maxsilence;
789 static int maxdeletedmsg;
790 static int silencethreshold = 128;
791 static char serveremail[80];
792 static char mailcmd[160]; /* Configurable mail cmd */
793 static char externnotify[160];
794 static struct ast_smdi_interface *smdi_iface = NULL;
795 static char vmfmts[80];
796 static double volgain;
797 static int vmminsecs;
798 static int vmmaxsecs;
801 static int maxlogins;
802 static int minpassword;
803 static int passwordlocation;
805 /*! Poll mailboxes for changes since there is something external to
806 * app_voicemail that may change them. */
807 static unsigned int poll_mailboxes;
809 /*! Polling frequency */
810 static unsigned int poll_freq;
811 /*! By default, poll every 30 seconds */
812 #define DEFAULT_POLL_FREQ 30
814 AST_MUTEX_DEFINE_STATIC(poll_lock);
815 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
816 static pthread_t poll_thread = AST_PTHREADT_NULL;
817 static unsigned char poll_thread_run;
819 /*! Subscription to ... MWI event subscriptions */
820 static struct ast_event_sub *mwi_sub_sub;
821 /*! Subscription to ... MWI event un-subscriptions */
822 static struct ast_event_sub *mwi_unsub_sub;
825 * \brief An MWI subscription
827 * This is so we can keep track of which mailboxes are subscribed to.
828 * This way, we know which mailboxes to poll when the pollmailboxes
829 * option is being used.
832 AST_RWLIST_ENTRY(mwi_sub) entry;
840 struct mwi_sub_task {
846 static struct ast_taskprocessor *mwi_subscription_tps;
848 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
850 /* custom audio control prompts for voicemail playback */
851 static char listen_control_forward_key[12];
852 static char listen_control_reverse_key[12];
853 static char listen_control_pause_key[12];
854 static char listen_control_restart_key[12];
855 static char listen_control_stop_key[12];
857 /* custom password sounds */
858 static char vm_password[80] = "vm-password";
859 static char vm_newpassword[80] = "vm-newpassword";
860 static char vm_passchanged[80] = "vm-passchanged";
861 static char vm_reenterpassword[80] = "vm-reenterpassword";
862 static char vm_mismatch[80] = "vm-mismatch";
863 static char vm_invalid_password[80] = "vm-invalid-password";
864 static char vm_pls_try_again[80] = "vm-pls-try-again";
867 * XXX If we have the time, motivation, etc. to fix up this prompt, one of the following would be appropriate:
868 * 1. create a sound along the lines of "Please try again. When done, press the pound key" which could be spliced
869 * from existing sound clips. This would require some programming changes in the area of vm_forward options and also
870 * app.c's __ast_play_and_record function
871 * 2. create a sound prompt saying "Please try again. When done recording, press any key to stop and send the prepended
872 * message." At the time of this comment, I think this would require new voice work to be commissioned.
873 * 3. Something way different like providing instructions before a time out or a post-recording menu. This would require
874 * more effort than either of the other two.
876 static char vm_prepend_timeout[80] = "vm-then-pound";
878 static struct ast_flags globalflags = {0};
880 static int saydurationminfo;
882 static char dialcontext[AST_MAX_CONTEXT] = "";
883 static char callcontext[AST_MAX_CONTEXT] = "";
884 static char exitcontext[AST_MAX_CONTEXT] = "";
886 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
889 static char *emailbody = NULL;
890 static char *emailsubject = NULL;
891 static char *pagerbody = NULL;
892 static char *pagersubject = NULL;
893 static char fromstring[100];
894 static char pagerfromstring[100];
895 static char charset[32] = "ISO-8859-1";
897 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
898 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
899 static int adsiver = 1;
900 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
901 static char pagerdateformat[32] = "%A, %B %d, %Y at %r";
903 /* Forward declarations - generic */
904 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
905 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);
906 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
907 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
908 char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
909 signed char record_gain, struct vm_state *vms, char *flag);
910 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
911 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
912 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);
913 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);
914 static void apply_options(struct ast_vm_user *vmu, const char *options);
915 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);
916 static int is_valid_dtmf(const char *key);
917 static void read_password_from_file(const char *secretfn, char *password, int passwordlen);
918 static int write_password_to_file(const char *secretfn, const char *password);
919 static const char *substitute_escapes(const char *value);
921 struct ao2_container *inprocess_container;
929 static int inprocess_hash_fn(const void *obj, const int flags)
931 const struct inprocess *i = obj;
932 return atoi(i->mailbox);
935 static int inprocess_cmp_fn(void *obj, void *arg, int flags)
937 struct inprocess *i = obj, *j = arg;
938 if (strcmp(i->mailbox, j->mailbox)) {
941 return !strcmp(i->context, j->context) ? CMP_MATCH : 0;
944 static int inprocess_count(const char *context, const char *mailbox, int delta)
946 struct inprocess *i, *arg = alloca(sizeof(*arg) + strlen(context) + strlen(mailbox) + 2);
947 arg->context = arg->mailbox + strlen(mailbox) + 1;
948 strcpy(arg->mailbox, mailbox); /* SAFE */
949 strcpy(arg->context, context); /* SAFE */
950 ao2_lock(inprocess_container);
951 if ((i = ao2_find(inprocess_container, arg, 0))) {
952 int ret = ast_atomic_fetchadd_int(&i->count, delta);
953 ao2_unlock(inprocess_container);
958 ast_log(LOG_WARNING, "BUG: ref count decrement on non-existing object???\n");
960 if (!(i = ao2_alloc(sizeof(*i) + strlen(context) + strlen(mailbox) + 2, NULL))) {
961 ao2_unlock(inprocess_container);
964 i->context = i->mailbox + strlen(mailbox) + 1;
965 strcpy(i->mailbox, mailbox); /* SAFE */
966 strcpy(i->context, context); /* SAFE */
968 ao2_link(inprocess_container, i);
969 ao2_unlock(inprocess_container);
974 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
975 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
979 * \brief Strips control and non 7-bit clean characters from input string.
981 * \note To map control and none 7-bit characters to a 7-bit clean characters
982 * please use ast_str_encode_mine().
984 static char *strip_control_and_high(const char *input, char *buf, size_t buflen)
987 for (; *input; input++) {
992 if (bufptr == buf + buflen - 1) {
1002 * \brief Sets default voicemail system options to a voicemail user.
1004 * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
1005 * - all the globalflags
1006 * - the saydurationminfo
1010 * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
1012 * - emailsubject, emailbody set to NULL
1014 static void populate_defaults(struct ast_vm_user *vmu)
1016 ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);
1017 vmu->passwordlocation = passwordlocation;
1018 if (saydurationminfo) {
1019 vmu->saydurationm = saydurationminfo;
1021 ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
1022 ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
1023 ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
1024 ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
1025 ast_copy_string(vmu->locale, locale, sizeof(vmu->locale));
1027 vmu->minsecs = vmminsecs;
1030 vmu->maxsecs = vmmaxsecs;
1033 vmu->maxmsg = maxmsg;
1035 if (maxdeletedmsg) {
1036 vmu->maxdeletedmsg = maxdeletedmsg;
1038 vmu->volgain = volgain;
1039 ast_free(vmu->emailsubject);
1040 vmu->emailsubject = NULL;
1041 ast_free(vmu->emailbody);
1042 vmu->emailbody = NULL;
1044 ast_copy_string(vmu->imapfolder, imapfolder, sizeof(vmu->imapfolder));
1049 * \brief Sets a a specific property value.
1050 * \param vmu The voicemail user object to work with.
1051 * \param var The name of the property to be set.
1052 * \param value The value to be set to the property.
1054 * The property name must be one of the understood properties. See the source for details.
1056 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
1059 if (!strcasecmp(var, "attach")) {
1060 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
1061 } else if (!strcasecmp(var, "attachfmt")) {
1062 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
1063 } else if (!strcasecmp(var, "serveremail")) {
1064 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
1065 } else if (!strcasecmp(var, "emailbody")) {
1066 ast_free(vmu->emailbody);
1067 vmu->emailbody = ast_strdup(substitute_escapes(value));
1068 } else if (!strcasecmp(var, "emailsubject")) {
1069 ast_free(vmu->emailsubject);
1070 vmu->emailsubject = ast_strdup(substitute_escapes(value));
1071 } else if (!strcasecmp(var, "language")) {
1072 ast_copy_string(vmu->language, value, sizeof(vmu->language));
1073 } else if (!strcasecmp(var, "tz")) {
1074 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
1075 } else if (!strcasecmp(var, "locale")) {
1076 ast_copy_string(vmu->locale, value, sizeof(vmu->locale));
1078 } else if (!strcasecmp(var, "imapuser")) {
1079 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
1080 vmu->imapversion = imapversion;
1081 } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
1082 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
1083 vmu->imapversion = imapversion;
1084 } else if (!strcasecmp(var, "imapfolder")) {
1085 ast_copy_string(vmu->imapfolder, value, sizeof(vmu->imapfolder));
1086 } else if (!strcasecmp(var, "imapvmshareid")) {
1087 ast_copy_string(vmu->imapvmshareid, value, sizeof(vmu->imapvmshareid));
1088 vmu->imapversion = imapversion;
1090 } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
1091 ast_set2_flag(vmu, ast_true(value), VM_DELETE);
1092 } else if (!strcasecmp(var, "saycid")){
1093 ast_set2_flag(vmu, ast_true(value), VM_SAYCID);
1094 } else if (!strcasecmp(var, "sendvoicemail")){
1095 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);
1096 } else if (!strcasecmp(var, "review")){
1097 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
1098 } else if (!strcasecmp(var, "tempgreetwarn")){
1099 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);
1100 } else if (!strcasecmp(var, "messagewrap")){
1101 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);
1102 } else if (!strcasecmp(var, "operator")) {
1103 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);
1104 } else if (!strcasecmp(var, "envelope")){
1105 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);
1106 } else if (!strcasecmp(var, "moveheard")){
1107 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
1108 } else if (!strcasecmp(var, "sayduration")){
1109 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);
1110 } else if (!strcasecmp(var, "saydurationm")){
1111 if (sscanf(value, "%30d", &x) == 1) {
1112 vmu->saydurationm = x;
1114 ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
1116 } else if (!strcasecmp(var, "forcename")){
1117 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);
1118 } else if (!strcasecmp(var, "forcegreetings")){
1119 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);
1120 } else if (!strcasecmp(var, "callback")) {
1121 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
1122 } else if (!strcasecmp(var, "dialout")) {
1123 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
1124 } else if (!strcasecmp(var, "exitcontext")) {
1125 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
1126 } else if (!strcasecmp(var, "minsecs")) {
1127 if (sscanf(value, "%30d", &x) == 1 && x >= 0) {
1130 ast_log(LOG_WARNING, "Invalid min message length of %s. Using global value %d\n", value, vmminsecs);
1131 vmu->minsecs = vmminsecs;
1133 } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
1134 vmu->maxsecs = atoi(value);
1135 if (vmu->maxsecs <= 0) {
1136 ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
1137 vmu->maxsecs = vmmaxsecs;
1139 vmu->maxsecs = atoi(value);
1141 if (!strcasecmp(var, "maxmessage"))
1142 ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'. Please make that change in your voicemail config.\n");
1143 } else if (!strcasecmp(var, "maxmsg")) {
1144 vmu->maxmsg = atoi(value);
1145 /* Accept maxmsg=0 (Greetings only voicemail) */
1146 if (vmu->maxmsg < 0) {
1147 ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
1148 vmu->maxmsg = MAXMSG;
1149 } else if (vmu->maxmsg > MAXMSGLIMIT) {
1150 ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
1151 vmu->maxmsg = MAXMSGLIMIT;
1153 } else if (!strcasecmp(var, "nextaftercmd")) {
1154 ast_set2_flag(vmu, ast_true(value), VM_SKIPAFTERCMD);
1155 } else if (!strcasecmp(var, "backupdeleted")) {
1156 if (sscanf(value, "%30d", &x) == 1)
1157 vmu->maxdeletedmsg = x;
1158 else if (ast_true(value))
1159 vmu->maxdeletedmsg = MAXMSG;
1161 vmu->maxdeletedmsg = 0;
1163 if (vmu->maxdeletedmsg < 0) {
1164 ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
1165 vmu->maxdeletedmsg = MAXMSG;
1166 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
1167 ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
1168 vmu->maxdeletedmsg = MAXMSGLIMIT;
1170 } else if (!strcasecmp(var, "volgain")) {
1171 sscanf(value, "%30lf", &vmu->volgain);
1172 } else if (!strcasecmp(var, "passwordlocation")) {
1173 if (!strcasecmp(value, "spooldir")) {
1174 vmu->passwordlocation = OPT_PWLOC_SPOOLDIR;
1176 vmu->passwordlocation = OPT_PWLOC_VOICEMAILCONF;
1178 } else if (!strcasecmp(var, "options")) {
1179 apply_options(vmu, value);
1183 static char *vm_check_password_shell(char *command, char *buf, size_t len)
1185 int fds[2], pid = 0;
1187 memset(buf, 0, len);
1190 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
1193 pid = ast_safe_fork(0);
1199 snprintf(buf, len, "FAILURE: Fork failed");
1203 if (read(fds[0], buf, len) < 0) {
1204 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
1209 AST_DECLARE_APP_ARGS(arg,
1212 char *mycmd = ast_strdupa(command);
1215 dup2(fds[1], STDOUT_FILENO);
1217 ast_close_fds_above_n(STDOUT_FILENO);
1219 AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
1221 execv(arg.v[0], arg.v);
1222 printf("FAILURE: %s", strerror(errno));
1230 * \brief Check that password meets minimum required length
1231 * \param vmu The voicemail user to change the password for.
1232 * \param password The password string to check
1234 * \return zero on ok, 1 on not ok.
1236 static int check_password(struct ast_vm_user *vmu, char *password)
1238 /* check minimum length */
1239 if (strlen(password) < minpassword)
1241 /* check that password does not contain '*' character */
1242 if (!ast_strlen_zero(password) && password[0] == '*')
1244 if (!ast_strlen_zero(ext_pass_check_cmd)) {
1245 char cmd[255], buf[255];
1247 ast_debug(1, "Verify password policies for %s\n", password);
1249 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
1250 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
1251 ast_debug(5, "Result: %s\n", buf);
1252 if (!strncasecmp(buf, "VALID", 5)) {
1253 ast_debug(3, "Passed password check: '%s'\n", buf);
1255 } else if (!strncasecmp(buf, "FAILURE", 7)) {
1256 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
1259 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
1268 * \brief Performs a change of the voicemail passowrd in the realtime engine.
1269 * \param vmu The voicemail user to change the password for.
1270 * \param password The new value to be set to the password for this user.
1272 * This only works if there is a realtime engine configured.
1273 * This is called from the (top level) vm_change_password.
1275 * \return zero on success, -1 on error.
1277 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
1280 if (!strcmp(vmu->password, password)) {
1281 /* No change (but an update would return 0 rows updated, so we opt out here) */
1285 if (strlen(password) > 10) {
1286 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
1288 if (ast_update2_realtime("voicemail", "context", vmu->context, "mailbox", vmu->mailbox, SENTINEL, "password", password, SENTINEL) > 0) {
1289 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: realtime engine updated with new password\r\nPasswordSource: realtime");
1290 ast_copy_string(vmu->password, password, sizeof(vmu->password));
1297 * \brief Destructively Parse options and apply.
1299 static void apply_options(struct ast_vm_user *vmu, const char *options)
1304 stringp = ast_strdupa(options);
1305 while ((s = strsep(&stringp, "|"))) {
1307 if ((var = strsep(&value, "=")) && value) {
1308 apply_option(vmu, var, value);
1314 * \brief Loads the options specific to a voicemail user.
1316 * This is called when a vm_user structure is being set up, such as from load_options.
1318 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
1320 for (; var; var = var->next) {
1321 if (!strcasecmp(var->name, "vmsecret")) {
1322 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1323 } else if (!strcasecmp(var->name, "secret") || !strcasecmp(var->name, "password")) { /* don't overwrite vmsecret if it exists */
1324 if (ast_strlen_zero(retval->password)) {
1325 if (!ast_strlen_zero(var->value) && var->value[0] == '*') {
1326 ast_log(LOG_WARNING, "Invalid password detected for mailbox %s. The password"
1327 "\n\tmust be reset in voicemail.conf.\n", retval->mailbox);
1329 ast_copy_string(retval->password, var->value, sizeof(retval->password));
1332 } else if (!strcasecmp(var->name, "uniqueid")) {
1333 ast_copy_string(retval->uniqueid, var->value, sizeof(retval->uniqueid));
1334 } else if (!strcasecmp(var->name, "pager")) {
1335 ast_copy_string(retval->pager, var->value, sizeof(retval->pager));
1336 } else if (!strcasecmp(var->name, "email")) {
1337 ast_copy_string(retval->email, var->value, sizeof(retval->email));
1338 } else if (!strcasecmp(var->name, "fullname")) {
1339 ast_copy_string(retval->fullname, var->value, sizeof(retval->fullname));
1340 } else if (!strcasecmp(var->name, "context")) {
1341 ast_copy_string(retval->context, var->value, sizeof(retval->context));
1342 } else if (!strcasecmp(var->name, "emailsubject")) {
1343 ast_free(retval->emailsubject);
1344 retval->emailsubject = ast_strdup(substitute_escapes(var->value));
1345 } else if (!strcasecmp(var->name, "emailbody")) {
1346 ast_free(retval->emailbody);
1347 retval->emailbody = ast_strdup(substitute_escapes(var->value));
1349 } else if (!strcasecmp(var->name, "imapuser")) {
1350 ast_copy_string(retval->imapuser, var->value, sizeof(retval->imapuser));
1351 retval->imapversion = imapversion;
1352 } else if (!strcasecmp(var->name, "imappassword") || !strcasecmp(var->name, "imapsecret")) {
1353 ast_copy_string(retval->imappassword, var->value, sizeof(retval->imappassword));
1354 retval->imapversion = imapversion;
1355 } else if (!strcasecmp(var->name, "imapfolder")) {
1356 ast_copy_string(retval->imapfolder, var->value, sizeof(retval->imapfolder));
1357 } else if (!strcasecmp(var->name, "imapvmshareid")) {
1358 ast_copy_string(retval->imapvmshareid, var->value, sizeof(retval->imapvmshareid));
1359 retval->imapversion = imapversion;
1362 apply_option(retval, var->name, var->value);
1367 * \brief Determines if a DTMF key entered is valid.
1368 * \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.
1370 * Tests the character entered against the set of valid DTMF characters.
1371 * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1373 static int is_valid_dtmf(const char *key)
1376 char *local_key = ast_strdupa(key);
1378 for (i = 0; i < strlen(key); ++i) {
1379 if (!strchr(VALID_DTMF, *local_key)) {
1380 ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1389 * \brief Finds a voicemail user from the realtime engine.
1394 * 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.
1396 * \return The ast_vm_user structure for the user that was found.
1398 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1400 struct ast_variable *var;
1401 struct ast_vm_user *retval;
1403 if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1405 ast_set_flag(retval, VM_ALLOCED);
1407 memset(retval, 0, sizeof(*retval));
1409 ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1410 populate_defaults(retval);
1411 if (!context && ast_test_flag((&globalflags), VM_SEARCH))
1412 var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1414 var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1416 apply_options_full(retval, var);
1417 ast_variables_destroy(var);
1428 * \brief Finds a voicemail user from the users file or the realtime engine.
1433 * \return The ast_vm_user structure for the user that was found.
1435 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1437 /* This function could be made to generate one from a database, too */
1438 struct ast_vm_user *vmu = NULL, *cur;
1439 AST_LIST_LOCK(&users);
1441 if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1442 context = "default";
1444 AST_LIST_TRAVERSE(&users, cur, list) {
1446 if (cur->imapversion != imapversion) {
1450 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1452 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
1456 /* Make a copy, so that on a reload, we have no race */
1457 if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
1460 vmu->emailbody = ast_strdup(cur->emailbody);
1461 vmu->emailsubject = ast_strdup(cur->emailsubject);
1463 ast_set2_flag(vmu, !ivm, VM_ALLOCED);
1464 AST_LIST_NEXT(vmu, list) = NULL;
1467 vmu = find_user_realtime(ivm, context, mailbox);
1468 AST_LIST_UNLOCK(&users);
1473 * \brief Resets a user password to a specified password.
1478 * This does the actual change password work, called by the vm_change_password() function.
1480 * \return zero on success, -1 on error.
1482 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
1484 /* This function could be made to generate one from a database, too */
1485 struct ast_vm_user *cur;
1487 AST_LIST_LOCK(&users);
1488 AST_LIST_TRAVERSE(&users, cur, list) {
1489 if ((!context || !strcasecmp(context, cur->context)) &&
1490 (!strcasecmp(mailbox, cur->mailbox)))
1494 ast_copy_string(cur->password, newpass, sizeof(cur->password));
1497 AST_LIST_UNLOCK(&users);
1502 * \brief The handler for the change password option.
1503 * \param vmu The voicemail user to work with.
1504 * \param newpassword The new password (that has been gathered from the appropriate prompting).
1505 * 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.
1506 * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
1508 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
1510 struct ast_config *cfg = NULL;
1511 struct ast_variable *var = NULL;
1512 struct ast_category *cat = NULL;
1513 char *category = NULL, *value = NULL, *new = NULL;
1514 const char *tmp = NULL;
1515 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
1516 char secretfn[PATH_MAX] = "";
1519 if (!change_password_realtime(vmu, newpassword))
1522 /* check if we should store the secret in the spool directory next to the messages */
1523 switch (vmu->passwordlocation) {
1524 case OPT_PWLOC_SPOOLDIR:
1525 snprintf(secretfn, sizeof(secretfn), "%s%s/%s/secret.conf", VM_SPOOL_DIR, vmu->context, vmu->mailbox);
1526 if (write_password_to_file(secretfn, newpassword) == 0) {
1527 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: secret.conf updated with new password\r\nPasswordSource: secret.conf");
1528 ast_verb(4, "Writing voicemail password to file %s succeeded\n", secretfn);
1529 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1530 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1533 ast_verb(4, "Writing voicemail password to file %s failed, falling back to config file\n", secretfn);
1536 case OPT_PWLOC_VOICEMAILCONF:
1537 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1538 while ((category = ast_category_browse(cfg, category))) {
1539 if (!strcasecmp(category, vmu->context)) {
1540 if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
1541 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
1544 value = strstr(tmp, ",");
1546 new = alloca(strlen(newpassword)+1);
1547 sprintf(new, "%s", newpassword);
1549 new = alloca((strlen(value) + strlen(newpassword) + 1));
1550 sprintf(new, "%s%s", newpassword, value);
1552 if (!(cat = ast_category_get(cfg, category))) {
1553 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
1556 ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
1560 /* save the results */
1562 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: voicemail.conf updated with new password\r\nPasswordSource: voicemail.conf");
1563 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1564 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1565 ast_config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
1570 case OPT_PWLOC_USERSCONF:
1571 /* check users.conf and update the password stored for the mailbox */
1572 /* if no vmsecret entry exists create one. */
1573 if ((cfg = ast_config_load("users.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1574 ast_debug(4, "we are looking for %s\n", vmu->mailbox);
1575 for (category = ast_category_browse(cfg, NULL); category; category = ast_category_browse(cfg, category)) {
1576 ast_debug(4, "users.conf: %s\n", category);
1577 if (!strcasecmp(category, vmu->mailbox)) {
1578 if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
1579 ast_debug(3, "looks like we need to make vmsecret!\n");
1580 var = ast_variable_new("vmsecret", newpassword, "");
1584 new = alloca(strlen(newpassword) + 1);
1585 sprintf(new, "%s", newpassword);
1586 if (!(cat = ast_category_get(cfg, category))) {
1587 ast_debug(4, "failed to get category!\n");
1592 ast_variable_update(cat, "vmsecret", new, NULL, 0);
1594 ast_variable_append(cat, var);
1600 /* save the results and clean things up */
1602 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: users.conf updated with new password\r\nPasswordSource: users.conf");
1603 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1604 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1605 ast_config_text_file_save("users.conf", cfg, "AppVoicemail");
1611 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
1614 snprintf(buf, sizeof(buf), "%s %s %s %s", ext_pass_cmd, vmu->context, vmu->mailbox, newpassword);
1615 ast_debug(1, "External password: %s\n",buf);
1616 if (!ast_safe_system(buf)) {
1617 ast_test_suite_event_notify("PASSWORDCHANGED", "Message: external script updated with new password\r\nPasswordSource: external");
1618 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1619 /* Reset the password in memory, too */
1620 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1625 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1626 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1627 * \param len The length of the path string that was written out.
1632 * The path is constructed as
1633 * VM_SPOOL_DIRcontext/ext/folder
1635 * \return zero on success, -1 on error.
1637 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
1639 return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
1643 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1644 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1645 * \param len The length of the path string that was written out.
1649 * The path is constructed as
1650 * VM_SPOOL_DIRcontext/ext/folder
1652 * \return zero on success, -1 on error.
1654 static int make_file(char *dest, const int len, const char *dir, const int num)
1656 return snprintf(dest, len, "%s/msg%04d", dir, num);
1659 /* same as mkstemp, but return a FILE * */
1660 static FILE *vm_mkftemp(char *template)
1663 int pfd = mkstemp(template);
1664 chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
1666 p = fdopen(pfd, "w+");
1675 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
1676 * \param dest String. base directory.
1677 * \param len Length of dest.
1678 * \param context String. Ignored if is null or empty string.
1679 * \param ext String. Ignored if is null or empty string.
1680 * \param folder String. Ignored if is null or empty string.
1681 * \return -1 on failure, 0 on success.
1683 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
1685 mode_t mode = VOICEMAIL_DIR_MODE;
1688 make_dir(dest, len, context, ext, folder);
1689 if ((res = ast_mkdir(dest, mode))) {
1690 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
1696 static const char * const mailbox_folders[] = {
1715 static const char *mbox(struct ast_vm_user *vmu, int id)
1718 if (vmu && id == 0) {
1719 return vmu->imapfolder;
1722 return (id >= 0 && id < ARRAY_LEN(mailbox_folders)) ? mailbox_folders[id] : "Unknown";
1725 static int get_folder_by_name(const char *name)
1729 for (i = 0; i < ARRAY_LEN(mailbox_folders); i++) {
1730 if (strcasecmp(name, mailbox_folders[i]) == 0) {
1738 static void free_user(struct ast_vm_user *vmu)
1740 if (ast_test_flag(vmu, VM_ALLOCED)) {
1742 ast_free(vmu->emailbody);
1743 vmu->emailbody = NULL;
1745 ast_free(vmu->emailsubject);
1746 vmu->emailsubject = NULL;
1752 static int vm_allocate_dh(struct vm_state *vms, struct ast_vm_user *vmu, int count_msg) {
1754 int arraysize = (vmu->maxmsg > count_msg ? vmu->maxmsg : count_msg);
1755 if (!vms->dh_arraysize) {
1756 /* initial allocation */
1757 if (!(vms->deleted = ast_calloc(arraysize, sizeof(int)))) {
1760 if (!(vms->heard = ast_calloc(arraysize, sizeof(int)))) {
1763 vms->dh_arraysize = arraysize;
1764 } else if (vms->dh_arraysize < arraysize) {
1765 if (!(vms->deleted = ast_realloc(vms->deleted, arraysize * sizeof(int)))) {
1768 if (!(vms->heard = ast_realloc(vms->heard, arraysize * sizeof(int)))) {
1771 memset(vms->deleted, 0, arraysize * sizeof(int));
1772 memset(vms->heard, 0, arraysize * sizeof(int));
1773 vms->dh_arraysize = arraysize;
1779 /* All IMAP-specific functions should go in this block. This
1780 * keeps them from being spread out all over the code */
1782 static void vm_imap_delete(char *file, int msgnum, struct ast_vm_user *vmu)
1785 struct vm_state *vms;
1786 unsigned long messageNum;
1788 /* If greetings aren't stored in IMAP, just delete the file */
1789 if (msgnum < 0 && !imapgreetings) {
1790 ast_filedelete(file, NULL);
1794 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1795 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);
1799 /* find real message number based on msgnum */
1800 /* this may be an index into vms->msgArray based on the msgnum. */
1801 messageNum = vms->msgArray[msgnum];
1802 if (messageNum == 0) {
1803 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n", msgnum, messageNum);
1806 ast_debug(3, "deleting msgnum %d, which is mailbox message %lu\n", msgnum, messageNum);
1807 /* delete message */
1808 snprintf (arg, sizeof(arg), "%lu", messageNum);
1809 ast_mutex_lock(&vms->lock);
1810 mail_setflag (vms->mailstream, arg, "\\DELETED");
1811 mail_expunge(vms->mailstream);
1812 ast_mutex_unlock(&vms->lock);
1815 static int imap_retrieve_greeting(const char *dir, const int msgnum, struct ast_vm_user *vmu)
1817 struct vm_state *vms_p;
1818 char *file, *filename;
1823 /* This function is only used for retrieval of IMAP greetings
1824 * regular messages are not retrieved this way, nor are greetings
1825 * if they are stored locally*/
1826 if (msgnum > -1 || !imapgreetings) {
1829 file = strrchr(ast_strdupa(dir), '/');
1833 ast_debug(1, "Failed to procure file name from directory passed.\n");
1838 /* check if someone is accessing this box right now... */
1839 if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) &&
1840 !(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1841 /* Unlike when retrieving a message, it is reasonable not to be able to find a
1842 * vm_state for a mailbox when trying to retrieve a greeting. Just create one,
1843 * that's all we need to do.
1845 if (!(vms_p = create_vm_state_from_user(vmu))) {
1846 ast_log(LOG_NOTICE, "Unable to create vm_state object!\n");
1851 /* Greetings will never have a prepended message */
1852 *vms_p->introfn = '\0';
1854 ast_mutex_lock(&vms_p->lock);
1855 ret = init_mailstream(vms_p, GREETINGS_FOLDER);
1856 if (!vms_p->mailstream) {
1857 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL\n");
1858 ast_mutex_unlock(&vms_p->lock);
1862 /*XXX Yuck, this could probably be done a lot better */
1863 for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
1864 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
1865 /* We have the body, now we extract the file name of the first attachment. */
1866 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1867 attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
1869 ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
1870 ast_mutex_unlock(&vms_p->lock);
1873 filename = strsep(&attachment, ".");
1874 if (!strcmp(filename, file)) {
1875 ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
1876 vms_p->msgArray[vms_p->curmsg] = i + 1;
1877 save_body(body, vms_p, "2", attachment, 0);
1878 ast_mutex_unlock(&vms_p->lock);
1882 ast_mutex_unlock(&vms_p->lock);
1887 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
1890 char *header_content;
1891 char *attachedfilefmt;
1893 struct vm_state *vms;
1894 char text_file[PATH_MAX];
1895 FILE *text_file_ptr;
1897 struct ast_vm_user *vmu;
1899 if (!(vmu = find_user(NULL, context, mailbox))) {
1900 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
1905 if (imapgreetings) {
1906 res = imap_retrieve_greeting(dir, msgnum, vmu);
1914 /* Before anything can happen, we need a vm_state so that we can
1915 * actually access the imap server through the vms->mailstream
1917 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1918 /* This should not happen. If it does, then I guess we'd
1919 * need to create the vm_state, extract which mailbox to
1920 * open, and then set up the msgArray so that the correct
1921 * IMAP message could be accessed. If I have seen correctly
1922 * though, the vms should be obtainable from the vmstates list
1923 * and should have its msgArray properly set up.
1925 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
1930 make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
1931 snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
1933 /* Don't try to retrieve a message from IMAP if it already is on the file system */
1934 if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
1939 ast_debug(3, "Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
1940 if (vms->msgArray[msgnum] == 0) {
1941 ast_log(LOG_WARNING, "Trying to access unknown message\n");
1946 /* This will only work for new messages... */
1947 ast_mutex_lock(&vms->lock);
1948 header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
1949 ast_mutex_unlock(&vms->lock);
1950 /* empty string means no valid header */
1951 if (ast_strlen_zero(header_content)) {
1952 ast_log(LOG_ERROR, "Could not fetch header for message number %ld\n", vms->msgArray[msgnum]);
1957 ast_mutex_lock(&vms->lock);
1958 mail_fetchstructure(vms->mailstream, vms->msgArray[msgnum], &body);
1959 ast_mutex_unlock(&vms->lock);
1961 /* We have the body, now we extract the file name of the first attachment. */
1962 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1963 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
1965 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
1970 /* Find the format of the attached file */
1972 strsep(&attachedfilefmt, ".");
1973 if (!attachedfilefmt) {
1974 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
1979 save_body(body, vms, "2", attachedfilefmt, 0);
1980 if (save_body(body, vms, "3", attachedfilefmt, 1)) {
1981 *vms->introfn = '\0';
1984 /* Get info from headers!! */
1985 snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
1987 if (!(text_file_ptr = fopen(text_file, "w"))) {
1988 ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
1991 fprintf(text_file_ptr, "%s\n", "[message]");
1993 get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf));
1994 fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
1995 get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf));
1996 fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
1997 get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf));
1998 fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
1999 get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf));
2000 fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
2001 get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf));
2002 fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
2003 get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf));
2004 fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
2005 get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf));
2006 fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
2007 fclose(text_file_ptr);
2014 static int folder_int(const char *folder)
2016 /*assume a NULL folder means INBOX*/
2020 if (!strcasecmp(folder, imapfolder)) {
2022 } else if (!strcasecmp(folder, "Old")) {
2024 } else if (!strcasecmp(folder, "Work")) {
2026 } else if (!strcasecmp(folder, "Family")) {
2028 } else if (!strcasecmp(folder, "Friends")) {
2030 } else if (!strcasecmp(folder, "Cust1")) {
2032 } else if (!strcasecmp(folder, "Cust2")) {
2034 } else if (!strcasecmp(folder, "Cust3")) {
2036 } else if (!strcasecmp(folder, "Cust4")) {
2038 } else if (!strcasecmp(folder, "Cust5")) {
2040 } else if (!strcasecmp(folder, "Urgent")) {
2042 } else { /*assume they meant INBOX if folder is not found otherwise*/
2047 static int __messagecount(const char *context, const char *mailbox, const char *folder)
2052 struct ast_vm_user *vmu, vmus;
2053 struct vm_state *vms_p;
2055 int fold = folder_int(folder);
2058 /* If URGENT, then look at INBOX */
2064 if (ast_strlen_zero(mailbox))
2067 /* We have to get the user before we can open the stream! */
2068 vmu = find_user(&vmus, context, mailbox);
2070 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailbox, context);
2073 /* No IMAP account available */
2074 if (vmu->imapuser[0] == '\0') {
2075 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2080 /* No IMAP account available */
2081 if (vmu->imapuser[0] == '\0') {
2082 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
2087 /* check if someone is accessing this box right now... */
2088 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1);
2090 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
2093 ast_debug(3, "Returning before search - user is logged in\n");
2094 if (fold == 0) { /* INBOX */
2095 return urgent ? vms_p->urgentmessages : vms_p->newmessages;
2097 if (fold == 1) { /* Old messages */
2098 return vms_p->oldmessages;
2102 /* add one if not there... */
2103 vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0);
2105 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
2109 vms_p = create_vm_state_from_user(vmu);
2111 ret = init_mailstream(vms_p, fold);
2112 if (!vms_p->mailstream) {
2113 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
2117 ast_mutex_lock(&vms_p->lock);
2118 pgm = mail_newsearchpgm ();
2119 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)(!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : mailbox));
2120 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", (char *) S_OR(context, "default"));
2122 if (fold != OLD_FOLDER) {
2126 /* In the special case where fold is 1 (old messages) we have to do things a bit
2127 * differently. Old messages are stored in the INBOX but are marked as "seen"
2133 /* look for urgent messages */
2134 if (fold == NEW_FOLDER) {
2146 vms_p->vmArrayIndex = 0;
2147 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
2148 if (fold == 0 && urgent == 0)
2149 vms_p->newmessages = vms_p->vmArrayIndex;
2151 vms_p->oldmessages = vms_p->vmArrayIndex;
2152 if (fold == 0 && urgent == 1)
2153 vms_p->urgentmessages = vms_p->vmArrayIndex;
2154 /*Freeing the searchpgm also frees the searchhdr*/
2155 mail_free_searchpgm(&pgm);
2156 ast_mutex_unlock(&vms_p->lock);
2158 return vms_p->vmArrayIndex;
2160 ast_mutex_lock(&vms_p->lock);
2161 mail_ping(vms_p->mailstream);
2162 ast_mutex_unlock(&vms_p->lock);
2167 static int imap_check_limits(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu, int msgnum)
2169 /* Check if mailbox is full */
2170 check_quota(vms, vmu->imapfolder);
2171 if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
2172 ast_debug(1, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
2173 ast_play_and_wait(chan, "vm-mailboxfull");
2177 /* Check if we have exceeded maxmsg */
2178 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));
2179 if (msgnum >= vmu->maxmsg - inprocess_count(vmu->mailbox, vmu->context, +1)) {
2180 ast_log(LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u >= %u)\n", msgnum, vmu->maxmsg);
2181 ast_play_and_wait(chan, "vm-mailboxfull");
2182 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
2190 * \brief Gets the number of messages that exist in a mailbox folder.
2195 * This method is used when IMAP backend is used.
2196 * \return The number of messages in this mailbox folder (zero or more).
2198 static int messagecount(const char *context, const char *mailbox, const char *folder)
2200 if (ast_strlen_zero(folder) || !strcmp(folder, "INBOX")) {
2201 return __messagecount(context, mailbox, "INBOX") + __messagecount(context, mailbox, "Urgent");
2203 return __messagecount(context, mailbox, folder);
2207 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)
2209 char *myserveremail = serveremail;
2211 char introfn[PATH_MAX];
2215 char tmp[80] = "/tmp/astmail-XXXXXX";
2220 int ret; /* for better error checking */
2221 char *imap_flags = NIL;
2222 int msgcount = (messagecount(vmu->context, vmu->mailbox, "INBOX") + messagecount(vmu->context, vmu->mailbox, "Old"));
2223 int box = NEW_FOLDER;
2225 /* Back out early if this is a greeting and we don't want to store greetings in IMAP */
2227 if(!imapgreetings) {
2230 box = GREETINGS_FOLDER;
2234 if (imap_check_limits(chan, vms, vmu, msgcount)) {
2238 /* Set urgent flag for IMAP message */
2239 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
2240 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
2241 imap_flags = "\\FLAGGED";
2244 /* Attach only the first format */
2245 fmt = ast_strdupa(fmt);
2247 strsep(&stringp, "|");
2249 if (!ast_strlen_zero(vmu->serveremail))
2250 myserveremail = vmu->serveremail;
2253 make_file(fn, sizeof(fn), dir, msgnum);
2255 ast_copy_string (fn, dir, sizeof(fn));
2257 snprintf(introfn, sizeof(introfn), "%sintro", fn);
2258 if (ast_fileexists(introfn, NULL, NULL) <= 0) {
2262 if (ast_strlen_zero(vmu->email)) {
2263 /* We need the vmu->email to be set when we call make_email_file, but
2264 * if we keep it set, a duplicate e-mail will be created. So at the end
2265 * of this function, we will revert back to an empty string if tempcopy
2268 ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
2272 if (!strcmp(fmt, "wav49"))
2274 ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
2276 /* Make a temporary file instead of piping directly to sendmail, in case the mail
2278 if (!(p = vm_mkftemp(tmp))) {
2279 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
2281 *(vmu->email) = '\0';
2285 if (msgnum < 0 && imapgreetings) {
2286 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
2287 ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
2290 imap_delete_old_greeting(fn, vms);
2293 make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, "INBOX",
2294 S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
2295 S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL),
2296 fn, introfn, fmt, duration, 1, chan, NULL, 1, flag);
2297 /* read mail file to memory */
2300 if (!(buf = ast_malloc(len + 1))) {
2301 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
2304 *(vmu->email) = '\0';
2307 if (fread(buf, len, 1, p) < len) {
2309 ast_log(LOG_ERROR, "Short read while reading in mail file.\n");
2313 ((char *) buf)[len] = '\0';
2314 INIT(&str, mail_string, buf, len);
2315 ret = init_mailstream(vms, box);
2317 imap_mailbox_name(mailbox, sizeof(mailbox), vms, box, 1);
2318 ast_mutex_lock(&vms->lock);
2319 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
2320 ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
2321 ast_mutex_unlock(&vms->lock);
2326 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n", mailbox);
2332 ast_debug(3, "%s stored\n", fn);
2335 *(vmu->email) = '\0';
2336 inprocess_count(vmu->mailbox, vmu->context, -1);
2342 * \brief Gets the number of messages that exist in the inbox folder.
2343 * \param mailbox_context
2344 * \param newmsgs The variable that is updated with the count of new messages within this inbox.
2345 * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
2346 * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
2348 * This method is used when IMAP backend is used.
2349 * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
2351 * \return zero on success, -1 on error.
2354 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
2356 char tmp[PATH_MAX] = "";
2368 ast_debug(3, "Mailbox is set to %s\n", mailbox_context);
2369 /* If no mailbox, return immediately */
2370 if (ast_strlen_zero(mailbox_context))
2373 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2374 context = strchr(tmp, '@');
2375 if (strchr(mailbox_context, ',')) {
2376 int tmpnew, tmpold, tmpurgent;
2377 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
2379 while ((cur = strsep(&mb, ", "))) {
2380 if (!ast_strlen_zero(cur)) {
2381 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2389 *urgentmsgs += tmpurgent;
2400 context = "default";
2401 mailboxnc = (char *) mailbox_context;
2405 struct ast_vm_user *vmu = find_user(NULL, context, mailboxnc);
2407 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
2410 if ((*newmsgs = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
2415 if ((*oldmsgs = __messagecount(context, mailboxnc, "Old")) < 0) {
2420 if ((*urgentmsgs = __messagecount(context, mailboxnc, "Urgent")) < 0) {
2428 * \brief Determines if the given folder has messages.
2429 * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
2430 * \param folder the folder to look in
2432 * This function is used when the mailbox is stored in an IMAP back end.
2433 * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
2434 * \return 1 if the folder has one or more messages. zero otherwise.
2437 static int has_voicemail(const char *mailbox, const char *folder)
2439 char tmp[256], *tmp2, *box, *context;
2440 ast_copy_string(tmp, mailbox, sizeof(tmp));
2442 if (strchr(tmp2, ',') || strchr(tmp2, '&')) {
2443 while ((box = strsep(&tmp2, ",&"))) {
2444 if (!ast_strlen_zero(box)) {
2445 if (has_voicemail(box, folder)) {
2451 if ((context = strchr(tmp, '@'))) {
2454 context = "default";
2456 return __messagecount(context, tmp, folder) ? 1 : 0;
2460 * \brief Copies a message from one mailbox to another.
2470 * This works with IMAP storage based mailboxes.
2472 * \return zero on success, -1 on error.
2474 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)
2476 struct vm_state *sendvms = NULL, *destvms = NULL;
2477 char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
2478 if (msgnum >= recip->maxmsg) {
2479 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
2482 if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
2483 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
2486 if (!(destvms = get_vm_state_by_imapuser(recip->imapuser, 0))) {
2487 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
2490 snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
2491 ast_mutex_lock(&sendvms->lock);
2492 if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(vmu, imbox)) == T)) {
2493 ast_mutex_unlock(&sendvms->lock);
2496 ast_mutex_unlock(&sendvms->lock);
2497 ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
2501 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
2503 char tmp[256], *t = tmp;
2504 size_t left = sizeof(tmp);
2506 if (box == OLD_FOLDER) {
2507 ast_copy_string(vms->curbox, mbox(NULL, NEW_FOLDER), sizeof(vms->curbox));
2509 ast_copy_string(vms->curbox, mbox(NULL, box), sizeof(vms->curbox));
2512 if (box == NEW_FOLDER) {
2513 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
2515 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(NULL, box));
2518 /* Build up server information */
2519 ast_build_string(&t, &left, "{%s:%s/imap", imapserver, imapport);
2521 /* Add authentication user if present */
2522 if (!ast_strlen_zero(authuser))
2523 ast_build_string(&t, &left, "/authuser=%s", authuser);
2525 /* Add flags if present */
2526 if (!ast_strlen_zero(imapflags))
2527 ast_build_string(&t, &left, "/%s", imapflags);
2529 /* End with username */
2531 ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
2533 ast_build_string(&t, &left, "/user=%s/novalidate-cert}", vms->imapuser);
2535 if (box == NEW_FOLDER || box == OLD_FOLDER)
2536 snprintf(spec, len, "%s%s", tmp, use_folder? vms->imapfolder: "INBOX");
2537 else if (box == GREETINGS_FOLDER)
2538 snprintf(spec, len, "%s%s", tmp, greetingfolder);
2539 else { /* Other folders such as Friends, Family, etc... */
2540 if (!ast_strlen_zero(imapparentfolder)) {
2541 /* imapparentfolder would typically be set to INBOX */
2542 snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(NULL, box));
2544 snprintf(spec, len, "%s%s", tmp, mbox(NULL, box));
2549 static int init_mailstream(struct vm_state *vms, int box)
2551 MAILSTREAM *stream = NIL;
2556 ast_log(LOG_ERROR, "vm_state is NULL!\n");
2559 ast_debug(3, "vm_state user is:%s\n", vms->imapuser);
2560 if (vms->mailstream == NIL || !vms->mailstream) {
2561 ast_debug(1, "mailstream not set.\n");
2563 stream = vms->mailstream;
2565 /* debug = T; user wants protocol telemetry? */
2566 debug = NIL; /* NO protocol telemetry? */
2568 if (delimiter == '\0') { /* did not probe the server yet */
2570 #ifdef USE_SYSTEM_IMAP
2571 #include <imap/linkage.c>
2572 #elif defined(USE_SYSTEM_CCLIENT)
2573 #include <c-client/linkage.c>
2575 #include "linkage.c"
2577 /* Connect to INBOX first to get folders delimiter */
2578 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
2579 ast_mutex_lock(&vms->lock);
2580 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2581 ast_mutex_unlock(&vms->lock);
2582 if (stream == NIL) {
2583 ast_log(LOG_ERROR, "Can't connect to imap server %s\n", tmp);
2586 get_mailbox_delimiter(stream);
2587 /* update delimiter in imapfolder */
2588 for (cp = vms->imapfolder; *cp; cp++)
2592 /* Now connect to the target folder */
2593 imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
2594 ast_debug(3, "Before mail_open, server: %s, box:%d\n", tmp, box);
2595 ast_mutex_lock(&vms->lock);
2596 vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2597 ast_mutex_unlock(&vms->lock);
2598 if (vms->mailstream == NIL) {
2605 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
2609 int ret, urgent = 0;
2611 /* If Urgent, then look at INBOX */
2617 ast_copy_string(vms->imapuser, vmu->imapuser, sizeof(vms->imapuser));
2618 ast_copy_string(vms->imapfolder, vmu->imapfolder, sizeof(vms->imapfolder));
2619 vms->imapversion = vmu->imapversion;
2620 ast_debug(3, "Before init_mailstream, user is %s\n", vmu->imapuser);
2622 if ((ret = init_mailstream(vms, box)) || !vms->mailstream) {
2623 ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
2627 create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
2631 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(vmu, box));
2632 check_quota(vms, (char *) mbox(vmu, box));
2635 ast_mutex_lock(&vms->lock);
2636 pgm = mail_newsearchpgm();
2638 /* Check IMAP folder for Asterisk messages only... */
2639 hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (!ast_strlen_zero(vmu->imapvmshareid) ? vmu->imapvmshareid : vmu->mailbox));
2640 hdr->next = mail_newsearchheader("X-Asterisk-VM-Context", vmu->context);
2645 /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
2646 if (box == NEW_FOLDER && urgent == 1) {
2651 } else if (box == NEW_FOLDER && urgent == 0) {
2656 } else if (box == OLD_FOLDER) {
2661 ast_debug(3, "Before mail_search_full, user is %s\n", vmu->imapuser);
2663 vms->vmArrayIndex = 0;
2664 mail_search_full (vms->mailstream, NULL, pgm, NIL);
2665 vms->lastmsg = vms->vmArrayIndex - 1;
2666 mail_free_searchpgm(&pgm);
2667 /* Since IMAP storage actually stores both old and new messages in the same IMAP folder,
2668 * ensure to allocate enough space to account for all of them. Warn if old messages
2669 * have not been checked first as that is required.
2671 if (box == 0 && !vms->dh_arraysize) {
2672 ast_log(LOG_WARNING, "The code expects the old messages to be checked first, fix the code.\n");
2674 if (vm_allocate_dh(vms, vmu, box == 0 ? vms->vmArrayIndex + vms->oldmessages : vms->lastmsg)) {
2675 ast_mutex_unlock(&vms->lock);
2679 ast_mutex_unlock(&vms->lock);
2683 static void write_file(char *filename, char *buffer, unsigned long len)
2687 output = fopen (filename, "w");
2688 if (fwrite(buffer, len, 1, output) != 1) {
2689 if (ferror(output)) {
2690 ast_log(LOG_ERROR, "Short write while writing e-mail body: %s.\n", strerror(errno));
2696 static void update_messages_by_imapuser(const char *user, unsigned long number)
2698 struct vm_state *vms = get_vm_state_by_imapuser(user, 1);
2700 if (!vms && !(vms = get_vm_state_by_imapuser(user, 0))) {
2704 ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vms->vmArrayIndex, vms->interactive);
2705 vms->msgArray[vms->vmArrayIndex++] = number;
2708 void mm_searched(MAILSTREAM *stream, unsigned long number)
2710 char *mailbox = stream->mailbox, buf[1024] = "", *user;
2712 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
2715 update_messages_by_imapuser(user, number);
2718 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
2720 struct ast_variable *var;
2721 struct ast_vm_user *vmu;
2723 vmu = ast_calloc(1, sizeof *vmu);
2726 ast_set_flag(vmu, VM_ALLOCED);
2727 populate_defaults(vmu);
2729 var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
2731 apply_options_full(vmu, var);
2732 ast_variables_destroy(var);
2740 /* Interfaces to C-client */
2742 void mm_exists(MAILSTREAM * stream, unsigned long number)
2744 /* mail_ping will callback here if new mail! */
2745 ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
2746 if (number == 0) return;
2751 void mm_expunged(MAILSTREAM * stream, unsigned long number)
2753 /* mail_ping will callback here if expunged mail! */
2754 ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
2755 if (number == 0) return;
2760 void mm_flags(MAILSTREAM * stream, unsigned long number)
2762 /* mail_ping will callback here if read mail! */
2763 ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
2764 if (number == 0) return;
2769 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
2771 ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
2772 mm_log (string, errflg);
2776 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2778 if (delimiter == '\0') {
2782 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
2783 if (attributes & LATT_NOINFERIORS)
2784 ast_debug(5, "no inferiors\n");
2785 if (attributes & LATT_NOSELECT)
2786 ast_debug(5, "no select\n");
2787 if (attributes & LATT_MARKED)
2788 ast_debug(5, "marked\n");
2789 if (attributes & LATT_UNMARKED)
2790 ast_debug(5, "unmarked\n");
2794 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2796 ast_debug(5, "Delimiter set to %c and mailbox %s\n", delim, mailbox);
2797 if (attributes & LATT_NOINFERIORS)
2798 ast_debug(5, "no inferiors\n");
2799 if (attributes & LATT_NOSELECT)
2800 ast_debug(5, "no select\n");
2801 if (attributes & LATT_MARKED)
2802 ast_debug(5, "marked\n");
2803 if (attributes & LATT_UNMARKED)
2804 ast_debug(5, "unmarked\n");
2808 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
2810 ast_log(AST_LOG_NOTICE, " Mailbox %s", mailbox);
2811 if (status->flags & SA_MESSAGES)
2812 ast_log(AST_LOG_NOTICE, ", %lu messages", status->messages);
2813 if (status->flags & SA_RECENT)
2814 ast_log(AST_LOG_NOTICE, ", %lu recent", status->recent);
2815 if (status->flags & SA_UNSEEN)
2816 ast_log(AST_LOG_NOTICE, ", %lu unseen", status->unseen);
2817 if (status->flags & SA_UIDVALIDITY)
2818 ast_log(AST_LOG_NOTICE, ", %lu UID validity", status->uidvalidity);
2819 if (status->flags & SA_UIDNEXT)
2820 ast_log(AST_LOG_NOTICE, ", %lu next UID", status->uidnext);
2821 ast_log(AST_LOG_NOTICE, "\n");
2825 void mm_log(char *string, long errflg)
2827 switch ((short) errflg) {
2829 ast_debug(1, "IMAP Info: %s\n", string);
2833 ast_log(AST_LOG_WARNING, "IMAP Warning: %s\n", string);
2836 ast_log(AST_LOG_ERROR, "IMAP Error: %s\n", string);
2842 void mm_dlog(char *string)
2844 ast_log(AST_LOG_NOTICE, "%s\n", string);
2848 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
2850 struct ast_vm_user *vmu;
2852 ast_debug(4, "Entering callback mm_login\n");
2854 ast_copy_string(user, mb->user, MAILTMPLEN);
2856 /* We should only do this when necessary */
2857 if (!ast_strlen_zero(authpassword)) {
2858 ast_copy_string(pwd, authpassword, MAILTMPLEN);
2860 AST_LIST_TRAVERSE(&users, vmu, list) {
2861 if (!strcasecmp(mb->user, vmu->imapuser)) {
2862 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2867 if ((vmu = find_user_realtime_imapuser(mb->user))) {
2868 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2876 void mm_critical(MAILSTREAM * stream)
2881 void mm_nocritical(MAILSTREAM * stream)
2886 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
2888 kill (getpid (), SIGSTOP);
2893 void mm_fatal(char *string)
2895 ast_log(AST_LOG_ERROR, "IMAP access FATAL error: %s\n", string);
2898 /* C-client callback to handle quota */
2899 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
2901 struct vm_state *vms;
2902 char *mailbox = stream->mailbox, *user;
2903 char buf[1024] = "";
2904 unsigned long usage = 0, limit = 0;
2907 usage = pquota->usage;
2908 limit = pquota->limit;
2909 pquota = pquota->next;
2912 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || (!(vms = get_vm_state_by_imapuser(user, 2)) && !(vms = get_vm_state_by_imapuser(user, 0)))) {
2913 ast_log(AST_LOG_ERROR, "No state found.\n");
2917 ast_debug(3, "User %s usage is %lu, limit is %lu\n", user, usage, limit);
2919 vms->quota_usage = usage;
2920 vms->quota_limit = limit;
2923 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len)
2925 char *start, *eol_pnt;
2928 if (ast_strlen_zero(header) || ast_strlen_zero(tag))
2931 taglen = strlen(tag) + 1;
2935 if (!(start = strstr(header, tag)))
2938 /* Since we can be called multiple times we should clear our buffer */
2939 memset(buf, 0, len);
2941 ast_copy_string(buf, start+taglen, len);
2942 if ((eol_pnt = strchr(buf,'\r')) || (eol_pnt = strchr(buf,'\n')))
2947 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len)
2949 char *start, *quote, *eol_pnt;
2951 if (ast_strlen_zero(mailbox))
2954 if (!(start = strstr(mailbox, "/user=")))
2957 ast_copy_string(buf, start+6, len);
2959 if (!(quote = strchr(buf, '\"'))) {
2960 if (!(eol_pnt = strchr(buf, '/')))
2961 eol_pnt = strchr(buf,'}');
2965 eol_pnt = strchr(buf+1,'\"');
2971 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
2973 struct vm_state *vms_p;
2975 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
2976 if ((vms_p = pthread_getspecific(ts_vmstate.key)) && !strcmp(vms_p->imapuser, vmu->imapuser) && !strcmp(vms_p->username, vmu->mailbox)) {
2979 ast_debug(5, "Adding new vmstate for %s\n", vmu->imapuser);
2980 if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
2982 ast_copy_string(vms_p->imapuser, vmu->imapuser, sizeof(vms_p->imapuser));
2983 ast_copy_string(vms_p->imapfolder, vmu->imapfolder, sizeof(vms_p->imapfolder));
2984 ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
2985 ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
2986 vms_p->mailstream = NIL; /* save for access from interactive entry point */
2987 vms_p->imapversion = vmu->imapversion;
2988 ast_debug(5, "Copied %s to %s\n", vmu->imapuser, vms_p->imapuser);
2990 /* set mailbox to INBOX! */
2991 ast_copy_string(vms_p->curbox, mbox(vmu, 0), sizeof(vms_p->curbox));
2992 init_vm_state(vms_p);
2993 vmstate_insert(vms_p);
2997 static struct vm_state *get_vm_state_by_imapuser(const char *user, int interactive)
2999 struct vmstate *vlist = NULL;
3002 struct vm_state *vms;
3003 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
3004 vms = pthread_getspecific(ts_vmstate.key);
3008 AST_LIST_LOCK(&vmstates);
3009 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
3011 ast_debug(3, "error: vms is NULL for %s\n", user);
3014 if (vlist->vms->imapversion != imapversion) {
3017 if (!vlist->vms->imapuser) {
3018 ast_debug(3, "error: imapuser is NULL for %s\n", user);
3022 if (!strcmp(vlist->vms->imapuser, user) && (interactive == 2 || vlist->vms->interactive == interactive)) {
3023 AST_LIST_UNLOCK(&vmstates);
3027 AST_LIST_UNLOCK(&vmstates);
3029 ast_debug(3, "%s not found in vmstates\n", user);
3034 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
3037 struct vmstate *vlist = NULL;
3038 const char *local_context = S_OR(context, "default");
3041 struct vm_state *vms;
3042 pthread_once(&ts_vmstate.once, ts_vmstate.key_init);
3043 vms = pthread_getspecific(ts_vmstate.key);
3047 AST_LIST_LOCK(&vmstates);
3048 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
3050 ast_debug(3, "error: vms is NULL for %s\n", mailbox);
3053 if (vlist->vms->imapversion != imapversion) {
3056 if (!vlist->vms->username || !vlist->vms->context) {
3057 ast_debug(3, "error: username is NULL for %s\n", mailbox);
3061 ast_debug(3, "comparing mailbox %s@%s (i=%d) to vmstate mailbox %s@%s (i=%d)\n", mailbox, local_context, interactive, vlist->vms->username, vlist->vms->context, vlist->vms->interactive);
3063 if (!strcmp(vlist->vms->username, mailbox) && !strcmp(vlist->vms->context, local_context) && vlist->vms->interactive == interactive) {
3064 ast_debug(3, "Found it!\n");
3065 AST_LIST_UNLOCK(&vmstates);
3069 AST_LIST_UNLOCK(&vmstates);
3071 ast_debug(3, "%s not found in vmstates\n", mailbox);
3076 static void vmstate_insert(struct vm_state *vms)
3079 struct vm_state *altvms;
3081 /* If interactive, it probably already exists, and we should
3082 use the one we already have since it is more up to date.
3083 We can compare the username to find the duplicate */
3084 if (vms->interactive == 1) {
3085 altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
3087 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
3088 vms->newmessages = altvms->newmessages;
3089 vms->oldmessages = altvms->oldmessages;
3090 vms->vmArrayIndex = altvms->vmArrayIndex;
3091 vms->lastmsg = altvms->lastmsg;
3092 vms->curmsg = altvms->curmsg;
3093 /* get a pointer to the persistent store */
3094 vms->persist_vms = altvms;
3095 /* Reuse the mailstream? */
3096 #ifdef REALLY_FAST_EVEN_IF_IT_MEANS_RESOURCE_LEAKS
3097 vms->mailstream = altvms->mailstream;
3099 vms->mailstream = NIL;
3105 if (!(v = ast_calloc(1, sizeof(*v))))
3110 ast_debug(3, "Inserting vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
3112 AST_LIST_LOCK(&vmstates);
3113 AST_LIST_INSERT_TAIL(&vmstates, v, list);
3114 AST_LIST_UNLOCK(&vmstates);