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 * \brief Comedian Mail - Voicemail System
23 * \author Mark Spencer <markster@digium.com>
25 * \extref Unixodbc - http://www.unixodbc.org
26 * \extref A source distribution of University of Washington's IMAP
27 c-client (http://www.washington.edu/imap/
31 * \note For information about voicemail IMAP storage, read doc/imapstorage.txt
32 * \ingroup applications
33 * \note This module requires res_adsi to load. This needs to be optional
38 * \note This file is now almost impossible to work with, due to all \#ifdefs.
39 * Feels like the database code before realtime. Someone - please come up
40 * with a plan to clean this up.
44 <depend>res_smdi</depend>
48 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" remove_on_change="apps/app_voicemail.o apps/app_directory.o">
49 <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
50 <depend>unixodbc_or_iodbc</depend>
54 <conflict>IMAP_STORAGE</conflict>
55 <defaultenabled>no</defaultenabled>
57 <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
58 <depend>imap_tk</depend>
59 <conflict>ODBC_STORAGE</conflict>
61 <defaultenabled>no</defaultenabled>
66 /* It is important to include the IMAP_STORAGE related headers
67 * before asterisk.h since asterisk.h includes logger.h. logger.h
68 * and c-client.h have conflicting definitions for AST_LOG_WARNING and
69 * AST_LOG_DEBUG, so it's important that we use Asterisk's definitions
70 * here instead of the c-client's
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>
93 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
95 #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR */
102 #include "asterisk/lock.h"
103 #include "asterisk/file.h"
104 #include "asterisk/channel.h"
105 #include "asterisk/pbx.h"
106 #include "asterisk/config.h"
107 #include "asterisk/say.h"
108 #include "asterisk/module.h"
109 #include "asterisk/adsi.h"
110 #include "asterisk/app.h"
111 #include "asterisk/manager.h"
112 #include "asterisk/dsp.h"
113 #include "asterisk/localtime.h"
114 #include "asterisk/cli.h"
115 #include "asterisk/utils.h"
116 #include "asterisk/stringfields.h"
117 #include "asterisk/smdi.h"
118 #include "asterisk/event.h"
119 #include "asterisk/taskprocessor.h"
122 #include "asterisk/res_odbc.h"
126 static char imapserver[48];
127 static char imapport[8];
128 static char imapflags[128];
129 static char imapfolder[64];
130 static char imapparentfolder[64] = "\0";
131 static char greetingfolder[64];
132 static char authuser[32];
133 static char authpassword[42];
135 static int expungeonhangup = 1;
136 static int imapgreetings = 0;
137 static char delimiter = '\0';
142 /* Forward declarations for IMAP */
143 static int init_mailstream(struct vm_state *vms, int box);
144 static void write_file(char *filename, char *buffer, unsigned long len);
145 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
146 static void vm_imap_delete(int msgnum, struct ast_vm_user *vmu);
147 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
148 static struct vm_state *get_vm_state_by_imapuser(char *user, int interactive);
149 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
150 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
151 static void vmstate_insert(struct vm_state *vms);
152 static void vmstate_delete(struct vm_state *vms);
153 static void set_update(MAILSTREAM * stream);
154 static void init_vm_state(struct vm_state *vms);
155 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro);
156 static void get_mailbox_delimiter(MAILSTREAM *stream);
157 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
158 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
159 static int imap_store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms, const char *flag);
160 static void update_messages_by_imapuser(const char *user, unsigned long number);
162 static int imap_remove_file (char *dir, int msgnum);
163 static int imap_retrieve_file (const char *dir, const int msgnum, const char *mailbox, const char *context);
164 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
165 static void check_quota(struct vm_state *vms, char *mailbox);
166 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
168 struct vm_state *vms;
169 AST_LIST_ENTRY(vmstate) list;
172 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
176 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
178 #define COMMAND_TIMEOUT 5000
179 /* Don't modify these here; set your umask at runtime instead */
180 #define VOICEMAIL_DIR_MODE 0777
181 #define VOICEMAIL_FILE_MODE 0666
182 #define CHUNKSIZE 65536
184 #define VOICEMAIL_CONFIG "voicemail.conf"
185 #define ASTERISK_USERNAME "asterisk"
187 /* Define fast-forward, pause, restart, and reverse keys
188 while listening to a voicemail message - these are
189 strings, not characters */
190 #define DEFAULT_LISTEN_CONTROL_FORWARD_KEY "#"
191 #define DEFAULT_LISTEN_CONTROL_REVERSE_KEY "*"
192 #define DEFAULT_LISTEN_CONTROL_PAUSE_KEY "0"
193 #define DEFAULT_LISTEN_CONTROL_RESTART_KEY "2"
194 #define DEFAULT_LISTEN_CONTROL_STOP_KEY "13456789"
195 #define VALID_DTMF "1234567890*#" /* Yes ABCD are valid dtmf but what phones have those? */
197 /* Default mail command to mail voicemail. Change it with the
198 mailcmd= command in voicemail.conf */
199 #define SENDMAIL "/usr/sbin/sendmail -t"
201 #define INTRO "vm-intro"
204 #define MAXMSGLIMIT 9999
206 #define MINPASSWORD 0 /*!< Default minimum mailbox password length */
208 #define BASELINELEN 72
209 #define BASEMAXINLINE 256
212 #define MAX_DATETIME_FORMAT 512
213 #define MAX_NUM_CID_CONTEXTS 10
215 #define VM_REVIEW (1 << 0) /*!< After recording, permit the caller to review the recording before saving */
216 #define VM_OPERATOR (1 << 1) /*!< Allow 0 to be pressed to go to 'o' extension */
217 #define VM_SAYCID (1 << 2) /*!< Repeat the CallerID info during envelope playback */
218 #define VM_SVMAIL (1 << 3) /*!< Allow the user to compose a new VM from within VoicemailMain */
219 #define VM_ENVELOPE (1 << 4) /*!< Play the envelope information (who-from, time received, etc.) */
220 #define VM_SAYDURATION (1 << 5) /*!< Play the length of the message during envelope playback */
221 #define VM_SKIPAFTERCMD (1 << 6) /*!< After deletion, assume caller wants to go to the next message */
222 #define VM_FORCENAME (1 << 7) /*!< Have new users record their name */
223 #define VM_FORCEGREET (1 << 8) /*!< Have new users record their greetings */
224 #define VM_PBXSKIP (1 << 9) /*!< Skip the [PBX] preamble in the Subject line of emails */
225 #define VM_DIRECFORWARD (1 << 10) /*!< Permit caller to use the Directory app for selecting to which mailbox to forward a VM */
226 #define VM_ATTACH (1 << 11) /*!< Attach message to voicemail notifications? */
227 #define VM_DELETE (1 << 12) /*!< Delete message after sending notification */
228 #define VM_ALLOCED (1 << 13) /*!< Structure was malloc'ed, instead of placed in a return (usually static) buffer */
229 #define VM_SEARCH (1 << 14) /*!< Search all contexts for a matching mailbox */
230 #define VM_TEMPGREETWARN (1 << 15) /*!< Remind user tempgreeting is set */
231 #define VM_MOVEHEARD (1 << 16) /*!< Move a "heard" message to Old after listening to it */
232 #define VM_MESSAGEWRAP (1 << 17) /*!< Wrap around from the last message to the first, and vice-versa */
233 #define ERROR_LOCK_PATH -100
246 OPT_SILENT = (1 << 0),
247 OPT_BUSY_GREETING = (1 << 1),
248 OPT_UNAVAIL_GREETING = (1 << 2),
249 OPT_RECORDGAIN = (1 << 3),
250 OPT_PREPEND_MAILBOX = (1 << 4),
251 OPT_AUTOPLAY = (1 << 6),
252 OPT_DTMFEXIT = (1 << 7),
253 OPT_MESSAGE_Urgent = (1 << 8),
254 OPT_MESSAGE_PRIORITY = (1 << 9)
258 OPT_ARG_RECORDGAIN = 0,
259 OPT_ARG_PLAYFOLDER = 1,
260 OPT_ARG_DTMFEXIT = 2,
261 /* This *must* be the last value in this enum! */
262 OPT_ARG_ARRAY_SIZE = 3,
265 AST_APP_OPTIONS(vm_app_options, {
266 AST_APP_OPTION('s', OPT_SILENT),
267 AST_APP_OPTION('b', OPT_BUSY_GREETING),
268 AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
269 AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
270 AST_APP_OPTION_ARG('d', OPT_DTMFEXIT, OPT_ARG_DTMFEXIT),
271 AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
272 AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
273 AST_APP_OPTION('U', OPT_MESSAGE_Urgent),
274 AST_APP_OPTION('P', OPT_MESSAGE_PRIORITY)
277 static int load_config(int reload);
279 /*! \page vmlang Voicemail Language Syntaxes Supported
281 \par Syntaxes supported, not really language codes.
288 \arg \b pt - Portuguese
289 \arg \b pt_BR - Portuguese (Brazil)
291 \arg \b no - Norwegian
293 \arg \b tw - Chinese (Taiwan)
294 \arg \b ua - Ukrainian
296 German requires the following additional soundfile:
297 \arg \b 1F einE (feminine)
299 Spanish requires the following additional soundfile:
300 \arg \b 1M un (masculine)
302 Dutch, Portuguese & Spanish require the following additional soundfiles:
303 \arg \b vm-INBOXs singular of 'new'
304 \arg \b vm-Olds singular of 'old/heard/read'
307 \arg \b vm-INBOX nieuwe (nl)
308 \arg \b vm-Old oude (nl)
311 \arg \b vm-new-a 'new', feminine singular accusative
312 \arg \b vm-new-e 'new', feminine plural accusative
313 \arg \b vm-new-ych 'new', feminine plural genitive
314 \arg \b vm-old-a 'old', feminine singular accusative
315 \arg \b vm-old-e 'old', feminine plural accusative
316 \arg \b vm-old-ych 'old', feminine plural genitive
317 \arg \b digits/1-a 'one', not always same as 'digits/1'
318 \arg \b digits/2-ie 'two', not always same as 'digits/2'
321 \arg \b vm-nytt singular of 'new'
322 \arg \b vm-nya plural of 'new'
323 \arg \b vm-gammalt singular of 'old'
324 \arg \b vm-gamla plural of 'old'
325 \arg \b digits/ett 'one', not always same as 'digits/1'
328 \arg \b vm-ny singular of 'new'
329 \arg \b vm-nye plural of 'new'
330 \arg \b vm-gammel singular of 'old'
331 \arg \b vm-gamle plural of 'old'
339 Ukrainian requires the following additional soundfile:
340 \arg \b vm-nove 'nove'
341 \arg \b vm-stare 'stare'
342 \arg \b digits/ua/1e 'odne'
344 Italian requires the following additional soundfile:
348 \arg \b vm-nuovi new plural
349 \arg \b vm-vecchio old
350 \arg \b vm-vecchi old plural
352 Chinese (Taiwan) requires the following additional soundfile:
353 \arg \b vm-tong A class-word for call (tong1)
354 \arg \b vm-ri A class-word for day (ri4)
355 \arg \b vm-you You (ni3)
356 \arg \b vm-haveno Have no (mei2 you3)
357 \arg \b vm-have Have (you3)
358 \arg \b vm-listen To listen (yao4 ting1)
361 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
362 spelled among others when you have to change folder. For the above reasons, vm-INBOX
363 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
372 unsigned char iobuf[BASEMAXINLINE];
375 /*! Structure for linked list of users
376 * Use ast_vm_user_destroy() to free one of these structures. */
378 char context[AST_MAX_CONTEXT]; /*!< Voicemail context */
379 char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
380 char password[80]; /*!< Secret pin code, numbers only */
381 char fullname[80]; /*!< Full name, for directory app */
382 char email[80]; /*!< E-mail address */
383 char pager[80]; /*!< E-mail address to pager (no attachment) */
384 char serveremail[80]; /*!< From: Mail address */
385 char mailcmd[160]; /*!< Configurable mail command */
386 char language[MAX_LANGUAGE]; /*!< Config: Language setting */
387 char zonetag[80]; /*!< Time zone */
390 char uniqueid[80]; /*!< Unique integer identifier */
392 char attachfmt[20]; /*!< Attachment format */
393 unsigned int flags; /*!< VM_ flags */
395 int maxmsg; /*!< Maximum number of msgs per folder for this mailbox */
396 int maxdeletedmsg; /*!< Maximum number of deleted msgs saved for this mailbox */
397 int maxsecs; /*!< Maximum number of seconds per message for this mailbox */
399 char imapuser[80]; /*!< IMAP server login */
400 char imappassword[80]; /*!< IMAP server password if authpassword not defined */
402 double volgain; /*!< Volume gain for voicemails sent via email */
403 AST_LIST_ENTRY(ast_vm_user) list;
406 /*! Voicemail time zones */
408 AST_LIST_ENTRY(vm_zone) list;
411 char msg_format[512];
414 #define VMSTATE_MAX_MSG_ARRAY 256
416 /*! Voicemail mailbox state */
421 char curdir[PATH_MAX];
422 char vmbox[PATH_MAX];
424 char intro[PATH_MAX];
436 int updated; /*!< decremented on each mail check until 1 -allows delay */
437 long msgArray[VMSTATE_MAX_MSG_ARRAY];
438 MAILSTREAM *mailstream;
440 char imapuser[80]; /*!< IMAP server login */
442 char introfn[PATH_MAX]; /*!< Name of prepended file */
443 unsigned int quota_limit;
444 unsigned int quota_usage;
445 struct vm_state *persist_vms;
450 static char odbc_database[80];
451 static char odbc_table[80];
452 #define RETRIEVE(a,b,c,d) retrieve_file(a,b)
453 #define DISPOSE(a,b) remove_file(a,b)
454 #define STORE(a,b,c,d,e,f,g,h,i,j) store_file(a,b,c,d)
455 #define EXISTS(a,b,c,d) (message_exists(a,b))
456 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
457 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
458 #define DELETE(a,b,c,d) (delete_file(a,b))
461 #define DISPOSE(a,b) (imap_remove_file(a,b))
462 #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))
463 #define RETRIEVE(a,b,c,d) imap_retrieve_file(a,b,c,d)
464 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
465 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
466 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
467 #define DELETE(a,b,c,d) (vm_imap_delete(b,d))
469 #define RETRIEVE(a,b,c,d)
471 #define STORE(a,b,c,d,e,f,g,h,i,j)
472 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
473 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
474 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
475 #define DELETE(a,b,c,d) (vm_delete(c))
479 static char VM_SPOOL_DIR[PATH_MAX];
481 static char ext_pass_cmd[128];
482 static char ext_pass_check_cmd[128];
486 #define PWDCHANGE_INTERNAL (1 << 1)
487 #define PWDCHANGE_EXTERNAL (1 << 2)
488 static int pwdchange = PWDCHANGE_INTERNAL;
491 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
494 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
496 # define tdesc "Comedian Mail (Voicemail System)"
500 static char userscontext[AST_MAX_EXTENSION] = "default";
502 static char *addesc = "Comedian Mail";
504 static char *synopsis_vm = "Leave a Voicemail message";
506 static char *descrip_vm =
507 " VoiceMail(mailbox[@context][&mailbox[@context]][...][,options]): This\n"
508 "application allows the calling party to leave a message for the specified\n"
509 "list of mailboxes. When multiple mailboxes are specified, the greeting will\n"
510 "be taken from the first mailbox specified. Dialplan execution will stop if the\n"
511 "specified mailbox does not exist.\n"
512 " The Voicemail application will exit if any of the following DTMF digits are\n"
514 " 0 - Jump to the 'o' extension in the current dialplan context.\n"
515 " * - Jump to the 'a' extension in the current dialplan context.\n"
516 " This application will set the following channel variable upon completion:\n"
517 " VMSTATUS - This indicates the status of the execution of the VoiceMail\n"
518 " application. The possible values are:\n"
519 " SUCCESS | USEREXIT | FAILED\n\n"
521 " b - Play the 'busy' greeting to the calling party.\n"
522 " d([c]) - Accept digits for a new extension in context c, if played during\n"
523 " the greeting. Context defaults to the current context.\n"
524 " g(#) - Use the specified amount of gain when recording the voicemail\n"
525 " message. The units are whole-number decibels (dB).\n"
526 " Only works on supported technologies, which is DAHDI only.\n"
527 " s - Skip the playback of instructions for leaving a message to the\n"
529 " u - Play the 'unavailable' greeting.\n"
530 " U - Mark message as Urgent.\n"
531 " P - Mark message as PRIORITY.\n";
533 static char *synopsis_vmain = "Check Voicemail messages";
535 static char *descrip_vmain =
536 " VoiceMailMain([mailbox][@context][,options]): This application allows the\n"
537 "calling party to check voicemail messages. A specific mailbox, and optional\n"
538 "corresponding context, may be specified. If a mailbox is not provided, the\n"
539 "calling party will be prompted to enter one. If a context is not specified,\n"
540 "the 'default' context will be used.\n\n"
542 " p - Consider the mailbox parameter as a prefix to the mailbox that\n"
543 " is entered by the caller.\n"
544 " g(#) - Use the specified amount of gain when recording a voicemail\n"
545 " message. The units are whole-number decibels (dB).\n"
546 " s - Skip checking the passcode for the mailbox.\n"
547 " a(#) - Skip folder prompt and go directly to folder specified.\n"
548 " Defaults to INBOX\n";
550 static char *synopsis_vm_box_exists =
551 "Check to see if Voicemail mailbox exists";
553 static char *descrip_vm_box_exists =
554 " MailboxExists(mailbox[@context][,options]): Check to see if the specified\n"
555 "mailbox exists. If no voicemail context is specified, the 'default' context\n"
557 " This application will set the following channel variable upon completion:\n"
558 " VMBOXEXISTSSTATUS - This will contain the status of the execution of the\n"
559 " MailboxExists application. Possible values include:\n"
560 " SUCCESS | FAILED\n\n"
561 " Options: (none)\n";
563 static char *synopsis_vmauthenticate = "Authenticate with Voicemail passwords";
565 static char *descrip_vmauthenticate =
566 " VMAuthenticate([mailbox][@context][,options]): This application behaves the\n"
567 "same way as the Authenticate application, but the passwords are taken from\n"
569 " If the mailbox is specified, only that mailbox's password will be considered\n"
570 "valid. If the mailbox is not specified, the channel variable AUTH_MAILBOX will\n"
571 "be set with the authenticated mailbox.\n\n"
573 " s - Skip playing the initial prompts.\n";
575 /* Leave a message */
576 static char *app = "VoiceMail";
578 /* Check mail, control, etc */
579 static char *app2 = "VoiceMailMain";
581 static char *app3 = "MailboxExists";
582 static char *app4 = "VMAuthenticate";
584 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
585 static AST_LIST_HEAD_STATIC(zones, vm_zone);
586 static int maxsilence;
588 static int maxdeletedmsg;
589 static int silencethreshold = 128;
590 static char serveremail[80];
591 static char mailcmd[160]; /* Configurable mail cmd */
592 static char externnotify[160];
593 static struct ast_smdi_interface *smdi_iface = NULL;
594 static char vmfmts[80];
595 static double volgain;
596 static int vmminsecs;
597 static int vmmaxsecs;
600 static int maxlogins;
601 static int minpassword;
603 /*! Poll mailboxes for changes since there is something external to
604 * app_voicemail that may change them. */
605 static unsigned int poll_mailboxes;
607 /*! Polling frequency */
608 static unsigned int poll_freq;
609 /*! By default, poll every 30 seconds */
610 #define DEFAULT_POLL_FREQ 30
612 AST_MUTEX_DEFINE_STATIC(poll_lock);
613 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
614 static pthread_t poll_thread = AST_PTHREADT_NULL;
615 static unsigned char poll_thread_run;
617 /*! Subscription to ... MWI event subscriptions */
618 static struct ast_event_sub *mwi_sub_sub;
619 /*! Subscription to ... MWI event un-subscriptions */
620 static struct ast_event_sub *mwi_unsub_sub;
623 * \brief An MWI subscription
625 * This is so we can keep track of which mailboxes are subscribed to.
626 * This way, we know which mailboxes to poll when the pollmailboxes
627 * option is being used.
630 AST_RWLIST_ENTRY(mwi_sub) entry;
638 struct mwi_sub_task {
644 static struct ast_taskprocessor *mwi_subscription_tps;
646 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
648 /* custom audio control prompts for voicemail playback */
649 static char listen_control_forward_key[12];
650 static char listen_control_reverse_key[12];
651 static char listen_control_pause_key[12];
652 static char listen_control_restart_key[12];
653 static char listen_control_stop_key[12];
655 /* custom password sounds */
656 static char vm_password[80] = "vm-password";
657 static char vm_newpassword[80] = "vm-newpassword";
658 static char vm_passchanged[80] = "vm-passchanged";
659 static char vm_reenterpassword[80] = "vm-reenterpassword";
660 static char vm_mismatch[80] = "vm-mismatch";
661 static char vm_invalid_password[80] = "vm-invalid-password";
663 static struct ast_flags globalflags = {0};
665 static int saydurationminfo;
667 static char dialcontext[AST_MAX_CONTEXT] = "";
668 static char callcontext[AST_MAX_CONTEXT] = "";
669 static char exitcontext[AST_MAX_CONTEXT] = "";
671 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
674 static char *emailbody = NULL;
675 static char *emailsubject = NULL;
676 static char *pagerbody = NULL;
677 static char *pagersubject = NULL;
678 static char fromstring[100];
679 static char pagerfromstring[100];
680 static char charset[32] = "ISO-8859-1";
682 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
683 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
684 static int adsiver = 1;
685 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
687 /* Forward declarations - generic */
688 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
689 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);
690 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
691 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
692 char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
693 signed char record_gain, struct vm_state *vms, char *flag);
694 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
695 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
696 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);
697 static void make_email_file(FILE *p, char *srcemail, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, 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);
698 static void apply_options(struct ast_vm_user *vmu, const char *options);
699 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);
700 static int is_valid_dtmf(const char *key);
702 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
703 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
706 static char *strip_control(const char *input, char *buf, size_t buflen)
709 for (; *input; input++) {
714 if (bufptr == buf + buflen - 1) {
724 * \brief Sets default voicemail system options to a voicemail user.
726 * This applies select global settings to a newly created (dynamic) instance of a voicemail user.
727 * - all the globalflags
728 * - the saydurationminfo
732 * - vmmaxsecs, vmmaxmsg, maxdeletedmsg
735 static void populate_defaults(struct ast_vm_user *vmu)
737 ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);
738 if (saydurationminfo)
739 vmu->saydurationm = saydurationminfo;
740 ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
741 ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
742 ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
744 vmu->maxsecs = vmmaxsecs;
746 vmu->maxmsg = maxmsg;
748 vmu->maxdeletedmsg = maxdeletedmsg;
749 vmu->volgain = volgain;
753 * \brief Sets a a specific property value.
754 * \param vmu The voicemail user object to work with.
755 * \param var The name of the property to be set.
756 * \param value The value to be set to the property.
758 * The property name must be one of the understood properties. See the source for details.
760 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
763 if (!strcasecmp(var, "attach")) {
764 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
765 } else if (!strcasecmp(var, "attachfmt")) {
766 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
767 } else if (!strcasecmp(var, "serveremail")) {
768 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
769 } else if (!strcasecmp(var, "language")) {
770 ast_copy_string(vmu->language, value, sizeof(vmu->language));
771 } else if (!strcasecmp(var, "tz")) {
772 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
774 } else if (!strcasecmp(var, "imapuser")) {
775 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
776 } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
777 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
779 } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
780 ast_set2_flag(vmu, ast_true(value), VM_DELETE);
781 } else if (!strcasecmp(var, "saycid")){
782 ast_set2_flag(vmu, ast_true(value), VM_SAYCID);
783 } else if (!strcasecmp(var,"sendvoicemail")){
784 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL);
785 } else if (!strcasecmp(var, "review")){
786 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
787 } else if (!strcasecmp(var, "tempgreetwarn")){
788 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);
789 } else if (!strcasecmp(var, "messagewrap")){
790 ast_set2_flag(vmu, ast_true(value), VM_MESSAGEWRAP);
791 } else if (!strcasecmp(var, "operator")) {
792 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);
793 } else if (!strcasecmp(var, "envelope")){
794 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);
795 } else if (!strcasecmp(var, "moveheard")){
796 ast_set2_flag(vmu, ast_true(value), VM_MOVEHEARD);
797 } else if (!strcasecmp(var, "sayduration")){
798 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);
799 } else if (!strcasecmp(var, "saydurationm")){
800 if (sscanf(value, "%d", &x) == 1) {
801 vmu->saydurationm = x;
803 ast_log(AST_LOG_WARNING, "Invalid min duration for say duration\n");
805 } else if (!strcasecmp(var, "forcename")){
806 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);
807 } else if (!strcasecmp(var, "forcegreetings")){
808 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);
809 } else if (!strcasecmp(var, "callback")) {
810 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
811 } else if (!strcasecmp(var, "dialout")) {
812 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
813 } else if (!strcasecmp(var, "exitcontext")) {
814 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
815 } else if (!strcasecmp(var, "maxmessage") || !strcasecmp(var, "maxsecs")) {
816 if (vmu->maxsecs <= 0) {
817 ast_log(AST_LOG_WARNING, "Invalid max message length of %s. Using global value %d\n", value, vmmaxsecs);
818 vmu->maxsecs = vmmaxsecs;
820 vmu->maxsecs = atoi(value);
822 if (!strcasecmp(var, "maxmessage"))
823 ast_log(AST_LOG_WARNING, "Option 'maxmessage' has been deprecated in favor of 'maxsecs'. Please make that change in your voicemail config.\n");
824 } else if (!strcasecmp(var, "maxmsg")) {
825 vmu->maxmsg = atoi(value);
826 if (vmu->maxmsg <= 0) {
827 ast_log(AST_LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %d\n", value, MAXMSG);
828 vmu->maxmsg = MAXMSG;
829 } else if (vmu->maxmsg > MAXMSGLIMIT) {
830 ast_log(AST_LOG_WARNING, "Maximum number of messages per folder is %d. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
831 vmu->maxmsg = MAXMSGLIMIT;
833 } else if (!strcasecmp(var, "backupdeleted")) {
834 if (sscanf(value, "%d", &x) == 1)
835 vmu->maxdeletedmsg = x;
836 else if (ast_true(value))
837 vmu->maxdeletedmsg = MAXMSG;
839 vmu->maxdeletedmsg = 0;
841 if (vmu->maxdeletedmsg < 0) {
842 ast_log(AST_LOG_WARNING, "Invalid number of deleted messages saved per mailbox backupdeleted=%s. Using default value %d\n", value, MAXMSG);
843 vmu->maxdeletedmsg = MAXMSG;
844 } else if (vmu->maxdeletedmsg > MAXMSGLIMIT) {
845 ast_log(AST_LOG_WARNING, "Maximum number of deleted messages saved per mailbox is %d. Cannot accept value backupdeleted=%s\n", MAXMSGLIMIT, value);
846 vmu->maxdeletedmsg = MAXMSGLIMIT;
848 } else if (!strcasecmp(var, "volgain")) {
849 sscanf(value, "%lf", &vmu->volgain);
850 } else if (!strcasecmp(var, "options")) {
851 apply_options(vmu, value);
855 static char *vm_check_password_shell(char *command, char *buf, size_t len)
862 snprintf(buf, len, "FAILURE: Pipe failed: %s", strerror(errno));
865 pid = ast_safe_fork(0);
871 snprintf(buf, len, "FAILURE: Fork failed");
875 read(fds[0], buf, len);
879 AST_DECLARE_APP_ARGS(arg,
882 char *mycmd = ast_strdupa(command);
885 dup2(fds[1], STDOUT_FILENO);
887 ast_close_fds_above_n(STDOUT_FILENO);
889 AST_NONSTANDARD_APP_ARGS(arg, mycmd, ' ');
891 execv(arg.v[0], arg.v);
892 printf("FAILURE: %s", strerror(errno));
900 * \brief Check that password meets minimum required length
901 * \param vmu The voicemail user to change the password for.
902 * \param password The password string to check
904 * \return zero on ok, 1 on not ok.
906 static int check_password(struct ast_vm_user *vmu, char *password)
908 /* check minimum length */
909 if (strlen(password) < minpassword)
911 if (!ast_strlen_zero(ext_pass_check_cmd)) {
912 char cmd[255], buf[255];
914 ast_log(AST_LOG_DEBUG, "Verify password policies for %s\n", password);
916 snprintf(cmd, sizeof(cmd), "%s %s %s %s %s", ext_pass_check_cmd, vmu->mailbox, vmu->context, vmu->password, password);
917 if (vm_check_password_shell(cmd, buf, sizeof(buf))) {
918 ast_debug(5, "Result: %s\n", buf);
919 if (!strncasecmp(buf, "VALID", 5)) {
920 ast_debug(3, "Passed password check: '%s'\n", buf);
922 } else if (!strncasecmp(buf, "FAILURE", 7)) {
923 ast_log(AST_LOG_WARNING, "Unable to execute password validation script: '%s'.\n", buf);
926 ast_log(AST_LOG_NOTICE, "Password doesn't match policies for user %s %s\n", vmu->mailbox, password);
935 * \brief Performs a change of the voicemail passowrd in the realtime engine.
936 * \param vmu The voicemail user to change the password for.
937 * \param password The new value to be set to the password for this user.
939 * This only works if the voicemail user has a unique id, and if there is a realtime engine configured.
940 * This is called from the (top level) vm_change_password.
942 * \return zero on success, -1 on error.
944 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
947 if (!ast_strlen_zero(vmu->uniqueid)) {
948 if (strlen(password) > 10) {
949 ast_realtime_require_field("voicemail", "password", RQ_CHAR, strlen(password), SENTINEL);
951 res = ast_update_realtime("voicemail", "uniqueid", vmu->uniqueid, "password", password, SENTINEL);
953 ast_copy_string(vmu->password, password, sizeof(vmu->password));
964 * \brief Destructively Parse options and apply.
966 static void apply_options(struct ast_vm_user *vmu, const char *options)
971 stringp = ast_strdupa(options);
972 while ((s = strsep(&stringp, "|"))) {
974 if ((var = strsep(&value, "=")) && value) {
975 apply_option(vmu, var, value);
981 * \brief Loads the options specific to a voicemail user.
983 * This is called when a vm_user structure is being set up, such as from load_options.
985 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
987 struct ast_variable *tmp;
990 if (!strcasecmp(tmp->name, "vmsecret")) {
991 ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
992 } else if (!strcasecmp(tmp->name, "secret") || !strcasecmp(tmp->name, "password")) { /* don't overwrite vmsecret if it exists */
993 if (ast_strlen_zero(retval->password))
994 ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
995 } else if (!strcasecmp(tmp->name, "uniqueid")) {
996 ast_copy_string(retval->uniqueid, tmp->value, sizeof(retval->uniqueid));
997 } else if (!strcasecmp(tmp->name, "pager")) {
998 ast_copy_string(retval->pager, tmp->value, sizeof(retval->pager));
999 } else if (!strcasecmp(tmp->name, "email")) {
1000 ast_copy_string(retval->email, tmp->value, sizeof(retval->email));
1001 } else if (!strcasecmp(tmp->name, "fullname")) {
1002 ast_copy_string(retval->fullname, tmp->value, sizeof(retval->fullname));
1003 } else if (!strcasecmp(tmp->name, "context")) {
1004 ast_copy_string(retval->context, tmp->value, sizeof(retval->context));
1006 } else if (!strcasecmp(tmp->name, "imapuser")) {
1007 ast_copy_string(retval->imapuser, tmp->value, sizeof(retval->imapuser));
1008 } else if (!strcasecmp(tmp->name, "imappassword") || !strcasecmp(tmp->name, "imapsecret")) {
1009 ast_copy_string(retval->imappassword, tmp->value, sizeof(retval->imappassword));
1012 apply_option(retval, tmp->name, tmp->value);
1018 * \brief Determines if a DTMF key entered is valid.
1019 * \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.
1021 * Tests the character entered against the set of valid DTMF characters.
1022 * \return 1 if the character entered is a valid DTMF digit, 0 if the character is invalid.
1024 static int is_valid_dtmf(const char *key)
1027 char *local_key = ast_strdupa(key);
1029 for (i = 0; i < strlen(key); ++i) {
1030 if (!strchr(VALID_DTMF, *local_key)) {
1031 ast_log(AST_LOG_WARNING, "Invalid DTMF key \"%c\" used in voicemail configuration file\n", *local_key);
1040 * \brief Finds a voicemail user from the realtime engine.
1045 * 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.
1047 * \return The ast_vm_user structure for the user that was found.
1049 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1051 struct ast_variable *var;
1052 struct ast_vm_user *retval;
1054 if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
1056 ast_set_flag(retval, VM_ALLOCED);
1058 memset(retval, 0, sizeof(*retval));
1060 ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
1061 populate_defaults(retval);
1062 if (!context && ast_test_flag((&globalflags), VM_SEARCH))
1063 var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
1065 var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
1067 apply_options_full(retval, var);
1068 ast_variables_destroy(var);
1079 * \brief Finds a voicemail user from the users file or the realtime engine.
1084 * \return The ast_vm_user structure for the user that was found.
1086 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
1088 /* This function could be made to generate one from a database, too */
1089 struct ast_vm_user *vmu=NULL, *cur;
1090 AST_LIST_LOCK(&users);
1092 if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
1093 context = "default";
1095 AST_LIST_TRAVERSE(&users, cur, list) {
1096 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
1098 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
1102 /* Make a copy, so that on a reload, we have no race */
1103 if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
1104 memcpy(vmu, cur, sizeof(*vmu));
1105 ast_set2_flag(vmu, !ivm, VM_ALLOCED);
1106 AST_LIST_NEXT(vmu, list) = NULL;
1109 vmu = find_user_realtime(ivm, context, mailbox);
1110 AST_LIST_UNLOCK(&users);
1115 * \brief Resets a user password to a specified password.
1120 * This does the actual change password work, called by the vm_change_password() function.
1122 * \return zero on success, -1 on error.
1124 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
1126 /* This function could be made to generate one from a database, too */
1127 struct ast_vm_user *cur;
1129 AST_LIST_LOCK(&users);
1130 AST_LIST_TRAVERSE(&users, cur, list) {
1131 if ((!context || !strcasecmp(context, cur->context)) &&
1132 (!strcasecmp(mailbox, cur->mailbox)))
1136 ast_copy_string(cur->password, newpass, sizeof(cur->password));
1139 AST_LIST_UNLOCK(&users);
1144 * \brief The handler for the change password option.
1145 * \param vmu The voicemail user to work with.
1146 * \param newpassword The new password (that has been gathered from the appropriate prompting).
1147 * 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.
1148 * It is also called when the user wants to change their password from menu option '5' on the mailbox options menu.
1150 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
1152 struct ast_config *cfg=NULL;
1153 struct ast_variable *var=NULL;
1154 struct ast_category *cat=NULL;
1155 char *category=NULL, *value=NULL, *new=NULL;
1156 const char *tmp=NULL;
1157 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
1158 if (!change_password_realtime(vmu, newpassword))
1161 /* check voicemail.conf */
1162 if ((cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1163 while ((category = ast_category_browse(cfg, category))) {
1164 if (!strcasecmp(category, vmu->context)) {
1165 if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
1166 ast_log(AST_LOG_WARNING, "We could not find the mailbox.\n");
1169 value = strstr(tmp,",");
1171 ast_log(AST_LOG_WARNING, "variable has bad format.\n");
1174 new = alloca((strlen(value)+strlen(newpassword)+1));
1175 sprintf(new,"%s%s", newpassword, value);
1176 if (!(cat = ast_category_get(cfg, category))) {
1177 ast_log(AST_LOG_WARNING, "Failed to get category structure.\n");
1180 ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
1183 /* save the results */
1184 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1185 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1186 config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
1190 /* check users.conf and update the password stored for the mailbox*/
1191 /* if no vmsecret entry exists create one. */
1192 if ((cfg = ast_config_load("users.conf", config_flags)) && cfg != CONFIG_STATUS_FILEINVALID) {
1193 ast_debug(4, "we are looking for %s\n", vmu->mailbox);
1194 while ((category = ast_category_browse(cfg, category))) {
1195 ast_debug(4, "users.conf: %s\n", category);
1196 if (!strcasecmp(category, vmu->mailbox)) {
1197 if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
1198 ast_debug(3, "looks like we need to make vmsecret!\n");
1199 var = ast_variable_new("vmsecret", newpassword, "");
1201 new = alloca(strlen(newpassword)+1);
1202 sprintf(new, "%s", newpassword);
1203 if (!(cat = ast_category_get(cfg, category))) {
1204 ast_debug(4, "failed to get category!\n");
1208 ast_variable_update(cat, "vmsecret", new, NULL, 0);
1210 ast_variable_append(cat, var);
1213 /* save the results and clean things up */
1214 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1215 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1216 config_text_file_save("users.conf", cfg, "AppVoicemail");
1220 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
1223 snprintf(buf,255,"%s %s %s %s",ext_pass_cmd,vmu->context,vmu->mailbox,newpassword);
1224 if (!ast_safe_system(buf)) {
1225 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
1226 /* Reset the password in memory, too */
1227 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
1232 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1233 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1234 * \param len The length of the path string that was written out.
1236 * The path is constructed as
1237 * VM_SPOOL_DIRcontext/ext/folder
1239 * \return zero on success, -1 on error.
1241 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
1243 return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
1247 * \brief Creates a file system path expression for a folder within the voicemail data folder and the appropriate context.
1248 * \param dest The variable to hold the output generated path expression. This buffer should be of size PATH_MAX.
1249 * \param len The length of the path string that was written out.
1251 * The path is constructed as
1252 * VM_SPOOL_DIRcontext/ext/folder
1254 * \return zero on success, -1 on error.
1256 static int make_file(char *dest, const int len, const char *dir, const int num)
1258 return snprintf(dest, len, "%s/msg%04d", dir, num);
1261 /* same as mkstemp, but return a FILE * */
1262 static FILE *vm_mkftemp(char *template)
1265 int pfd = mkstemp(template);
1266 chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
1268 p = fdopen(pfd, "w+");
1277 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
1278 * \param dest String. base directory.
1279 * \param len Length of dest.
1280 * \param context String. Ignored if is null or empty string.
1281 * \param ext String. Ignored if is null or empty string.
1282 * \param folder String. Ignored if is null or empty string.
1283 * \return -1 on failure, 0 on success.
1285 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
1287 mode_t mode = VOICEMAIL_DIR_MODE;
1290 make_dir(dest, len, context, ext, folder);
1291 if ((res = ast_mkdir(dest, mode))) {
1292 ast_log(AST_LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
1298 static const char *mbox(int id)
1300 static const char *msgs[] = {
1318 return (id >= 0 && id < (sizeof(msgs)/sizeof(msgs[0]))) ? msgs[id] : "Unknown";
1321 static void free_user(struct ast_vm_user *vmu)
1323 if (ast_test_flag(vmu, VM_ALLOCED))
1327 /* All IMAP-specific functions should go in this block. This
1328 * keeps them from being spread out all over the code */
1330 static void vm_imap_delete(int msgnum, struct ast_vm_user *vmu)
1333 struct vm_state *vms;
1334 unsigned long messageNum;
1336 /* Greetings aren't stored in IMAP, so we can't delete them there */
1341 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1342 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);
1346 /* find real message number based on msgnum */
1347 /* this may be an index into vms->msgArray based on the msgnum. */
1348 messageNum = vms->msgArray[msgnum];
1349 if (messageNum == 0) {
1350 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n",msgnum,messageNum);
1353 if (option_debug > 2)
1354 ast_log(LOG_DEBUG, "deleting msgnum %d, which is mailbox message %lu\n",msgnum,messageNum);
1355 /* delete message */
1356 snprintf (arg, sizeof(arg), "%lu",messageNum);
1357 mail_setflag (vms->mailstream,arg,"\\DELETED");
1360 static int imap_retrieve_greeting (const char *dir, const int msgnum, struct ast_vm_user *vmu)
1362 struct vm_state *vms_p;
1363 char *file, *filename;
1368 /* This function is only used for retrieval of IMAP greetings
1369 * regular messages are not retrieved this way, nor are greetings
1370 * if they are stored locally*/
1371 if (msgnum > -1 || !imapgreetings) {
1374 file = strrchr(ast_strdupa(dir), '/');
1378 ast_debug (1, "Failed to procure file name from directory passed.\n");
1383 /* check if someone is accessing this box right now... */
1384 if (!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) ||!(vms_p = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1385 ast_log(AST_LOG_ERROR, "Voicemail state not found!\n");
1389 /* Greetings will never have a prepended message */
1390 *vms_p->introfn = '\0';
1392 ret = init_mailstream(vms_p, GREETINGS_FOLDER);
1393 if (!vms_p->mailstream) {
1394 ast_log(AST_LOG_ERROR, "IMAP mailstream is NULL\n");
1398 /*XXX Yuck, this could probably be done a lot better */
1399 for (i = 0; i < vms_p->mailstream->nmsgs; i++) {
1400 mail_fetchstructure(vms_p->mailstream, i + 1, &body);
1401 /* We have the body, now we extract the file name of the first attachment. */
1402 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1403 attachment = ast_strdupa(body->nested.part->next->body.parameter->value);
1405 ast_log(AST_LOG_ERROR, "There is no file attached to this IMAP message.\n");
1408 filename = strsep(&attachment, ".");
1409 if (!strcmp(filename, file)) {
1410 ast_copy_string(vms_p->fn, dir, sizeof(vms_p->fn));
1411 vms_p->msgArray[vms_p->curmsg] = i + 1;
1412 save_body(body, vms_p, "2", attachment, 0);
1420 static int imap_retrieve_file(const char *dir, const int msgnum, const char *mailbox, const char *context)
1423 char *header_content;
1424 char *attachedfilefmt;
1426 struct vm_state *vms;
1427 char text_file[PATH_MAX];
1428 FILE *text_file_ptr;
1430 struct ast_vm_user *vmu;
1432 if (!(vmu = find_user(NULL, context, mailbox))) {
1433 ast_log(LOG_WARNING, "Couldn't find user with mailbox %s@%s\n", mailbox, context);
1438 if (imapgreetings) {
1439 res = imap_retrieve_greeting(dir, msgnum, vmu);
1447 /* Before anything can happen, we need a vm_state so that we can
1448 * actually access the imap server through the vms->mailstream
1450 if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
1451 /* This should not happen. If it does, then I guess we'd
1452 * need to create the vm_state, extract which mailbox to
1453 * open, and then set up the msgArray so that the correct
1454 * IMAP message could be accessed. If I have seen correctly
1455 * though, the vms should be obtainable from the vmstates list
1456 * and should have its msgArray properly set up.
1458 ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
1463 make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
1464 snprintf(vms->introfn, sizeof(vms->introfn), "%sintro", vms->fn);
1466 /* Don't try to retrieve a message from IMAP if it already is on the file system */
1467 if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
1472 if (option_debug > 2)
1473 ast_log (LOG_DEBUG,"Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
1474 if (vms->msgArray[msgnum] == 0) {
1475 ast_log (LOG_WARNING,"Trying to access unknown message\n");
1480 /* This will only work for new messages... */
1481 header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
1482 /* empty string means no valid header */
1483 if (ast_strlen_zero(header_content)) {
1484 ast_log (LOG_ERROR,"Could not fetch header for message number %ld\n",vms->msgArray[msgnum]);
1489 mail_fetchstructure (vms->mailstream,vms->msgArray[msgnum],&body);
1491 /* We have the body, now we extract the file name of the first attachment. */
1492 if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
1493 attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
1495 ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
1500 /* Find the format of the attached file */
1502 strsep(&attachedfilefmt, ".");
1503 if (!attachedfilefmt) {
1504 ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
1509 save_body(body, vms, "2", attachedfilefmt, 0);
1510 if (save_body(body, vms, "3", attachedfilefmt, 1)) {
1511 *vms->introfn = '\0';
1514 /* Get info from headers!! */
1515 snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
1517 if (!(text_file_ptr = fopen(text_file, "w"))) {
1518 ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
1521 fprintf(text_file_ptr, "%s\n", "[message]");
1523 get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:", buf, sizeof(buf));
1524 fprintf(text_file_ptr, "callerid=\"%s\" ", S_OR(buf, ""));
1525 get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:", buf, sizeof(buf));
1526 fprintf(text_file_ptr, "<%s>\n", S_OR(buf, ""));
1527 get_header_by_tag(header_content, "X-Asterisk-VM-Context:", buf, sizeof(buf));
1528 fprintf(text_file_ptr, "context=%s\n", S_OR(buf, ""));
1529 get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:", buf, sizeof(buf));
1530 fprintf(text_file_ptr, "origtime=%s\n", S_OR(buf, ""));
1531 get_header_by_tag(header_content, "X-Asterisk-VM-Duration:", buf, sizeof(buf));
1532 fprintf(text_file_ptr, "duration=%s\n", S_OR(buf, ""));
1533 get_header_by_tag(header_content, "X-Asterisk-VM-Category:", buf, sizeof(buf));
1534 fprintf(text_file_ptr, "category=%s\n", S_OR(buf, ""));
1535 get_header_by_tag(header_content, "X-Asterisk-VM-Flag:", buf, sizeof(buf));
1536 fprintf(text_file_ptr, "flag=%s\n", S_OR(buf, ""));
1537 fclose(text_file_ptr);
1544 static int folder_int(const char *folder)
1546 /*assume a NULL folder means INBOX*/
1550 if (!strcasecmp(folder, imapfolder))
1552 if (!strcasecmp(folder, "INBOX"))
1555 else if (!strcasecmp(folder, "Old"))
1557 else if (!strcasecmp(folder, "Work"))
1559 else if (!strcasecmp(folder, "Family"))
1561 else if (!strcasecmp(folder, "Friends"))
1563 else if (!strcasecmp(folder, "Cust1"))
1565 else if (!strcasecmp(folder, "Cust2"))
1567 else if (!strcasecmp(folder, "Cust3"))
1569 else if (!strcasecmp(folder, "Cust4"))
1571 else if (!strcasecmp(folder, "Cust5"))
1573 else /*assume they meant INBOX if folder is not found otherwise*/
1578 * \brief Gets the number of messages that exist in a mailbox folder.
1583 * This method is used when IMAP backend is used.
1584 * \return The number of messages in this mailbox folder (zero or more).
1586 static int messagecount(const char *context, const char *mailbox, const char *folder)
1591 struct ast_vm_user *vmu, vmus;
1592 struct vm_state *vms_p;
1594 int fold = folder_int(folder);
1597 if (ast_strlen_zero(mailbox))
1600 /* We have to get the user before we can open the stream! */
1601 vmu = find_user(&vmus, context, mailbox);
1603 ast_log(AST_LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailbox, context);
1606 /* No IMAP account available */
1607 if (vmu->imapuser[0] == '\0') {
1608 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
1613 /* No IMAP account available */
1614 if (vmu->imapuser[0] == '\0') {
1615 ast_log(AST_LOG_WARNING, "IMAP user not set for mailbox %s\n", vmu->mailbox);
1620 /* check if someone is accessing this box right now... */
1621 vms_p = get_vm_state_by_imapuser(vmu->imapuser,1);
1623 vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
1626 ast_debug(3, "Returning before search - user is logged in\n");
1627 if (fold == 0) { /* INBOX */
1628 return vms_p->newmessages;
1630 if (fold == 1) { /* Old messages */
1631 return vms_p->oldmessages;
1633 if (fold == 11) {/*Urgent messages*/
1634 return vms_p->urgentmessages;
1638 /* add one if not there... */
1639 vms_p = get_vm_state_by_imapuser(vmu->imapuser,0);
1641 vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
1644 /* If URGENT, then look at INBOX */
1651 ast_debug(3,"Adding new vmstate for %s\n",vmu->imapuser);
1652 if (!(vms_p = ast_calloc(1, sizeof(*vms_p)))) {
1655 ast_copy_string(vms_p->imapuser,vmu->imapuser, sizeof(vms_p->imapuser));
1656 ast_copy_string(vms_p->username, mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
1657 vms_p->mailstream = NIL; /* save for access from interactive entry point */
1658 ast_debug(3, "Copied %s to %s\n",vmu->imapuser,vms_p->imapuser);
1660 ast_copy_string(vms_p->curbox, mbox(fold), sizeof(vms_p->curbox));
1661 init_vm_state(vms_p);
1662 vmstate_insert(vms_p);
1664 ret = init_mailstream(vms_p, fold);
1665 if (!vms_p->mailstream) {
1666 ast_log(AST_LOG_ERROR, "Houston we have a problem - IMAP mailstream is NULL\n");
1670 pgm = mail_newsearchpgm ();
1671 hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)mailbox);
1677 /* In the special case where fold is 1 (old messages) we have to do things a bit
1678 * differently. Old messages are stored in the INBOX but are marked as "seen"
1684 /* look for urgent messages */
1692 vms_p->vmArrayIndex = 0;
1693 mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
1694 if (fold == 0 && urgent == 0)
1695 vms_p->newmessages = vms_p->vmArrayIndex;
1697 vms_p->oldmessages = vms_p->vmArrayIndex;
1698 if (fold == 0 && urgent == 1)
1699 vms_p->urgentmessages = vms_p->vmArrayIndex;
1700 /*Freeing the searchpgm also frees the searchhdr*/
1701 mail_free_searchpgm(&pgm);
1703 return vms_p->vmArrayIndex;
1705 mail_ping(vms_p->mailstream);
1710 static int imap_store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms, const char *flag)
1712 char *myserveremail = serveremail;
1714 char introfn[PATH_MAX];
1718 char tmp[80] = "/tmp/astmail-XXXXXX";
1723 int ret; /* for better error checking */
1724 char *imap_flags = NIL;
1726 /* Set urgent flag for IMAP message */
1727 if (!ast_strlen_zero(flag) && !strcmp(flag, "Urgent")) {
1728 ast_debug(3, "Setting message flag \\\\FLAGGED.\n");
1729 imap_flags="\\FLAGGED";
1732 /* Attach only the first format */
1733 fmt = ast_strdupa(fmt);
1735 strsep(&stringp, "|");
1737 if (!ast_strlen_zero(vmu->serveremail))
1738 myserveremail = vmu->serveremail;
1741 make_file(fn, sizeof(fn), dir, msgnum);
1743 ast_copy_string (fn, dir, sizeof(fn));
1745 snprintf(introfn, sizeof(introfn), "%sintro", fn);
1746 if (ast_fileexists(introfn, NULL, NULL) <= 0) {
1750 if (ast_strlen_zero(vmu->email)) {
1751 /* We need the vmu->email to be set when we call make_email_file, but
1752 * if we keep it set, a duplicate e-mail will be created. So at the end
1753 * of this function, we will revert back to an empty string if tempcopy
1756 ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
1760 if (!strcmp(fmt, "wav49"))
1762 ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
1764 /* Make a temporary file instead of piping directly to sendmail, in case the mail
1766 if (!(p = vm_mkftemp(tmp))) {
1767 ast_log(AST_LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
1769 *(vmu->email) = '\0';
1773 if (msgnum < 0 && imapgreetings) {
1774 if ((ret = init_mailstream(vms, GREETINGS_FOLDER))) {
1775 ast_log(AST_LOG_WARNING, "Unable to open mailstream.\n");
1778 imap_delete_old_greeting(fn, vms);
1781 make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, S_OR(chan->cid.cid_num, NULL), S_OR(chan->cid.cid_name, NULL), fn, introfn, fmt, duration, 1, chan, NULL, 1, flag);
1782 /* read mail file to memory */
1785 if (!(buf = ast_malloc(len + 1))) {
1786 ast_log(AST_LOG_ERROR, "Can't allocate %ld bytes to read message\n", len + 1);
1789 *(vmu->email) = '\0';
1792 fread(buf, len, 1, p);
1793 ((char *)buf)[len] = '\0';
1794 INIT(&str, mail_string, buf, len);
1795 ret = init_mailstream(vms, NEW_FOLDER);
1797 imap_mailbox_name(mailbox, sizeof(mailbox), vms, NEW_FOLDER, 1);
1798 if(!mail_append_full(vms->mailstream, mailbox, imap_flags, NIL, &str))
1799 ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
1804 ast_log(LOG_ERROR, "Could not initialize mailstream for %s\n",mailbox);
1810 ast_debug(3, "%s stored\n", fn);
1813 *(vmu->email) = '\0';
1820 * \brief Gets the number of messages that exist in the inbox folder.
1821 * \param mailbox_context
1822 * \param newmsgs The variable that is updated with the count of new messages within this inbox.
1823 * \param oldmsgs The variable that is updated with the count of old messages within this inbox.
1824 * \param urgentmsgs The variable that is updated with the count of urgent messages within this inbox.
1826 * This method is used when IMAP backend is used.
1827 * Simultaneously determines the count of new,old, and urgent messages. The total messages would then be the sum of these three.
1829 * \return zero on success, -1 on error.
1832 static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsgs, int *oldmsgs)
1834 char tmp[PATH_MAX] = "";
1846 ast_debug(3,"Mailbox is set to %s\n",mailbox_context);
1847 /* If no mailbox, return immediately */
1848 if (ast_strlen_zero(mailbox_context))
1851 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
1852 context = strchr(tmp, '@');
1853 if (strchr(mailbox_context, ',')) {
1854 int tmpnew, tmpold, tmpurgent;
1855 ast_copy_string(tmp, mailbox_context, sizeof(tmp));
1857 while ((cur = strsep(&mb, ", "))) {
1858 if (!ast_strlen_zero(cur)) {
1859 if (inboxcount2(cur, urgentmsgs ? &tmpurgent : NULL, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
1867 *urgentmsgs += tmpurgent;
1878 context = "default";
1879 mailboxnc = (char *)mailbox_context;
1882 if ((*newmsgs = messagecount(context, mailboxnc, imapfolder)) < 0)
1886 if ((*oldmsgs = messagecount(context, mailboxnc, "Old")) < 0)
1890 if((*urgentmsgs = messagecount(context, mailboxnc, "Urgent")) < 0)
1896 static int inboxcount(const char *mailbox_context, int *newmsgs, int *oldmsgs)
1898 return inboxcount2(mailbox_context, NULL, newmsgs, oldmsgs);
1902 * \brief Determines if the given folder has messages.
1903 * \param mailbox The @ delimited string for user@context. If no context is found, uses 'default' for the context.
1904 * \param folder the folder to look in
1906 * This function is used when the mailbox is stored in an IMAP back end.
1907 * This invokes the messagecount(). Here we are interested in the presence of messages (> 0) only, not the actual count.
1908 * \return 1 if the folder has one or more messages. zero otherwise.
1911 static int has_voicemail(const char *mailbox, const char *folder)
1913 char tmp[256], *tmp2, *box, *context;
1914 ast_copy_string(tmp, mailbox, sizeof(tmp));
1916 if (strchr(tmp2, ',')) {
1917 while ((box = strsep(&tmp2, ","))) {
1918 if (!ast_strlen_zero(box)) {
1919 if (has_voicemail(box, folder))
1924 if ((context= strchr(tmp, '@')))
1927 context = "default";
1928 return messagecount(context, tmp, folder) ? 1 : 0;
1932 * \brief Copies a message from one mailbox to another.
1942 * This works with IMAP storage based mailboxes.
1944 * \return zero on success, -1 on error.
1946 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)
1948 struct vm_state *sendvms = NULL, *destvms = NULL;
1949 char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
1950 if (msgnum >= recip->maxmsg) {
1951 ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
1954 if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
1955 ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
1958 if (!(destvms = get_vm_state_by_imapuser(recip->imapuser, 0))) {
1959 ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
1962 snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
1963 if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(imbox)) == T))
1965 ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
1969 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
1971 char tmp[256], *t = tmp;
1972 size_t left = sizeof(tmp);
1974 if (box == OLD_FOLDER) {
1975 ast_copy_string(vms->curbox, mbox(NEW_FOLDER), sizeof(vms->curbox));
1977 ast_copy_string(vms->curbox, mbox(box), sizeof(vms->curbox));
1980 if (box == NEW_FOLDER) {
1981 ast_copy_string(vms->vmbox, "vm-INBOX", sizeof(vms->vmbox));
1983 snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(box));
1986 /* Build up server information */
1987 ast_build_string(&t, &left, "{%s:%s/imap", imapserver, imapport);
1989 /* Add authentication user if present */
1990 if (!ast_strlen_zero(authuser))
1991 ast_build_string(&t, &left, "/authuser=%s", authuser);
1993 /* Add flags if present */
1994 if (!ast_strlen_zero(imapflags))
1995 ast_build_string(&t, &left, "/%s", imapflags);
1997 /* End with username */
1998 ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
1999 if (box == NEW_FOLDER || box == OLD_FOLDER)
2000 snprintf(spec, len, "%s%s", tmp, use_folder? imapfolder: "INBOX");
2001 else if (box == GREETINGS_FOLDER)
2002 snprintf(spec, len, "%s%s", tmp, greetingfolder);
2003 else { /* Other folders such as Friends, Family, etc... */
2004 if (!ast_strlen_zero(imapparentfolder)) {
2005 /* imapparentfolder would typically be set to INBOX */
2006 snprintf(spec, len, "%s%s%c%s", tmp, imapparentfolder, delimiter, mbox(box));
2008 snprintf(spec, len, "%s%s", tmp, mbox(box));
2013 static int init_mailstream(struct vm_state *vms, int box)
2015 MAILSTREAM *stream = NIL;
2020 ast_log (LOG_ERROR,"vm_state is NULL!\n");
2023 if (option_debug > 2)
2024 ast_log (LOG_DEBUG,"vm_state user is:%s\n",vms->imapuser);
2025 if (vms->mailstream == NIL || !vms->mailstream) {
2027 ast_log (LOG_DEBUG,"mailstream not set.\n");
2029 stream = vms->mailstream;
2031 /* debug = T; user wants protocol telemetry? */
2032 debug = NIL; /* NO protocol telemetry? */
2034 if (delimiter == '\0') { /* did not probe the server yet */
2036 #ifdef USE_SYSTEM_IMAP
2037 #include <imap/linkage.c>
2038 #elif defined(USE_SYSTEM_CCLIENT)
2039 #include <c-client/linkage.c>
2041 #include "linkage.c"
2043 /* Connect to INBOX first to get folders delimiter */
2044 imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
2045 ast_mutex_lock(&vms->lock);
2046 stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2047 ast_mutex_unlock(&vms->lock);
2048 if (stream == NIL) {
2049 ast_log (LOG_ERROR, "Can't connect to imap server %s\n", tmp);
2052 get_mailbox_delimiter(stream);
2053 /* update delimiter in imapfolder */
2054 for (cp = imapfolder; *cp; cp++)
2058 /* Now connect to the target folder */
2059 imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
2060 if (option_debug > 2)
2061 ast_log (LOG_DEBUG,"Before mail_open, server: %s, box:%d\n", tmp, box);
2062 ast_mutex_lock(&vms->lock);
2063 vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
2064 ast_mutex_unlock(&vms->lock);
2065 if (vms->mailstream == NIL) {
2072 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
2076 int ret, urgent = 0;
2078 /* If Urgent, then look at INBOX */
2084 ast_copy_string(vms->imapuser,vmu->imapuser, sizeof(vms->imapuser));
2085 ast_debug(3,"Before init_mailstream, user is %s\n",vmu->imapuser);
2087 if ((ret = init_mailstream(vms, box)) || !vms->mailstream) {
2088 ast_log(AST_LOG_ERROR, "Could not initialize mailstream\n");
2092 create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
2096 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mbox(box));
2097 check_quota(vms,(char *)mbox(box));
2100 pgm = mail_newsearchpgm();
2102 /* Check IMAP folder for Asterisk messages only... */
2103 hdr = mail_newsearchheader("X-Asterisk-VM-Extension", vmu->mailbox);
2108 /* if box = NEW_FOLDER, check for new, if box = OLD_FOLDER, check for read */
2109 if (box == NEW_FOLDER && urgent == 1) {
2114 } else if (box == NEW_FOLDER && urgent == 0) {
2119 } else if (box == OLD_FOLDER) {
2124 ast_debug(3,"Before mail_search_full, user is %s\n",vmu->imapuser);
2126 vms->vmArrayIndex = 0;
2127 mail_search_full (vms->mailstream, NULL, pgm, NIL);
2128 vms->lastmsg = vms->vmArrayIndex - 1;
2129 mail_free_searchpgm(&pgm);
2134 static void write_file(char *filename, char *buffer, unsigned long len)
2138 output = fopen (filename, "w");
2139 fwrite (buffer, len, 1, output);
2143 static void update_messages_by_imapuser(const char *user, unsigned long number)
2145 struct vmstate *vlist = NULL;
2147 AST_LIST_LOCK(&vmstates);
2148 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
2150 ast_debug(3, "error: vms is NULL for %s\n", user);
2153 if (!vlist->vms->imapuser) {
2154 ast_debug(3, "error: imapuser is NULL for %s\n", user);
2157 ast_debug(3, "saving mailbox message number %lu as message %d. Interactive set to %d\n", number, vlist->vms->vmArrayIndex, vlist->vms->interactive);
2158 vlist->vms->msgArray[vlist->vms->vmArrayIndex++] = number;
2160 AST_LIST_UNLOCK(&vmstates);
2163 void mm_searched(MAILSTREAM *stream, unsigned long number)
2165 char *mailbox = stream->mailbox, buf[1024] = "", *user;
2167 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))))
2170 update_messages_by_imapuser(user, number);
2173 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
2175 struct ast_variable *var;
2176 struct ast_vm_user *vmu;
2178 vmu = ast_calloc(1, sizeof *vmu);
2181 ast_set_flag(vmu, VM_ALLOCED);
2182 populate_defaults(vmu);
2184 var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
2186 apply_options_full(vmu, var);
2187 ast_variables_destroy(var);
2195 /* Interfaces to C-client */
2197 void mm_exists(MAILSTREAM * stream, unsigned long number)
2199 /* mail_ping will callback here if new mail! */
2200 ast_debug(4, "Entering EXISTS callback for message %ld\n", number);
2201 if (number == 0) return;
2206 void mm_expunged(MAILSTREAM * stream, unsigned long number)
2208 /* mail_ping will callback here if expunged mail! */
2209 ast_debug(4, "Entering EXPUNGE callback for message %ld\n", number);
2210 if (number == 0) return;
2215 void mm_flags(MAILSTREAM * stream, unsigned long number)
2217 /* mail_ping will callback here if read mail! */
2218 ast_debug(4, "Entering FLAGS callback for message %ld\n", number);
2219 if (number == 0) return;
2224 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
2226 ast_debug(5, "Entering NOTIFY callback, errflag is %ld, string is %s\n", errflg, string);
2227 mm_log (string, errflg);
2231 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2233 if (delimiter == '\0') {
2237 ast_debug(5, "Delimiter set to %c and mailbox %s\n",delim, mailbox);
2238 if (attributes & LATT_NOINFERIORS)
2239 ast_debug(5, "no inferiors\n");
2240 if (attributes & LATT_NOSELECT)
2241 ast_debug(5, "no select\n");
2242 if (attributes & LATT_MARKED)
2243 ast_debug(5, "marked\n");
2244 if (attributes & LATT_UNMARKED)
2245 ast_debug(5, "unmarked\n");
2249 void mm_lsub(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
2251 ast_debug(5, "Delimiter set to %c and mailbox %s\n",delim, mailbox);
2252 if (attributes & LATT_NOINFERIORS)
2253 ast_debug(5, "no inferiors\n");
2254 if (attributes & LATT_NOSELECT)
2255 ast_debug(5, "no select\n");
2256 if (attributes & LATT_MARKED)
2257 ast_debug(5, "marked\n");
2258 if (attributes & LATT_UNMARKED)
2259 ast_debug(5, "unmarked\n");
2263 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
2265 ast_log(AST_LOG_NOTICE, " Mailbox %s", mailbox);
2266 if (status->flags & SA_MESSAGES)
2267 ast_log(AST_LOG_NOTICE, ", %lu messages", status->messages);
2268 if (status->flags & SA_RECENT)
2269 ast_log(AST_LOG_NOTICE, ", %lu recent", status->recent);
2270 if (status->flags & SA_UNSEEN)
2271 ast_log(AST_LOG_NOTICE, ", %lu unseen", status->unseen);
2272 if (status->flags & SA_UIDVALIDITY)
2273 ast_log(AST_LOG_NOTICE, ", %lu UID validity", status->uidvalidity);
2274 if (status->flags & SA_UIDNEXT)
2275 ast_log(AST_LOG_NOTICE, ", %lu next UID", status->uidnext);
2276 ast_log(AST_LOG_NOTICE, "\n");
2280 void mm_log(char *string, long errflg)
2282 switch ((short) errflg) {
2284 ast_debug(1,"IMAP Info: %s\n", string);
2288 ast_log(AST_LOG_WARNING, "IMAP Warning: %s\n", string);
2291 ast_log(AST_LOG_ERROR, "IMAP Error: %s\n", string);
2297 void mm_dlog(char *string)
2299 ast_log(AST_LOG_NOTICE, "%s\n", string);
2303 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
2305 struct ast_vm_user *vmu;
2307 ast_debug(4, "Entering callback mm_login\n");
2309 ast_copy_string(user, mb->user, MAILTMPLEN);
2311 /* We should only do this when necessary */
2312 if (!ast_strlen_zero(authpassword)) {
2313 ast_copy_string(pwd, authpassword, MAILTMPLEN);
2315 AST_LIST_TRAVERSE(&users, vmu, list) {
2316 if (!strcasecmp(mb->user, vmu->imapuser)) {
2317 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2322 if ((vmu = find_user_realtime_imapuser(mb->user))) {
2323 ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
2331 void mm_critical(MAILSTREAM * stream)
2336 void mm_nocritical(MAILSTREAM * stream)
2341 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
2343 kill (getpid (), SIGSTOP);
2348 void mm_fatal(char *string)
2350 ast_log(AST_LOG_ERROR, "IMAP access FATAL error: %s\n", string);
2353 /* C-client callback to handle quota */
2354 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
2356 struct vm_state *vms;
2357 char *mailbox = stream->mailbox, *user;
2358 char buf[1024] = "";
2359 unsigned long usage = 0, limit = 0;
2362 usage = pquota->usage;
2363 limit = pquota->limit;
2364 pquota = pquota->next;
2367 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || !(vms = get_vm_state_by_imapuser(user, 2))) {
2368 ast_log(AST_LOG_ERROR, "No state found.\n");
2372 ast_debug(3, "User %s usage is %lu, limit is %lu\n", user, usage, limit);
2374 vms->quota_usage = usage;
2375 vms->quota_limit = limit;
2378 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len)
2380 char *start, *eol_pnt;
2383 if (ast_strlen_zero(header) || ast_strlen_zero(tag))
2386 taglen = strlen(tag) + 1;
2390 if (!(start = strstr(header, tag)))
2393 /* Since we can be called multiple times we should clear our buffer */
2394 memset(buf, 0, len);
2396 ast_copy_string(buf, start+taglen, len);
2397 if ((eol_pnt = strchr(buf,'\r')) || (eol_pnt = strchr(buf,'\n')))
2402 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len)
2404 char *start, *quote, *eol_pnt;
2406 if (ast_strlen_zero(mailbox))
2409 if (!(start = strstr(mailbox, "/user=")))
2412 ast_copy_string(buf, start+6, len);
2414 if (!(quote = strchr(buf, '\"'))) {
2415 if (!(eol_pnt = strchr(buf, '/')))
2416 eol_pnt = strchr(buf,'}');
2420 eol_pnt = strchr(buf+1,'\"');
2426 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
2428 struct vm_state *vms_p;
2430 if (option_debug > 4)
2431 ast_log(AST_LOG_DEBUG,"Adding new vmstate for %s\n",vmu->imapuser);
2432 if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
2434 ast_copy_string(vms_p->imapuser, vmu->imapuser, sizeof(vms_p->imapuser));
2435 ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
2436 ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
2437 vms_p->mailstream = NIL; /* save for access from interactive entry point */
2438 if (option_debug > 4)
2439 ast_log(AST_LOG_DEBUG,"Copied %s to %s\n",vmu->imapuser,vms_p->imapuser);
2441 /* set mailbox to INBOX! */
2442 ast_copy_string(vms_p->curbox, mbox(0), sizeof(vms_p->curbox));
2443 init_vm_state(vms_p);
2444 vmstate_insert(vms_p);
2448 static struct vm_state *get_vm_state_by_imapuser(char *user, int interactive)
2450 struct vmstate *vlist = NULL;
2452 AST_LIST_LOCK(&vmstates);
2453 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
2455 ast_debug(3, "error: vms is NULL for %s\n", user);
2458 if (!vlist->vms->imapuser) {
2459 ast_debug(3, "error: imapuser is NULL for %s\n", user);
2463 if (!strcmp(vlist->vms->imapuser, user) && (interactive == 2 || vlist->vms->interactive == interactive)) {
2464 AST_LIST_UNLOCK(&vmstates);
2468 AST_LIST_UNLOCK(&vmstates);
2470 ast_debug(3, "%s not found in vmstates\n", user);
2475 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
2478 struct vmstate *vlist = NULL;
2479 const char *local_context = S_OR(context, "default");
2481 AST_LIST_LOCK(&vmstates);
2482 AST_LIST_TRAVERSE(&vmstates, vlist, list) {
2484 ast_debug(3, "error: vms is NULL for %s\n", mailbox);
2487 if (!vlist->vms->username || !vlist->vms->context) {
2488 ast_debug(3, "error: username is NULL for %s\n", mailbox);
2492 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);
2494 if (!strcmp(vlist->vms->username,mailbox) && !strcmp(vlist->vms->context, local_context) && vlist->vms->interactive == interactive) {
2495 ast_debug(3, "Found it!\n");
2496 AST_LIST_UNLOCK(&vmstates);
2500 AST_LIST_UNLOCK(&vmstates);
2502 ast_debug(3, "%s not found in vmstates\n", mailbox);
2507 static void vmstate_insert(struct vm_state *vms)
2510 struct vm_state *altvms;
2512 /* If interactive, it probably already exists, and we should
2513 use the one we already have since it is more up to date.
2514 We can compare the username to find the duplicate */
2515 if (vms->interactive == 1) {
2516 altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
2518 ast_debug(3, "Duplicate mailbox %s, copying message info...\n",vms->username);
2519 vms->newmessages = altvms->newmessages;
2520 vms->oldmessages = altvms->oldmessages;
2521 vms->vmArrayIndex = altvms->vmArrayIndex;
2522 vms->lastmsg = altvms->lastmsg;
2523 vms->curmsg = altvms->curmsg;
2524 /* get a pointer to the persistent store */
2525 vms->persist_vms = altvms;
2526 /* Reuse the mailstream? */
2527 vms->mailstream = altvms->mailstream;
2528 /* vms->mailstream = NIL; */
2532 if (!(v = ast_calloc(1, sizeof(*v))))
2537 ast_debug(3, "Inserting vm_state for user:%s, mailbox %s\n",vms->imapuser,vms->username);
2539 AST_LIST_LOCK(&vmstates);
2540 AST_LIST_INSERT_TAIL(&vmstates, v, list);
2541 AST_LIST_UNLOCK(&vmstates);
2544 static void vmstate_delete(struct vm_state *vms)
2546 struct vmstate *vc = NULL;
2547 struct vm_state *altvms = NULL;
2549 /* If interactive, we should copy pertinent info
2550 back to the persistent state (to make update immediate) */
2551 if (vms->interactive == 1 && (altvms = vms->persist_vms)) {
2552 ast_debug(3, "Duplicate mailbox %s, copying message info...\n", vms->username);
2553 altvms->newmessages = vms->newmessages;
2554 altvms->oldmessages = vms->oldmessages;
2555 altvms->updated = 1;
2558 ast_debug(3, "Removing vm_state for user:%s, mailbox %s\n", vms->imapuser, vms->username);
2560 AST_LIST_LOCK(&vmstates);
2561 AST_LIST_TRAVERSE_SAFE_BEGIN(&vmstates, vc, list) {
2562 if (vc->vms == vms) {
2563 AST_LIST_REMOVE_CURRENT(list);
2567 AST_LIST_TRAVERSE_SAFE_END
2568 AST_LIST_UNLOCK(&vmstates);
2571 ast_mutex_destroy(&vc->vms->lock);
2575 ast_log(AST_LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n", vms->imapuser, vms->username);
2578 static void set_update(MAILSTREAM * stream)
2580 struct vm_state *vms;
2581 char *mailbox = stream->mailbox, *user;
2582 char buf[1024] = "";
2584 if (!(user = get_user_by_mailbox(mailbox, buf, sizeof(buf))) || !(vms = get_vm_state_by_imapuser(user, 0))) {
2585 if (user && option_debug > 2)
2586 ast_log(AST_LOG_WARNING, "User %s mailbox not found for update.\n", user);
2590 ast_debug(3, "User %s mailbox set for update.\n", user);
2592 vms->updated = 1; /* Set updated flag since mailbox changed */
2595 static void init_vm_state(struct vm_state *vms)
2598 vms->vmArrayIndex = 0;
2599 for (x = 0; x < VMSTATE_MAX_MSG_ARRAY; x++) {
2600 vms->msgArray[x] = 0;
2602 ast_mutex_init(&vms->lock);
2605 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format, int is_intro)
2609 char *fn = is_intro ? vms->introfn : vms->fn;
2611 unsigned long newlen;
2614 if (!body || body == NIL)
2617 body_content = mail_fetchbody(vms->mailstream, vms->msgArray[vms->curmsg], section, &len);
2618 if (body_content != NIL) {
2619 snprintf(filename, sizeof(filename), "%s.%s", fn, format);
2620 /* ast_debug(1,body_content); */
2621 body_decoded = rfc822_base64((unsigned char *)body_content, len, &newlen);
2622 /* If the body of the file is empty, return an error */
2626 write_file(filename, (char *) body_decoded, newlen);
2628 ast_debug(5, "Body of message is NULL.\n");
2635 * \brief Get delimiter via mm_list callback
2638 * Determines the delimiter character that is used by the underlying IMAP based mail store.
2640 static void get_mailbox_delimiter(MAILSTREAM *stream) {
2642 snprintf(tmp, sizeof(tmp), "{%s}", imapserver);
2643 mail_list(stream, tmp, "*");
2647 * \brief Check Quota for user
2648 * \param vms a pointer to a vm_state struct, will use the mailstream property of this.
2649 * \param mailbox the mailbox to check the quota for.
2651 * Calls imap_getquotaroot, which will populate its results into the vm_state vms input structure.
2653 static void check_quota(struct vm_state *vms, char *mailbox) {
2654 mail_parameters(NULL, SET_QUOTA, (void *) mm_parsequota);
2655 ast_debug(3, "Mailbox name set to: %s, about to check quotas\n", mailbox);
2656 if (vms && vms->mailstream != NULL) {
2657 imap_getquotaroot(vms->mailstream, mailbox);
2659 ast_log(AST_LOG_WARNING, "Mailstream not available for mailbox: %s\n", mailbox);
2663 #endif /* IMAP_STORAGE */
2665 /*! \brief Lock file path
2666 only return failure if ast_lock_path returns 'timeout',
2667 not if the path does not exist or any other reason
2669 static int vm_lock_path(const char *path)
2671 switch (ast_lock_path(path)) {
2672 case AST_LOCK_TIMEOUT:
2681 struct generic_prepare_struct {
2687 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
2689 struct generic_prepare_struct *gps = data;
2693 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
2694 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2695 ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
2698 res = SQLPrepare(stmt, (unsigned char *)gps->sql, SQL_NTS);
2699 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2700 ast_log(AST_LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
2701 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
2704 for (i = 0; i < gps->argc; i++)
2705 SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
2711 * \brief Retrieves a file from an ODBC data store.
2712 * \param dir the path to the file to be retreived.
2713 * \param msgnum the message number, such as within a mailbox folder.
2715 * This method is used by the RETRIEVE macro when mailboxes are stored in an ODBC back end.
2716 * The purpose is to get the message from the database store to the local file system, so that the message may be played, or the information file may be read.
2718 * The file is looked up by invoking a SQL on the odbc_table (default 'voicemessages') using the dir and msgnum input parameters.
2719 * The output is the message information file with the name msgnum and the extension .txt
2720 * and the message file with the extension of its format, in the directory with base file name of the msgnum.
2722 * \return 0 on success, -1 on error.
2724 static int retrieve_file(char *dir, int msgnum)
2730 void *fdm = MAP_FAILED;
2731 SQLSMALLINT colcount=0;
2738 SQLSMALLINT datatype;
2739 SQLSMALLINT decimaldigits;
2740 SQLSMALLINT nullable;
2746 char full_fn[PATH_MAX];
2748 char *argv[] = { dir, msgnums };
2749 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
2751 struct odbc_obj *obj;
2752 obj = ast_odbc_request_obj(odbc_database, 0);
2754 ast_copy_string(fmt, vmfmts, sizeof(fmt));
2755 c = strchr(fmt, '|');
2758 if (!strcasecmp(fmt, "wav49"))
2760 snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
2762 make_file(fn, sizeof(fn), dir, msgnum);
2764 ast_copy_string(fn, dir, sizeof(fn));
2766 /* Create the information file */
2767 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
2769 if (!(f = fopen(full_fn, "w+"))) {
2770 ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
2774 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
2775 snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?",odbc_table);
2776 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
2778 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
2779 ast_odbc_release_obj(obj);
2782 res = SQLFetch(stmt);
2783 if (res == SQL_NO_DATA) {
2784 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2785 ast_odbc_release_obj(obj);
2787 } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2788 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
2789 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2790 ast_odbc_release_obj(obj);
2793 fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
2795 ast_log(AST_LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
2796 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2797 ast_odbc_release_obj(obj);
2800 res = SQLNumResultCols(stmt, &colcount);
2801 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2802 ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
2803 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2804 ast_odbc_release_obj(obj);
2808 fprintf(f, "[message]\n");
2809 for (x=0;x<colcount;x++) {
2811 collen = sizeof(coltitle);
2812 res = SQLDescribeCol(stmt, x + 1, (unsigned char *)coltitle, sizeof(coltitle), &collen,
2813 &datatype, &colsize, &decimaldigits, &nullable);
2814 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2815 ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
2816 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2817 ast_odbc_release_obj(obj);
2820 if (!strcasecmp(coltitle, "recording")) {
2822 res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
2826 lseek(fd, fdlen - 1, SEEK_SET);
2827 if (write(fd, tmp, 1) != 1) {
2832 /* Read out in small chunks */
2833 for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
2834 if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
2835 ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
2836 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
2837 ast_odbc_release_obj(obj);
2840 res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
2841 munmap(fdm, CHUNKSIZE);
2842 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2843 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
2845 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
2846 ast_odbc_release_obj(obj);
2851 truncate(full_fn, fdlen);
2854 res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
2855 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2856 ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
2857 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2858 ast_odbc_release_obj(obj);
2861 if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
2862 fprintf(f, "%s=%s\n", coltitle, rowdata);
2865 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2866 ast_odbc_release_obj(obj);
2868 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
2878 * \brief Determines the highest message number in use for a given user and mailbox folder.
2880 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
2882 * This method is used when mailboxes are stored in an ODBC back end.
2883 * Typical use to set the msgnum would be to take the value returned from this method and add one to it.
2885 * \return the value of zero or greaterto indicate the last message index in use, -1 to indicate none.
2887 static int last_message_index(struct ast_vm_user *vmu, char *dir)
2894 char *argv[] = { dir };
2895 struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
2897 struct odbc_obj *obj;
2898 obj = ast_odbc_request_obj(odbc_database, 0);
2900 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?",odbc_table);
2901 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
2903 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
2904 ast_odbc_release_obj(obj);
2907 res = SQLFetch(stmt);
2908 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2909 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
2910 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2911 ast_odbc_release_obj(obj);
2914 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
2915 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2916 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
2917 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2918 ast_odbc_release_obj(obj);
2921 if (sscanf(rowdata, "%d", &x) != 1)
2922 ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
2923 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2924 ast_odbc_release_obj(obj);
2926 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
2932 * \brief Determines if the specified message exists.
2933 * \param dir the folder the mailbox folder to look for messages.
2934 * \param msgnum the message index to query for.
2936 * This method is used when mailboxes are stored in an ODBC back end.
2938 * \return greater than zero if the message exists, zero when the message does not exist or on error.
2940 static int message_exists(char *dir, int msgnum)
2948 char *argv[] = { dir, msgnums };
2949 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
2951 struct odbc_obj *obj;
2952 obj = ast_odbc_request_obj(odbc_database, 0);
2954 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
2955 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?",odbc_table);
2956 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
2958 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
2959 ast_odbc_release_obj(obj);
2962 res = SQLFetch(stmt);
2963 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2964 ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
2965 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2966 ast_odbc_release_obj(obj);
2969 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
2970 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2971 ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
2972 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2973 ast_odbc_release_obj(obj);
2976 if (sscanf(rowdata, "%d", &x) != 1)
2977 ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
2978 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2979 ast_odbc_release_obj(obj);
2981 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
2987 * \brief returns the one-based count for messages.
2989 * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
2991 * This method is used when mailboxes are stored in an ODBC back end.
2992 * The message index is zero-based, the first message will be index 0. For convenient display it is good to have the
2993 * one-based messages.
2994 * This method just calls last_message_index and returns +1 of its value.
2996 * \return the value greater than zero on success to indicate the one-based count of messages, less than zero on error.
2998 static int count_messages(struct ast_vm_user *vmu, char *dir)
3000 return last_message_index(vmu, dir) + 1;
3004 * \brief Deletes a message from the mailbox folder.
3005 * \param sdir The mailbox folder to work in.
3006 * \param smsg The message index to be deleted.
3008 * This method is used when mailboxes are stored in an ODBC back end.
3009 * The specified message is directly deleted from the database 'voicemessages' table.
3011 * \return the value greater than zero on success to indicate the number of messages, less than zero on error.
3013 static void delete_file(char *sdir, int smsg)
3018 char *argv[] = { sdir, msgnums };
3019 struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
3021 struct odbc_obj *obj;
3022 obj = ast_odbc_request_obj(odbc_database, 0);
3024 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
3025 snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?",odbc_table);
3026 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3028 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
3030 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
3031 ast_odbc_release_obj(obj);
3033 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3038 * \brief Copies a voicemail from one mailbox to another.
3039 * \param sdir the folder for which to look for the message to be copied.
3040 * \param smsg the index of the message to be copied.
3041 * \param ddir the destination folder to copy the message into.
3042 * \param dmsg the index to be used for the copied message.
3043 * \param dmailboxuser The user who owns the mailbox tha contains the destination folder.
3044 * \param dmailboxcontext The context for the destination user.
3046 * This method is used for the COPY macro when mailboxes are stored in an ODBC back end.
3048 static void copy_file(char *sdir, int smsg, char *ddir, int dmsg, char *dmailboxuser, char *dmailboxcontext)
3054 struct odbc_obj *obj;
3055 char *argv[] = { ddir, msgnumd, dmailboxuser, dmailboxcontext, sdir, msgnums };
3056 struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
3058 delete_file(ddir, dmsg);
3059 obj = ast_odbc_request_obj(odbc_database, 0);
3061 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
3062 snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
3063 snprintf(sql, sizeof(sql), "INSERT INTO %s (dir, msgnum, context, macrocontext, callerid, origtime, duration, recording, mailboxuser, mailboxcontext, flag) SELECT ?,?,context,macrocontext,callerid,origtime,duration,recording,flag,?,? FROM %s WHERE dir=? AND msgnum=?",odbc_table,odbc_table);
3064 stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
3066 ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
3068 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3069 ast_odbc_release_obj(obj);
3071 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3075 struct insert_data {
3082 const char *context;
3083 const char *macrocontext;
3084 const char *callerid;
3085 const char *origtime;
3086 const char *duration;
3088 char *mailboxcontext;
3089 const char *category;
3093 static SQLHSTMT insert_data_cb(struct odbc_obj *obj, void *vdata)
3095 struct insert_data *data = vdata;
3099 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
3100 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3101 ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
3102 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3106 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->dir), 0, (void *)data->dir, 0, NULL);
3107 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->msgnums), 0, (void *)data->msgnums, 0, NULL);
3108 SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, data->datalen, 0, (void *)data->data, data->datalen, &data->indlen);
3109 SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->context), 0, (void *)data->context, 0, NULL);
3110 SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->macrocontext), 0, (void *)data->macrocontext, 0, NULL);
3111 SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->callerid), 0, (void *)data->callerid, 0, NULL);
3112 SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->origtime), 0, (void *)data->origtime, 0, NULL);
3113 SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->duration), 0, (void *)data->duration, 0, NULL);
3114 SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxuser), 0, (void *)data->mailboxuser, 0, NULL);
3115 SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->mailboxcontext), 0, (void *)data->mailboxcontext, 0, NULL);
3116 SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->flag), 0, (void *)data->flag, 0, NULL);
3117 if (!ast_strlen_zero(data->category)) {
3118 SQLBindParameter(stmt, 12, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->category), 0, (void *)data->category, 0, NULL);
3120 res = SQLExecDirect(stmt, (unsigned char *)data->sql, SQL_NTS);
3121 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
3122 ast_log(AST_LOG_WARNING, "SQL Direct Execute failed!\n");
3123 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
3131 * \brief Stores a voicemail into the database.
3132 * \param dir the folder the mailbox folder to store the message.
3133 * \param mailboxuser the user owning the mailbox folder.
3134 * \param mailboxcontext
3135 * \param msgnum the message index for the message to be stored.
3137 * This method is used when mailboxes are stored in an ODBC back end.
3138 * The message sound file and information file is looked up on the file system.
3139 * A SQL query is invoked to store the message into the (MySQL) database.
3141 * \return the zero on success -1 on error.
3143 static int store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum)
3147 void *fdm = MAP_FAILED;
3153 char full_fn[PATH_MAX];
3156 struct ast_config *cfg=NULL;
3157 struct odbc_obj *obj;
3158 struct insert_data idata = { .sql = sql, .msgnums = msgnums, .dir = dir, .mailboxuser = mailboxuser, .mailboxcontext = mailboxcontext };
3159 struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
3161 delete_file(dir, msgnum);
3162 if (!(obj = ast_odbc_request_obj(odbc_database, 0))) {
3163 ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
3168 ast_copy_string(fmt, vmfmts, sizeof(fmt));
3169 c = strchr(fmt, '|');
3172 if (!strcasecmp(fmt, "wav49"))
3174 snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
3176 make_file(fn, sizeof(fn), dir, msgnum);
3178 ast_copy_string(fn, dir, sizeof(fn));
3179 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
3180 cfg = ast_config_load(full_fn, config_flags);
3181 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
3182 fd = open(full_fn, O_RDWR);
3184 ast_log(AST_LOG_WARNING, "Open of sound file '%s' failed: %s\n", full_fn, strerror(errno));
3188 if (cfg && cfg != CONFIG_STATUS_FILEINVALID) {
3189 if (!(idata.context = ast_variable_retrieve(cfg, "message", "context"))) {
3192 if (!(idata.macrocontext = ast_variable_retrieve(cfg, "message", "macrocontext"))) {