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