install_prereq: Download latest Jansson.
[asterisk/asterisk.git] / funcs / func_env.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*! \file
18  *
19  * \brief Environment related dialplan functions
20  *
21  * \ingroup functions
22  */
23
24 /*** MODULEINFO
25         <support_level>core</support_level>
26  ***/
27
28 #include "asterisk.h"
29
30 #include <sys/stat.h>   /* stat(2) */
31
32 #include "asterisk/module.h"
33 #include "asterisk/channel.h"
34 #include "asterisk/pbx.h"
35 #include "asterisk/utils.h"
36 #include "asterisk/app.h"
37 #include "asterisk/file.h"
38
39 /*** DOCUMENTATION
40         <function name="ENV" language="en_US">
41                 <synopsis>
42                         Gets or sets the environment variable specified.
43                 </synopsis>
44                 <syntax>
45                         <parameter name="varname" required="true">
46                                 <para>Environment variable name</para>
47                         </parameter>
48                 </syntax>
49                 <description>
50                         <para>Variables starting with <literal>AST_</literal> are reserved to the system and may not be set.</para>
51                 </description>
52         </function>
53         <function name="STAT" language="en_US">
54                 <synopsis>
55                         Does a check on the specified file.
56                 </synopsis>
57                 <syntax>
58                         <parameter name="flag" required="true">
59                                 <para>Flag may be one of the following:</para>
60                                 <para>d - Checks if the file is a directory.</para>
61                                 <para>e - Checks if the file exists.</para>
62                                 <para>f - Checks if the file is a regular file.</para>
63                                 <para>m - Returns the file mode (in octal)</para>
64                                 <para>s - Returns the size (in bytes) of the file</para>
65                                 <para>A - Returns the epoch at which the file was last accessed.</para>
66                                 <para>C - Returns the epoch at which the inode was last changed.</para>
67                                 <para>M - Returns the epoch at which the file was last modified.</para>
68                         </parameter>
69                         <parameter name="filename" required="true" />
70                 </syntax>
71                 <description>
72                         <note>
73                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
74                                 is set to <literal>no</literal>, this function can only be executed from the
75                                 dialplan, and not directly from external protocols.</para>
76                         </note>
77                 </description>
78         </function>
79         <function name="FILE" language="en_US">
80                 <synopsis>
81                         Read or write text file.
82                 </synopsis>
83                 <syntax>
84                         <parameter name="filename" required="true" />
85                         <parameter name="offset">
86                                 <para>Maybe specified as any number. If negative, <replaceable>offset</replaceable> specifies the number
87                                 of bytes back from the end of the file.</para>
88                         </parameter>
89                         <parameter name="length">
90                                 <para>If specified, will limit the length of the data read to that size. If negative,
91                                 trims <replaceable>length</replaceable> bytes from the end of the file.</para>
92                         </parameter>
93                         <parameter name="options">
94                                 <optionlist>
95                                         <option name="l">
96                                                 <para>Line mode:  offset and length are assumed to be
97                                                 measured in lines, instead of byte offsets.</para>
98                                         </option>
99                                         <option name="a">
100                                                 <para>In write mode only, the append option is used to
101                                                 append to the end of the file, instead of overwriting
102                                                 the existing file.</para>
103                                         </option>
104                                         <option name="d">
105                                                 <para>In write mode and line mode only, this option does
106                                                 not automatically append a newline string to the end of
107                                                 a value.  This is useful for deleting lines, instead of
108                                                 setting them to blank.</para>
109                                         </option>
110                                 </optionlist>
111                         </parameter>
112                         <parameter name="format">
113                                 <para>The <replaceable>format</replaceable> parameter may be
114                                 used to delimit the type of line terminators in line mode.</para>
115                                 <optionlist>
116                                         <option name="u">
117                                                 <para>Unix newline format.</para>
118                                         </option>
119                                         <option name="d">
120                                                 <para>DOS newline format.</para>
121                                         </option>
122                                         <option name="m">
123                                                 <para>Macintosh newline format.</para>
124                                         </option>
125                                 </optionlist>
126                         </parameter>
127                 </syntax>
128                 <description>
129                         <para>Read and write text file in character and line mode.</para>
130                         <para>Examples:</para>
131                         <para/>
132                         <para>Read mode (byte):</para>
133                         <para>    ;reads the entire content of the file.</para>
134                         <para>    Set(foo=${FILE(/tmp/test.txt)})</para>
135                         <para>    ;reads from the 11th byte to the end of the file (i.e. skips the first 10).</para>
136                         <para>    Set(foo=${FILE(/tmp/test.txt,10)})</para>
137                         <para>    ;reads from the 11th to 20th byte in the file (i.e. skip the first 10, then read 10 bytes).</para>
138                         <para>    Set(foo=${FILE(/tmp/test.txt,10,10)})</para>
139                         <para/>
140                         <para>Read mode (line):</para>
141                         <para>    ; reads the 3rd line of the file.</para>
142                         <para>    Set(foo=${FILE(/tmp/test.txt,3,1,l)})</para>
143                         <para>    ; reads the 3rd and 4th lines of the file.</para>
144                         <para>    Set(foo=${FILE(/tmp/test.txt,3,2,l)})</para>
145                         <para>    ; reads from the third line to the end of the file.</para>
146                         <para>    Set(foo=${FILE(/tmp/test.txt,3,,l)})</para>
147                         <para>    ; reads the last three lines of the file.</para>
148                         <para>    Set(foo=${FILE(/tmp/test.txt,-3,,l)})</para>
149                         <para>    ; reads the 3rd line of a DOS-formatted file.</para>
150                         <para>    Set(foo=${FILE(/tmp/test.txt,3,1,l,d)})</para>
151                         <para/>
152                         <para>Write mode (byte):</para>
153                         <para>    ; truncate the file and write "bar"</para>
154                         <para>    Set(FILE(/tmp/test.txt)=bar)</para>
155                         <para>    ; Append "bar"</para>
156                         <para>    Set(FILE(/tmp/test.txt,,,a)=bar)</para>
157                         <para>    ; Replace the first byte with "bar" (replaces 1 character with 3)</para>
158                         <para>    Set(FILE(/tmp/test.txt,0,1)=bar)</para>
159                         <para>    ; Replace 10 bytes beginning at the 21st byte of the file with "bar"</para>
160                         <para>    Set(FILE(/tmp/test.txt,20,10)=bar)</para>
161                         <para>    ; Replace all bytes from the 21st with "bar"</para>
162                         <para>    Set(FILE(/tmp/test.txt,20)=bar)</para>
163                         <para>    ; Insert "bar" after the 4th character</para>
164                         <para>    Set(FILE(/tmp/test.txt,4,0)=bar)</para>
165                         <para/>
166                         <para>Write mode (line):</para>
167                         <para>    ; Replace the first line of the file with "bar"</para>
168                         <para>    Set(FILE(/tmp/foo.txt,0,1,l)=bar)</para>
169                         <para>    ; Replace the last line of the file with "bar"</para>
170                         <para>    Set(FILE(/tmp/foo.txt,-1,,l)=bar)</para>
171                         <para>    ; Append "bar" to the file with a newline</para>
172                         <para>    Set(FILE(/tmp/foo.txt,,,al)=bar)</para>
173                         <note>
174                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
175                                 is set to <literal>no</literal>, this function can only be executed from the
176                                 dialplan, and not directly from external protocols.</para>
177                         </note>
178                 </description>
179                 <see-also>
180                         <ref type="function">FILE_COUNT_LINE</ref>
181                         <ref type="function">FILE_FORMAT</ref>
182                 </see-also>
183         </function>
184         <function name="FILE_COUNT_LINE" language="en_US">
185                 <synopsis>
186                         Obtains the number of lines of a text file.
187                 </synopsis>
188                 <syntax>
189                         <parameter name="filename" required="true" />
190                         <parameter name="format">
191                                 <para>Format may be one of the following:</para>
192                                 <optionlist>
193                                         <option name="u">
194                                                 <para>Unix newline format.</para>
195                                         </option>
196                                         <option name="d">
197                                                 <para>DOS newline format.</para>
198                                         </option>
199                                         <option name="m">
200                                                 <para>Macintosh newline format.</para>
201                                         </option>
202                                 </optionlist>
203                                 <note><para>If not specified, an attempt will be made to determine the newline format type.</para></note>
204                         </parameter>
205                 </syntax>
206                 <description>
207                         <para>Returns the number of lines, or <literal>-1</literal> on error.</para>
208                         <note>
209                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
210                                 is set to <literal>no</literal>, this function can only be executed from the
211                                 dialplan, and not directly from external protocols.</para>
212                         </note>
213                 </description>
214                 <see-also>
215                         <ref type="function">FILE</ref>
216                         <ref type="function">FILE_FORMAT</ref>
217                 </see-also>
218         </function>
219         <function name="FILE_FORMAT" language="en_US">
220                 <synopsis>
221                         Return the newline format of a text file.
222                 </synopsis>
223                 <syntax>
224                         <parameter name="filename" required="true" />
225                 </syntax>
226                 <description>
227                         <para>Return the line terminator type:</para>
228                         <para>'u' - Unix "\n" format</para>
229                         <para>'d' - DOS "\r\n" format</para>
230                         <para>'m' - Macintosh "\r" format</para>
231                         <para>'x' - Cannot be determined</para>
232                         <note>
233                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
234                                 is set to <literal>no</literal>, this function can only be executed from the
235                                 dialplan, and not directly from external protocols.</para>
236                         </note>
237                 </description>
238                 <see-also>
239                         <ref type="function">FILE</ref>
240                         <ref type="function">FILE_COUNT_LINE</ref>
241                 </see-also>
242         </function>
243  ***/
244
245 static int env_read(struct ast_channel *chan, const char *cmd, char *data,
246                         char *buf, size_t len)
247 {
248         char *ret = NULL;
249
250         *buf = '\0';
251
252         if (data)
253                 ret = getenv(data);
254
255         if (ret)
256                 ast_copy_string(buf, ret, len);
257
258         return 0;
259 }
260
261 static int env_write(struct ast_channel *chan, const char *cmd, char *data,
262                          const char *value)
263 {
264         if (!ast_strlen_zero(data) && strncmp(data, "AST_", 4)) {
265                 if (!ast_strlen_zero(value)) {
266                         setenv(data, value, 1);
267                 } else {
268                         unsetenv(data);
269                 }
270         }
271
272         return 0;
273 }
274
275 static int stat_read(struct ast_channel *chan, const char *cmd, char *data,
276                          char *buf, size_t len)
277 {
278         char *action;
279         struct stat s;
280
281         ast_copy_string(buf, "0", len);
282
283         action = strsep(&data, ",");
284         if (stat(data, &s)) {
285                 return 0;
286         } else {
287                 switch (*action) {
288                 case 'e':
289                         strcpy(buf, "1");
290                         break;
291                 case 's':
292                         snprintf(buf, len, "%u", (unsigned int) s.st_size);
293                         break;
294                 case 'f':
295                         snprintf(buf, len, "%d", S_ISREG(s.st_mode) ? 1 : 0);
296                         break;
297                 case 'd':
298                         snprintf(buf, len, "%d", S_ISDIR(s.st_mode) ? 1 : 0);
299                         break;
300                 case 'M':
301                         snprintf(buf, len, "%d", (int) s.st_mtime);
302                         break;
303                 case 'A':
304                         snprintf(buf, len, "%d", (int) s.st_mtime);
305                         break;
306                 case 'C':
307                         snprintf(buf, len, "%d", (int) s.st_ctime);
308                         break;
309                 case 'm':
310                         snprintf(buf, len, "%o", s.st_mode);
311                         break;
312                 }
313         }
314
315         return 0;
316 }
317
318 enum file_format {
319         FF_UNKNOWN = -1,
320         FF_UNIX,
321         FF_DOS,
322         FF_MAC,
323 };
324
325 static int64_t count_lines(const char *filename, enum file_format newline_format)
326 {
327         int count = 0;
328         char fbuf[4096];
329         FILE *ff;
330
331         if (!(ff = fopen(filename, "r"))) {
332                 ast_log(LOG_ERROR, "Unable to open '%s': %s\n", filename, strerror(errno));
333                 return -1;
334         }
335
336         while (fgets(fbuf, sizeof(fbuf), ff)) {
337                 char *next = fbuf, *first_cr = NULL, *first_nl = NULL;
338
339                 /* Must do it this way, because if the fileformat is FF_MAC, then Unix
340                  * assumptions about line-format will not come into play. */
341                 while (next) {
342                         if (newline_format == FF_DOS || newline_format == FF_MAC || newline_format == FF_UNKNOWN) {
343                                 first_cr = strchr(next, '\r');
344                         }
345                         if (newline_format == FF_UNIX || newline_format == FF_UNKNOWN) {
346                                 first_nl = strchr(next, '\n');
347                         }
348
349                         /* No terminators found in buffer */
350                         if (!first_cr && !first_nl) {
351                                 break;
352                         }
353
354                         if (newline_format == FF_UNKNOWN) {
355                                 if ((first_cr && !first_nl) || (first_cr && first_cr < first_nl)) {
356                                         if (first_nl && first_nl == first_cr + 1) {
357                                                 newline_format = FF_DOS;
358                                         } else if (first_cr && first_cr == &fbuf[sizeof(fbuf) - 2]) {
359                                                 /* Get it on the next pass */
360                                                 fseek(ff, -1, SEEK_CUR);
361                                                 break;
362                                         } else {
363                                                 newline_format = FF_MAC;
364                                                 first_nl = NULL;
365                                         }
366                                 } else {
367                                         newline_format = FF_UNIX;
368                                         first_cr = NULL;
369                                 }
370                                 /* Jump down into next section */
371                         }
372
373                         if (newline_format == FF_DOS) {
374                                 if (first_nl && first_cr && first_nl == first_cr + 1) {
375                                         next = first_nl + 1;
376                                         count++;
377                                 } else if (first_cr == &fbuf[sizeof(fbuf) - 2]) {
378                                         /* Get it on the next pass */
379                                         fseek(ff, -1, SEEK_CUR);
380                                         break;
381                                 }
382                         } else if (newline_format == FF_MAC) {
383                                 if (first_cr) {
384                                         next = first_cr + 1;
385                                         count++;
386                                 }
387                         } else if (newline_format == FF_UNIX) {
388                                 if (first_nl) {
389                                         next = first_nl + 1;
390                                         count++;
391                                 }
392                         }
393                 }
394         }
395         fclose(ff);
396
397         return count;
398 }
399
400 static int file_count_line(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
401 {
402         enum file_format newline_format = FF_UNKNOWN;
403         int64_t count;
404         AST_DECLARE_APP_ARGS(args,
405                 AST_APP_ARG(filename);
406                 AST_APP_ARG(format);
407         );
408
409         AST_STANDARD_APP_ARGS(args, data);
410         if (args.argc > 1) {
411                 if (tolower(args.format[0]) == 'd') {
412                         newline_format = FF_DOS;
413                 } else if (tolower(args.format[0]) == 'm') {
414                         newline_format = FF_MAC;
415                 } else if (tolower(args.format[0]) == 'u') {
416                         newline_format = FF_UNIX;
417                 }
418         }
419
420         count = count_lines(args.filename, newline_format);
421         ast_str_set(buf, len, "%" PRId64, count);
422         return 0;
423 }
424
425 #define LINE_COUNTER(cptr, term, counter) \
426         if (*cptr == '\n' && term == FF_UNIX) { \
427                 counter++; \
428         } else if (*cptr == '\n' && term == FF_DOS && dos_state == 0) { \
429                 dos_state = 1; \
430         } else if (*cptr == '\r' && term == FF_DOS && dos_state == 1) { \
431                 dos_state = 0; \
432                 counter++; \
433         } else if (*cptr == '\r' && term == FF_MAC) { \
434                 counter++; \
435         } else if (term == FF_DOS) { \
436                 dos_state = 0; \
437         }
438
439 static enum file_format file2format(const char *filename)
440 {
441         FILE *ff;
442         char fbuf[4096];
443         char *first_cr, *first_nl;
444         enum file_format newline_format = FF_UNKNOWN;
445
446         if (!(ff = fopen(filename, "r"))) {
447                 ast_log(LOG_ERROR, "Cannot open '%s': %s\n", filename, strerror(errno));
448                 return -1;
449         }
450
451         while (fgets(fbuf, sizeof(fbuf), ff)) {
452                 first_cr = strchr(fbuf, '\r');
453                 first_nl = strchr(fbuf, '\n');
454
455                 if (!first_cr && !first_nl) {
456                         continue;
457                 }
458
459                 if ((first_cr && !first_nl) || (first_cr && first_cr < first_nl)) {
460
461                         if (first_nl && first_nl == first_cr + 1) {
462                                 newline_format = FF_DOS;
463                         } else if (first_cr && first_cr == &fbuf[sizeof(fbuf) - 2]) {
464                                 /* Edge case: get it on the next pass */
465                                 fseek(ff, -1, SEEK_CUR);
466                                 continue;
467                         } else {
468                                 newline_format = FF_MAC;
469                         }
470                 } else {
471                         newline_format = FF_UNIX;
472                 }
473                 break;
474         }
475         fclose(ff);
476         return newline_format;
477 }
478
479 static int file_format(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
480 {
481         enum file_format newline_format = file2format(data);
482         ast_str_set(buf, len, "%c", newline_format == FF_UNIX ? 'u' : newline_format == FF_DOS ? 'd' : newline_format == FF_MAC ? 'm' : 'x');
483         return 0;
484 }
485
486 static int file_read(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
487 {
488         FILE *ff;
489         int64_t offset = 0, length = LLONG_MAX;
490         enum file_format format = FF_UNKNOWN;
491         char fbuf[4096];
492         int64_t flength, i; /* iterator needs to be signed, so it can go negative and terminate the loop */
493         int64_t offset_offset = -1, length_offset = -1;
494         char dos_state = 0;
495         AST_DECLARE_APP_ARGS(args,
496                 AST_APP_ARG(filename);
497                 AST_APP_ARG(offset);
498                 AST_APP_ARG(length);
499                 AST_APP_ARG(options);
500                 AST_APP_ARG(fileformat);
501         );
502
503         AST_STANDARD_APP_ARGS(args, data);
504
505         if (args.argc > 1) {
506                 sscanf(args.offset, "%" SCNd64, &offset);
507         }
508         if (args.argc > 2) {
509                 sscanf(args.length, "%" SCNd64, &length);
510         }
511
512         if (args.argc < 4 || !strchr(args.options, 'l')) {
513                 /* Character-based mode */
514                 off_t off_i;
515
516                 if (!(ff = fopen(args.filename, "r"))) {
517                         ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", args.filename, strerror(errno));
518                         return 0;
519                 }
520
521                 if (fseeko(ff, 0, SEEK_END) < 0) {
522                         ast_log(LOG_ERROR, "Cannot seek to end of '%s': %s\n", args.filename, strerror(errno));
523                         fclose(ff);
524                         return -1;
525                 }
526                 flength = ftello(ff);
527
528                 if (offset < 0) {
529                         fseeko(ff, offset, SEEK_END);
530                         if ((offset = ftello(ff)) < 0) {
531                                 ast_log(AST_LOG_ERROR, "Cannot determine offset position of '%s': %s\n", args.filename, strerror(errno));
532                                 fclose(ff);
533                                 return -1;
534                         }
535                 }
536                 if (length < 0) {
537                         fseeko(ff, length, SEEK_END);
538                         if ((length = ftello(ff)) - offset < 0) {
539                                 /* Eliminates all results */
540                                 fclose(ff);
541                                 return -1;
542                         }
543                 } else if (length == LLONG_MAX) {
544                         fseeko(ff, 0, SEEK_END);
545                         length = ftello(ff);
546                 }
547
548                 ast_str_reset(*buf);
549
550                 fseeko(ff, offset, SEEK_SET);
551                 for (off_i = ftello(ff); off_i < flength && off_i < offset + length; off_i += sizeof(fbuf)) {
552                         /* Calculate if we need to retrieve just a portion of the file in memory */
553                         size_t toappend = sizeof(fbuf);
554
555                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
556                                 ast_log(LOG_ERROR, "Short read?!!\n");
557                                 break;
558                         }
559
560                         /* Don't go past the length requested */
561                         if (off_i + toappend > offset + length) {
562                                 toappend = MIN(offset + length - off_i, flength - off_i);
563                         }
564
565                         ast_str_append_substr(buf, len, fbuf, toappend);
566                 }
567                 fclose(ff);
568                 return 0;
569         }
570
571         /* Line-based read */
572         if (args.argc == 5) {
573                 if (tolower(args.fileformat[0]) == 'd') {
574                         format = FF_DOS;
575                 } else if (tolower(args.fileformat[0]) == 'm') {
576                         format = FF_MAC;
577                 } else if (tolower(args.fileformat[0]) == 'u') {
578                         format = FF_UNIX;
579                 }
580         }
581
582         if (format == FF_UNKNOWN) {
583                 if ((format = file2format(args.filename)) == FF_UNKNOWN) {
584                         ast_log(LOG_WARNING, "'%s' is not a line-based file\n", args.filename);
585                         return -1;
586                 }
587         }
588
589         if (offset < 0 && length <= offset) {
590                 /* Length eliminates all content */
591                 return -1;
592         } else if (offset == 0) {
593                 offset_offset = 0;
594         }
595
596         if (!(ff = fopen(args.filename, "r"))) {
597                 ast_log(LOG_ERROR, "Cannot open '%s': %s\n", args.filename, strerror(errno));
598                 return -1;
599         }
600
601         if (fseek(ff, 0, SEEK_END)) {
602                 ast_log(LOG_ERROR, "Cannot seek to end of file '%s': %s\n", args.filename, strerror(errno));
603                 fclose(ff);
604                 return -1;
605         }
606
607         flength = ftello(ff);
608
609         if (length == LLONG_MAX) {
610                 length_offset = flength;
611         }
612
613         /* For negative offset and/or negative length */
614         if (offset < 0 || length < 0) {
615                 int64_t count = 0;
616                 /* Start with an even multiple of fbuf, so at the end of reading with a
617                  * 0 offset, we don't try to go past the beginning of the file. */
618                 for (i = (flength / sizeof(fbuf)) * sizeof(fbuf); i >= 0; i -= sizeof(fbuf)) {
619                         size_t end;
620                         char *pos;
621                         if (fseeko(ff, i, SEEK_SET)) {
622                                 ast_log(LOG_ERROR, "Cannot seek to offset %" PRId64 ": %s\n", i, strerror(errno));
623                         }
624                         end = fread(fbuf, 1, sizeof(fbuf), ff);
625                         for (pos = (end < sizeof(fbuf) ? fbuf + end - 1 : fbuf + sizeof(fbuf) - 1); pos >= fbuf; pos--) {
626                                 LINE_COUNTER(pos, format, count);
627
628                                 if (length < 0 && count * -1 == length) {
629                                         length_offset = i + (pos - fbuf);
630                                 } else if (offset < 0 && count * -1 == (offset - 1)) {
631                                         /* Found our initial offset.  We're done with reverse motion! */
632                                         if (format == FF_DOS) {
633                                                 offset_offset = i + (pos - fbuf) + 2;
634                                         } else {
635                                                 offset_offset = i + (pos - fbuf) + 1;
636                                         }
637                                         break;
638                                 }
639                         }
640                         if ((offset < 0 && offset_offset >= 0) || (offset >= 0 && length_offset >= 0)) {
641                                 break;
642                         }
643                 }
644                 /* We're at the beginning, and the negative offset indicates the exact number of lines in the file */
645                 if (offset < 0 && offset_offset < 0 && offset == count * -1) {
646                         offset_offset = 0;
647                 }
648         }
649
650         /* Positve line offset */
651         if (offset > 0) {
652                 int64_t count = 0;
653                 fseek(ff, 0, SEEK_SET);
654                 for (i = 0; i < flength; i += sizeof(fbuf)) {
655                         char *pos;
656                         if (i + sizeof(fbuf) <= flength) {
657                                 /* Don't let previous values influence current counts, due to short reads */
658                                 memset(fbuf, 0, sizeof(fbuf));
659                         }
660                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
661                                 ast_log(LOG_ERROR, "Short read?!!\n");
662                                 fclose(ff);
663                                 return -1;
664                         }
665                         for (pos = fbuf; pos < fbuf + sizeof(fbuf); pos++) {
666                                 LINE_COUNTER(pos, format, count);
667
668                                 if (count == offset) {
669                                         offset_offset = i + (pos - fbuf) + 1;
670                                         break;
671                                 }
672                         }
673                         if (offset_offset >= 0) {
674                                 break;
675                         }
676                 }
677         }
678
679         if (offset_offset < 0) {
680                 ast_log(LOG_ERROR, "Offset '%s' refers to before the beginning of the file!\n", args.offset);
681                 fclose(ff);
682                 return -1;
683         }
684
685         ast_str_reset(*buf);
686         if (fseeko(ff, offset_offset, SEEK_SET)) {
687                 ast_log(LOG_ERROR, "fseeko failed: %s\n", strerror(errno));
688         }
689
690         /* If we have both offset_offset and length_offset, then grabbing the
691          * buffer is simply a matter of just retrieving the file and adding it
692          * to buf.  Otherwise, we need to run byte-by-byte forward until the
693          * length is complete. */
694         if (length_offset >= 0) {
695                 ast_debug(3, "offset=%" PRId64 ", length=%" PRId64 ", offset_offset=%" PRId64 ", length_offset=%" PRId64 "\n", offset, length, offset_offset, length_offset);
696                 for (i = offset_offset; i < length_offset; i += sizeof(fbuf)) {
697                         if (fread(fbuf, 1, i + sizeof(fbuf) > flength ? flength - i : sizeof(fbuf), ff) < (i + sizeof(fbuf) > flength ? flength - i : sizeof(fbuf))) {
698                                 ast_log(LOG_ERROR, "Short read?!!\n");
699                         }
700                         ast_debug(3, "Appending first %" PRId64" bytes of fbuf=%s\n", (int64_t)(i + sizeof(fbuf) > length_offset ? length_offset - i : sizeof(fbuf)), fbuf);
701                         ast_str_append_substr(buf, len, fbuf, i + sizeof(fbuf) > length_offset ? length_offset - i : sizeof(fbuf));
702                 }
703         } else if (length == 0) {
704                 /* Nothing to do */
705         } else {
706                 /* Positive line offset */
707                 int64_t current_length = 0;
708                 char dos_state = 0;
709                 ast_debug(3, "offset=%" PRId64 ", length=%" PRId64 ", offset_offset=%" PRId64 ", length_offset=%" PRId64 "\n", offset, length, offset_offset, length_offset);
710                 for (i = offset_offset; i < flength; i += sizeof(fbuf)) {
711                         char *pos;
712                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
713                                 ast_log(LOG_ERROR, "Short read?!!\n");
714                                 fclose(ff);
715                                 return -1;
716                         }
717                         for (pos = fbuf; pos < fbuf + sizeof(fbuf); pos++) {
718                                 LINE_COUNTER(pos, format, current_length);
719
720                                 if (current_length == length) {
721                                         length_offset = i + (pos - fbuf) + 1;
722                                         break;
723                                 }
724                         }
725                         ast_debug(3, "length_offset=%" PRId64 ", length_offset - i=%" PRId64 "\n", length_offset, length_offset - i);
726                         ast_str_append_substr(buf, len, fbuf, (length_offset >= 0) ? length_offset - i : (flength > i + sizeof(fbuf)) ? sizeof(fbuf) : flength - i);
727
728                         if (length_offset >= 0) {
729                                 break;
730                         }
731                 }
732         }
733
734         fclose(ff);
735         return 0;
736 }
737
738 const char *format2term(enum file_format f) __attribute__((const));
739 const char *format2term(enum file_format f)
740 {
741         const char *term[] = { "", "\n", "\r\n", "\r" };
742         return term[f + 1];
743 }
744
745 static int file_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
746 {
747         AST_DECLARE_APP_ARGS(args,
748                 AST_APP_ARG(filename);
749                 AST_APP_ARG(offset);
750                 AST_APP_ARG(length);
751                 AST_APP_ARG(options);
752                 AST_APP_ARG(format);
753         );
754         int64_t offset = 0, length = LLONG_MAX;
755         off_t flength, vlength;
756         size_t foplen = 0;
757         FILE *ff;
758
759         AST_STANDARD_APP_ARGS(args, data);
760
761         if (args.argc > 1) {
762                 sscanf(args.offset, "%" SCNd64, &offset);
763         }
764         if (args.argc > 2) {
765                 sscanf(args.length, "%" SCNd64, &length);
766         }
767
768         vlength = strlen(value);
769
770         if (args.argc < 4 || !strchr(args.options, 'l')) {
771                 /* Character-based mode */
772
773                 if (args.argc > 3 && strchr(args.options, 'a')) {
774                         /* Append mode */
775                         if (!(ff = fopen(args.filename, "a"))) {
776                                 ast_log(LOG_WARNING, "Cannot open file '%s' for appending: %s\n", args.filename, strerror(errno));
777                                 return 0;
778                         }
779                         if (fwrite(value, 1, vlength, ff) < vlength) {
780                                 ast_log(LOG_ERROR, "Short write?!!\n");
781                         }
782                         fclose(ff);
783                         return 0;
784                 } else if (offset == 0 && length == LLONG_MAX) {
785                         if (!(ff = fopen(args.filename, "w"))) {
786                                 ast_log(LOG_WARNING, "Cannot open file '%s' for writing: %s\n", args.filename, strerror(errno));
787                                 return 0;
788                         }
789                         if (fwrite(value, 1, vlength, ff) < vlength) {
790                                 ast_log(LOG_ERROR, "Short write?!!\n");
791                         }
792                         fclose(ff);
793                         return 0;
794                 }
795
796                 if (!(ff = fopen(args.filename, "r+"))) {
797                         ast_log(LOG_WARNING, "Cannot open file '%s' for modification: %s\n", args.filename, strerror(errno));
798                         return 0;
799                 }
800                 fseeko(ff, 0, SEEK_END);
801                 flength = ftello(ff);
802
803                 if (offset < 0) {
804                         if (fseeko(ff, offset, SEEK_END)) {
805                                 ast_log(LOG_ERROR, "Cannot seek to offset of '%s': %s\n", args.filename, strerror(errno));
806                                 fclose(ff);
807                                 return -1;
808                         }
809                         if ((offset = ftello(ff)) < 0) {
810                                 ast_log(AST_LOG_ERROR, "Cannot determine offset position of '%s': %s\n", args.filename, strerror(errno));
811                                 fclose(ff);
812                                 return -1;
813                         }
814                 }
815
816                 if (length < 0) {
817                         length = flength - offset + length;
818                         if (length < 0) {
819                                 ast_log(LOG_ERROR, "Length '%s' exceeds the file length.  No data will be written.\n", args.length);
820                                 fclose(ff);
821                                 return -1;
822                         }
823                 }
824
825                 fseeko(ff, offset, SEEK_SET);
826
827                 ast_debug(3, "offset=%s/%" PRId64 ", length=%s/%" PRId64 ", vlength=%" PRId64 ", flength=%" PRId64 "\n",
828                         S_OR(args.offset, "(null)"), offset, S_OR(args.length, "(null)"), length, vlength, flength);
829
830                 if (length == vlength) {
831                         /* Simplest case, a straight replace */
832                         if (fwrite(value, 1, vlength, ff) < vlength) {
833                                 ast_log(LOG_ERROR, "Short write?!!\n");
834                         }
835                         fclose(ff);
836                 } else if (length == LLONG_MAX) {
837                         /* Simple truncation */
838                         if (fwrite(value, 1, vlength, ff) < vlength) {
839                                 ast_log(LOG_ERROR, "Short write?!!\n");
840                         }
841                         fclose(ff);
842                         if (truncate(args.filename, offset + vlength)) {
843                                 ast_log(LOG_ERROR, "Unable to truncate the file: %s\n", strerror(errno));
844                         }
845                 } else if (length > vlength) {
846                         /* More complex -- need to close a gap */
847                         char fbuf[4096];
848                         off_t cur;
849                         if (fwrite(value, 1, vlength, ff) < vlength) {
850                                 ast_log(LOG_ERROR, "Short write?!!\n");
851                         }
852                         fseeko(ff, length - vlength, SEEK_CUR);
853                         while ((cur = ftello(ff)) < flength) {
854                                 if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
855                                         ast_log(LOG_ERROR, "Short read?!!\n");
856                                 }
857                                 fseeko(ff, cur + vlength - length, SEEK_SET);
858                                 if (fwrite(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf)) {
859                                         ast_log(LOG_ERROR, "Short write?!!\n");
860                                 }
861                                 /* Seek to where we stopped reading */
862                                 if (fseeko(ff, cur + sizeof(fbuf), SEEK_SET) < 0) {
863                                         /* Only reason for seek to fail is EOF */
864                                         break;
865                                 }
866                         }
867                         fclose(ff);
868                         if (truncate(args.filename, flength - (length - vlength))) {
869                                 ast_log(LOG_ERROR, "Unable to truncate the file: %s\n", strerror(errno));
870                         }
871                 } else {
872                         /* Most complex -- need to open a gap */
873                         char fbuf[4096];
874                         off_t lastwritten = flength + vlength - length;
875
876                         /* Start reading exactly the buffer size back from the end. */
877                         fseeko(ff, flength - sizeof(fbuf), SEEK_SET);
878                         while (offset < ftello(ff)) {
879                                 if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf)) {
880                                         ast_log(LOG_ERROR, "Short read?!!\n");
881                                         fclose(ff);
882                                         return -1;
883                                 }
884                                 /* Since the read moved our file ptr forward, we reverse, but
885                                  * seek an offset equal to the amount we want to extend the
886                                  * file by */
887                                 fseeko(ff, vlength - length - sizeof(fbuf), SEEK_CUR);
888
889                                 /* Note the location of this buffer -- we must not overwrite this position. */
890                                 lastwritten = ftello(ff);
891
892                                 if (fwrite(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf)) {
893                                         ast_log(LOG_ERROR, "Short write?!!\n");
894                                         fclose(ff);
895                                         return -1;
896                                 }
897
898                                 if (lastwritten < offset + sizeof(fbuf)) {
899                                         break;
900                                 }
901                                 /* Our file pointer is now either pointing to the end of the
902                                  * file (new position) or a multiple of the fbuf size back from
903                                  * that point.  Move back to where we want to start reading
904                                  * again.  We never actually try to read beyond the end of the
905                                  * file, so we don't have do deal with short reads, as we would
906                                  * when we're shortening the file. */
907                                 fseeko(ff, 2 * sizeof(fbuf) + vlength - length, SEEK_CUR);
908                         }
909
910                         /* Last part of the file that we need to preserve */
911                         if (fseeko(ff, offset + length, SEEK_SET)) {
912                                 ast_log(LOG_WARNING, "Unable to seek to %" PRId64 " + %" PRId64 " != %" PRId64 "?)\n", offset, length, ftello(ff));
913                         }
914
915                         /* Doesn't matter how much we read -- just need to restrict the write */
916                         ast_debug(1, "Reading at %" PRId64 "\n", ftello(ff));
917                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
918                                 ast_log(LOG_ERROR, "Short read?!!\n");
919                         }
920                         fseek(ff, offset, SEEK_SET);
921                         /* Write out the value, then write just up until where we last moved some data */
922                         if (fwrite(value, 1, vlength, ff) < vlength) {
923                                 ast_log(LOG_ERROR, "Short write?!!\n");
924                         } else {
925                                 off_t curpos = ftello(ff);
926                                 foplen = lastwritten - curpos;
927                                 if (fwrite(fbuf, 1, foplen, ff) < foplen) {
928                                         ast_log(LOG_ERROR, "Short write?!!\n");
929                                 }
930                         }
931                         fclose(ff);
932                 }
933         } else {
934                 enum file_format newline_format = FF_UNKNOWN;
935
936                 /* Line mode */
937                 if (args.argc == 5) {
938                         if (tolower(args.format[0]) == 'u') {
939                                 newline_format = FF_UNIX;
940                         } else if (tolower(args.format[0]) == 'm') {
941                                 newline_format = FF_MAC;
942                         } else if (tolower(args.format[0]) == 'd') {
943                                 newline_format = FF_DOS;
944                         }
945                 }
946                 if (newline_format == FF_UNKNOWN && (newline_format = file2format(args.filename)) == FF_UNKNOWN) {
947                         ast_log(LOG_ERROR, "File '%s' not in line format\n", args.filename);
948                         return -1;
949                 }
950
951                 if (strchr(args.options, 'a')) {
952                         /* Append to file */
953                         if (!(ff = fopen(args.filename, "a"))) {
954                                 ast_log(LOG_ERROR, "Unable to open '%s' for appending: %s\n", args.filename, strerror(errno));
955                                 return -1;
956                         }
957                         if (fwrite(value, 1, vlength, ff) < vlength) {
958                                 ast_log(LOG_ERROR, "Short write?!!\n");
959                         } else if (!strchr(args.options, 'd') && fwrite(format2term(newline_format), 1, strlen(format2term(newline_format)), ff) < strlen(format2term(newline_format))) {
960                                 ast_log(LOG_ERROR, "Short write?!!\n");
961                         }
962                         fclose(ff);
963                 } else if (offset == 0 && length == LLONG_MAX) {
964                         /* Overwrite file */
965                         off_t truncsize;
966                         if (!(ff = fopen(args.filename, "w"))) {
967                                 ast_log(LOG_ERROR, "Unable to open '%s' for writing: %s\n", args.filename, strerror(errno));
968                                 return -1;
969                         }
970                         if (fwrite(value, 1, vlength, ff) < vlength) {
971                                 ast_log(LOG_ERROR, "Short write?!!\n");
972                         } else if (!strchr(args.options, 'd') && fwrite(format2term(newline_format), 1, strlen(format2term(newline_format)), ff) < strlen(format2term(newline_format))) {
973                                 ast_log(LOG_ERROR, "Short write?!!\n");
974                         }
975                         if ((truncsize = ftello(ff)) < 0) {
976                                 ast_log(AST_LOG_ERROR, "Unable to determine truncate position of '%s': %s\n", args.filename, strerror(errno));
977                         }
978                         fclose(ff);
979                         if (truncsize >= 0 && truncate(args.filename, truncsize)) {
980                                 ast_log(LOG_ERROR, "Unable to truncate file '%s': %s\n", args.filename, strerror(errno));
981                                 return -1;
982                         }
983                 } else {
984                         int64_t offset_offset = (offset == 0 ? 0 : -1), length_offset = -1, flength, i, current_length = 0;
985                         char dos_state = 0, fbuf[4096];
986
987                         if (offset < 0 && length < offset) {
988                                 /* Nonsense! */
989                                 ast_log(LOG_ERROR, "Length cannot specify a position prior to the offset\n");
990                                 return -1;
991                         }
992
993                         if (!(ff = fopen(args.filename, "r+"))) {
994                                 ast_log(LOG_ERROR, "Cannot open '%s' for modification: %s\n", args.filename, strerror(errno));
995                                 return -1;
996                         }
997
998                         if (fseek(ff, 0, SEEK_END)) {
999                                 ast_log(LOG_ERROR, "Cannot seek to end of file '%s': %s\n", args.filename, strerror(errno));
1000                                 fclose(ff);
1001                                 return -1;
1002                         }
1003                         if ((flength = ftello(ff)) < 0) {
1004                                 ast_log(AST_LOG_ERROR, "Cannot determine end position of file '%s': %s\n", args.filename, strerror(errno));
1005                                 fclose(ff);
1006                                 return -1;
1007                         }
1008
1009                         /* For negative offset and/or negative length */
1010                         if (offset < 0 || length < 0) {
1011                                 int64_t count = 0;
1012                                 for (i = (flength / sizeof(fbuf)) * sizeof(fbuf); i >= 0; i -= sizeof(fbuf)) {
1013                                         char *pos;
1014                                         if (fseeko(ff, i, SEEK_SET)) {
1015                                                 ast_log(LOG_ERROR, "Cannot seek to offset %" PRId64 ": %s\n", i, strerror(errno));
1016                                         }
1017                                         if (i + sizeof(fbuf) >= flength) {
1018                                                 memset(fbuf, 0, sizeof(fbuf));
1019                                         }
1020                                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
1021                                                 ast_log(LOG_ERROR, "Short read: %s\n", strerror(errno));
1022                                                 fclose(ff);
1023                                                 return -1;
1024                                         }
1025                                         for (pos = fbuf + sizeof(fbuf) - 1; pos >= fbuf; pos--) {
1026                                                 LINE_COUNTER(pos, newline_format, count);
1027
1028                                                 if (length < 0 && count * -1 == length) {
1029                                                         length_offset = i + (pos - fbuf);
1030                                                 } else if (offset < 0 && count * -1 == (offset - 1)) {
1031                                                         /* Found our initial offset.  We're done with reverse motion! */
1032                                                         if (newline_format == FF_DOS) {
1033                                                                 offset_offset = i + (pos - fbuf) + 2;
1034                                                         } else {
1035                                                                 offset_offset = i + (pos - fbuf) + 1;
1036                                                         }
1037                                                         break;
1038                                                 }
1039                                         }
1040                                         if ((offset < 0 && offset_offset >= 0) || (offset >= 0 && length_offset >= 0)) {
1041                                                 break;
1042                                         }
1043                                 }
1044                                 /* We're at the beginning, and the negative offset indicates the exact number of lines in the file */
1045                                 if (offset < 0 && offset_offset < 0 && offset == count * -1) {
1046                                         offset_offset = 0;
1047                                 }
1048                         }
1049
1050                         /* Positve line offset */
1051                         if (offset > 0) {
1052                                 int64_t count = 0;
1053                                 fseek(ff, 0, SEEK_SET);
1054                                 for (i = 0; i < flength; i += sizeof(fbuf)) {
1055                                         char *pos;
1056                                         if (i + sizeof(fbuf) >= flength) {
1057                                                 memset(fbuf, 0, sizeof(fbuf));
1058                                         }
1059                                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
1060                                                 ast_log(LOG_ERROR, "Short read?!!\n");
1061                                                 fclose(ff);
1062                                                 return -1;
1063                                         }
1064                                         for (pos = fbuf; pos < fbuf + sizeof(fbuf); pos++) {
1065                                                 LINE_COUNTER(pos, newline_format, count);
1066
1067                                                 if (count == offset) {
1068                                                         offset_offset = i + (pos - fbuf) + 1;
1069                                                         break;
1070                                                 }
1071                                         }
1072                                         if (offset_offset >= 0) {
1073                                                 break;
1074                                         }
1075                                 }
1076                         }
1077
1078                         if (offset_offset < 0) {
1079                                 ast_log(LOG_ERROR, "Offset '%s' refers to before the beginning of the file!\n", args.offset);
1080                                 fclose(ff);
1081                                 return -1;
1082                         }
1083
1084                         if (length == 0) {
1085                                 length_offset = offset_offset;
1086                         } else if (length == LLONG_MAX) {
1087                                 length_offset = flength;
1088                         }
1089
1090                         /* Positive line length */
1091                         if (length_offset < 0) {
1092                                 fseeko(ff, offset_offset, SEEK_SET);
1093                                 for (i = offset_offset; i < flength; i += sizeof(fbuf)) {
1094                                         char *pos;
1095                                         if (i + sizeof(fbuf) >= flength) {
1096                                                 memset(fbuf, 0, sizeof(fbuf));
1097                                         }
1098                                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
1099                                                 ast_log(LOG_ERROR, "Short read?!!\n");
1100                                                 fclose(ff);
1101                                                 return -1;
1102                                         }
1103                                         for (pos = fbuf; pos < fbuf + sizeof(fbuf); pos++) {
1104                                                 LINE_COUNTER(pos, newline_format, current_length);
1105
1106                                                 if (current_length == length) {
1107                                                         length_offset = i + (pos - fbuf) + 1;
1108                                                         break;
1109                                                 }
1110                                         }
1111                                         if (length_offset >= 0) {
1112                                                 break;
1113                                         }
1114                                 }
1115                                 if (length_offset < 0) {
1116                                         /* Exceeds length of file */
1117                                         ast_debug(3, "Exceeds length of file? length=%" PRId64 ", count=%" PRId64 ", flength=%" PRId64 "\n", length, current_length, flength);
1118                                         length_offset = flength;
1119                                 }
1120                         }
1121
1122                         /* Have offset_offset and length_offset now */
1123                         if (length_offset - offset_offset == vlength + (strchr(args.options, 'd') ? 0 : strlen(format2term(newline_format)))) {
1124                                 /* Simple case - replacement of text inline */
1125                                 fseeko(ff, offset_offset, SEEK_SET);
1126                                 if (fwrite(value, 1, vlength, ff) < vlength) {
1127                                         ast_log(LOG_ERROR, "Short write?!!\n");
1128                                 } else if (!strchr(args.options, 'd') && fwrite(format2term(newline_format), 1, strlen(format2term(newline_format)), ff) < strlen(format2term(newline_format))) {
1129                                         ast_log(LOG_ERROR, "Short write?!!\n");
1130                                 }
1131                                 fclose(ff);
1132                         } else if (length_offset - offset_offset > vlength + (strchr(args.options, 'd') ? 0 : strlen(format2term(newline_format)))) {
1133                                 /* More complex case - need to shorten file */
1134                                 off_t cur;
1135                                 int64_t length_length = length_offset - offset_offset;
1136                                 size_t vlen = vlength + (strchr(args.options, 'd') ? 0 : strlen(format2term(newline_format)));
1137
1138                                 ast_debug(3, "offset=%s/%" PRId64 ", length=%s/%" PRId64 " (%" PRId64 "), vlength=%" PRId64 ", flength=%" PRId64 "\n",
1139                                         args.offset, offset_offset, args.length, length_offset, length_length, vlength, flength);
1140
1141                                 fseeko(ff, offset_offset, SEEK_SET);
1142                                 if (fwrite(value, 1, vlength, ff) < vlength) {
1143                                         ast_log(LOG_ERROR, "Short write?!!\n");
1144                                         fclose(ff);
1145                                         return -1;
1146                                 } else if (!strchr(args.options, 'd') && fwrite(format2term(newline_format), 1, vlen - vlength, ff) < vlen - vlength) {
1147                                         ast_log(LOG_ERROR, "Short write?!!\n");
1148                                         fclose(ff);
1149                                         return -1;
1150                                 }
1151                                 while ((cur = ftello(ff)) < flength) {
1152                                         if (cur < 0) {
1153                                                 ast_log(AST_LOG_ERROR, "Unable to determine last write position for '%s': %s\n", args.filename, strerror(errno));
1154                                                 fclose(ff);
1155                                                 return -1;
1156                                         }
1157                                         fseeko(ff, length_length - vlen, SEEK_CUR);
1158                                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
1159                                                 ast_log(LOG_ERROR, "Short read?!!\n");
1160                                                 fclose(ff);
1161                                                 return -1;
1162                                         }
1163                                         /* Seek to where we last stopped writing */
1164                                         fseeko(ff, cur, SEEK_SET);
1165                                         if (fwrite(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf)) {
1166                                                 ast_log(LOG_ERROR, "Short write?!!\n");
1167                                                 fclose(ff);
1168                                                 return -1;
1169                                         }
1170                                 }
1171                                 fclose(ff);
1172                                 if (truncate(args.filename, flength - (length_length - vlen))) {
1173                                         ast_log(LOG_ERROR, "Truncation of file failed: %s\n", strerror(errno));
1174                                 }
1175                         } else {
1176                                 /* Most complex case - need to lengthen file */
1177                                 size_t vlen = vlength + (strchr(args.options, 'd') ? 0 : strlen(format2term(newline_format)));
1178                                 int64_t origlen = length_offset - offset_offset;
1179                                 off_t lastwritten = flength + vlen - origlen;
1180
1181                                 ast_debug(3, "offset=%s/%" PRId64 ", length=%s/%" PRId64 ", vlength=%" PRId64 ", flength=%" PRId64 "\n",
1182                                         args.offset, offset_offset, args.length, length_offset, vlength, flength);
1183
1184                                 fseeko(ff, flength - sizeof(fbuf), SEEK_SET);
1185                                 while (offset_offset + sizeof(fbuf) < ftello(ff)) {
1186                                         if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf)) {
1187                                                 ast_log(LOG_ERROR, "Short read?!!\n");
1188                                                 fclose(ff);
1189                                                 return -1;
1190                                         }
1191                                         fseeko(ff, sizeof(fbuf) - vlen - origlen, SEEK_CUR);
1192                                         if (fwrite(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf)) {
1193                                                 ast_log(LOG_ERROR, "Short write?!!\n");
1194                                                 fclose(ff);
1195                                                 return -1;
1196                                         }
1197                                         if ((lastwritten = ftello(ff) - sizeof(fbuf)) < offset_offset + sizeof(fbuf)) {
1198                                                 break;
1199                                         }
1200                                         fseeko(ff, 2 * sizeof(fbuf) + vlen - origlen, SEEK_CUR);
1201                                 }
1202                                 fseek(ff, length_offset, SEEK_SET);
1203                                 if (fread(fbuf, 1, sizeof(fbuf), ff) < sizeof(fbuf) && !feof(ff)) {
1204                                         ast_log(LOG_ERROR, "Short read?!!\n");
1205                                         fclose(ff);
1206                                         return -1;
1207                                 }
1208                                 fseek(ff, offset_offset, SEEK_SET);
1209                                 if (fwrite(value, 1, vlength, ff) < vlength) {
1210                                         ast_log(LOG_ERROR, "Short write?!!\n");
1211                                         fclose(ff);
1212                                         return -1;
1213                                 } else if (!strchr(args.options, 'd') && fwrite(format2term(newline_format), 1, strlen(format2term(newline_format)), ff) < strlen(format2term(newline_format))) {
1214                                         ast_log(LOG_ERROR, "Short write?!!\n");
1215                                         fclose(ff);
1216                                         return -1;
1217                                 } else {
1218                                         off_t curpos = ftello(ff);
1219                                         foplen = lastwritten - curpos;
1220                                         if (fwrite(fbuf, 1, foplen, ff) < foplen) {
1221                                                 ast_log(LOG_ERROR, "Short write?!!\n");
1222                                         }
1223                                 }
1224                                 fclose(ff);
1225                         }
1226                 }
1227         }
1228
1229         return 0;
1230 }
1231
1232 static struct ast_custom_function env_function = {
1233         .name = "ENV",
1234         .read = env_read,
1235         .write = env_write
1236 };
1237
1238 static struct ast_custom_function stat_function = {
1239         .name = "STAT",
1240         .read = stat_read,
1241         .read_max = 12,
1242 };
1243
1244 static struct ast_custom_function file_function = {
1245         .name = "FILE",
1246         .read2 = file_read,
1247         .write = file_write,
1248 };
1249
1250 static struct ast_custom_function file_count_line_function = {
1251         .name = "FILE_COUNT_LINE",
1252         .read2 = file_count_line,
1253         .read_max = 12,
1254 };
1255
1256 static struct ast_custom_function file_format_function = {
1257         .name = "FILE_FORMAT",
1258         .read2 = file_format,
1259         .read_max = 2,
1260 };
1261
1262 static int unload_module(void)
1263 {
1264         int res = 0;
1265
1266         res |= ast_custom_function_unregister(&env_function);
1267         res |= ast_custom_function_unregister(&stat_function);
1268         res |= ast_custom_function_unregister(&file_function);
1269         res |= ast_custom_function_unregister(&file_count_line_function);
1270         res |= ast_custom_function_unregister(&file_format_function);
1271
1272         return res;
1273 }
1274
1275 static int load_module(void)
1276 {
1277         int res = 0;
1278
1279         res |= ast_custom_function_register(&env_function);
1280         res |= ast_custom_function_register_escalating(&stat_function, AST_CFE_READ);
1281         res |= ast_custom_function_register_escalating(&file_function, AST_CFE_BOTH);
1282         res |= ast_custom_function_register_escalating(&file_count_line_function, AST_CFE_READ);
1283         res |= ast_custom_function_register_escalating(&file_format_function, AST_CFE_READ);
1284
1285         return res;
1286 }
1287
1288 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Environment/filesystem dialplan functions");