Issue 9990 - New API ast_mkdir, which creates parent directories as necessary (and...
[asterisk/asterisk.git] / apps / app_voicemail.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Comedian Mail - Voicemail System
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
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/
28  * 
29  * \par See also
30  * \arg \ref Config_vm
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
34  * during compilation.
35  *
36  *
37  *
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.
41  */
42
43 /*** MODULEINFO
44         <depend>res_smdi</depend>
45  ***/
46
47 /*** MAKEOPTS
48 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" remove_on_change="apps/app_voicemail.o">
49         <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
50                 <depend>unixodbc</depend>
51                 <depend>ltdl</depend>
52                 <conflict>IMAP_STORAGE</conflict>
53                 <defaultenabled>no</defaultenabled>
54         </member>
55         <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
56                 <depend>imap_tk</depend>
57                 <conflict>ODBC_STORAGE</conflict>
58                 <use>ssl</use>
59                 <defaultenabled>no</defaultenabled>
60         </member>
61 </category>
62  ***/
63
64 #include "asterisk.h"
65
66 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
67
68 #include <stdlib.h>
69 #include <errno.h>
70 #include <unistd.h>
71 #include <string.h>
72 #include <stdlib.h>
73 #include <stdio.h>
74 #include <sys/time.h>
75 #include <sys/stat.h>
76 #include <sys/types.h>
77 #include <sys/mman.h>
78 #include <time.h>
79 #include <dirent.h>
80
81 #ifdef IMAP_STORAGE
82 #include <ctype.h>
83 #include <signal.h>
84 #include <pwd.h>
85 #include "c-client.h"
86 #include "imap4r1.h"
87 #include "linkage.h"
88 #endif
89
90 #include "asterisk/lock.h"
91 #include "asterisk/file.h"
92 #include "asterisk/logger.h"
93 #include "asterisk/channel.h"
94 #include "asterisk/pbx.h"
95 #include "asterisk/options.h"
96 #include "asterisk/config.h"
97 #include "asterisk/say.h"
98 #include "asterisk/module.h"
99 #include "asterisk/adsi.h"
100 #include "asterisk/app.h"
101 #include "asterisk/manager.h"
102 #include "asterisk/dsp.h"
103 #include "asterisk/localtime.h"
104 #include "asterisk/cli.h"
105 #include "asterisk/utils.h"
106 #include "asterisk/stringfields.h"
107 #include "asterisk/smdi.h"
108 #include "asterisk/event.h"
109
110 #ifdef ODBC_STORAGE
111 #include "asterisk/res_odbc.h"
112 #endif
113
114 #ifdef IMAP_STORAGE
115 static char imapserver[48];
116 static char imapport[8];
117 static char imapflags[128];
118 static char imapfolder[64];
119 static char authuser[32];
120 static char authpassword[42];
121
122 static int expungeonhangup = 1;
123 AST_MUTEX_DEFINE_STATIC(delimiter_lock);
124 static char delimiter = '\0';
125
126 struct vm_state;
127 struct ast_vm_user;
128
129 /* Forward declarations for IMAP */
130 static int init_mailstream(struct vm_state *vms, int box);
131 static void write_file(char *filename, char *buffer, unsigned long len);
132 static void display_body(BODY *body, char *pfx, long i);
133 static char *get_header_by_tag(char *header, char *tag, char *buf, size_t len);
134 static void vm_imap_delete(int msgnum, struct vm_state *vms);
135 static char *get_user_by_mailbox(char *mailbox, char *buf, size_t len);
136 static struct vm_state *get_vm_state_by_imapuser(char *user, int interactive);
137 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, int interactive);
138 static void vmstate_insert(struct vm_state *vms);
139 static void vmstate_delete(struct vm_state *vms);
140 static void set_update(MAILSTREAM * stream);
141 static void init_vm_state(struct vm_state *vms);
142 static void check_msgArray(struct vm_state *vms);
143 static void copy_msgArray(struct vm_state *dst, struct vm_state *src);
144 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format);
145 static int make_gsm_file(char *dest, char *imapuser, char *dir, int num);
146 static void get_mailbox_delimiter(MAILSTREAM *stream);
147 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
148 static void imap_mailbox_name(char *spec, struct vm_state *vms, int box, int target);
149 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);
150 static void update_messages_by_imapuser(const char *user, unsigned long number);
151
152
153 struct vmstate {
154         struct vm_state *vms;
155         AST_LIST_ENTRY(vmstate) list;
156 };
157
158 static AST_LIST_HEAD_STATIC(vmstates, vmstate);
159
160 #endif
161
162 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
163
164 #define COMMAND_TIMEOUT 5000
165 /* Don't modify these here; set your umask at runtime instead */
166 #define VOICEMAIL_DIR_MODE      0777
167 #define VOICEMAIL_FILE_MODE     0666
168 #define CHUNKSIZE       65536
169
170 #define VOICEMAIL_CONFIG "voicemail.conf"
171 #define ASTERISK_USERNAME "asterisk"
172
173 /* Default mail command to mail voicemail. Change it with the
174     mailcmd= command in voicemail.conf */
175 #define SENDMAIL "/usr/sbin/sendmail -t"
176
177 #define INTRO "vm-intro"
178
179 #define MAXMSG 100
180 #define MAXMSGLIMIT 9999
181
182 #define BASEMAXINLINE 256
183 #define BASELINELEN 72
184 #define BASEMAXINLINE 256
185 #define eol "\r\n"
186
187 #define MAX_DATETIME_FORMAT     512
188 #define MAX_NUM_CID_CONTEXTS 10
189
190 #define VM_REVIEW        (1 << 0)
191 #define VM_OPERATOR      (1 << 1)
192 #define VM_SAYCID        (1 << 2)
193 #define VM_SVMAIL        (1 << 3)
194 #define VM_ENVELOPE      (1 << 4)
195 #define VM_SAYDURATION   (1 << 5)
196 #define VM_SKIPAFTERCMD  (1 << 6)
197 #define VM_FORCENAME     (1 << 7)   /*!< Have new users record their name */
198 #define VM_FORCEGREET    (1 << 8)   /*!< Have new users record their greetings */
199 #define VM_PBXSKIP       (1 << 9)
200 #define VM_DIRECFORWARD  (1 << 10)  /*!< directory_forward */
201 #define VM_ATTACH        (1 << 11)
202 #define VM_DELETE        (1 << 12)
203 #define VM_ALLOCED       (1 << 13)
204 #define VM_SEARCH        (1 << 14)
205 #define VM_TEMPGREETWARN (1 << 15)  /*!< Remind user tempgreeting is set */
206 #define ERROR_LOCK_PATH  -100
207
208
209 enum {
210         OPT_SILENT =           (1 << 0),
211         OPT_BUSY_GREETING =    (1 << 1),
212         OPT_UNAVAIL_GREETING = (1 << 2),
213         OPT_RECORDGAIN =       (1 << 3),
214         OPT_PREPEND_MAILBOX =  (1 << 4),
215         OPT_AUTOPLAY =         (1 << 6),
216 } vm_option_flags;
217
218 enum {
219         OPT_ARG_RECORDGAIN = 0,
220         OPT_ARG_PLAYFOLDER = 1,
221         /* This *must* be the last value in this enum! */
222         OPT_ARG_ARRAY_SIZE = 2,
223 } vm_option_args;
224
225 AST_APP_OPTIONS(vm_app_options, {
226         AST_APP_OPTION('s', OPT_SILENT),
227         AST_APP_OPTION('b', OPT_BUSY_GREETING),
228         AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
229         AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
230         AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
231         AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
232 });
233
234 static int load_config(void);
235
236 /*! \page vmlang Voicemail Language Syntaxes Supported
237
238         \par Syntaxes supported, not really language codes.
239         \arg \b en    - English
240         \arg \b de    - German
241         \arg \b es    - Spanish
242         \arg \b fr    - French
243         \arg \b it    - Italian
244         \arg \b nl    - Dutch
245         \arg \b pt    - Portuguese
246         \arg \b pt_BR - Portuguese (Brazil)
247         \arg \b gr    - Greek
248         \arg \b no    - Norwegian
249         \arg \b se    - Swedish
250         \arg \b tw    - Chinese (Taiwan)
251
252 German requires the following additional soundfile:
253 \arg \b 1F      einE (feminine)
254
255 Spanish requires the following additional soundfile:
256 \arg \b 1M      un (masculine)
257
258 Dutch, Portuguese & Spanish require the following additional soundfiles:
259 \arg \b vm-INBOXs       singular of 'new'
260 \arg \b vm-Olds         singular of 'old/heard/read'
261
262 NB these are plural:
263 \arg \b vm-INBOX        nieuwe (nl)
264 \arg \b vm-Old          oude (nl)
265
266 Polish uses:
267 \arg \b vm-new-a        'new', feminine singular accusative
268 \arg \b vm-new-e        'new', feminine plural accusative
269 \arg \b vm-new-ych      'new', feminine plural genitive
270 \arg \b vm-old-a        'old', feminine singular accusative
271 \arg \b vm-old-e        'old', feminine plural accusative
272 \arg \b vm-old-ych      'old', feminine plural genitive
273 \arg \b digits/1-a      'one', not always same as 'digits/1'
274 \arg \b digits/2-ie     'two', not always same as 'digits/2'
275
276 Swedish uses:
277 \arg \b vm-nytt         singular of 'new'
278 \arg \b vm-nya          plural of 'new'
279 \arg \b vm-gammalt      singular of 'old'
280 \arg \b vm-gamla        plural of 'old'
281 \arg \b digits/ett      'one', not always same as 'digits/1'
282
283 Norwegian uses:
284 \arg \b vm-ny           singular of 'new'
285 \arg \b vm-nye          plural of 'new'
286 \arg \b vm-gammel       singular of 'old'
287 \arg \b vm-gamle        plural of 'old'
288
289 Dutch also uses:
290 \arg \b nl-om           'at'?
291
292 Spanish also uses:
293 \arg \b vm-youhaveno
294
295 Italian requires the following additional soundfile:
296
297 For vm_intro_it:
298 \arg \b vm-nuovo        new
299 \arg \b vm-nuovi        new plural
300 \arg \b vm-vecchio      old
301 \arg \b vm-vecchi       old plural
302
303 Chinese (Taiwan) requires the following additional soundfile:
304 \arg \b vm-tong         A class-word for call (tong1)
305 \arg \b vm-ri           A class-word for day (ri4)
306 \arg \b vm-you          You (ni3)
307 \arg \b vm-haveno   Have no (mei2 you3)
308 \arg \b vm-have     Have (you3)
309 \arg \b vm-listen   To listen (yao4 ting1)
310
311
312 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
313 spelled among others when you have to change folder. For the above reasons, vm-INBOX
314 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
315
316 */
317
318 struct baseio {
319         int iocp;
320         int iolen;
321         int linelength;
322         int ateof;
323         unsigned char iobuf[BASEMAXINLINE];
324 };
325
326 /*! Structure for linked list of users 
327  * Use ast_vm_user_destroy() to free one of these structures. */
328 struct ast_vm_user {
329         char context[AST_MAX_CONTEXT];   /*!< Voicemail context */
330         char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
331         char password[80];               /*!< Secret pin code, numbers only */
332         char fullname[80];               /*!< Full name, for directory app */
333         char email[80];                  /*!< E-mail address */
334         char pager[80];                  /*!< E-mail address to pager (no attachment) */
335         char serveremail[80];            /*!< From: Mail address */
336         char mailcmd[160];               /*!< Configurable mail command */
337         char language[MAX_LANGUAGE];     /*!< Config: Language setting */
338         char zonetag[80];                /*!< Time zone */
339         char callback[80];
340         char dialout[80];
341         char uniqueid[20];               /*!< Unique integer identifier */
342         char exit[80];
343         char attachfmt[20];              /*!< Attachment format */
344         unsigned int flags;              /*!< VM_ flags */      
345         int saydurationm;
346         int maxmsg;                      /*!< Maximum number of msgs per folder for this mailbox */
347         int maxsecs;                     /*!< Maximum number of seconds per message for this mailbox */
348 #ifdef IMAP_STORAGE
349         char imapuser[80];               /*!< IMAP server login */
350         char imappassword[80];           /*!< IMAP server password if authpassword not defined */
351 #endif
352         double volgain;                  /*!< Volume gain for voicemails sent via email */
353         AST_LIST_ENTRY(ast_vm_user) list;
354 };
355
356 /*! Voicemail time zones */
357 struct vm_zone {
358         AST_LIST_ENTRY(vm_zone) list;
359         char name[80];
360         char timezone[80];
361         char msg_format[512];
362 };
363
364 /*! Voicemail mailbox state */
365 struct vm_state {
366         char curbox[80];
367         char username[80];
368         char curdir[PATH_MAX];
369         char vmbox[PATH_MAX];
370         char fn[PATH_MAX];
371         char fn2[PATH_MAX];
372         int *deleted;
373         int *heard;
374         int curmsg;
375         int lastmsg;
376         int newmessages;
377         int oldmessages;
378         int starting;
379         int repeats;
380 #ifdef IMAP_STORAGE
381         int updated;                         /*!< decremented on each mail check until 1 -allows delay */
382         long msgArray[256];
383         MAILSTREAM *mailstream;
384         int vmArrayIndex;
385         char imapuser[80];                   /*!< IMAP server login */
386         int interactive;
387         unsigned int quota_limit;
388         unsigned int quota_usage;
389         struct vm_state *persist_vms;
390 #endif
391 };
392
393
394 #ifdef ODBC_STORAGE
395 static char odbc_database[80];
396 static char odbc_table[80];
397 #define RETRIEVE(a,b) retrieve_file(a,b)
398 #define DISPOSE(a,b) remove_file(a,b)
399 #define STORE(a,b,c,d,e,f,g,h,i) store_file(a,b,c,d)
400 #define EXISTS(a,b,c,d) (message_exists(a,b))
401 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
402 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
403 #define DELETE(a,b,c) (delete_file(a,b))
404 #else
405 #ifdef IMAP_STORAGE
406 #define RETRIEVE(a,b)
407 #define DISPOSE(a,b)
408 #define STORE(a,b,c,d,e,f,g,h,i) (imap_store_file(a,b,c,d,e,f,g,h,i))
409 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
410 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
411 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
412 #define IMAP_DELETE(a,b,c,d) (vm_imap_delete(b,d))
413 #define DELETE(a,b,c) (vm_delete(c))
414 #else
415 #define RETRIEVE(a,b)
416 #define DISPOSE(a,b)
417 #define STORE(a,b,c,d,e,f,g,h,i)
418 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
419 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
420 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
421 #define DELETE(a,b,c) (vm_delete(c))
422 #endif
423 #endif
424
425 static char VM_SPOOL_DIR[PATH_MAX];
426
427 static char ext_pass_cmd[128];
428
429 #define PWDCHANGE_INTERNAL (1 << 1)
430 #define PWDCHANGE_EXTERNAL (1 << 2)
431 static int pwdchange = PWDCHANGE_INTERNAL;
432
433 #ifdef ODBC_STORAGE
434 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
435 #else
436 # ifdef IMAP_STORAGE
437 # define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
438 # else
439 # define tdesc "Comedian Mail (Voicemail System)"
440 # endif
441 #endif
442
443 static char userscontext[AST_MAX_EXTENSION] = "default";
444
445 static char *addesc = "Comedian Mail";
446
447 static char *synopsis_vm = "Leave a Voicemail message";
448
449 static char *descrip_vm =
450         "  VoiceMail(mailbox[@context][&mailbox[@context]][...][|options]): This\n"
451         "application allows the calling party to leave a message for the specified\n"
452         "list of mailboxes. When multiple mailboxes are specified, the greeting will\n"
453         "be taken from the first mailbox specified. Dialplan execution will stop if the\n"
454         "specified mailbox does not exist.\n"
455         "  The Voicemail application will exit if any of the following DTMF digits are\n"
456         "received:\n"
457         "    0 - Jump to the 'o' extension in the current dialplan context.\n"
458         "    * - Jump to the 'a' extension in the current dialplan context.\n"
459         "  This application will set the following channel variable upon completion:\n"
460         "    VMSTATUS - This indicates the status of the execution of the VoiceMail\n"
461         "               application. The possible values are:\n"
462         "               SUCCESS | USEREXIT | FAILED\n\n"
463         "  Options:\n"
464         "    b    - Play the 'busy' greeting to the calling party.\n"
465         "    g(#) - Use the specified amount of gain when recording the voicemail\n"
466         "           message. The units are whole-number decibels (dB).\n"
467         "    s    - Skip the playback of instructions for leaving a message to the\n"
468         "           calling party.\n"
469         "    u    - Play the 'unavailable greeting.\n";
470
471 static char *synopsis_vmain = "Check Voicemail messages";
472
473 static char *descrip_vmain =
474         "  VoiceMailMain([mailbox][@context][|options]): This application allows the\n"
475         "calling party to check voicemail messages. A specific mailbox, and optional\n"
476         "corresponding context, may be specified. If a mailbox is not provided, the\n"
477         "calling party will be prompted to enter one. If a context is not specified,\n"
478         "the 'default' context will be used.\n\n"
479         "  Options:\n"
480         "    p    - Consider the mailbox parameter as a prefix to the mailbox that\n"
481         "           is entered by the caller.\n"
482         "    g(#) - Use the specified amount of gain when recording a voicemail\n"
483         "           message. The units are whole-number decibels (dB).\n"
484         "    s    - Skip checking the passcode for the mailbox.\n"
485         "    a(#) - Skip folder prompt and go directly to folder specified.\n"
486         "           Defaults to INBOX\n";
487
488 static char *synopsis_vm_box_exists =
489 "Check to see if Voicemail mailbox exists";
490
491 static char *descrip_vm_box_exists =
492         "  MailboxExists(mailbox[@context][|options]): Check to see if the specified\n"
493         "mailbox exists. If no voicemail context is specified, the 'default' context\n"
494         "will be used.\n"
495         "  This application will set the following channel variable upon completion:\n"
496         "    VMBOXEXISTSSTATUS - This will contain the status of the execution of the\n"
497         "                        MailboxExists application. Possible values include:\n"
498         "                        SUCCESS | FAILED\n\n"
499         "  Options: (none)\n";
500
501 static char *synopsis_vmauthenticate = "Authenticate with Voicemail passwords";
502
503 static char *descrip_vmauthenticate =
504         "  VMAuthenticate([mailbox][@context][|options]): This application behaves the\n"
505         "same way as the Authenticate application, but the passwords are taken from\n"
506         "voicemail.conf.\n"
507         "  If the mailbox is specified, only that mailbox's password will be considered\n"
508         "valid. If the mailbox is not specified, the channel variable AUTH_MAILBOX will\n"
509         "be set with the authenticated mailbox.\n\n"
510         "  Options:\n"
511         "    s - Skip playing the initial prompts.\n";
512
513 /* Leave a message */
514 static char *app = "VoiceMail";
515
516 /* Check mail, control, etc */
517 static char *app2 = "VoiceMailMain";
518
519 static char *app3 = "MailboxExists";
520 static char *app4 = "VMAuthenticate";
521
522 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
523 static AST_LIST_HEAD_STATIC(zones, vm_zone);
524 static int maxsilence;
525 static int maxmsg;
526 static int silencethreshold = 128;
527 static char serveremail[80];
528 static char mailcmd[160];       /* Configurable mail cmd */
529 static char externnotify[160]; 
530 static struct ast_smdi_interface *smdi_iface = NULL;
531 static char vmfmts[80];
532 static double volgain;
533 static int vmminsecs;
534 static int vmmaxsecs;
535 static int maxgreet;
536 static int skipms;
537 static int maxlogins;
538
539 /*! Poll mailboxes for changes since there is something external to
540  *  app_voicemail that may change them. */
541 static unsigned int poll_mailboxes;
542
543 /*! Polling frequency */
544 static unsigned int poll_freq;
545 /*! By default, poll every 30 seconds */
546 #define DEFAULT_POLL_FREQ 30
547
548 AST_MUTEX_DEFINE_STATIC(poll_lock);
549 static ast_cond_t poll_cond = PTHREAD_COND_INITIALIZER;
550 static pthread_t poll_thread = AST_PTHREADT_NULL;
551 static unsigned char poll_thread_run;
552
553 /*! Subscription to ... MWI event subscriptions */
554 static struct ast_event_sub *mwi_sub_sub;
555 /*! Subscription to ... MWI event un-subscriptions */
556 static struct ast_event_sub *mwi_unsub_sub;
557
558 /*!
559  * \brief An MWI subscription
560  *
561  * This is so we can keep track of which mailboxes are subscribed to.
562  * This way, we know which mailboxes to poll when the pollmailboxes
563  * option is being used.
564  */
565 struct mwi_sub {
566         AST_RWLIST_ENTRY(mwi_sub) entry;
567         int old_new;
568         int old_old;
569         uint32_t uniqueid;
570         char mailbox[1];
571 };
572
573 static AST_RWLIST_HEAD_STATIC(mwi_subs, mwi_sub);
574
575 /* custom password sounds */
576 static char vm_password[80] = "vm-password";
577 static char vm_newpassword[80] = "vm-newpassword";
578 static char vm_passchanged[80] = "vm-passchanged";
579 static char vm_reenterpassword[80] = "vm-reenterpassword";
580 static char vm_mismatch[80] = "vm-mismatch";
581
582 static struct ast_flags globalflags = {0};
583
584 static int saydurationminfo;
585
586 static char dialcontext[AST_MAX_CONTEXT];
587 static char callcontext[AST_MAX_CONTEXT];
588 static char exitcontext[AST_MAX_CONTEXT];
589
590 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
591
592
593 static char *emailbody = NULL;
594 static char *emailsubject = NULL;
595 static char *pagerbody = NULL;
596 static char *pagersubject = NULL;
597 static char fromstring[100];
598 static char pagerfromstring[100];
599 static char emailtitle[100];
600 static char charset[32] = "ISO-8859-1";
601
602 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
603 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
604 static int adsiver = 1;
605 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
606
607 /* Forward declarations - generic */
608 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu,int box);
609 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);
610 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
611 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
612                         char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
613                         signed char record_gain, struct vm_state *vms);
614 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
615 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
616 static int notify_new_message(struct ast_channel *chan, struct ast_vm_user *vmu, int msgnum, long duration, char *fmt, char *cidnum, char *cidname);
617 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 *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category, int imap);
618 static void apply_options(struct ast_vm_user *vmu, const char *options);
619
620 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
621 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
622 #endif
623
624
625
626 static void populate_defaults(struct ast_vm_user *vmu)
627 {
628         ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);     
629         if (saydurationminfo)
630                 vmu->saydurationm = saydurationminfo;
631         if (callcontext)
632                 ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
633         if (dialcontext)
634                 ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
635         if (exitcontext)
636                 ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
637         if (vmmaxsecs)
638                 vmu->maxsecs = vmmaxsecs;
639         if (maxmsg)
640                 vmu->maxmsg = maxmsg;
641         vmu->volgain = volgain;
642 }
643
644 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
645 {
646         int x;
647         if (!strcasecmp(var, "attach")) {
648                 ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
649         } else if (!strcasecmp(var, "attachfmt")) {
650                 ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
651         } else if (!strcasecmp(var, "serveremail")) {
652                 ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
653         } else if (!strcasecmp(var, "language")) {
654                 ast_copy_string(vmu->language, value, sizeof(vmu->language));
655         } else if (!strcasecmp(var, "tz")) {
656                 ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
657 #ifdef IMAP_STORAGE
658         } else if (!strcasecmp(var, "imapuser")) {
659                 ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
660         } else if (!strcasecmp(var, "imappassword")) {
661                 ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
662 #endif
663         } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
664                 ast_set2_flag(vmu, ast_true(value), VM_DELETE); 
665         } else if (!strcasecmp(var, "saycid")){
666                 ast_set2_flag(vmu, ast_true(value), VM_SAYCID); 
667         } else if (!strcasecmp(var,"sendvoicemail")){
668                 ast_set2_flag(vmu, ast_true(value), VM_SVMAIL); 
669         } else if (!strcasecmp(var, "review")){
670                 ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
671         } else if (!strcasecmp(var, "tempgreetwarn")){
672                 ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);  
673         } else if (!strcasecmp(var, "operator")){
674                 ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);       
675         } else if (!strcasecmp(var, "envelope")){
676                 ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);       
677         } else if (!strcasecmp(var, "sayduration")){
678                 ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);    
679         } else if (!strcasecmp(var, "saydurationm")){
680                 if (sscanf(value, "%d", &x) == 1) {
681                         vmu->saydurationm = x;
682                 } else {
683                         ast_log(LOG_WARNING, "Invalid min duration for say duration\n");
684                 }
685         } else if (!strcasecmp(var, "forcename")){
686                 ast_set2_flag(vmu, ast_true(value), VM_FORCENAME);      
687         } else if (!strcasecmp(var, "forcegreetings")){
688                 ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);     
689         } else if (!strcasecmp(var, "callback")) {
690                 ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
691         } else if (!strcasecmp(var, "dialout")) {
692                 ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
693         } else if (!strcasecmp(var, "exitcontext")) {
694                 ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
695         } else if (!strcasecmp(var, "maxmessage")) {
696                 if (vmu->maxsecs <= 0) {
697                         ast_log(LOG_WARNING, "Invalid max message length of %s. Using global value %i\n", value, vmmaxsecs);
698                         vmu->maxsecs = vmmaxsecs;
699                 } else {
700                         vmu->maxsecs = atoi(value);
701                 }
702         } else if (!strcasecmp(var, "maxmsg")) {
703                 vmu->maxmsg = atoi(value);
704                 if (vmu->maxmsg <= 0) {
705                         ast_log(LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %i\n", value, MAXMSG);
706                         vmu->maxmsg = MAXMSG;
707                 } else if (vmu->maxmsg > MAXMSGLIMIT) {
708                         ast_log(LOG_WARNING, "Maximum number of messages per folder is %i. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
709                         vmu->maxmsg = MAXMSGLIMIT;
710                 }
711         } else if (!strcasecmp(var, "volgain")) {
712                 sscanf(value, "%lf", &vmu->volgain);
713         } else if (!strcasecmp(var, "options")) {
714                 apply_options(vmu, value);
715         }
716 }
717
718 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
719 {
720         int res;
721         if (!ast_strlen_zero(vmu->uniqueid)) {
722                 res = ast_update_realtime("voicemail", "uniqueid", vmu->uniqueid, "password", password, NULL);
723                 if (res > 0) {
724                         ast_copy_string(vmu->password, password, sizeof(vmu->password));
725                         res = 0;
726                 } else if (!res) {
727                         res = -1;
728                 }
729                 return res;
730         }
731         return -1;
732 }
733
734 static void apply_options(struct ast_vm_user *vmu, const char *options)
735 {       /* Destructively Parse options and apply */
736         char *stringp;
737         char *s;
738         char *var, *value;
739         stringp = ast_strdupa(options);
740         while ((s = strsep(&stringp, "|"))) {
741                 value = s;
742                 if ((var = strsep(&value, "=")) && value) {
743                         apply_option(vmu, var, value);
744                 }
745         }       
746 }
747
748 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
749 {
750         struct ast_variable *tmp;
751         tmp = var;
752         while (tmp) {
753                 if (!strcasecmp(tmp->name, "vmsecret")) {
754                         ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
755                 } else if (!strcasecmp(tmp->name, "secret") || !strcasecmp(tmp->name, "password")) { /* don't overwrite vmsecret if it exists */
756                         if (ast_strlen_zero(retval->password))
757                                 ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
758                 } else if (!strcasecmp(tmp->name, "uniqueid")) {
759                         ast_copy_string(retval->uniqueid, tmp->value, sizeof(retval->uniqueid));
760                 } else if (!strcasecmp(tmp->name, "pager")) {
761                         ast_copy_string(retval->pager, tmp->value, sizeof(retval->pager));
762                 } else if (!strcasecmp(tmp->name, "email")) {
763                         ast_copy_string(retval->email, tmp->value, sizeof(retval->email));
764                 } else if (!strcasecmp(tmp->name, "fullname")) {
765                         ast_copy_string(retval->fullname, tmp->value, sizeof(retval->fullname));
766                 } else if (!strcasecmp(tmp->name, "context")) {
767                         ast_copy_string(retval->context, tmp->value, sizeof(retval->context));
768 #ifdef IMAP_STORAGE
769                 } else if (!strcasecmp(tmp->name, "imapuser")) {
770                         ast_copy_string(retval->imapuser, tmp->value, sizeof(retval->imapuser));
771                 } else if (!strcasecmp(tmp->name, "imappassword")) {
772                         ast_copy_string(retval->imappassword, tmp->value, sizeof(retval->imappassword));
773 #endif
774                 } else
775                         apply_option(retval, tmp->name, tmp->value);
776                 tmp = tmp->next;
777         } 
778 }
779
780 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
781 {
782         struct ast_variable *var;
783         struct ast_vm_user *retval;
784
785         if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
786                 if (!ivm)
787                         ast_set_flag(retval, VM_ALLOCED);       
788                 else
789                         memset(retval, 0, sizeof(*retval));
790                 if (mailbox) 
791                         ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
792                 populate_defaults(retval);
793                 if (!context && ast_test_flag((&globalflags), VM_SEARCH))
794                         var = ast_load_realtime("voicemail", "mailbox", mailbox, NULL);
795                 else
796                         var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, NULL);
797                 if (var) {
798                         apply_options_full(retval, var);
799                         ast_variables_destroy(var);
800                 } else { 
801                         if (!ivm) 
802                                 ast_free(retval);
803                         retval = NULL;
804                 }       
805         } 
806         return retval;
807 }
808
809 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
810 {
811         /* This function could be made to generate one from a database, too */
812         struct ast_vm_user *vmu=NULL, *cur;
813         AST_LIST_LOCK(&users);
814
815         if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
816                 context = "default";
817
818         AST_LIST_TRAVERSE(&users, cur, list) {
819                 if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
820                         break;
821                 if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
822                         break;
823         }
824         if (cur) {
825                 /* Make a copy, so that on a reload, we have no race */
826                 if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
827                         memcpy(vmu, cur, sizeof(*vmu));
828                         ast_set2_flag(vmu, !ivm, VM_ALLOCED);
829                         AST_LIST_NEXT(vmu, list) = NULL;
830                 }
831         } else
832                 vmu = find_user_realtime(ivm, context, mailbox);
833         AST_LIST_UNLOCK(&users);
834         return vmu;
835 }
836
837 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
838 {
839         /* This function could be made to generate one from a database, too */
840         struct ast_vm_user *cur;
841         int res = -1;
842         AST_LIST_LOCK(&users);
843         AST_LIST_TRAVERSE(&users, cur, list) {
844                 if ((!context || !strcasecmp(context, cur->context)) &&
845                         (!strcasecmp(mailbox, cur->mailbox)))
846                                 break;
847         }
848         if (cur) {
849                 ast_copy_string(cur->password, newpass, sizeof(cur->password));
850                 res = 0;
851         }
852         AST_LIST_UNLOCK(&users);
853         return res;
854 }
855
856 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
857 {
858         struct ast_config   *cfg=NULL;
859         struct ast_variable *var=NULL;
860         struct ast_category *cat=NULL;
861         char *category=NULL, *value=NULL, *new=NULL;
862         const char *tmp=NULL;
863                                         
864         if (!change_password_realtime(vmu, newpassword))
865                 return;
866
867         /* check voicemail.conf */
868         if ((cfg = ast_config_load_with_comments(VOICEMAIL_CONFIG))) {
869                 while ((category = ast_category_browse(cfg, category))) {
870                         if (!strcasecmp(category, vmu->context)) {
871                                 if (!(tmp = ast_variable_retrieve(cfg, category, vmu->mailbox))) {
872                                         ast_log(LOG_WARNING, "We could not find the mailbox.\n");
873                                         break;
874                                 }
875                                 value = strstr(tmp,",");
876                                 if (!value) {
877                                         ast_log(LOG_WARNING, "variable has bad format.\n");
878                                         break;
879                                 }
880                                 new = alloca((strlen(value)+strlen(newpassword)+1));
881                                 sprintf(new,"%s%s", newpassword, value);
882                                 if (!(cat = ast_category_get(cfg, category))) {
883                                         ast_log(LOG_WARNING, "Failed to get category structure.\n");
884                                         break;
885                                 }
886                                 ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
887                         }
888                 }
889                 /* save the results */
890                 reset_user_pw(vmu->context, vmu->mailbox, newpassword);
891                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
892                 config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
893         }
894         category = NULL;
895         var = NULL;
896         /* check users.conf and update the password stored for the mailbox*/
897         /* if no vmsecret entry exists create one. */
898         if ((cfg = ast_config_load_with_comments("users.conf"))) {
899                 ast_debug(4, "we are looking for %s\n", vmu->mailbox);
900                 while ((category = ast_category_browse(cfg, category))) {
901                         ast_debug(4, "users.conf: %s\n", category);
902                         if (!strcasecmp(category, vmu->mailbox)) {
903                                 if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
904                                         ast_debug(3, "looks like we need to make vmsecret!\n");
905                                         var = ast_variable_new("vmsecret", newpassword);
906                                 } 
907                                 new = alloca(strlen(newpassword)+1);
908                                 sprintf(new, "%s", newpassword);
909                                 if (!(cat = ast_category_get(cfg, category))) {
910                                         ast_debug(4, "failed to get category!\n");
911                                         break;
912                                 }
913                                 if (!var)               
914                                         ast_variable_update(cat, "vmsecret", new, NULL, 0);
915                                 else
916                                         ast_variable_append(cat, var);
917                         }
918                 }
919                 /* save the results and clean things up */
920                 reset_user_pw(vmu->context, vmu->mailbox, newpassword); 
921                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
922                 config_text_file_save("users.conf", cfg, "AppVoicemail");
923         }
924 }
925
926 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
927 {
928         char buf[255];
929         snprintf(buf,255,"%s %s %s %s",ext_pass_cmd,vmu->context,vmu->mailbox,newpassword);
930         if (!ast_safe_system(buf))
931                 ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
932 }
933
934 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
935 {
936         return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
937 }
938
939 #ifdef IMAP_STORAGE
940 static int make_gsm_file(char *dest, char *imapuser, char *dir, int num)
941 {
942         int res;
943         if ((res = ast_mkdir(dir, 01777))) {
944                 ast_log(LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dir, strerror(res));
945                 return sprintf(dest, "%s/msg%04d", dir, num);
946         }
947         /* return sprintf(dest, "%s/s/msg%04d", dir, imapuser, num); */
948         return sprintf(dest, "%s/msg%04d", dir, num);
949 }
950
951 static void vm_imap_delete(int msgnum, struct vm_state *vms)
952 {
953         unsigned long messageNum = 0;
954         char arg[10];
955
956         /* find real message number based on msgnum */
957         /* this may be an index into vms->msgArray based on the msgnum. */
958
959         messageNum = vms->msgArray[msgnum];
960         if (messageNum == 0) {
961                 ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n",msgnum,messageNum);
962                 return;
963         }
964         ast_debug(3, "deleting msgnum %d, which is mailbox message %lu\n",msgnum,messageNum);
965         /* delete message */
966         sprintf (arg,"%lu",messageNum);
967         mail_setflag (vms->mailstream,arg,"\\DELETED");
968 }
969
970 #endif
971 static int make_file(char *dest, int len, char *dir, int num)
972 {
973         return snprintf(dest, len, "%s/msg%04d", dir, num);
974 }
975
976 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
977  * \param dest    String. base directory.
978  * \param len     Length of dest.
979  * \param context String. Ignored if is null or empty string.
980  * \param ext     String. Ignored if is null or empty string.
981  * \param folder  String. Ignored if is null or empty string. 
982  * \return -1 on failure, 0 on success.
983  */
984 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
985 {
986         mode_t  mode = VOICEMAIL_DIR_MODE;
987         int res;
988
989         make_dir(dest, len, context, ext, folder);
990         if ((res = ast_mkdir(dest, mode))) {
991                 ast_log(LOG_WARNING, "ast_mkdir '%s' failed: %s\n", dest, strerror(res));
992                 return -1;
993         }
994         return 0;
995 }
996
997 /*! \brief Lock file path
998     only return failure if ast_lock_path returns 'timeout',
999    not if the path does not exist or any other reason
1000 */
1001 static int vm_lock_path(const char *path)
1002 {
1003         switch (ast_lock_path(path)) {
1004         case AST_LOCK_TIMEOUT:
1005                 return -1;
1006         default:
1007                 return 0;
1008         }
1009 }
1010
1011
1012 #ifdef ODBC_STORAGE
1013 static int retrieve_file(char *dir, int msgnum)
1014 {
1015         int x = 0;
1016         int res;
1017         int fd=-1;
1018         size_t fdlen = 0;
1019         void *fdm = MAP_FAILED;
1020         SQLSMALLINT colcount=0;
1021         SQLHSTMT stmt;
1022         char sql[PATH_MAX];
1023         char fmt[80]="";
1024         char *c;
1025         char coltitle[256];
1026         SQLSMALLINT collen;
1027         SQLSMALLINT datatype;
1028         SQLSMALLINT decimaldigits;
1029         SQLSMALLINT nullable;
1030         SQLULEN colsize;
1031         SQLLEN colsize2;
1032         FILE *f=NULL;
1033         char rowdata[80];
1034         char fn[PATH_MAX];
1035         char full_fn[PATH_MAX];
1036         char msgnums[80];
1037         
1038         struct odbc_obj *obj;
1039         obj = ast_odbc_request_obj(odbc_database, 0);
1040         if (obj) {
1041                 ast_copy_string(fmt, vmfmts, sizeof(fmt));
1042                 c = strchr(fmt, '|');
1043                 if (c)
1044                         *c = '\0';
1045                 if (!strcasecmp(fmt, "wav49"))
1046                         strcpy(fmt, "WAV");
1047                 snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
1048                 if (msgnum > -1)
1049                         make_file(fn, sizeof(fn), dir, msgnum);
1050                 else
1051                         ast_copy_string(fn, dir, sizeof(fn));
1052                 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
1053                 
1054                 if (!(f = fopen(full_fn, "w+"))) {
1055                         ast_log(LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
1056                         goto yuck;
1057                 }
1058                 
1059                 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
1060                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1061                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1062                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1063                         ast_odbc_release_obj(obj);
1064                         goto yuck;
1065                 }
1066                 snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?",odbc_table);
1067                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1068                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1069                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1070                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1071                         ast_odbc_release_obj(obj);
1072                         goto yuck;
1073                 }
1074                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dir), 0, (void *)dir, 0, NULL);
1075                 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
1076                 res = ast_odbc_smart_execute(obj, stmt);
1077                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1078                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
1079                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1080                         ast_odbc_release_obj(obj);
1081                         goto yuck;
1082                 }
1083                 res = SQLFetch(stmt);
1084                 if (res == SQL_NO_DATA) {
1085                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1086                         ast_odbc_release_obj(obj);
1087                         goto yuck;
1088                 }
1089                 else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1090                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
1091                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1092                         ast_odbc_release_obj(obj);
1093                         goto yuck;
1094                 }
1095                 fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
1096                 if (fd < 0) {
1097                         ast_log(LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
1098                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1099                         ast_odbc_release_obj(obj);
1100                         goto yuck;
1101                 }
1102                 res = SQLNumResultCols(stmt, &colcount);
1103                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {   
1104                         ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
1105                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1106                         ast_odbc_release_obj(obj);
1107                         goto yuck;
1108                 }
1109                 if (f) 
1110                         fprintf(f, "[message]\n");
1111                 for (x=0;x<colcount;x++) {
1112                         rowdata[0] = '\0';
1113                         collen = sizeof(coltitle);
1114                         res = SQLDescribeCol(stmt, x + 1, (unsigned char *)coltitle, sizeof(coltitle), &collen, 
1115                                                 &datatype, &colsize, &decimaldigits, &nullable);
1116                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1117                                 ast_log(LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
1118                                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1119                                 ast_odbc_release_obj(obj);
1120                                 goto yuck;
1121                         }
1122                         if (!strcasecmp(coltitle, "recording")) {
1123                                 off_t offset;
1124                                 res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
1125                                 fdlen = colsize2;
1126                                 if (fd > -1) {
1127                                         char tmp[1]="";
1128                                         lseek(fd, fdlen - 1, SEEK_SET);
1129                                         if (write(fd, tmp, 1) != 1) {
1130                                                 close(fd);
1131                                                 fd = -1;
1132                                                 continue;
1133                                         }
1134                                         /* Read out in small chunks */
1135                                         for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
1136                                                 if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
1137                                                         ast_log(LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
1138                                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1139                                                         ast_odbc_release_obj(obj);
1140                                                         goto yuck;
1141                                                 } else {
1142                                                         res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
1143                                                         munmap(fdm, CHUNKSIZE);
1144                                                         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1145                                                                 ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
1146                                                                 unlink(full_fn);
1147                                                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
1148                                                                 ast_odbc_release_obj(obj);
1149                                                                 goto yuck;
1150                                                         }
1151                                                 }
1152                                         }
1153                                         truncate(full_fn, fdlen);
1154                                 }
1155                         } else {
1156                                 res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
1157                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1158                                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
1159                                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1160                                         ast_odbc_release_obj(obj);
1161                                         goto yuck;
1162                                 }
1163                                 if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
1164                                         fprintf(f, "%s=%s\n", coltitle, rowdata);
1165                         }
1166                 }
1167                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1168                 ast_odbc_release_obj(obj);
1169         } else
1170                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1171 yuck:   
1172         if (f)
1173                 fclose(f);
1174         if (fd > -1)
1175                 close(fd);
1176         return x - 1;
1177 }
1178
1179 static int remove_file(char *dir, int msgnum)
1180 {
1181         char fn[PATH_MAX];
1182         char full_fn[PATH_MAX];
1183         char msgnums[80];
1184         
1185         if (msgnum > -1) {
1186                 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
1187                 make_file(fn, sizeof(fn), dir, msgnum);
1188         } else
1189                 ast_copy_string(fn, dir, sizeof(fn));
1190         ast_filedelete(fn, NULL);       
1191         if (ast_check_realtime("voicemail_data")) {
1192                 ast_destroy_realtime("voicemail_data", "filename", fn, NULL);
1193         }
1194         snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
1195         unlink(full_fn);
1196         return 0;
1197 }
1198
1199 static int last_message_index(struct ast_vm_user *vmu, char *dir)
1200 {
1201         int x = 0;
1202         int res;
1203         SQLHSTMT stmt;
1204         char sql[PATH_MAX];
1205         char rowdata[20];
1206         
1207         struct odbc_obj *obj;
1208         obj = ast_odbc_request_obj(odbc_database, 0);
1209         if (obj) {
1210                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1211                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1212                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1213                         ast_odbc_release_obj(obj);
1214                         goto yuck;
1215                 }
1216                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?",odbc_table);
1217                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1218                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1219                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1220                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1221                         ast_odbc_release_obj(obj);
1222                         goto yuck;
1223                 }
1224                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dir), 0, (void *)dir, 0, NULL);
1225                 res = ast_odbc_smart_execute(obj, stmt);
1226                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1227                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
1228                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1229                         ast_odbc_release_obj(obj);
1230                         goto yuck;
1231                 }
1232                 res = SQLFetch(stmt);
1233                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1234                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
1235                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1236                         ast_odbc_release_obj(obj);
1237                         goto yuck;
1238                 }
1239                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
1240                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1241                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
1242                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1243                         ast_odbc_release_obj(obj);
1244                         goto yuck;
1245                 }
1246                 if (sscanf(rowdata, "%d", &x) != 1)
1247                         ast_log(LOG_WARNING, "Failed to read message count!\n");
1248                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1249                 ast_odbc_release_obj(obj);
1250         } else
1251                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1252 yuck:   
1253         return x - 1;
1254 }
1255
1256 static int message_exists(char *dir, int msgnum)
1257 {
1258         int x = 0;
1259         int res;
1260         SQLHSTMT stmt;
1261         char sql[PATH_MAX];
1262         char rowdata[20];
1263         char msgnums[20];
1264         
1265         struct odbc_obj *obj;
1266         obj = ast_odbc_request_obj(odbc_database, 0);
1267         if (obj) {
1268                 snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
1269                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1270                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1271                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1272                         ast_odbc_release_obj(obj);
1273                         goto yuck;
1274                 }
1275                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?",odbc_table);
1276                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1277                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1278                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1279                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1280                         ast_odbc_release_obj(obj);
1281                         goto yuck;
1282                 }
1283                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dir), 0, (void *)dir, 0, NULL);
1284                 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
1285                 res = ast_odbc_smart_execute(obj, stmt);
1286                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1287                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
1288                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1289                         ast_odbc_release_obj(obj);
1290                         goto yuck;
1291                 }
1292                 res = SQLFetch(stmt);
1293                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1294                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
1295                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1296                         ast_odbc_release_obj(obj);
1297                         goto yuck;
1298                 }
1299                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
1300                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1301                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
1302                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1303                         ast_odbc_release_obj(obj);
1304                         goto yuck;
1305                 }
1306                 if (sscanf(rowdata, "%d", &x) != 1)
1307                         ast_log(LOG_WARNING, "Failed to read message count!\n");
1308                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1309                 ast_odbc_release_obj(obj);
1310         } else
1311                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1312 yuck:   
1313         return x;
1314 }
1315
1316 static int count_messages(struct ast_vm_user *vmu, char *dir)
1317 {
1318         return last_message_index(vmu, dir) + 1;
1319 }
1320
1321 static void delete_file(char *sdir, int smsg)
1322 {
1323         int res;
1324         SQLHSTMT stmt;
1325         char sql[PATH_MAX];
1326         char msgnums[20];
1327         
1328         struct odbc_obj *obj;
1329         obj = ast_odbc_request_obj(odbc_database, 0);
1330         if (obj) {
1331                 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
1332                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1333                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1334                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1335                         ast_odbc_release_obj(obj);
1336                         goto yuck;
1337                 }
1338                 snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?",odbc_table);
1339                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1340                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1341                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1342                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1343                         ast_odbc_release_obj(obj);
1344                         goto yuck;
1345                 }
1346                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(sdir), 0, (void *)sdir, 0, NULL);
1347                 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
1348                 res = ast_odbc_smart_execute(obj, stmt);
1349                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1350                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
1351                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1352                         ast_odbc_release_obj(obj);
1353                         goto yuck;
1354                 }
1355                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1356                 ast_odbc_release_obj(obj);
1357         } else
1358                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1359 yuck:
1360         return; 
1361 }
1362
1363 static void copy_file(char *sdir, int smsg, char *ddir, int dmsg, char *dmailboxuser, char *dmailboxcontext)
1364 {
1365         int res;
1366         SQLHSTMT stmt;
1367         char sql[512];
1368         char msgnums[20];
1369         char msgnumd[20];
1370         struct odbc_obj *obj;
1371
1372         delete_file(ddir, dmsg);
1373         obj = ast_odbc_request_obj(odbc_database, 0);
1374         if (obj) {
1375                 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
1376                 snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
1377                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1378                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1379                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1380                         ast_odbc_release_obj(obj);
1381                         goto yuck;
1382                 }
1383                 snprintf(sql, sizeof(sql), "INSERT INTO %s (dir, msgnum, context, macrocontext, callerid, origtime, duration, recording, mailboxuser, mailboxcontext) SELECT ?,?,context,macrocontext,callerid,origtime,duration,recording,?,? FROM %s WHERE dir=? AND msgnum=?",odbc_table,odbc_table); 
1384                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1385                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1386                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1387                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1388                         ast_odbc_release_obj(obj);
1389                         goto yuck;
1390                 }
1391                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(ddir), 0, (void *)ddir, 0, NULL);
1392                 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnumd), 0, (void *)msgnumd, 0, NULL);
1393                 SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dmailboxuser), 0, (void *)dmailboxuser, 0, NULL);
1394                 SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dmailboxcontext), 0, (void *)dmailboxcontext, 0, NULL);
1395                 SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(sdir), 0, (void *)sdir, 0, NULL);
1396                 SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
1397                 res = ast_odbc_smart_execute(obj, stmt);
1398                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1399                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
1400                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1401                         ast_odbc_release_obj(obj);
1402                         goto yuck;
1403                 }
1404                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1405                 ast_odbc_release_obj(obj);
1406         } else
1407                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1408 yuck:
1409         return; 
1410 }
1411
1412 static int store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum)
1413 {
1414         int x = 0;
1415         int res;
1416         int fd = -1;
1417         void *fdm = MAP_FAILED;
1418         size_t fdlen = -1;
1419         SQLHSTMT stmt;
1420         SQLLEN len;
1421         char sql[PATH_MAX];
1422         char msgnums[20];
1423         char fn[PATH_MAX];
1424         char full_fn[PATH_MAX];
1425         char fmt[80]="";
1426         char *c;
1427         const char *context="", *macrocontext="", *callerid="", *origtime="", *duration="";
1428         const char *category = "";
1429         struct ast_config *cfg=NULL;
1430         struct odbc_obj *obj;
1431
1432         delete_file(dir, msgnum);
1433         obj = ast_odbc_request_obj(odbc_database, 0);
1434         if (obj) {
1435                 ast_copy_string(fmt, vmfmts, sizeof(fmt));
1436                 c = strchr(fmt, '|');
1437                 if (c)
1438                         *c = '\0';
1439                 if (!strcasecmp(fmt, "wav49"))
1440                         strcpy(fmt, "WAV");
1441                 snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
1442                 if (msgnum > -1)
1443                         make_file(fn, sizeof(fn), dir, msgnum);
1444                 else
1445                         ast_copy_string(fn, dir, sizeof(fn));
1446                 snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
1447                 cfg = ast_config_load(full_fn);
1448                 snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
1449                 fd = open(full_fn, O_RDWR);
1450                 if (fd < 0) {
1451                         ast_log(LOG_WARNING, "Open of sound file '%s' failed: %s\n", full_fn, strerror(errno));
1452                         ast_odbc_release_obj(obj);
1453                         goto yuck;
1454                 }
1455                 if (cfg) {
1456                         context = ast_variable_retrieve(cfg, "message", "context");
1457                         if (!context) context = "";
1458                         macrocontext = ast_variable_retrieve(cfg, "message", "macrocontext");
1459                         if (!macrocontext) macrocontext = "";
1460                         callerid = ast_variable_retrieve(cfg, "message", "callerid");
1461                         if (!callerid) callerid = "";
1462                         origtime = ast_variable_retrieve(cfg, "message", "origtime");
1463                         if (!origtime) origtime = "";
1464                         duration = ast_variable_retrieve(cfg, "message", "duration");
1465                         if (!duration) duration = "";
1466                         category = ast_variable_retrieve(cfg, "message", "category");
1467                         if (!category) category = "";
1468                 }
1469                 fdlen = lseek(fd, 0, SEEK_END);
1470                 lseek(fd, 0, SEEK_SET);
1471                 printf("Length is %zd\n", fdlen);
1472                 fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED,fd, 0);
1473                 if (fdm == MAP_FAILED) {
1474                         ast_log(LOG_WARNING, "Memory map failed!\n");
1475                         ast_odbc_release_obj(obj);
1476                         goto yuck;
1477                 } 
1478                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1479                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1480                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1481                         ast_odbc_release_obj(obj);
1482                         goto yuck;
1483                 }
1484                 if (!ast_strlen_zero(category)) 
1485                         snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,category) VALUES (?,?,?,?,?,?,?,?,?,?,?)",odbc_table); 
1486                 else
1487                         snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext) VALUES (?,?,?,?,?,?,?,?,?,?)",odbc_table);
1488                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1489                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1490                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1491                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1492                         ast_odbc_release_obj(obj);
1493                         goto yuck;
1494                 }
1495                 len = fdlen; /* SQL_LEN_DATA_AT_EXEC(fdlen); */
1496                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(dir), 0, (void *)dir, 0, NULL);
1497                 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
1498                 SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, fdlen, 0, (void *)fdm, fdlen, &len);
1499                 SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(context), 0, (void *)context, 0, NULL);
1500                 SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(macrocontext), 0, (void *)macrocontext, 0, NULL);
1501                 SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(callerid), 0, (void *)callerid, 0, NULL);
1502                 SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(origtime), 0, (void *)origtime, 0, NULL);
1503                 SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(duration), 0, (void *)duration, 0, NULL);
1504                 SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(mailboxuser), 0, (void *)mailboxuser, 0, NULL);
1505                 SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(mailboxcontext), 0, (void *)mailboxcontext, 0, NULL);
1506                 if (!ast_strlen_zero(category))
1507                         SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(category), 0, (void *)category, 0, NULL);
1508                 res = ast_odbc_smart_execute(obj, stmt);
1509                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1510                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
1511                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1512                         ast_odbc_release_obj(obj);
1513                         goto yuck;
1514                 }
1515                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1516                 ast_odbc_release_obj(obj);
1517         } else
1518                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1519 yuck:   
1520         if (cfg)
1521                 ast_config_destroy(cfg);
1522         if (fdm != MAP_FAILED)
1523                 munmap(fdm, fdlen);
1524         if (fd > -1)
1525                 close(fd);
1526         return x;
1527 }
1528
1529 static void rename_file(char *sdir, int smsg, char *mailboxuser, char *mailboxcontext, char *ddir, int dmsg)
1530 {
1531         int res;
1532         SQLHSTMT stmt;
1533         char sql[PATH_MAX];
1534         char msgnums[20];
1535         char msgnumd[20];
1536         struct odbc_obj *obj;
1537
1538         delete_file(ddir, dmsg);
1539         obj = ast_odbc_request_obj(odbc_database, 0);
1540         if (obj) {
1541                 snprintf(msgnums, sizeof(msgnums), "%d", smsg);
1542                 snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
1543                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
1544                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1545                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
1546                         ast_odbc_release_obj(obj);
1547                         goto yuck;
1548                 }
1549                 snprintf(sql, sizeof(sql), "UPDATE %s SET dir=?, msgnum=?, mailboxuser=?, mailboxcontext=? WHERE dir=? AND msgnum=?",odbc_table);
1550                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
1551                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1552                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
1553                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1554                         ast_odbc_release_obj(obj);
1555                         goto yuck;
1556                 }
1557                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(ddir), 0, (void *)ddir, 0, NULL);
1558                 SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnumd), 0, (void *)msgnumd, 0, NULL);
1559                 SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(mailboxuser), 0, (void *)mailboxuser, 0, NULL);
1560                 SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(mailboxcontext), 0, (void *)mailboxcontext, 0, NULL);
1561                 SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(sdir), 0, (void *)sdir, 0, NULL);
1562                 SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(msgnums), 0, (void *)msgnums, 0, NULL);
1563                 res = ast_odbc_smart_execute(obj, stmt);
1564                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
1565                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
1566                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1567                         ast_odbc_release_obj(obj);
1568                         goto yuck;
1569                 }
1570                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
1571                 ast_odbc_release_obj(obj);
1572         } else
1573                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
1574 yuck:
1575         return; 
1576 }
1577
1578 #else
1579 #ifndef IMAP_STORAGE
1580 static int count_messages(struct ast_vm_user *vmu, char *dir)
1581 {
1582         /* Find all .txt files - even if they are not in sequence from 0000 */
1583
1584         int vmcount = 0;
1585         DIR *vmdir = NULL;
1586         struct dirent *vment = NULL;
1587
1588         if (vm_lock_path(dir))
1589                 return ERROR_LOCK_PATH;
1590
1591         if ((vmdir = opendir(dir))) {
1592                 while ((vment = readdir(vmdir))) {
1593                         if (strlen(vment->d_name) > 7 && !strncmp(vment->d_name + 7, ".txt", 4)) 
1594                                 vmcount++;
1595                 }
1596                 closedir(vmdir);
1597         }
1598         ast_unlock_path(dir);
1599         
1600         return vmcount;
1601 }
1602
1603 static void rename_file(char *sfn, char *dfn)
1604 {
1605         char stxt[PATH_MAX];
1606         char dtxt[PATH_MAX];
1607         ast_filerename(sfn,dfn,NULL);
1608         snprintf(stxt, sizeof(stxt), "%s.txt", sfn);
1609         snprintf(dtxt, sizeof(dtxt), "%s.txt", dfn);
1610         if (ast_check_realtime("voicemail_data")) {
1611                 ast_update_realtime("voicemail_data", "filename", sfn, "filename", dfn, NULL);
1612         }
1613         rename(stxt, dtxt);
1614 }
1615
1616 static int copy(char *infile, char *outfile)
1617 {
1618         int ifd;
1619         int ofd;
1620         int res;
1621         int len;
1622         char buf[4096];
1623
1624 #ifdef HARDLINK_WHEN_POSSIBLE
1625         /* Hard link if possible; saves disk space & is faster */
1626         if (link(infile, outfile)) {
1627 #endif
1628                 if ((ifd = open(infile, O_RDONLY)) < 0) {
1629                         ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
1630                         return -1;
1631                 }
1632                 if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, VOICEMAIL_FILE_MODE)) < 0) {
1633                         ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
1634                         close(ifd);
1635                         return -1;
1636                 }
1637                 do {
1638                         len = read(ifd, buf, sizeof(buf));
1639                         if (len < 0) {
1640                                 ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
1641                                 close(ifd);
1642                                 close(ofd);
1643                                 unlink(outfile);
1644                         }
1645                         if (len) {
1646                                 res = write(ofd, buf, len);
1647                                 if (errno == ENOMEM || errno == ENOSPC || res != len) {
1648                                         ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
1649                                         close(ifd);
1650                                         close(ofd);
1651                                         unlink(outfile);
1652                                 }
1653                         }
1654                 } while (len);
1655                 close(ifd);
1656                 close(ofd);
1657                 return 0;
1658 #ifdef HARDLINK_WHEN_POSSIBLE
1659         } else {
1660                 /* Hard link succeeded */
1661                 return 0;
1662         }
1663 #endif
1664 }
1665
1666 static void copy_file(char *frompath, char *topath)
1667 {
1668         char frompath2[PATH_MAX], topath2[PATH_MAX];
1669         struct ast_variable *tmp,*var = NULL;
1670         char *origmailbox = NULL, *context = NULL, *macrocontext = NULL, *exten = NULL, *priority = NULL, *callerchan = NULL, *callerid = NULL, *origdate = NULL, *origtime = NULL, *category = NULL, *duration = NULL;
1671         ast_filecopy(frompath, topath, NULL);
1672         snprintf(frompath2, sizeof(frompath2), "%s.txt", frompath);
1673         snprintf(topath2, sizeof(topath2), "%s.txt", topath);
1674         if (ast_check_realtime("voicemail_data")) {
1675                 var = ast_load_realtime("voicemail_data", "filename", frompath, NULL);
1676                 /* This cycle converts ast_variable linked list, to va_list list of arguments, may be there is a better way to do it? */
1677                 for (tmp = var; tmp; tmp = tmp->next) {
1678                         if (!strcasecmp(tmp->name, "origmailbox")) {
1679                                 origmailbox = tmp->value;
1680                         } else if (!strcasecmp(tmp->name, "context")) {
1681                                 context = tmp->value;
1682                         } else if (!strcasecmp(tmp->name, "macrocontext")) {
1683                                 macrocontext = tmp->value;
1684                         } else if (!strcasecmp(tmp->name, "exten")) {
1685                                 exten = tmp->value;
1686                         } else if (!strcasecmp(tmp->name, "priority")) {
1687                                 priority = tmp->value;
1688                         } else if (!strcasecmp(tmp->name, "callerchan")) {
1689                                 callerchan = tmp->value;
1690                         } else if (!strcasecmp(tmp->name, "callerid")) {
1691                                 callerid = tmp->value;
1692                         } else if (!strcasecmp(tmp->name, "origdate")) {
1693                                 origdate = tmp->value;
1694                         } else if (!strcasecmp(tmp->name, "origtime")) {
1695                                 origtime = tmp->value;
1696                         } else if (!strcasecmp(tmp->name, "category")) {
1697                                 category = tmp->value;
1698                         } else if (!strcasecmp(tmp->name, "duration")) {
1699                                 duration = tmp->value;
1700                         }
1701                 }
1702                 ast_store_realtime("voicemail_data", "filename", topath, "origmailbox", origmailbox, "context", context, "macrocontext", macrocontext, "exten", exten, "priority", priority, "callerchan", callerchan, "callerid", callerid, "origdate", origdate, "origtime", origtime, "category", category, "duration", duration, NULL);
1703         }
1704         copy(frompath2, topath2);
1705         ast_variables_destroy(var);
1706 }
1707 #endif
1708
1709 /*! \brief
1710  * A negative return value indicates an error.
1711  * \note Should always be called with a lock already set on dir.
1712  */
1713 static int last_message_index(struct ast_vm_user *vmu, char *dir)
1714 {
1715         int x;
1716         unsigned char map[MAXMSGLIMIT] = "";
1717         DIR *msgdir;
1718         struct dirent *msgdirent;
1719         int msgdirint;
1720
1721         /* Reading the entire directory into a file map scales better than
1722          * doing a stat repeatedly on a predicted sequence.  I suspect this
1723          * is partially due to stat(2) internally doing a readdir(2) itself to
1724          * find each file. */
1725         msgdir = opendir(dir);
1726         while ((msgdirent = readdir(msgdir))) {
1727                 if (sscanf(msgdirent->d_name, "msg%d", &msgdirint) == 1 && msgdirint < MAXMSGLIMIT)
1728                         map[msgdirint] = 1;
1729         }
1730         closedir(msgdir);
1731
1732         for (x = 0; x < vmu->maxmsg; x++) {
1733                 if (map[x] == 0)
1734                         break;
1735         }
1736
1737         return x - 1;
1738 }
1739
1740 #endif
1741
1742 static int vm_delete(char *file)
1743 {
1744         char *txt;
1745         int txtsize = 0;
1746
1747         txtsize = (strlen(file) + 5)*sizeof(char);
1748         txt = alloca(txtsize);
1749         /* Sprintf here would safe because we alloca'd exactly the right length,
1750          * but trying to eliminate all sprintf's anyhow
1751          */
1752         if (ast_check_realtime("voicemail_data")) {
1753                 ast_destroy_realtime("voicemail_data", "filename", file, NULL);
1754         }
1755         snprintf(txt, txtsize, "%s.txt", file);
1756         unlink(txt);
1757         return ast_filedelete(file, NULL);
1758 }
1759
1760 static int inbuf(struct baseio *bio, FILE *fi)
1761 {
1762         int l;
1763
1764         if (bio->ateof)
1765                 return 0;
1766
1767         if ((l = fread(bio->iobuf,1,BASEMAXINLINE,fi)) <= 0) {
1768                 if (ferror(fi))
1769                         return -1;
1770
1771                 bio->ateof = 1;
1772                 return 0;
1773         }
1774
1775         bio->iolen= l;
1776         bio->iocp= 0;
1777
1778         return 1;
1779 }
1780
1781 static int inchar(struct baseio *bio, FILE *fi)
1782 {
1783         if (bio->iocp>=bio->iolen) {
1784                 if (!inbuf(bio, fi))
1785                         return EOF;
1786         }
1787
1788         return bio->iobuf[bio->iocp++];
1789 }
1790
1791 static int ochar(struct baseio *bio, int c, FILE *so)
1792 {
1793         if (bio->linelength >= BASELINELEN) {
1794                 if (fputs(eol,so) == EOF)
1795                         return -1;
1796
1797                 bio->linelength= 0;
1798         }
1799
1800         if (putc(((unsigned char)c),so) == EOF)
1801                 return -1;
1802
1803         bio->linelength++;
1804
1805         return 1;
1806 }
1807
1808 static int base_encode(char *filename, FILE *so)
1809 {
1810         unsigned char dtable[BASEMAXINLINE];
1811         int i,hiteof= 0;
1812         FILE *fi;
1813         struct baseio bio;
1814
1815         memset(&bio, 0, sizeof(bio));
1816         bio.iocp = BASEMAXINLINE;
1817
1818         if (!(fi = fopen(filename, "rb"))) {
1819                 ast_log(LOG_WARNING, "Failed to open log file: %s: %s\n", filename, strerror(errno));
1820                 return -1;
1821         }
1822
1823         for (i= 0; i<9; i++) {
1824                 dtable[i]= 'A'+i;
1825                 dtable[i+9]= 'J'+i;
1826                 dtable[26+i]= 'a'+i;
1827                 dtable[26+i+9]= 'j'+i;
1828         }
1829         for (i= 0; i<8; i++) {
1830                 dtable[i+18]= 'S'+i;
1831                 dtable[26+i+18]= 's'+i;
1832         }
1833         for (i= 0; i<10; i++) {
1834                 dtable[52+i]= '0'+i;
1835         }
1836         dtable[62]= '+';
1837         dtable[63]= '/';
1838
1839         while (!hiteof){
1840                 unsigned char igroup[3], ogroup[4];
1841                 int c,n;
1842
1843                 igroup[0]= igroup[1]= igroup[2]= 0;
1844
1845                 for (n= 0;n<3;n++) {
1846                         if ((c = inchar(&bio, fi)) == EOF) {
1847                                 hiteof= 1;
1848                                 break;
1849                         }
1850
1851                         igroup[n]= (unsigned char)c;
1852                 }
1853
1854                 if (n> 0) {
1855                         ogroup[0]= dtable[igroup[0]>>2];
1856                         ogroup[1]= dtable[((igroup[0]&3)<<4) | (igroup[1]>>4)];
1857                         ogroup[2]= dtable[((igroup[1]&0xF)<<2) | (igroup[2]>>6)];
1858                         ogroup[3]= dtable[igroup[2]&0x3F];
1859
1860                         if (n<3) {
1861                                 ogroup[3]= '=';
1862
1863                                 if (n<2)
1864                                         ogroup[2]= '=';
1865                         }
1866
1867                         for (i= 0;i<4;i++)
1868                                 ochar(&bio, ogroup[i], so);
1869                 }
1870         }
1871
1872         if (fputs(eol,so) == EOF)
1873                 return 0;
1874
1875         fclose(fi);
1876
1877         return 1;
1878 }
1879
1880 static void prep_email_sub_vars(struct ast_channel *ast, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, char *dur, char *date, char *passdata, size_t passdatasize, const char *category)
1881 {
1882         char callerid[256];
1883         /* Prepare variables for substitution in email body and subject */
1884         pbx_builtin_setvar_helper(ast, "VM_NAME", vmu->fullname);
1885         pbx_builtin_setvar_helper(ast, "VM_DUR", dur);
1886         snprintf(passdata, passdatasize, "%d", msgnum);
1887         pbx_builtin_setvar_helper(ast, "VM_MSGNUM", passdata);
1888         pbx_builtin_setvar_helper(ast, "VM_CONTEXT", context);
1889         pbx_builtin_setvar_helper(ast, "VM_MAILBOX", mailbox);
1890         pbx_builtin_setvar_helper(ast, "VM_CALLERID", ast_callerid_merge(callerid, sizeof(callerid), cidname, cidnum, "Unknown Caller"));
1891         pbx_builtin_setvar_helper(ast, "VM_CIDNAME", (cidname ? cidname : "an unknown caller"));
1892         pbx_builtin_setvar_helper(ast, "VM_CIDNUM", (cidnum ? cidnum : "an unknown caller"));
1893         pbx_builtin_setvar_helper(ast, "VM_DATE", date);
1894         pbx_builtin_setvar_helper(ast, "VM_CATEGORY", category ? ast_strdupa(category) : "no category");
1895 }
1896
1897 static char *quote(const char *from, char *to, size_t len)
1898 {
1899         char *ptr = to;
1900         *ptr++ = '"';
1901         for (; ptr < to + len - 1; from++) {
1902                 if (*from == '"')
1903                         *ptr++ = '\\';
1904                 else if (*from == '\0')
1905                         break;
1906                 *ptr++ = *from;
1907         }
1908         if (ptr < to + len - 1)
1909                 *ptr++ = '"';
1910         *ptr = '\0';
1911         return to;
1912 }
1913
1914 /*! \brief
1915  * fill in *tm for current time according to the proper timezone, if any.
1916  * Return tm so it can be used as a function argument.
1917  */
1918 static const struct tm *vmu_tm(const struct ast_vm_user *vmu, struct tm *tm)
1919 {
1920         const struct vm_zone *z = NULL;
1921         time_t t = time(NULL);
1922
1923         /* Does this user have a timezone specified? */
1924         if (!ast_strlen_zero(vmu->zonetag)) {
1925                 /* Find the zone in the list */
1926                 AST_LIST_LOCK(&zones);
1927                 AST_LIST_TRAVERSE(&zones, z, list) {
1928                         if (!strcmp(z->name, vmu->zonetag))
1929                                 break;
1930                 }
1931                 AST_LIST_UNLOCK(&zones);
1932         }
1933         ast_localtime(&t, tm, z ? z->timezone : NULL);
1934         return tm;
1935 }
1936
1937 /*! \brief same as mkstemp, but return a FILE * */
1938 static FILE *vm_mkftemp(char *template)
1939 {
1940         FILE *p = NULL;
1941         int pfd = mkstemp(template);
1942         if (pfd > -1) {
1943                 p = fdopen(pfd, "w+");
1944                 if (!p) {
1945                         close(pfd);
1946                         pfd = -1;
1947                 }
1948         }
1949         return p;
1950 }
1951
1952 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 *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category, int imap)
1953 {
1954         char date[256];
1955         char host[MAXHOSTNAMELEN] = "";
1956         char who[256];
1957         char bound[256];
1958         char fname[256];
1959         char dur[256];
1960         char tmpcmd[256];
1961         struct tm tm;
1962         char *passdata2;
1963         size_t len_passdata;
1964 #ifdef IMAP_STORAGE
1965 #define ENDL "\r\n"
1966 #else
1967 #define ENDL "\n"
1968 #endif
1969
1970         gethostname(host, sizeof(host)-1);
1971         if (strchr(srcemail, '@'))
1972                 ast_copy_string(who, srcemail, sizeof(who));
1973         else 
1974                 snprintf(who, sizeof(who), "%s@%s", srcemail, host);
1975         snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
1976         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm));
1977         fprintf(p, "Date: %s" ENDL, date);
1978
1979         /* Set date format for voicemail mail */
1980         strftime(date, sizeof(date), emaildateformat, &tm);
1981
1982         if (!ast_strlen_zero(fromstring)) {
1983                 struct ast_channel *ast;
1984                 if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, 0))) {
1985                         char *passdata;
1986                         int vmlen = strlen(fromstring)*3 + 200;
1987                         if ((passdata = alloca(vmlen))) {
1988                                 memset(passdata, 0, vmlen);
1989                                 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
1990                                 pbx_substitute_variables_helper(ast, fromstring, passdata, vmlen);
1991                                 len_passdata = strlen(passdata) * 2 + 3;
1992                                 passdata2 = alloca(len_passdata);
1993                                 fprintf(p, "From: %s <%s>" ENDL, quote(passdata, passdata2, len_passdata), who);
1994                         } else
1995                                 ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
1996                         ast_channel_free(ast);
1997                 } else
1998                         ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
1999         } else
2000                 fprintf(p, "From: Asterisk PBX <%s>" ENDL, who);
2001         len_passdata = strlen(vmu->fullname) * 2 + 3;
2002         passdata2 = alloca(len_passdata);
2003         fprintf(p, "To: %s <%s>" ENDL, quote(vmu->fullname, passdata2, len_passdata), vmu->email);
2004         if (!ast_strlen_zero(emailsubject)) {
2005                 struct ast_channel *ast;
2006                 if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, 0))) {
2007                         char *passdata;
2008                         int vmlen = strlen(emailsubject) * 3 + 200;
2009                         if ((passdata = alloca(vmlen))) {
2010                                 memset(passdata, 0, vmlen);
2011                                 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
2012                                 pbx_substitute_variables_helper(ast, emailsubject, passdata, vmlen);
2013                                 fprintf(p, "Subject: %s" ENDL, passdata);
2014                         } else
2015                                 ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
2016                         ast_channel_free(ast);
2017                 } else
2018                         ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
2019         } else  if (!ast_strlen_zero(emailtitle)) {
2020                 fprintf(p, emailtitle, msgnum + 1, mailbox) ;
2021                 fprintf(p, ENDL) ;
2022         } else if (ast_test_flag((&globalflags), VM_PBXSKIP))
2023                 fprintf(p, "Subject: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
2024         else
2025                 fprintf(p, "Subject: [PBX]: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
2026         fprintf(p, "Message-ID: <Asterisk-%d-%d-%s-%d@%s>" ENDL, msgnum + 1, (unsigned int)ast_random(), mailbox, getpid(), host);
2027         if(imap) {
2028                 /* additional information needed for IMAP searching */
2029                 fprintf(p, "X-Asterisk-VM-Message-Num: %d" ENDL, msgnum + 1);
2030                 /* fprintf(p, "X-Asterisk-VM-Orig-Mailbox: %s" ENDL, ext); */
2031                 fprintf(p, "X-Asterisk-VM-Server-Name: %s" ENDL, fromstring);
2032                 fprintf(p, "X-Asterisk-VM-Context: %s" ENDL, context);
2033                 fprintf(p, "X-Asterisk-VM-Extension: %s" ENDL, mailbox);
2034                 fprintf(p, "X-Asterisk-VM-Priority: %d" ENDL, chan->priority);
2035                 fprintf(p, "X-Asterisk-VM-Caller-channel: %s" ENDL, chan->name);
2036                 fprintf(p, "X-Asterisk-VM-Caller-ID-Num: %s" ENDL, cidnum);
2037                 fprintf(p, "X-Asterisk-VM-Caller-ID-Name: %s" ENDL, cidname);
2038                 fprintf(p, "X-Asterisk-VM-Duration: %d" ENDL, duration);
2039                 if (!ast_strlen_zero(category))
2040                         fprintf(p, "X-Asterisk-VM-Category: %s" ENDL, category);
2041                 fprintf(p, "X-Asterisk-VM-Orig-date: %s" ENDL, date);
2042                 fprintf(p, "X-Asterisk-VM-Orig-time: %ld" ENDL, (long)time(NULL));
2043         }
2044         if (!ast_strlen_zero(cidnum))
2045                 fprintf(p, "X-Asterisk-CallerID: %s" ENDL, cidnum);
2046         if (!ast_strlen_zero(cidname))
2047                 fprintf(p, "X-Asterisk-CallerIDName: %s" ENDL, cidname);
2048         fprintf(p, "MIME-Version: 1.0" ENDL);
2049         if (attach_user_voicemail) {
2050                 /* Something unique. */
2051                 snprintf(bound, sizeof(bound), "----voicemail_%d%s%d%d", msgnum + 1, mailbox, getpid(), (unsigned int)ast_random());
2052
2053                 fprintf(p, "Content-Type: multipart/mixed; boundary=\"%s\"" ENDL, bound);
2054                 fprintf(p, ENDL ENDL "This is a multi-part message in MIME format." ENDL ENDL);
2055                 fprintf(p, "--%s" ENDL, bound);
2056         }
2057         fprintf(p, "Content-Type: text/plain; charset=%s" ENDL "Content-Transfer-Encoding: 8bit" ENDL ENDL, charset);
2058         if (emailbody) {
2059                 struct ast_channel *ast;
2060                 if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, 0))) {
2061                         char *passdata;
2062                         int vmlen = strlen(emailbody)*3 + 200;
2063                         if ((passdata = alloca(vmlen))) {
2064                                 memset(passdata, 0, vmlen);
2065                                 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
2066                                 pbx_substitute_variables_helper(ast, emailbody, passdata, vmlen);
2067                                 fprintf(p, "%s" ENDL, passdata);
2068                         } else
2069                                 ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
2070                         ast_channel_free(ast);
2071                 } else
2072                         ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
2073         } else {
2074                 fprintf(p, "Dear %s:" ENDL ENDL "\tJust wanted to let you know you were just left a %s long message (number %d)" ENDL
2075
2076                 "in mailbox %s from %s, on %s so you might" ENDL
2077                 "want to check it when you get a chance.  Thanks!" ENDL ENDL "\t\t\t\t--Asterisk" ENDL ENDL, vmu->fullname, 
2078                 dur, msgnum + 1, mailbox, (cidname ? cidname : (cidnum ? cidnum : "an unknown caller")), date);
2079         }
2080         if (attach_user_voicemail) {
2081                 /* Eww. We want formats to tell us their own MIME type */
2082                 char *ctype = (!strcasecmp(format, "ogg")) ? "application/" : "audio/x-";
2083                 char tmpdir[256], newtmp[256];
2084                 int tmpfd = -1;
2085         
2086                 if (vmu->volgain < -.001 || vmu->volgain > .001) {
2087                         create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, vmu->mailbox, "tmp");
2088                         snprintf(newtmp, sizeof(newtmp), "%s/XXXXXX", tmpdir);
2089                         tmpfd = mkstemp(newtmp);
2090                         ast_debug(3, "newtmp: %s\n", newtmp);
2091                         if (tmpfd > -1) {
2092                                 snprintf(tmpcmd, sizeof(tmpcmd), "sox -v %.4f %s.%s %s.%s", vmu->volgain, attach, format, newtmp, format);
2093                                 ast_safe_system(tmpcmd);
2094                                 attach = newtmp;
2095                                 ast_debug(3, "VOLGAIN: Stored at: %s.%s - Level: %.4f - Mailbox: %s\n", attach, format, vmu->volgain, mailbox);
2096                         }
2097                 }
2098                 fprintf(p, "--%s" ENDL, bound);
2099                 fprintf(p, "Content-Type: %s%s; name=\"msg%04d.%s\"" ENDL, ctype, format, msgnum + 1, format);
2100                 fprintf(p, "Content-Transfer-Encoding: base64" ENDL);
2101                 fprintf(p, "Content-Description: Voicemail sound attachment." ENDL);
2102                 fprintf(p, "Content-Disposition: attachment; filename=\"msg%04d.%s\"" ENDL ENDL, msgnum + 1, format);
2103                 snprintf(fname, sizeof(fname), "%s.%s", attach, format);
2104                 base_encode(fname, p);
2105                 fprintf(p, ENDL "--%s--" ENDL "." ENDL, bound);
2106                 if (tmpfd > -1) {
2107                         unlink(fname);
2108                         close(tmpfd);
2109                         unlink(newtmp);
2110                 }
2111         }
2112 #undef ENDL
2113 }
2114
2115 static int sendmail(char *srcemail, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, char *attach, char *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category)
2116 {
2117         FILE *p=NULL;
2118         char tmp[80] = "/tmp/astmail-XXXXXX";
2119         char tmp2[256];
2120
2121         if (vmu && ast_strlen_zero(vmu->email)) {
2122                 ast_log(LOG_WARNING, "E-mail address missing for mailbox [%s].  E-mail will not be sent.\n", vmu->mailbox);
2123                 return(0);
2124         }
2125         if (!strcmp(format, "wav49"))
2126                 format = "WAV";
2127         ast_debug(3, "Attaching file '%s', format '%s', uservm is '%d', global is %d\n", attach, format, attach_user_voicemail, ast_test_flag((&globalflags), VM_ATTACH));
2128         /* Make a temporary file instead of piping directly to sendmail, in case the mail
2129            command hangs */
2130         if ((p = vm_mkftemp(tmp)) == NULL) {
2131                 ast_log(LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
2132                 return -1;
2133         } else {
2134                 make_email_file(p, srcemail, vmu, msgnum, context, mailbox, cidnum, cidname, attach, format, duration, attach_user_voicemail, chan, category, 0);
2135                 fclose(p);
2136                 snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
2137                 ast_safe_system(tmp2);
2138                 ast_debug(1, "Sent mail to %s with command '%s'\n", vmu->email, mailcmd);
2139         }
2140         return 0;
2141 }
2142
2143 static int sendpage(char *srcemail, char *pager, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, int duration, struct ast_vm_user *vmu, const char *category)
2144 {
2145         char date[256];
2146         char host[MAXHOSTNAMELEN] = "";
2147         char who[256];
2148         char dur[PATH_MAX];
2149         char tmp[80] = "/tmp/astmail-XXXXXX";
2150         char tmp2[PATH_MAX];
2151         struct tm tm;
2152         FILE *p;
2153
2154         if ((p = vm_mkftemp(tmp)) == NULL) {
2155                 ast_log(LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
2156                 return -1;
2157         }
2158         gethostname(host, sizeof(host)-1);
2159         if (strchr(srcemail, '@'))
2160                 ast_copy_string(who, srcemail, sizeof(who));
2161         else 
2162                 snprintf(who, sizeof(who), "%s@%s", srcemail, host);
2163         snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
2164         strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm));
2165         fprintf(p, "Date: %s\n", date);
2166
2167         if (*pagerfromstring) {
2168                 struct ast_channel *ast;
2169                 if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, 0))) {
2170                         char *passdata;
2171                         int vmlen = strlen(fromstring)*3 + 200;
2172                         if ((passdata = alloca(vmlen))) {
2173                                 memset(passdata, 0, vmlen);
2174                                 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
2175                                 pbx_substitute_variables_helper(ast, pagerfromstring, passdata, vmlen);
2176                                 fprintf(p, "From: %s <%s>\n", passdata, who);
2177                         } else 
2178                                 ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
2179                         ast_channel_free(ast);
2180                 } else 
2181                         ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
2182         } else
2183                 fprintf(p, "From: Asterisk PBX <%s>\n", who);
2184         fprintf(p, "To: %s\n", pager);
2185         if (pagersubject) {
2186                 struct ast_channel *ast;
2187                 if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, 0))) {
2188                         char *passdata;
2189                         int vmlen = strlen(pagersubject) * 3 + 200;
2190                         if ((passdata = alloca(vmlen))) {
2191                                 memset(passdata, 0, vmlen);
2192                                 prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
2193                                 pbx_substitute_variables_helper(ast, pagersubject, passdata, vmlen);
2194                                 fprintf(p, "Subject: %s\n\n", passdata);
2195                         } else
2196                                 ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
2197                         ast_channel_free(ast);
2198                 } else
2199                         ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
2200         } else
2201                 fprintf(p, "Subject: New VM\n\n");
2202
2203         strftime(date, sizeof(date), "%A, %B %d, %Y at %r", &tm);
2204         if (pagerbody) {
2205                 struct ast_channel *ast;
2206                 if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, 0))) {
2207                         char *passdata;
2208                         int vmlen = strlen(pagerbody) * 3 + 200;
2209                         passdata = alloca(vmlen);
2210                         memset(passdata, 0, vmlen);
2211                         prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
2212                         pbx_substitute_variables_helper(ast, pagerbody, passdata, vmlen);
2213                         fprintf(p, "%s\n", passdata);
2214                         ast_channel_free(ast);
2215                 } else
2216                         ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
2217         } else {
2218                 fprintf(p, "New %s long msg in box %s\n"
2219                                 "from %s, on %s", dur, mailbox, (cidname ? cidname : (cidnum ? cidnum : "unknown")), date);
2220         }
2221         fclose(p);
2222         snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
2223         ast_safe_system(tmp2);
2224         ast_debug(1, "Sent page to %s with command '%s'\n", pager, mailcmd);
2225         return 0;
2226 }
2227
2228 static int get_date(char *s, int len)
2229 {
2230         struct tm tm;
2231         time_t t;
2232         t = time(0);
2233         ast_localtime(&t, &tm, NULL);
2234         return strftime(s, len, "%a %b %e %r %Z %Y", &tm);
2235 }
2236
2237 static int invent_message(struct ast_channel *chan, char *context, char *ext, int busy, char *ecodes)
2238 {
2239         int res;
2240         char fn[PATH_MAX];
2241         char dest[PATH_MAX];
2242
2243         snprintf(fn, sizeof(fn), "%s%s/%s/greet", VM_SPOOL_DIR, context, ext);
2244
2245         if ((res = create_dirpath(dest, sizeof(dest), context, ext, "greet"))) {
2246                 ast_log(LOG_WARNING, "Failed to make directory(%s)\n", fn);
2247                 return -1;
2248         }
2249
2250         RETRIEVE(fn, -1);
2251         if (ast_fileexists(fn, NULL, NULL) > 0) {
2252                 res = ast_stream_and_wait(chan, fn, ecodes);
2253                 if (res) {
2254                         DISPOSE(fn, -1);
2255                         return res;
2256                 }
2257         } else {
2258                 /* Dispose just in case */
2259                 DISPOSE(fn, -1);
2260                 res = ast_stream_and_wait(chan, "vm-theperson", ecodes);
2261                 if (res)
2262                         return res;
2263                 res = ast_say_digit_str(chan, ext, ecodes, chan->language);
2264                 if (res)
2265                         return res;
2266         }
2267         res = ast_stream_and_wait(chan, busy ? "vm-isonphone" : "vm-isunavail", ecodes);
2268         return res;
2269 }
2270
2271 static void free_user(struct ast_vm_user *vmu)
2272 {
2273         if (!ast_test_flag(vmu, VM_ALLOCED))
2274                 return;
2275
2276         ast_free(vmu);
2277 }
2278
2279 static void free_zone(struct vm_zone *z)
2280 {
2281         ast_free(z);
2282 }
2283
2284 static const char *mbox(int id)
2285 {
2286         static const char *msgs[] = {
2287                 "INBOX",
2288                 "Old",
2289                 "Work",
2290                 "Family",
2291                 "Friends",
2292                 "Cust1",
2293                 "Cust2",
2294                 "Cust3",
2295                 "Cust4",
2296                 "Cust5",
2297         };
2298         return (id >= 0 && id < (sizeof(msgs)/sizeof(msgs[0]))) ? msgs[id] : "Unknown";
2299 }
2300
2301 #ifdef ODBC_STORAGE
2302 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
2303 {
2304         int x = -1;
2305         int res;
2306         SQLHSTMT stmt;
2307         char sql[PATH_MAX];
2308         char rowdata[20];
2309         char tmp[PATH_MAX] = "";
2310         struct odbc_obj *obj;
2311         char *context;
2312
2313         if (newmsgs)
2314                 *newmsgs = 0;
2315         if (oldmsgs)
2316                 *oldmsgs = 0;
2317
2318         /* If no mailbox, return immediately */
2319         if (ast_strlen_zero(mailbox))
2320                 return 0;
2321
2322         ast_copy_string(tmp, mailbox, sizeof(tmp));
2323         
2324         context = strchr(tmp, '@');
2325         if (context) {
2326                 *context = '\0';
2327                 context++;
2328         } else
2329                 context = "default";
2330         
2331         obj = ast_odbc_request_obj(odbc_database, 0);
2332         if (obj) {
2333                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
2334                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2335                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
2336                         ast_odbc_release_obj(obj);
2337                         goto yuck;
2338                 }
2339                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "INBOX");
2340                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
2341                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2342                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
2343                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2344                         ast_odbc_release_obj(obj);
2345                         goto yuck;
2346                 }
2347                 res = ast_odbc_smart_execute(obj, stmt);
2348                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2349                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
2350                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2351                         ast_odbc_release_obj(obj);
2352                         goto yuck;
2353                 }
2354                 res = SQLFetch(stmt);
2355                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2356                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
2357                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2358                         ast_odbc_release_obj(obj);
2359                         goto yuck;
2360                 }
2361                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
2362                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2363                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
2364                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2365                         ast_odbc_release_obj(obj);
2366                         goto yuck;
2367                 }
2368                 *newmsgs = atoi(rowdata);
2369                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2370
2371                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
2372                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2373                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
2374                         ast_odbc_release_obj(obj);
2375                         goto yuck;
2376                 }
2377                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "Old");
2378                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
2379                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2380                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
2381                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2382                         ast_odbc_release_obj(obj);
2383                         goto yuck;
2384                 }
2385                 res = ast_odbc_smart_execute(obj, stmt);
2386                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2387                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
2388                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2389                         ast_odbc_release_obj(obj);
2390                         goto yuck;
2391                 }
2392                 res = SQLFetch(stmt);
2393                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2394                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
2395                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2396                         ast_odbc_release_obj(obj);
2397                         goto yuck;
2398                 }
2399                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
2400                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2401                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
2402                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2403                         ast_odbc_release_obj(obj);
2404                         goto yuck;
2405                 }
2406                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2407                 ast_odbc_release_obj(obj);
2408                 *oldmsgs = atoi(rowdata);
2409                 x = 0;
2410         } else
2411                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
2412                 
2413 yuck:   
2414         return x;
2415 }
2416
2417 static int messagecount(const char *context, const char *mailbox, const char *folder)
2418 {
2419         struct odbc_obj *obj = NULL;
2420         int nummsgs = 0;
2421         int res;
2422         SQLHSTMT stmt = NULL;
2423         char sql[PATH_MAX];
2424         char rowdata[20];
2425         if (!folder)
2426                 folder = "INBOX";
2427         /* If no mailbox, return immediately */
2428         if (ast_strlen_zero(mailbox))
2429                 return 0;
2430
2431         obj = ast_odbc_request_obj(odbc_database, 0);
2432         if (obj) {
2433                 res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
2434                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2435                         ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
2436                         goto yuck;
2437                 }
2438                 snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
2439                 res = SQLPrepare(stmt, (unsigned char *)sql, SQL_NTS);
2440                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2441                         ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", sql);
2442                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
2443                         goto yuck;
2444                 }
2445                 res = ast_odbc_smart_execute(obj, stmt);
2446                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2447                         ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
2448                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2449                         goto yuck;
2450                 }
2451                 res = SQLFetch(stmt);
2452                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2453                         ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
2454                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2455                         goto yuck;
2456                 }
2457                 res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
2458                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
2459                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
2460                         SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2461                         goto yuck;
2462                 }
2463                 nummsgs = atoi(rowdata);
2464                 SQLFreeHandle (SQL_HANDLE_STMT, stmt);
2465         } else
2466                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
2467
2468 yuck:
2469         if (obj)
2470                 ast_odbc_release_obj(obj);
2471         return nummsgs;
2472 }
2473
2474 static int has_voicemail(const char *mailbox, const char *folder)
2475 {
2476         char *context, tmp[256];
2477         ast_copy_string(tmp, mailbox, sizeof(tmp));
2478         if ((context = strchr(tmp, '@')))
2479                 *context++ = '\0';
2480         else
2481                 context = "default";
2482
2483         if (messagecount(context, tmp, folder))
2484                 return 1;
2485         else
2486                 return 0;
2487 }
2488
2489 #elif defined(IMAP_STORAGE)
2490
2491 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)
2492 {
2493         char *myserveremail = serveremail;
2494         char fn[PATH_MAX];
2495         char mailbox[256];
2496         char *stringp;
2497         FILE *p=NULL;
2498         char tmp[80] = "/tmp/astmail-XXXXXX";
2499         long len;
2500         void *buf;
2501         STRING str;
2502         
2503         /* Attach only the first format */
2504         fmt = ast_strdupa(fmt);
2505         stringp = fmt;
2506         strsep(&stringp, "|");
2507
2508         if (!ast_strlen_zero(vmu->serveremail))
2509                 myserveremail = vmu->serveremail;
2510
2511         make_file(fn, sizeof(fn), dir, msgnum);
2512
2513         if (ast_strlen_zero(vmu->email))
2514                 ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
2515
2516         if (!strcmp(fmt, "wav49"))
2517                 fmt = "WAV";
2518         ast_debug(3, "Storing file '%s', format '%s'\n", fn, fmt);
2519
2520         /* Make a temporary file instead of piping directly to sendmail, in case the mail
2521            command hangs */
2522         if (!(p = vm_mkftemp(tmp))) {
2523                 ast_log(LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
2524                 return -1;
2525         }
2526         
2527         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, fmt, duration, 1, chan, NULL, 1);
2528         /* read mail file to memory */          
2529         len = ftell(p);
2530         rewind(p);
2531         if (!(buf = ast_malloc(len+1))) {
2532                 ast_log(LOG_ERROR, "Can't allocate %ld bytes to read message\n", len+1);
2533                 return -1;
2534         }
2535         fread(buf, len, 1, p);
2536         ((char *)buf)[len] = '\0';
2537         INIT(&str, mail_string, buf, len);
2538         init_mailstream(vms, 0);
2539         imap_mailbox_name(mailbox, vms, 0, 1);
2540         if(!mail_append(vms->mailstream, mailbox, &str))
2541                 ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
2542         fclose(p);
2543         unlink(tmp);
2544         ast_free(buf);
2545         ast_debug(3, "%s stored\n", fn);
2546         return 0;
2547
2548 }
2549
2550 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
2551 {
2552         SEARCHPGM *pgm;
2553         SEARCHHEADER *hdr;
2554  
2555         struct ast_vm_user *vmu;
2556         struct vm_state *vms_p;
2557         char tmp[256] = "";
2558         char *mb, *cur;
2559         char *mailboxnc; 
2560         char *context;
2561         int ret = 0;
2562
2563         if (newmsgs)
2564                 *newmsgs = 0;
2565
2566         if (oldmsgs)
2567                 *oldmsgs = 0;
2568  
2569          ast_debug(3,"Mailbox is set to %s\n",mailbox);
2570
2571         /* If no mailbox, return immediately */
2572         if (ast_strlen_zero(mailbox))
2573                 return 0;
2574
2575         if (strchr(mailbox, ',')) {
2576                 int tmpnew, tmpold;
2577                 ast_copy_string(tmp, mailbox, sizeof(tmp));
2578                 mb = tmp;
2579                 ret = 0;
2580                 while((cur = strsep(&mb, ", "))) {
2581                         if (!ast_strlen_zero(cur)) {
2582                                 if (inboxcount(cur, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2583                                         return -1;
2584                                 else {
2585                                         if (newmsgs)
2586                                                 *newmsgs += tmpnew; 
2587                                         if (oldmsgs)
2588                                                 *oldmsgs += tmpold;
2589                                 }
2590                         }
2591                 }
2592                 return 0;
2593         }
2594
2595         ast_copy_string(tmp, mailbox, sizeof(tmp));
2596
2597         if ((context = strchr(tmp, '@'))) {
2598                 *context = '\0';
2599                 mailboxnc = tmp;
2600                 context++;
2601         } else {
2602                 context = "default";
2603                 mailboxnc = (char *)mailbox;
2604         }
2605  
2606         /* We have to get the user before we can open the stream! */
2607         /*ast_debug(1,"Before find_user, context is %s and mailbox is %s\n",context,mailbox); */
2608         if (!(vmu = find_user(NULL, context, mailboxnc))) {
2609                 ast_log(LOG_ERROR, "Couldn't find mailbox %s in context %s\n", mailboxnc, context);
2610                 return -1;
2611         }
2612         
2613         /* No IMAP account available */
2614         if (vmu->imapuser[0] == '\0') {
2615                 ast_log (LOG_WARNING,"IMAP user not set for mailbox %s\n",vmu->mailbox);
2616                 free_user(vmu);
2617                 return -1;
2618         }
2619  
2620         /* check if someone is accessing this box right now... */
2621         if ((vms_p = get_vm_state_by_imapuser(vmu->imapuser, 1)) || (vms_p = get_vm_state_by_mailbox(mailboxnc, 1))) {
2622                 ast_debug(3,"Returning before search - user is logged in\n");
2623                 *newmsgs = vms_p->newmessages;
2624                 *oldmsgs = vms_p->oldmessages;
2625                 free_user(vmu);
2626                 return 0;
2627         }
2628  
2629         /* add one if not there... */
2630         if (!(vms_p = get_vm_state_by_imapuser(vmu->imapuser, 0)) && !(vms_p = get_vm_state_by_mailbox(mailboxnc, 0))) {
2631                 ast_debug(3,"Adding new vmstate for %s\n",vmu->imapuser);
2632                 if (!(vms_p = ast_calloc(1, sizeof(*vms_p)))) {
2633                         free_user(vmu);
2634                         return -1;
2635                 }
2636                 ast_copy_string(vms_p->imapuser,vmu->imapuser, sizeof(vms_p->imapuser));
2637                 ast_copy_string(vms_p->username, mailboxnc, sizeof(vms_p->username)); /* save for access from interactive entry point */
2638                 vms_p->mailstream = NIL; /* save for access from interactive entry point */
2639                 ast_debug(3,"Copied %s to %s\n",vmu->imapuser,vms_p->imapuser);
2640                 vms_p->updated = 1;
2641                 /* set mailbox to INBOX! */
2642                 ast_copy_string(vms_p->curbox, mbox(0), sizeof(vms_p->curbox));
2643                 init_vm_state(vms_p);
2644                 vmstate_insert(vms_p);
2645         }
2646
2647         /* If no mailstream exists yet and even after attempting to initialize it fails, bail out */
2648         ret = init_mailstream(vms_p, 0);
2649         if (!vms_p->mailstream) {
2650                 ast_log (LOG_ERROR,"Houston we have a problem - IMAP mailstream is NULL\n");
2651                 free_user(vmu);
2652                 return -1;
2653         }
2654
2655         if (!ret && vms_p->updated == 1) {
2656                 if (newmsgs) {
2657                         pgm = mail_newsearchpgm();
2658                         hdr = mail_newsearchheader("X-Asterisk-VM-Extension", (char *)mailboxnc);
2659                         pgm->header = hdr;
2660                         pgm->unseen = 1;
2661                         pgm->seen = 0;
2662                         pgm->undeleted = 1;
2663                         pgm->deleted = 0;
2664                         vms_p->vmArrayIndex = 0;
2665                         mail_search_full(vms_p->mailstream, NULL, pgm, NIL);
2666                         *newmsgs = vms_p->vmArrayIndex;
2667                         vms_p->newmessages = vms_p->vmArrayIndex;
2668                         mail_free_searchpgm(&pgm);
2669                 }
2670                 if (oldmsgs) {
2671                         pgm = mail_newsearchpgm ();
2672                         hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)mailboxnc);
2673                         pgm->header = hdr;
2674                         pgm->unseen = 0;
2675                         pgm->seen = 1;
2676                         pgm->undeleted = 1;
2677                         pgm->deleted = 0;
2678                         vms_p->vmArrayIndex = 0;
2679                         mail_search_full(vms_p->mailstream, NULL, pgm, NIL);
2680                         *oldmsgs = vms_p->vmArrayIndex;
2681                         vms_p->oldmessages = vms_p->vmArrayIndex;
2682                         mail_free_searchpgm(&pgm);
2683                 }
2684         }
2685
2686         if (vms_p->updated == 1) {  /* changes, so we did the searches above */
2687                 vms_p->updated = 0;
2688         } else if (vms_p->updated > 1) {  /* decrement delay count */
2689                 vms_p->updated--;
2690         } else {  /* no changes, so don't search */
2691                 mail_ping(vms_p->mailstream);
2692                 /* Keep the old data */
2693                 *newmsgs = vms_p->newmessages;
2694                 *oldmsgs = vms_p->oldmessages;
2695         }
2696
2697         free_user(vmu);
2698         return 0;
2699  }
2700
2701 static int has_voicemail(const char *mailbox, const char *folder)
2702 {
2703         int newmsgs, oldmsgs;
2704         
2705         if(inboxcount(mailbox, &newmsgs, &oldmsgs))
2706                 return folder? oldmsgs: newmsgs;
2707         else
2708                 return 0;
2709 }
2710
2711 static int messagecount(const char *context, const char *mailbox, const char *folder)
2712 {
2713         int newmsgs, oldmsgs;
2714         char tmp[256] = "";
2715         
2716         if (ast_strlen_zero(mailbox))
2717                 return 0;
2718         sprintf(tmp,"%s@%s", mailbox, ast_strlen_zero(context)? "default": context);
2719
2720         if(inboxcount(tmp, &newmsgs, &oldmsgs))
2721                 return folder? oldmsgs: newmsgs;
2722         else
2723                 return 0;
2724 }
2725
2726 #endif
2727 #ifndef IMAP_STORAGE
2728 /* copy message only used by file storage */
2729 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)
2730 {
2731         char fromdir[PATH_MAX], todir[PATH_MAX], frompath[PATH_MAX], topath[PATH_MAX];
2732         const char *frombox = mbox(imbox);
2733         int recipmsgnum;
2734
2735         ast_log(LOG_NOTICE, "Copying message from %s@%s to %s@%s\n", vmu->mailbox, vmu->context, recip->mailbox, recip->context);
2736
2737         create_dirpath(todir, sizeof(todir), recip->context, recip->mailbox, "INBOX");
2738         
2739         if (!dir)
2740                 make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, frombox);
2741         else
2742                 ast_copy_string(fromdir, dir, sizeof(fromdir));
2743
2744         make_file(frompath, sizeof(frompath), fromdir, msgnum);
2745         make_dir(todir, sizeof(todir), recip->context, recip->mailbox, frombox);
2746
2747         if (vm_lock_path(todir))
2748                 return ERROR_LOCK_PATH;
2749
2750         recipmsgnum = last_message_index(recip, todir) + 1;
2751         if (recipmsgnum < recip->maxmsg) {
2752                 make_file(topath, sizeof(topath), todir, recipmsgnum);
2753                 COPY(fromdir, msgnum, todir, recipmsgnum, recip->mailbox, recip->context, frompath, topath);
2754         } else {
2755                 ast_log(LOG_ERROR, "Recipient mailbox %s@%s is full\n", recip->mailbox, recip->context);
2756         }
2757         ast_unlock_path(todir);
2758         notify_new_message(chan, recip, recipmsgnum, duration, fmt, S_OR(chan->cid.cid_num, NULL), S_OR(chan->cid.cid_name, NULL));
2759         
2760         return 0;
2761 }
2762 #endif
2763 #if !(defined(IMAP_STORAGE) || defined(ODBC_STORAGE))
2764 static int messagecount(const char *context, const char *mailbox, const char *folder)
2765 {
2766         return __has_voicemail(context, mailbox, folder, 0);
2767 }
2768
2769
2770 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit)
2771 {
2772         DIR *dir;
2773         struct dirent *de;
2774         char fn[256];
2775         int ret = 0;
2776
2777         /* If no mailbox, return immediately */
2778         if (ast_strlen_zero(mailbox))
2779                 return 0;
2780
2781         if (ast_strlen_zero(folder))
2782                 folder = "INBOX";
2783         if (ast_strlen_zero(context))
2784                 context = "default";
2785
2786         snprintf(fn, sizeof(fn), "%s%s/%s/%s", VM_SPOOL_DIR, context, mailbox, folder);
2787
2788         if (!(dir = opendir(fn)))
2789                 return 0;
2790
2791         while ((de = readdir(dir))) {
2792                 if (!strncasecmp(de->d_name, "msg", 3)) {
2793                         if (shortcircuit) {
2794                                 ret = 1;
2795                                 break;
2796                         } else if (!strncasecmp(de->d_name + 8, "txt", 3))
2797                                 ret++;
2798                 }
2799         }
2800
2801         closedir(dir);
2802
2803         return ret;
2804 }
2805
2806
2807 static int has_voicemail(const char *mailbox, const char *folder)
2808 {
2809         char tmp[256], *tmp2 = tmp, *mbox, *context;
2810         ast_copy_string(tmp, mailbox, sizeof(tmp));
2811         while ((mbox = strsep(&tmp2, ","))) {
2812                 if ((context = strchr(mbox, '@')))
2813                         *context++ = '\0';
2814                 else
2815                         context = "default";
2816                 if (__has_voicemail(context, mbox, folder, 1))
2817                         return 1;
2818         }
2819         return 0;
2820 }
2821
2822
2823 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
2824 {
2825         char tmp[256];
2826         char *context;
2827
2828         /* If no mailbox, return immediately */
2829         if (ast_strlen_zero(mailbox))
2830                 return 0;
2831
2832         if (newmsgs)
2833                 *newmsgs = 0;
2834         if (oldmsgs)
2835                 *oldmsgs = 0;
2836
2837         if (strchr(mailbox, ',')) {
2838                 int tmpnew, tmpold;
2839                 char *mb, *cur;
2840
2841                 ast_copy_string(tmp, mailbox, sizeof(tmp));
2842                 mb = tmp;
2843                 while ((cur = strsep(&mb, ", "))) {
2844                         if (!ast_strlen_zero(cur)) {
2845                                 if (inboxcount(cur, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
2846                                         return -1;
2847                                 else {
2848                                         if (newmsgs)
2849                                                 *newmsgs += tmpnew; 
2850                                         if (oldmsgs)
2851                                                 *oldmsgs += tmpold;
2852                                 }
2853                         }
2854                 }
2855                 return 0;
2856         }
2857
2858         ast_copy_string(tmp, mailbox, sizeof(tmp));
2859         
2860         if ((context = strchr(tmp, '@')))
2861                 *context++ = '\0';
2862         else
2863                 context = "default";
2864
2865         if (newmsgs)
2866                 *newmsgs = __has_voicemail(context, tmp, "INBOX", 0);
2867         if (oldmsgs)
2868                 *oldmsgs = __has_voicemail(context, tmp, "Old", 0);
2869
2870         return 0;
2871 }
2872
2873 #endif
2874
2875 static void run_externnotify(char *context, char *extension)
2876 {
2877         char arguments[255];
2878         char ext_context[256] = "";
2879         int newvoicemails = 0, oldvoicemails = 0;
2880         struct ast_smdi_mwi_message *mwi_msg;
2881
2882         if (!ast_strlen_zero(context))
2883                 snprintf(ext_context, sizeof(ext_context), "%s@%s", extension, context);
2884         else
2885                 ast_copy_string(ext_context, extension, sizeof(ext_context));
2886
2887         if (smdi_iface) {
2888                 if (ast_app_has_voicemail(ext_context, NULL)) 
2889                         ast_smdi_mwi_set(smdi_iface, extension);
2890                 else
2891                         ast_smdi_mwi_unset(smdi_iface, extension);
2892
2893                 if ((mwi_msg = ast_smdi_mwi_message_wait(smdi_iface, SMDI_MWI_WAIT_TIMEOUT))) {
2894                         ast_log(LOG_ERROR, "Error executing SMDI MWI change for %s on %s\n", extension, smdi_iface->name);
2895                         if (!strncmp(mwi_msg->cause, "INV", 3))
2896                                 ast_log(LOG_ERROR, "Invalid MWI extension: %s\n", mwi_msg->fwd_st);
2897                         else if (!strncmp(mwi_msg->cause, "BLK", 3))
2898                                 ast_log(LOG_WARNING, "MWI light was already on or off for %s\n", mwi_msg->fwd_st);
2899                         ast_log(LOG_WARNING, "The switch reported '%s'\n", mwi_msg->cause);
2900                         ASTOBJ_UNREF(mwi_msg, ast_smdi_mwi_message_destroy);
2901                 } else {
2902                         ast_debug(1, "Successfully executed SMDI MWI change for %s on %s\n", extension, smdi_iface->name);
2903                 }
2904         }
2905
2906         if (!ast_strlen_zero(externnotify)) {
2907                 if (inboxcount(ext_context, &newvoicemails, &oldvoicemails)) {
2908                         ast_log(LOG_ERROR, "Problem in calculating number of voicemail messages available for extension %s\n", extension);
2909                 } else {
2910                         snprintf(arguments, sizeof(arguments), "%s %s %s %d&", externnotify, context, extension, newvoicemails);
2911                         ast_debug(1, "Executing %s\n", arguments);
2912                         ast_safe_system(arguments);
2913                 }
2914         }
2915 }
2916
2917 struct leave_vm_options {
2918         unsigned int flags;
2919         signed char record_gain;
2920 };
2921
2922 static int leave_voicemail(struct ast_channel *chan, char *ext, struct leave_vm_options *options)
2923 {
2924 #ifdef IMAP_STORAGE
2925         int newmsgs, oldmsgs;
2926         struct vm_state *vms = NULL;
2927 #endif
2928         char txtfile[PATH_MAX], tmptxtfile[PATH_MAX];
2929         char callerid[256];
2930         FILE *txt;
2931         char date[256];
2932         int txtdes;
2933         int res = 0;
2934         int msgnum;
2935         int duration = 0;
2936         int ausemacro = 0;
2937         int ousemacro = 0;
2938         int ouseexten = 0;
2939         int rtmsgid = 0;
2940         char tmpid[16];
2941         char tmpdur[16];
2942         char priority[16];
2943         char origtime[16];
2944         char dir[PATH_MAX], tmpdir[PATH_MAX];
2945         char dest[PATH_MAX];
2946         char fn[PATH_MAX];
2947         char prefile[PATH_MAX] = "";
2948         char tempfile[PATH_MAX] = "";
2949         char ext_context[256] = "";
2950         char fmt[80];
2951         char *context;
2952         char ecodes[16] = "#";
2953         char tmp[1024] = "", *tmpptr;
2954         struct ast_vm_user *vmu;
2955         struct ast_vm_user svm;
2956         const char *category = NULL;
2957
2958         ast_copy_string(tmp, ext, sizeof(tmp));
2959         ext = tmp;
2960         if ((context = strchr(tmp, '@'))) {
2961                 *context++ = '\0';
2962                 tmpptr = strchr(context, '&');
2963         } else {
2964                 tmpptr = strchr(ext, '&');
2965         }
2966
2967         if (tmpptr)
2968                 *tmpptr++ = '\0';
2969
2970         category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY");
2971
2972         ast_debug(3, "Before find_user\n");
2973         if (!(vmu = find_user(&svm, context, ext))) {
2974                 ast_log(LOG_WARNING, "No entry in voicemail config file for '%s'\n", ext);
2975                 pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
2976                 return res;
2977         }
2978         /* Setup pre-file if appropriate */
2979         if (strcmp(vmu->context, "default"))
2980                 snprintf(ext_context, sizeof(ext_context), "%s@%s", ext, vmu->context);
2981         else
2982                 ast_copy_string(ext_context, vmu->context, sizeof(ext_context));
2983         if (ast_test_flag(options, OPT_BUSY_GREETING)) {
2984                 res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "busy");
2985                 snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, ext);
2986         } else if (ast_test_flag(options, OPT_UNAVAIL_GREETING)) {
2987                 res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "unavail");
2988                 snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, ext);
2989         }
2990         snprintf(tempfile, sizeof(tempfile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, ext);
2991         if ((res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "temp"))) {
2992                 ast_log(LOG_WARNING, "Failed to make directory (%s)\n", tempfile);
2993                 return -1;
2994         }
2995         RETRIEVE(tempfile, -1);
2996         if (ast_fileexists(tempfile, NULL, NULL) > 0)
2997                 ast_copy_string(prefile, tempfile, sizeof(prefile));
2998         DISPOSE(tempfile, -1);
2999         /* It's easier just to try to make it than to check for its existence */
3000         create_dirpath(dir, sizeof(dir), vmu->context, ext, "INBOX");
3001         create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, ext, "tmp");
3002
3003         /* Check current or macro-calling context for special extensions */
3004         if (ast_test_flag(vmu, VM_OPERATOR)) {
3005                 if (!ast_strlen_zero(vmu->exit)) {
3006                         if (ast_exists_extension(chan, vmu->exit, "o", 1, chan->cid.cid_num)) {
3007                                 strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
3008                                 ouseexten = 1;
3009                         }
3010                 } else if (ast_exists_extension(chan, chan->context, "o", 1, chan->cid.cid_num)) {
3011                         strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
3012                         ouseexten = 1;
3013                 }
3014                 else if (!ast_strlen_zero(chan->macrocontext) && ast_exists_extension(chan, chan->macrocontext, "o", 1, chan->cid.cid_num)) {
3015                 strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
3016                 ousemacro = 1;
3017                 }
3018         }
3019
3020         if (!ast_strlen_zero(vmu->exit)) {
3021                 if (ast_exists_extension(chan, vmu->exit, "a", 1, chan->cid.cid_num))
3022                         strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
3023         } else if (ast_exists_extension(chan, chan->context, "a", 1, chan->cid.cid_num))
3024                 strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
3025         else if (!ast_strlen_zero(chan->macrocontext) && ast_exists_extension(chan, chan->macrocontext, "a", 1, chan->cid.cid_num)) {
3026                 strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
3027                 ausemacro = 1;
3028         }
3029
3030         /* Play the beginning intro if desired */
3031         if (!ast_strlen_zero(prefile)) {
3032                 RETRIEVE(prefile, -1);
3033                 if (ast_fileexists(prefile, NULL, NULL) > 0) {
3034                         if (ast_streamfile(chan, prefile, chan->language) > -1) 
3035                                 res = ast_waitstream(chan, ecodes);
3036                 } else {
3037                         ast_debug(1, "%s doesn't exist, doing what we can\n", prefile);
3038                         res = invent_message(chan, vmu->context, ext, ast_test_flag(options, OPT_BUSY_GREETING), ecodes);
3039                 }
3040                 DISPOSE(prefile, -1);
3041                 if (res < 0) {
3042                         ast_debug(1, "Hang up during prefile playback\n");
3043                         free_user(vmu);
3044                         pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
3045                         return -1;
3046                 }
3047         }
3048         if (res == '#') {
3049                 /* On a '#' we skip the instructions */
3050                 ast_set_flag(options, OPT_SILENT);
3051                 res = 0;
3052         }
3053         if (!res && !ast_test_flag(options, OPT_SILENT)) {
3054                 res = ast_stream_and_wait(chan, INTRO, ecodes);
3055                 if (res == '#') {
3056                         ast_set_flag(options, OPT_SILENT);
3057                         res = 0;
3058                 }
3059         }