Coverage Report

Created: 2026-02-14 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/php-src/ext/standard/file.c
Line
Count
Source
1
/*
2
   +----------------------------------------------------------------------+
3
   | Copyright (c) The PHP Group                                          |
4
   +----------------------------------------------------------------------+
5
   | This source file is subject to version 3.01 of the PHP license,      |
6
   | that is bundled with this package in the file LICENSE, and is        |
7
   | available through the world-wide-web at the following url:           |
8
   | https://www.php.net/license/3_01.txt                                 |
9
   | If you did not receive a copy of the PHP license and are unable to   |
10
   | obtain it through the world-wide-web, please send a note to          |
11
   | license@php.net so we can mail you a copy immediately.               |
12
   +----------------------------------------------------------------------+
13
   | Authors: Rasmus Lerdorf <rasmus@php.net>                             |
14
   |          Stig Bakken <ssb@php.net>                                   |
15
   |          Andi Gutmans <andi@php.net>                                 |
16
   |          Zeev Suraski <zeev@php.net>                                 |
17
   | PHP 4.0 patches by Thies C. Arntzen (thies@thieso.net)               |
18
   | PHP streams by Wez Furlong (wez@thebrainroom.com)                    |
19
   +----------------------------------------------------------------------+
20
*/
21
22
/* {{{ includes */
23
24
#include "php.h"
25
#include "ext/standard/flock_compat.h"
26
#include "ext/standard/php_filestat.h"
27
#include "php_open_temporary_file.h"
28
#include "ext/standard/basic_functions.h"
29
#include "php_ini.h"
30
#include "zend_smart_str.h"
31
32
#include <stdio.h>
33
#include <stdlib.h>
34
#include <errno.h>
35
#include <wchar.h>
36
#include <sys/types.h>
37
#include <sys/stat.h>
38
#include <fcntl.h>
39
40
#ifdef PHP_WIN32
41
# include <io.h>
42
# define O_RDONLY _O_RDONLY
43
# include "win32/param.h"
44
# include "win32/winutil.h"
45
# include "win32/fnmatch.h"
46
# include "win32/ioutil.h"
47
#else
48
# ifdef HAVE_SYS_PARAM_H
49
#  include <sys/param.h>
50
# endif
51
# ifdef HAVE_SYS_SELECT_H
52
#  include <sys/select.h>
53
# endif
54
# include <sys/socket.h>
55
# include <netinet/in.h>
56
# include <netdb.h>
57
# ifdef HAVE_ARPA_INET_H
58
#  include <arpa/inet.h>
59
# endif
60
#endif
61
62
#include "php_string.h"
63
#include "file.h"
64
65
#ifdef HAVE_PWD_H
66
# ifdef PHP_WIN32
67
#  include "win32/pwd.h"
68
# else
69
#  include <pwd.h>
70
# endif
71
#endif
72
73
#include "fsock.h"
74
#include "fopen_wrappers.h"
75
#include "streamsfuncs.h" /* To define constants in the arg_info */
76
77
#ifdef HAVE_SYS_FILE_H
78
# include <sys/file.h>
79
#endif
80
81
#ifdef HAVE_SYS_MMAN_H
82
# include <sys/mman.h>
83
#endif
84
85
#include "scanf.h"
86
#include "zend_API.h"
87
88
#ifdef ZTS
89
int file_globals_id;
90
#else
91
php_file_globals file_globals;
92
#endif
93
94
#if defined(HAVE_FNMATCH) && !defined(PHP_WIN32)
95
# ifndef _GNU_SOURCE
96
#  define _GNU_SOURCE
97
# endif
98
# include <fnmatch.h>
99
#endif
100
101
#include "zend_attributes.h"
102
#include "file_arginfo.h"
103
104
/* }}} */
105
106
/* {{{ ZTS-stuff / Globals / Prototypes */
107
108
/* sharing globals is *evil* */
109
static int le_stream_context = FAILURE;
110
111
PHPAPI int php_le_stream_context(void)
112
27
{
113
27
  return le_stream_context;
114
27
}
115
/* }}} */
116
117
/* {{{ Module-Stuff */
118
static ZEND_RSRC_DTOR_FUNC(file_context_dtor)
119
27
{
120
27
  php_stream_context *context = (php_stream_context*)res->ptr;
121
27
  if (Z_TYPE(context->options) != IS_UNDEF) {
122
27
    zval_ptr_dtor(&context->options);
123
27
    ZVAL_UNDEF(&context->options);
124
27
  }
125
27
  php_stream_context_free(context);
126
27
}
127
128
static void file_globals_ctor(php_file_globals *file_globals_p)
129
16
{
130
16
  memset(file_globals_p, 0, sizeof(php_file_globals));
131
16
  file_globals_p->def_chunk_size = PHP_SOCK_CHUNK_SIZE;
132
16
}
133
134
static void file_globals_dtor(php_file_globals *file_globals_p)
135
0
{
136
0
#if defined(HAVE_GETHOSTBYNAME_R)
137
0
  if (file_globals_p->tmp_host_buf) {
138
0
    free(file_globals_p->tmp_host_buf);
139
0
  }
140
0
#endif
141
0
}
142
143
static PHP_INI_MH(OnUpdateAutoDetectLineEndings)
144
16
{
145
16
  if (zend_ini_parse_bool(new_value)) {
146
0
    zend_error(E_DEPRECATED, "auto_detect_line_endings is deprecated");
147
0
  }
148
16
  return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
149
16
}
150
151
PHP_INI_BEGIN()
152
  STD_PHP_INI_ENTRY("user_agent", NULL, PHP_INI_ALL, OnUpdateString, user_agent, php_file_globals, file_globals)
153
  STD_PHP_INI_ENTRY("from", NULL, PHP_INI_ALL, OnUpdateString, from_address, php_file_globals, file_globals)
154
  STD_PHP_INI_ENTRY("default_socket_timeout", "60", PHP_INI_ALL, OnUpdateLong, default_socket_timeout, php_file_globals, file_globals)
155
  STD_PHP_INI_BOOLEAN("auto_detect_line_endings", "0", PHP_INI_ALL, OnUpdateAutoDetectLineEndings, auto_detect_line_endings, php_file_globals, file_globals)
156
PHP_INI_END()
157
158
PHP_MINIT_FUNCTION(file)
159
16
{
160
16
  le_stream_context = zend_register_list_destructors_ex(file_context_dtor, NULL, "stream-context", module_number);
161
162
#ifdef ZTS
163
  ts_allocate_id(&file_globals_id, sizeof(php_file_globals), (ts_allocate_ctor) file_globals_ctor, (ts_allocate_dtor) file_globals_dtor);
164
#else
165
16
  file_globals_ctor(&file_globals);
166
16
#endif
167
168
16
  REGISTER_INI_ENTRIES();
169
170
16
  register_file_symbols(module_number);
171
172
16
  return SUCCESS;
173
16
}
174
/* }}} */
175
176
PHP_MSHUTDOWN_FUNCTION(file) /* {{{ */
177
0
{
178
0
#ifndef ZTS
179
0
  file_globals_dtor(&file_globals);
180
0
#endif
181
0
  return SUCCESS;
182
0
}
183
/* }}} */
184
185
PHPAPI void php_flock_common(php_stream *stream, zend_long operation,
186
  uint32_t operation_arg_num, zval *wouldblock, zval *return_value)
187
0
{
188
0
  int flock_values[] = { LOCK_SH, LOCK_EX, LOCK_UN };
189
0
  int act;
190
191
0
  act = operation & PHP_LOCK_UN;
192
0
  if (act < 1 || act > 3) {
193
0
    zend_argument_value_error(operation_arg_num, "must be one of LOCK_SH, LOCK_EX, or LOCK_UN");
194
0
    RETURN_THROWS();
195
0
  }
196
197
0
  if (wouldblock) {
198
0
    ZEND_TRY_ASSIGN_REF_LONG(wouldblock, 0);
199
0
  }
200
201
  /* flock_values contains all possible actions if (operation & PHP_LOCK_NB) we won't block on the lock */
202
0
  act = flock_values[act - 1] | (operation & PHP_LOCK_NB ? LOCK_NB : 0);
203
0
  if (php_stream_lock(stream, act)) {
204
0
    if (operation && errno == EWOULDBLOCK && wouldblock) {
205
0
      ZEND_TRY_ASSIGN_REF_LONG(wouldblock, 1);
206
0
    }
207
0
    RETURN_FALSE;
208
0
  }
209
0
  RETURN_TRUE;
210
0
}
211
212
/* {{{ Portable file locking */
213
PHP_FUNCTION(flock)
214
0
{
215
0
  zval *wouldblock = NULL;
216
0
  php_stream *stream;
217
0
  zend_long operation = 0;
218
219
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
220
0
    PHP_Z_PARAM_STREAM(stream)
221
0
    Z_PARAM_LONG(operation)
222
0
    Z_PARAM_OPTIONAL
223
0
    Z_PARAM_ZVAL(wouldblock)
224
0
  ZEND_PARSE_PARAMETERS_END();
225
226
0
  php_flock_common(stream, operation, 2, wouldblock, return_value);
227
0
}
228
/* }}} */
229
230
0
#define PHP_META_UNSAFE ".\\+*?[^]$() "
231
232
/* {{{ Extracts all meta tag content attributes from a file and returns an array */
233
PHP_FUNCTION(get_meta_tags)
234
0
{
235
0
  char *filename;
236
0
  size_t filename_len;
237
0
  bool use_include_path = 0;
238
0
  int in_tag = 0, done = 0;
239
0
  int looking_for_val = 0, have_name = 0, have_content = 0;
240
0
  int saw_name = 0, saw_content = 0;
241
0
  char *name = NULL, *value = NULL, *temp = NULL;
242
0
  php_meta_tags_token tok, tok_last;
243
0
  php_meta_tags_data md;
244
245
  /* Initialize our structure */
246
0
  memset(&md, 0, sizeof(md));
247
248
  /* Parse arguments */
249
0
  ZEND_PARSE_PARAMETERS_START(1, 2)
250
0
    Z_PARAM_PATH(filename, filename_len)
251
0
    Z_PARAM_OPTIONAL
252
0
    Z_PARAM_BOOL(use_include_path)
253
0
  ZEND_PARSE_PARAMETERS_END();
254
255
0
  md.stream = php_stream_open_wrapper(filename, "rb",
256
0
      (use_include_path ? USE_PATH : 0) | REPORT_ERRORS,
257
0
      NULL);
258
0
  if (!md.stream) {
259
0
    RETURN_FALSE;
260
0
  }
261
262
0
  array_init(return_value);
263
264
0
  tok_last = TOK_EOF;
265
266
0
  while (!done && (tok = php_next_meta_token(&md)) != TOK_EOF) {
267
0
    if (tok == TOK_ID) {
268
0
      if (tok_last == TOK_OPENTAG) {
269
0
        md.in_meta = !strcasecmp("meta", md.token_data);
270
0
      } else if (tok_last == TOK_SLASH && in_tag) {
271
0
        if (strcasecmp("head", md.token_data) == 0) {
272
          /* We are done here! */
273
0
          done = 1;
274
0
        }
275
0
      } else if (tok_last == TOK_EQUAL && looking_for_val) {
276
0
        if (saw_name) {
277
0
          if (name) efree(name);
278
          /* Get the NAME attr (Single word attr, non-quoted) */
279
0
          temp = name = estrndup(md.token_data, md.token_len);
280
281
0
          while (temp && *temp) {
282
0
            if (strchr(PHP_META_UNSAFE, *temp)) {
283
0
              *temp = '_';
284
0
            }
285
0
            temp++;
286
0
          }
287
288
0
          have_name = 1;
289
0
        } else if (saw_content) {
290
0
          if (value) efree(value);
291
0
          value = estrndup(md.token_data, md.token_len);
292
0
          have_content = 1;
293
0
        }
294
295
0
        looking_for_val = 0;
296
0
      } else {
297
0
        if (md.in_meta) {
298
0
          if (strcasecmp("name", md.token_data) == 0) {
299
0
            saw_name = 1;
300
0
            saw_content = 0;
301
0
            looking_for_val = 1;
302
0
          } else if (strcasecmp("content", md.token_data) == 0) {
303
0
            saw_name = 0;
304
0
            saw_content = 1;
305
0
            looking_for_val = 1;
306
0
          }
307
0
        }
308
0
      }
309
0
    } else if (tok == TOK_STRING && tok_last == TOK_EQUAL && looking_for_val) {
310
0
      if (saw_name) {
311
0
        if (name) efree(name);
312
        /* Get the NAME attr (Quoted single/double) */
313
0
        temp = name = estrndup(md.token_data, md.token_len);
314
315
0
        while (temp && *temp) {
316
0
          if (strchr(PHP_META_UNSAFE, *temp)) {
317
0
            *temp = '_';
318
0
          }
319
0
          temp++;
320
0
        }
321
322
0
        have_name = 1;
323
0
      } else if (saw_content) {
324
0
        if (value) efree(value);
325
0
        value = estrndup(md.token_data, md.token_len);
326
0
        have_content = 1;
327
0
      }
328
329
0
      looking_for_val = 0;
330
0
    } else if (tok == TOK_OPENTAG) {
331
0
      if (looking_for_val) {
332
0
        looking_for_val = 0;
333
0
        have_name = saw_name = 0;
334
0
        have_content = saw_content = 0;
335
0
      }
336
0
      in_tag = 1;
337
0
    } else if (tok == TOK_CLOSETAG) {
338
0
      if (have_name) {
339
        /* For BC */
340
0
        zend_str_tolower(name, strlen(name));
341
0
        if (have_content) {
342
0
          add_assoc_string(return_value, name, value);
343
0
        } else {
344
0
          add_assoc_string(return_value, name, "");
345
0
        }
346
347
0
        efree(name);
348
0
        if (value) efree(value);
349
0
      } else if (have_content) {
350
0
        efree(value);
351
0
      }
352
353
0
      name = value = NULL;
354
355
      /* Reset all of our flags */
356
0
      in_tag = looking_for_val = 0;
357
0
      have_name = saw_name = 0;
358
0
      have_content = saw_content = 0;
359
0
      md.in_meta = 0;
360
0
    }
361
362
0
    tok_last = tok;
363
364
0
    if (md.token_data)
365
0
      efree(md.token_data);
366
367
0
    md.token_data = NULL;
368
0
  }
369
370
0
  if (value) efree(value);
371
0
  if (name) efree(name);
372
0
  php_stream_close(md.stream);
373
0
}
374
/* }}} */
375
376
/* {{{ Read the entire file into a string */
377
PHP_FUNCTION(file_get_contents)
378
5
{
379
5
  char *filename;
380
5
  size_t filename_len;
381
5
  bool use_include_path = 0;
382
5
  php_stream *stream;
383
5
  zend_long offset = 0;
384
5
  zend_long maxlen;
385
5
  bool maxlen_is_null = 1;
386
5
  zval *zcontext = NULL;
387
5
  php_stream_context *context = NULL;
388
5
  zend_string *contents;
389
390
  /* Parse arguments */
391
15
  ZEND_PARSE_PARAMETERS_START(1, 5)
392
20
    Z_PARAM_PATH(filename, filename_len)
393
5
    Z_PARAM_OPTIONAL
394
10
    Z_PARAM_BOOL(use_include_path)
395
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
396
0
    Z_PARAM_LONG(offset)
397
0
    Z_PARAM_LONG_OR_NULL(maxlen, maxlen_is_null)
398
5
  ZEND_PARSE_PARAMETERS_END();
399
400
5
  if (maxlen_is_null) {
401
5
    maxlen = (ssize_t) PHP_STREAM_COPY_ALL;
402
5
  } else if (maxlen < 0) {
403
0
    zend_argument_value_error(5, "must be greater than or equal to 0");
404
0
    RETURN_THROWS();
405
0
  }
406
407
5
  context = php_stream_context_from_zval(zcontext, 0);
408
409
5
  stream = php_stream_open_wrapper_ex(filename, "rb",
410
5
        (use_include_path ? USE_PATH : 0) | REPORT_ERRORS,
411
5
        NULL, context);
412
5
  if (!stream) {
413
5
    RETURN_FALSE;
414
5
  }
415
416
  /* disabling the read buffer allows doing the whole transfer
417
     in just one read() system call */
418
0
  if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) {
419
0
    php_stream_set_option(stream, PHP_STREAM_OPTION_READ_BUFFER, PHP_STREAM_BUFFER_NONE, NULL);
420
0
  }
421
422
0
  if (offset != 0 && php_stream_seek(stream, offset, ((offset > 0) ? SEEK_SET : SEEK_END)) < 0) {
423
0
    php_error_docref(NULL, E_WARNING, "Failed to seek to position " ZEND_LONG_FMT " in the stream", offset);
424
0
    php_stream_close(stream);
425
0
    RETURN_FALSE;
426
0
  }
427
428
0
  if ((contents = php_stream_copy_to_mem(stream, maxlen, 0)) != NULL) {
429
0
    RETVAL_STR(contents);
430
0
  } else {
431
0
    RETVAL_EMPTY_STRING();
432
0
  }
433
434
0
  php_stream_close(stream);
435
0
}
436
/* }}} */
437
438
/* {{{ Write/Create a file with contents data and return the number of bytes written */
439
PHP_FUNCTION(file_put_contents)
440
0
{
441
0
  php_stream *stream;
442
0
  char *filename;
443
0
  size_t filename_len;
444
0
  zval *data;
445
0
  ssize_t numbytes = 0;
446
0
  zend_long flags = 0;
447
0
  zval *zcontext = NULL;
448
0
  php_stream_context *context = NULL;
449
0
  php_stream *srcstream = NULL;
450
0
  char mode[3] = "wb";
451
452
0
  ZEND_PARSE_PARAMETERS_START(2, 4)
453
0
    Z_PARAM_PATH(filename, filename_len)
454
0
    Z_PARAM_ZVAL(data)
455
0
    Z_PARAM_OPTIONAL
456
0
    Z_PARAM_LONG(flags)
457
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
458
0
  ZEND_PARSE_PARAMETERS_END();
459
460
0
  if (Z_TYPE_P(data) == IS_RESOURCE) {
461
0
    php_stream_from_zval(srcstream, data);
462
0
  }
463
464
0
  context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
465
466
0
  if (flags & PHP_FILE_APPEND) {
467
0
    mode[0] = 'a';
468
0
  } else if (flags & LOCK_EX) {
469
    /* check to make sure we are dealing with a regular file */
470
0
    if (php_memnstr(filename, "://", sizeof("://") - 1, filename + filename_len)) {
471
0
      if (strncasecmp(filename, "file://", sizeof("file://") - 1)) {
472
0
        php_error_docref(NULL, E_WARNING, "Exclusive locks may only be set for regular files");
473
0
        RETURN_FALSE;
474
0
      }
475
0
    }
476
0
    mode[0] = 'c';
477
0
  }
478
0
  mode[2] = '\0';
479
480
0
  stream = php_stream_open_wrapper_ex(filename, mode, ((flags & PHP_FILE_USE_INCLUDE_PATH) ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
481
0
  if (stream == NULL) {
482
0
    RETURN_FALSE;
483
0
  }
484
485
0
  if ((flags & LOCK_EX) && (!php_stream_supports_lock(stream) || php_stream_lock(stream, LOCK_EX))) {
486
0
    php_stream_close(stream);
487
0
    php_error_docref(NULL, E_WARNING, "Exclusive locks are not supported for this stream");
488
0
    RETURN_FALSE;
489
0
  }
490
491
0
  if (mode[0] == 'c') {
492
0
    php_stream_truncate_set_size(stream, 0);
493
0
  }
494
495
0
  switch (Z_TYPE_P(data)) {
496
0
    case IS_RESOURCE: {
497
0
      size_t len;
498
0
      if (php_stream_copy_to_stream_ex(srcstream, stream, PHP_STREAM_COPY_ALL, &len) != SUCCESS) {
499
0
        numbytes = -1;
500
0
      } else {
501
0
        if (len > ZEND_LONG_MAX) {
502
0
          php_error_docref(NULL, E_WARNING, "content truncated from %zu to " ZEND_LONG_FMT " bytes", len, ZEND_LONG_MAX);
503
0
          len = ZEND_LONG_MAX;
504
0
        }
505
0
        numbytes = len;
506
0
      }
507
0
      break;
508
0
    }
509
0
    case IS_NULL:
510
0
    case IS_LONG:
511
0
    case IS_DOUBLE:
512
0
    case IS_FALSE:
513
0
    case IS_TRUE:
514
0
      convert_to_string(data);
515
0
      ZEND_FALLTHROUGH;
516
0
    case IS_STRING:
517
0
      if (Z_STRLEN_P(data)) {
518
0
        numbytes = php_stream_write(stream, Z_STRVAL_P(data), Z_STRLEN_P(data));
519
0
        if (numbytes != -1 && numbytes != Z_STRLEN_P(data)) {
520
0
          php_error_docref(NULL, E_WARNING, "Only %zd of %zd bytes written, possibly out of free disk space", numbytes, Z_STRLEN_P(data));
521
0
          numbytes = -1;
522
0
        }
523
0
      }
524
0
      break;
525
526
0
    case IS_ARRAY:
527
0
      if (zend_hash_num_elements(Z_ARRVAL_P(data))) {
528
0
        ssize_t bytes_written;
529
0
        zval *tmp;
530
531
0
        ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(data), tmp) {
532
0
          zend_string *t;
533
0
          zend_string *str = zval_get_tmp_string(tmp, &t);
534
0
          if (ZSTR_LEN(str)) {
535
0
            numbytes += ZSTR_LEN(str);
536
0
            bytes_written = php_stream_write(stream, ZSTR_VAL(str), ZSTR_LEN(str));
537
0
            if (bytes_written != ZSTR_LEN(str)) {
538
0
              php_error_docref(NULL, E_WARNING, "Failed to write %zd bytes to %s", ZSTR_LEN(str), filename);
539
0
              zend_tmp_string_release(t);
540
0
              numbytes = -1;
541
0
              break;
542
0
            }
543
0
          }
544
0
          zend_tmp_string_release(t);
545
0
        } ZEND_HASH_FOREACH_END();
546
0
      }
547
0
      break;
548
549
0
    case IS_OBJECT:
550
0
      if (Z_OBJ_HT_P(data) != NULL) {
551
0
        zval out;
552
553
0
        if (zend_std_cast_object_tostring(Z_OBJ_P(data), &out, IS_STRING) == SUCCESS) {
554
0
          numbytes = php_stream_write(stream, Z_STRVAL(out), Z_STRLEN(out));
555
0
          if (numbytes != -1 && numbytes != Z_STRLEN(out)) {
556
0
            php_error_docref(NULL, E_WARNING, "Only %zd of %zd bytes written, possibly out of free disk space", numbytes, Z_STRLEN(out));
557
0
            numbytes = -1;
558
0
          }
559
0
          zval_ptr_dtor_str(&out);
560
0
          break;
561
0
        }
562
0
      }
563
0
      ZEND_FALLTHROUGH;
564
0
    default:
565
0
      numbytes = -1;
566
0
      break;
567
0
  }
568
0
  php_stream_close(stream);
569
570
0
  if (numbytes < 0) {
571
0
    RETURN_FALSE;
572
0
  }
573
574
0
  RETURN_LONG(numbytes);
575
0
}
576
/* }}} */
577
578
#define PHP_FILE_BUF_SIZE 80
579
580
/* {{{ Read entire file into an array */
581
PHP_FUNCTION(file)
582
4
{
583
4
  char *filename;
584
4
  size_t filename_len;
585
4
  char *p, *s, *e;
586
4
  int i = 0;
587
4
  char eol_marker = '\n';
588
4
  zend_long flags = 0;
589
4
  bool use_include_path;
590
4
  bool include_new_line;
591
4
  bool skip_blank_lines;
592
4
  php_stream *stream;
593
4
  zval *zcontext = NULL;
594
4
  php_stream_context *context = NULL;
595
4
  zend_string *target_buf;
596
597
  /* Parse arguments */
598
12
  ZEND_PARSE_PARAMETERS_START(1, 3)
599
16
    Z_PARAM_PATH(filename, filename_len)
600
4
    Z_PARAM_OPTIONAL
601
8
    Z_PARAM_LONG(flags)
602
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
603
4
  ZEND_PARSE_PARAMETERS_END();
604
605
4
  if ((flags & ~(PHP_FILE_USE_INCLUDE_PATH | PHP_FILE_IGNORE_NEW_LINES | PHP_FILE_SKIP_EMPTY_LINES | PHP_FILE_NO_DEFAULT_CONTEXT)) != 0) {
606
0
    zend_argument_value_error(2, "must be a valid flag value");
607
0
    RETURN_THROWS();
608
0
  }
609
610
4
  use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
611
4
  include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES);
612
4
  skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES;
613
614
4
  context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
615
616
4
  stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
617
4
  if (!stream) {
618
0
    RETURN_FALSE;
619
0
  }
620
621
  /* Initialize return array */
622
4
  array_init(return_value);
623
624
4
  if ((target_buf = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
625
0
    s = ZSTR_VAL(target_buf);
626
0
    e = ZSTR_VAL(target_buf) + ZSTR_LEN(target_buf);
627
628
0
    if (!(p = (char*)php_stream_locate_eol(stream, target_buf))) {
629
0
      p = e;
630
0
      goto parse_eol;
631
0
    }
632
633
0
    if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
634
0
      eol_marker = '\r';
635
0
    }
636
637
    /* for performance reasons the code is duplicated, so that the if (include_new_line)
638
     * will not need to be done for every single line in the file. */
639
0
    if (include_new_line) {
640
0
      do {
641
0
        p++;
642
0
parse_eol:
643
0
        add_index_stringl(return_value, i++, s, p-s);
644
0
        s = p;
645
0
      } while ((p = memchr(p, eol_marker, (e-p))));
646
0
    } else {
647
0
      do {
648
0
        int windows_eol = 0;
649
0
        if (p != ZSTR_VAL(target_buf) && eol_marker == '\n' && *(p - 1) == '\r') {
650
0
          windows_eol++;
651
0
        }
652
0
        if (skip_blank_lines && !(p-s-windows_eol)) {
653
0
          s = ++p;
654
0
          continue;
655
0
        }
656
0
        add_index_stringl(return_value, i++, s, p-s-windows_eol);
657
0
        s = ++p;
658
0
      } while ((p = memchr(p, eol_marker, (e-p))));
659
0
    }
660
661
    /* handle any leftovers of files without new lines */
662
0
    if (s != e) {
663
0
      p = e;
664
0
      goto parse_eol;
665
0
    }
666
667
0
    zend_string_efree(target_buf);
668
0
  }
669
670
4
  php_stream_close(stream);
671
4
}
672
/* }}} */
673
674
/* {{{ Create a unique filename in a directory */
675
PHP_FUNCTION(tempnam)
676
0
{
677
0
  char *dir, *prefix;
678
0
  size_t dir_len, prefix_len;
679
0
  zend_string *opened_path;
680
0
  int fd;
681
0
  zend_string *p;
682
683
0
  ZEND_PARSE_PARAMETERS_START(2, 2)
684
0
    Z_PARAM_PATH(dir, dir_len)
685
0
    Z_PARAM_PATH(prefix, prefix_len)
686
0
  ZEND_PARSE_PARAMETERS_END();
687
688
0
  p = php_basename(prefix, prefix_len, NULL, 0);
689
0
  if (ZSTR_LEN(p) >= 64) {
690
0
    ZSTR_VAL(p)[63] = '\0';
691
0
  }
692
693
0
  RETVAL_FALSE;
694
695
0
  if ((fd = php_open_temporary_fd_ex(dir, ZSTR_VAL(p), &opened_path, PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ALWAYS)) >= 0) {
696
0
    close(fd);
697
0
    RETVAL_STR(opened_path);
698
0
  }
699
0
  zend_string_release_ex(p, 0);
700
0
}
701
/* }}} */
702
703
/* {{{ Create a temporary file that will be deleted automatically after use */
704
PHP_FUNCTION(tmpfile)
705
0
{
706
0
  php_stream *stream;
707
708
0
  ZEND_PARSE_PARAMETERS_NONE();
709
710
0
  stream = php_stream_fopen_tmpfile();
711
712
0
  if (stream) {
713
0
    php_stream_to_zval(stream, return_value);
714
0
  } else {
715
0
    RETURN_FALSE;
716
0
  }
717
0
}
718
/* }}} */
719
720
/* {{{ Open a file or a URL and return a file pointer */
721
PHP_FUNCTION(fopen)
722
0
{
723
0
  char *filename, *mode;
724
0
  size_t filename_len, mode_len;
725
0
  bool use_include_path = 0;
726
0
  zval *zcontext = NULL;
727
0
  php_stream *stream;
728
0
  php_stream_context *context = NULL;
729
730
0
  ZEND_PARSE_PARAMETERS_START(2, 4)
731
0
    Z_PARAM_PATH(filename, filename_len)
732
0
    Z_PARAM_STRING(mode, mode_len)
733
0
    Z_PARAM_OPTIONAL
734
0
    Z_PARAM_BOOL(use_include_path)
735
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
736
0
  ZEND_PARSE_PARAMETERS_END();
737
738
0
  context = php_stream_context_from_zval(zcontext, 0);
739
740
0
  stream = php_stream_open_wrapper_ex(filename, mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
741
742
0
  if (stream == NULL) {
743
0
    RETURN_FALSE;
744
0
  }
745
746
0
  php_stream_to_zval(stream, return_value);
747
0
}
748
/* }}} */
749
750
/* {{{ Close an open file pointer */
751
PHPAPI PHP_FUNCTION(fclose)
752
0
{
753
0
  php_stream *stream;
754
755
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
756
0
    PHP_Z_PARAM_STREAM(stream)
757
0
  ZEND_PARSE_PARAMETERS_END();
758
759
0
  if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) {
760
0
    php_error_docref(NULL, E_WARNING, "cannot close the provided stream, as it must not be manually closed");
761
0
    RETURN_FALSE;
762
0
  }
763
764
0
  php_stream_free(stream,
765
0
    PHP_STREAM_FREE_KEEP_RSRC |
766
0
    (stream->is_persistent ? PHP_STREAM_FREE_CLOSE_PERSISTENT : PHP_STREAM_FREE_CLOSE));
767
768
0
  RETURN_TRUE;
769
0
}
770
/* }}} */
771
772
/* {{{ Execute a command and open either a read or a write pipe to it */
773
PHP_FUNCTION(popen)
774
0
{
775
0
  char *command, *mode;
776
0
  size_t command_len, mode_len;
777
0
  FILE *fp;
778
0
  php_stream *stream;
779
0
  char *posix_mode;
780
781
0
  ZEND_PARSE_PARAMETERS_START(2, 2)
782
0
    Z_PARAM_PATH(command, command_len)
783
0
    Z_PARAM_STRING(mode, mode_len)
784
0
  ZEND_PARSE_PARAMETERS_END();
785
786
0
  posix_mode = estrndup(mode, mode_len);
787
0
#ifndef PHP_WIN32
788
0
  {
789
0
    char *z = memchr(posix_mode, 'b', mode_len);
790
0
    if (z) {
791
0
      memmove(z, z + 1, mode_len - (z - posix_mode));
792
0
      mode_len--;
793
0
    }
794
0
  }
795
0
#endif
796
797
  /* Musl only partially validates the mode. Manually check it to ensure consistent behavior. */
798
0
  if (mode_len > 2 ||
799
0
    (mode_len == 1 && (*posix_mode != 'r' && *posix_mode != 'w')) ||
800
0
    (mode_len == 2 && (memcmp(posix_mode, "rb", 2) && memcmp(posix_mode, "wb", 2)))
801
0
  ) {
802
0
    zend_argument_value_error(2, "must be one of \"r\", \"rb\", \"w\", or \"wb\"");
803
0
    efree(posix_mode);
804
0
    RETURN_THROWS();
805
0
  }
806
807
0
  fp = VCWD_POPEN(command, posix_mode);
808
0
  if (!fp) {
809
0
    php_error_docref2(NULL, command, posix_mode, E_WARNING, "%s", strerror(errno));
810
0
    efree(posix_mode);
811
0
    RETURN_FALSE;
812
0
  }
813
814
0
  stream = php_stream_fopen_from_pipe(fp, mode);
815
816
0
  if (stream == NULL) {
817
0
    php_error_docref2(NULL, command, mode, E_WARNING, "%s", strerror(errno));
818
0
    RETVAL_FALSE;
819
0
  } else {
820
0
    php_stream_to_zval(stream, return_value);
821
0
  }
822
823
0
  efree(posix_mode);
824
0
}
825
/* }}} */
826
827
/* {{{ Close a file pointer opened by popen() */
828
PHP_FUNCTION(pclose)
829
0
{
830
0
  php_stream *stream;
831
832
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
833
0
    PHP_Z_PARAM_STREAM(stream)
834
0
  ZEND_PARSE_PARAMETERS_END();
835
836
0
  FG(pclose_wait) = 1;
837
0
  zend_list_close(stream->res);
838
0
  FG(pclose_wait) = 0;
839
0
  RETURN_LONG(FG(pclose_ret));
840
0
}
841
/* }}} */
842
843
/* {{{ Test for end-of-file on a file pointer */
844
PHPAPI PHP_FUNCTION(feof)
845
7
{
846
7
  php_stream *stream;
847
848
21
  ZEND_PARSE_PARAMETERS_START(1, 1)
849
28
    PHP_Z_PARAM_STREAM(stream)
850
7
  ZEND_PARSE_PARAMETERS_END();
851
852
4
  if (php_stream_eof(stream)) {
853
4
    RETURN_TRUE;
854
4
  } else {
855
0
    RETURN_FALSE;
856
0
  }
857
4
}
858
/* }}} */
859
860
/* {{{ Get a line from file pointer */
861
PHPAPI PHP_FUNCTION(fgets)
862
0
{
863
0
  zend_long len = 1024;
864
0
  bool len_is_null = 1;
865
0
  char *buf = NULL;
866
0
  size_t line_len = 0;
867
0
  zend_string *str;
868
0
  php_stream *stream;
869
870
0
  ZEND_PARSE_PARAMETERS_START(1, 2)
871
0
    PHP_Z_PARAM_STREAM(stream)
872
0
    Z_PARAM_OPTIONAL
873
0
    Z_PARAM_LONG_OR_NULL(len, len_is_null)
874
0
  ZEND_PARSE_PARAMETERS_END();
875
876
0
  if (len_is_null) {
877
    /* ask streams to give us a buffer of an appropriate size */
878
0
    buf = php_stream_get_line(stream, NULL, 0, &line_len);
879
0
    if (buf == NULL) {
880
0
      RETURN_FALSE;
881
0
    }
882
    // TODO: avoid reallocation ???
883
0
    RETVAL_STRINGL(buf, line_len);
884
0
    efree(buf);
885
0
  } else {
886
0
    if (len <= 0) {
887
0
      zend_argument_value_error(2, "must be greater than 0");
888
0
      RETURN_THROWS();
889
0
    }
890
891
0
    str = zend_string_alloc(len, 0);
892
0
    if (php_stream_get_line(stream, ZSTR_VAL(str), len, &line_len) == NULL) {
893
0
      zend_string_efree(str);
894
0
      RETURN_FALSE;
895
0
    }
896
    /* resize buffer if it's much larger than the result.
897
     * Only needed if the user requested a buffer size. */
898
0
    if (line_len < (size_t)len / 2) {
899
0
      str = zend_string_truncate(str, line_len, 0);
900
0
    } else {
901
0
      ZSTR_LEN(str) = line_len;
902
0
    }
903
0
    RETURN_NEW_STR(str);
904
0
  }
905
0
}
906
/* }}} */
907
908
/* {{{ Get a character from file pointer */
909
PHPAPI PHP_FUNCTION(fgetc)
910
0
{
911
0
  php_stream *stream;
912
913
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
914
0
    PHP_Z_PARAM_STREAM(stream)
915
0
  ZEND_PARSE_PARAMETERS_END();
916
917
0
  int result = php_stream_getc(stream);
918
919
0
  if (result == EOF) {
920
0
    RETVAL_FALSE;
921
0
  } else {
922
0
    RETURN_CHAR(result);
923
0
  }
924
0
}
925
/* }}} */
926
927
/* {{{ Implements a mostly ANSI compatible fscanf() */
928
PHP_FUNCTION(fscanf)
929
0
{
930
0
  int result, argc = 0;
931
0
  size_t format_len;
932
0
  zval *args = NULL;
933
0
  zval *file_handle;
934
0
  char *buf, *format;
935
0
  size_t len;
936
0
  void *what;
937
938
0
  ZEND_PARSE_PARAMETERS_START(2, -1)
939
0
    Z_PARAM_RESOURCE(file_handle)
940
0
    Z_PARAM_STRING(format, format_len)
941
0
    Z_PARAM_VARIADIC('*', args, argc)
942
0
  ZEND_PARSE_PARAMETERS_END();
943
944
0
  what = zend_fetch_resource2(Z_RES_P(file_handle), "File-Handle", php_file_le_stream(), php_file_le_pstream());
945
946
  /* we can't do a ZEND_VERIFY_RESOURCE(what), otherwise we end up
947
   * with a leak if we have an invalid filehandle. This needs changing
948
   * if the code behind ZEND_VERIFY_RESOURCE changed. - cc */
949
0
  if (!what) {
950
0
    RETURN_THROWS();
951
0
  }
952
953
0
  buf = php_stream_get_line((php_stream *) what, NULL, 0, &len);
954
0
  if (buf == NULL) {
955
0
    RETURN_FALSE;
956
0
  }
957
958
0
  result = php_sscanf_internal(buf, format, argc, args, 0, return_value);
959
960
0
  efree(buf);
961
962
0
  if (SCAN_ERROR_WRONG_PARAM_COUNT == result) {
963
0
    zend_wrong_param_count();
964
0
    RETURN_THROWS();
965
0
  }
966
0
}
967
/* }}} */
968
969
/* {{{ Binary-safe file write */
970
PHPAPI PHP_FUNCTION(fwrite)
971
0
{
972
0
  char *input;
973
0
  size_t inputlen;
974
0
  ssize_t ret;
975
0
  size_t num_bytes;
976
0
  zend_long maxlen = 0;
977
0
  bool maxlen_is_null = 1;
978
0
  php_stream *stream;
979
980
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
981
0
    PHP_Z_PARAM_STREAM(stream)
982
0
    Z_PARAM_STRING(input, inputlen)
983
0
    Z_PARAM_OPTIONAL
984
0
    Z_PARAM_LONG_OR_NULL(maxlen, maxlen_is_null)
985
0
  ZEND_PARSE_PARAMETERS_END();
986
987
0
  if (maxlen_is_null) {
988
0
    num_bytes = inputlen;
989
0
  } else if (maxlen <= 0) {
990
0
    num_bytes = 0;
991
0
  } else {
992
0
    num_bytes = MIN((size_t) maxlen, inputlen);
993
0
  }
994
995
0
  if (!num_bytes) {
996
0
    RETURN_LONG(0);
997
0
  }
998
999
0
  ret = php_stream_write(stream, input, num_bytes);
1000
0
  if (ret < 0) {
1001
0
    RETURN_FALSE;
1002
0
  }
1003
1004
0
  RETURN_LONG(ret);
1005
0
}
1006
/* }}} */
1007
1008
/* {{{ Flushes output */
1009
PHPAPI PHP_FUNCTION(fflush)
1010
0
{
1011
0
  int ret;
1012
0
  php_stream *stream;
1013
1014
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
1015
0
    PHP_Z_PARAM_STREAM(stream)
1016
0
  ZEND_PARSE_PARAMETERS_END();
1017
1018
0
  ret = php_stream_flush(stream);
1019
1020
0
  RETURN_BOOL(!ret);
1021
0
}
1022
/* }}} */
1023
1024
/* {{{ Rewind the position of a file pointer */
1025
PHPAPI PHP_FUNCTION(rewind)
1026
3
{
1027
3
  php_stream *stream;
1028
1029
6
  ZEND_PARSE_PARAMETERS_START(1, 1)
1030
6
    PHP_Z_PARAM_STREAM(stream)
1031
3
  ZEND_PARSE_PARAMETERS_END();
1032
1033
0
  RETURN_BOOL(-1 != php_stream_rewind(stream));
1034
0
}
1035
/* }}} */
1036
1037
/* {{{ Get file pointer's read/write position */
1038
PHPAPI PHP_FUNCTION(ftell)
1039
0
{
1040
0
  zend_long ret;
1041
0
  php_stream *stream;
1042
1043
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
1044
0
    PHP_Z_PARAM_STREAM(stream)
1045
0
  ZEND_PARSE_PARAMETERS_END();
1046
1047
0
  ret = php_stream_tell(stream);
1048
0
  if (ret == -1) {
1049
0
    RETURN_FALSE;
1050
0
  }
1051
0
  RETURN_LONG(ret);
1052
0
}
1053
/* }}} */
1054
1055
/* {{{ Seek on a file pointer */
1056
PHPAPI PHP_FUNCTION(fseek)
1057
0
{
1058
0
  zend_long offset, whence = SEEK_SET;
1059
0
  php_stream *stream;
1060
1061
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
1062
0
    PHP_Z_PARAM_STREAM(stream)
1063
0
    Z_PARAM_LONG(offset)
1064
0
    Z_PARAM_OPTIONAL
1065
0
    Z_PARAM_LONG(whence)
1066
0
  ZEND_PARSE_PARAMETERS_END();
1067
1068
0
  RETURN_LONG(php_stream_seek(stream, offset, (int) whence));
1069
0
}
1070
/* }}} */
1071
1072
/* {{{ Create a directory */
1073
PHP_FUNCTION(mkdir)
1074
0
{
1075
0
  char *dir;
1076
0
  size_t dir_len;
1077
0
  zval *zcontext = NULL;
1078
0
  zend_long mode = 0777;
1079
0
  bool recursive = 0;
1080
0
  php_stream_context *context;
1081
1082
0
  ZEND_PARSE_PARAMETERS_START(1, 4)
1083
0
    Z_PARAM_PATH(dir, dir_len)
1084
0
    Z_PARAM_OPTIONAL
1085
0
    Z_PARAM_LONG(mode)
1086
0
    Z_PARAM_BOOL(recursive)
1087
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
1088
0
  ZEND_PARSE_PARAMETERS_END();
1089
1090
0
  context = php_stream_context_from_zval(zcontext, 0);
1091
1092
0
  RETURN_BOOL(php_stream_mkdir(dir, (int)mode, (recursive ? PHP_STREAM_MKDIR_RECURSIVE : 0) | REPORT_ERRORS, context));
1093
0
}
1094
/* }}} */
1095
1096
/* {{{ Remove a directory */
1097
PHP_FUNCTION(rmdir)
1098
0
{
1099
0
  char *dir;
1100
0
  size_t dir_len;
1101
0
  zval *zcontext = NULL;
1102
0
  php_stream_context *context;
1103
1104
0
  ZEND_PARSE_PARAMETERS_START(1, 2)
1105
0
    Z_PARAM_PATH(dir, dir_len)
1106
0
    Z_PARAM_OPTIONAL
1107
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
1108
0
  ZEND_PARSE_PARAMETERS_END();
1109
1110
0
  context = php_stream_context_from_zval(zcontext, 0);
1111
1112
0
  RETURN_BOOL(php_stream_rmdir(dir, REPORT_ERRORS, context));
1113
0
}
1114
/* }}} */
1115
1116
/* {{{ Output a file or a URL */
1117
PHP_FUNCTION(readfile)
1118
0
{
1119
0
  char *filename;
1120
0
  size_t filename_len;
1121
0
  size_t size = 0;
1122
0
  bool use_include_path = 0;
1123
0
  zval *zcontext = NULL;
1124
0
  php_stream *stream;
1125
0
  php_stream_context *context = NULL;
1126
1127
0
  ZEND_PARSE_PARAMETERS_START(1, 3)
1128
0
    Z_PARAM_PATH(filename, filename_len)
1129
0
    Z_PARAM_OPTIONAL
1130
0
    Z_PARAM_BOOL(use_include_path)
1131
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
1132
0
  ZEND_PARSE_PARAMETERS_END();
1133
1134
0
  context = php_stream_context_from_zval(zcontext, 0);
1135
1136
0
  stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
1137
0
  if (stream) {
1138
0
    size = php_stream_passthru(stream);
1139
0
    php_stream_close(stream);
1140
0
    RETURN_LONG(size);
1141
0
  }
1142
1143
0
  RETURN_FALSE;
1144
0
}
1145
/* }}} */
1146
1147
/* {{{ Return or change the umask */
1148
PHP_FUNCTION(umask)
1149
0
{
1150
0
  zend_long mask = 0;
1151
0
  bool mask_is_null = 1;
1152
0
  int oldumask;
1153
1154
0
  ZEND_PARSE_PARAMETERS_START(0, 1)
1155
0
    Z_PARAM_OPTIONAL
1156
0
    Z_PARAM_LONG_OR_NULL(mask, mask_is_null)
1157
0
  ZEND_PARSE_PARAMETERS_END();
1158
1159
0
  oldumask = umask(077);
1160
1161
0
  if (BG(umask) == -1) {
1162
0
    BG(umask) = oldumask;
1163
0
  }
1164
1165
0
  if (mask_is_null) {
1166
0
    umask(oldumask);
1167
0
  } else {
1168
0
    umask((int) mask);
1169
0
  }
1170
1171
0
  RETURN_LONG(oldumask);
1172
0
}
1173
/* }}} */
1174
1175
/* {{{ Output all remaining data from a file pointer */
1176
PHPAPI PHP_FUNCTION(fpassthru)
1177
0
{
1178
0
  size_t size;
1179
0
  php_stream *stream;
1180
1181
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
1182
0
    PHP_Z_PARAM_STREAM(stream)
1183
0
  ZEND_PARSE_PARAMETERS_END();
1184
1185
0
  size = php_stream_passthru(stream);
1186
0
  RETURN_LONG(size);
1187
0
}
1188
/* }}} */
1189
1190
/* {{{ Rename a file */
1191
PHP_FUNCTION(rename)
1192
0
{
1193
0
  char *old_name, *new_name;
1194
0
  size_t old_name_len, new_name_len;
1195
0
  zval *zcontext = NULL;
1196
0
  php_stream_wrapper *wrapper;
1197
0
  php_stream_context *context;
1198
1199
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
1200
0
    Z_PARAM_PATH(old_name, old_name_len)
1201
0
    Z_PARAM_PATH(new_name, new_name_len)
1202
0
    Z_PARAM_OPTIONAL
1203
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
1204
0
  ZEND_PARSE_PARAMETERS_END();
1205
1206
0
  wrapper = php_stream_locate_url_wrapper(old_name, NULL, 0);
1207
1208
0
  if (!wrapper || !wrapper->wops) {
1209
0
    php_error_docref(NULL, E_WARNING, "Unable to locate stream wrapper");
1210
0
    RETURN_FALSE;
1211
0
  }
1212
1213
0
  if (!wrapper->wops->rename) {
1214
0
    php_error_docref(NULL, E_WARNING, "%s wrapper does not support renaming", wrapper->wops->label ? wrapper->wops->label : "Source");
1215
0
    RETURN_FALSE;
1216
0
  }
1217
1218
0
  if (wrapper != php_stream_locate_url_wrapper(new_name, NULL, 0)) {
1219
0
    php_error_docref(NULL, E_WARNING, "Cannot rename a file across wrapper types");
1220
0
    RETURN_FALSE;
1221
0
  }
1222
1223
0
  context = php_stream_context_from_zval(zcontext, 0);
1224
1225
0
  RETURN_BOOL(wrapper->wops->rename(wrapper, old_name, new_name, 0, context));
1226
0
}
1227
/* }}} */
1228
1229
/* {{{ Delete a file */
1230
PHP_FUNCTION(unlink)
1231
0
{
1232
0
  char *filename;
1233
0
  size_t filename_len;
1234
0
  php_stream_wrapper *wrapper;
1235
0
  zval *zcontext = NULL;
1236
0
  php_stream_context *context = NULL;
1237
1238
0
  ZEND_PARSE_PARAMETERS_START(1, 2)
1239
0
    Z_PARAM_PATH(filename, filename_len)
1240
0
    Z_PARAM_OPTIONAL
1241
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
1242
0
  ZEND_PARSE_PARAMETERS_END();
1243
1244
0
  context = php_stream_context_from_zval(zcontext, 0);
1245
1246
0
  wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
1247
1248
0
  if (!wrapper || !wrapper->wops) {
1249
0
    php_error_docref(NULL, E_WARNING, "Unable to locate stream wrapper");
1250
0
    RETURN_FALSE;
1251
0
  }
1252
1253
0
  if (!wrapper->wops->unlink) {
1254
0
    php_error_docref(NULL, E_WARNING, "%s does not allow unlinking", wrapper->wops->label ? wrapper->wops->label : "Wrapper");
1255
0
    RETURN_FALSE;
1256
0
  }
1257
0
  RETURN_BOOL(wrapper->wops->unlink(wrapper, filename, REPORT_ERRORS, context));
1258
0
}
1259
/* }}} */
1260
1261
PHP_FUNCTION(fsync)
1262
0
{
1263
0
  php_stream *stream;
1264
1265
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
1266
0
    PHP_Z_PARAM_STREAM(stream)
1267
0
  ZEND_PARSE_PARAMETERS_END();
1268
1269
0
  if (!php_stream_sync_supported(stream)) {
1270
0
    php_error_docref(NULL, E_WARNING, "Can't fsync this stream!");
1271
0
    RETURN_FALSE;
1272
0
  }
1273
1274
0
  RETURN_BOOL(php_stream_sync(stream, /* data_only */ 0) == 0);
1275
0
}
1276
1277
PHP_FUNCTION(fdatasync)
1278
0
{
1279
0
  php_stream *stream;
1280
1281
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
1282
0
    PHP_Z_PARAM_STREAM(stream)
1283
0
  ZEND_PARSE_PARAMETERS_END();
1284
1285
0
  if (!php_stream_sync_supported(stream)) {
1286
0
    php_error_docref(NULL, E_WARNING, "Can't fsync this stream!");
1287
0
    RETURN_FALSE;
1288
0
  }
1289
1290
0
  RETURN_BOOL(php_stream_sync(stream, /* data_only */ 1) == 0);
1291
0
}
1292
1293
/* {{{ Truncate file to 'size' length */
1294
PHP_FUNCTION(ftruncate)
1295
0
{
1296
0
  zend_long size;
1297
0
  php_stream *stream;
1298
1299
0
  ZEND_PARSE_PARAMETERS_START(2, 2)
1300
0
    PHP_Z_PARAM_STREAM(stream)
1301
0
    Z_PARAM_LONG(size)
1302
0
  ZEND_PARSE_PARAMETERS_END();
1303
1304
0
  if (size < 0) {
1305
0
    zend_argument_value_error(2, "must be greater than or equal to 0");
1306
0
    RETURN_THROWS();
1307
0
  }
1308
1309
0
  if (!php_stream_truncate_supported(stream)) {
1310
0
    php_error_docref(NULL, E_WARNING, "Can't truncate this stream!");
1311
0
    RETURN_FALSE;
1312
0
  }
1313
1314
0
  RETURN_BOOL(0 == php_stream_truncate_set_size(stream, size));
1315
0
}
1316
/* }}} */
1317
PHPAPI void php_fstat(php_stream *stream, zval *return_value)
1318
0
{
1319
0
  php_stream_statbuf stat_ssb;
1320
0
  zval stat_dev, stat_ino, stat_mode, stat_nlink, stat_uid, stat_gid, stat_rdev,
1321
0
     stat_size, stat_atime, stat_mtime, stat_ctime, stat_blksize, stat_blocks;
1322
0
  char *stat_sb_names[13] = {
1323
0
    "dev", "ino", "mode", "nlink", "uid", "gid", "rdev",
1324
0
    "size", "atime", "mtime", "ctime", "blksize", "blocks"
1325
0
  };
1326
1327
0
  if (php_stream_stat(stream, &stat_ssb)) {
1328
0
    RETURN_FALSE;
1329
0
  }
1330
1331
0
  array_init(return_value);
1332
1333
0
  ZVAL_LONG(&stat_dev, stat_ssb.sb.st_dev);
1334
0
  ZVAL_LONG(&stat_ino, stat_ssb.sb.st_ino);
1335
0
  ZVAL_LONG(&stat_mode, stat_ssb.sb.st_mode);
1336
0
  ZVAL_LONG(&stat_nlink, stat_ssb.sb.st_nlink);
1337
0
  ZVAL_LONG(&stat_uid, stat_ssb.sb.st_uid);
1338
0
  ZVAL_LONG(&stat_gid, stat_ssb.sb.st_gid);
1339
0
#ifdef HAVE_STRUCT_STAT_ST_RDEV
1340
0
  ZVAL_LONG(&stat_rdev, stat_ssb.sb.st_rdev);
1341
#else
1342
  ZVAL_LONG(&stat_rdev, -1);
1343
#endif
1344
0
  ZVAL_LONG(&stat_size, stat_ssb.sb.st_size);
1345
0
  ZVAL_LONG(&stat_atime, stat_ssb.sb.st_atime);
1346
0
  ZVAL_LONG(&stat_mtime, stat_ssb.sb.st_mtime);
1347
0
  ZVAL_LONG(&stat_ctime, stat_ssb.sb.st_ctime);
1348
0
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1349
0
  ZVAL_LONG(&stat_blksize, stat_ssb.sb.st_blksize);
1350
#else
1351
  ZVAL_LONG(&stat_blksize,-1);
1352
#endif
1353
0
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1354
0
  ZVAL_LONG(&stat_blocks, stat_ssb.sb.st_blocks);
1355
#else
1356
  ZVAL_LONG(&stat_blocks,-1);
1357
#endif
1358
  /* Store numeric indexes in proper order */
1359
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_dev);
1360
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_ino);
1361
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_mode);
1362
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_nlink);
1363
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_uid);
1364
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_gid);
1365
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_rdev);
1366
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_size);
1367
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_atime);
1368
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_mtime);
1369
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_ctime);
1370
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_blksize);
1371
0
  zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_blocks);
1372
1373
  /* Store string indexes referencing the same zval*/
1374
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[0], strlen(stat_sb_names[0]), &stat_dev);
1375
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[1], strlen(stat_sb_names[1]), &stat_ino);
1376
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[2], strlen(stat_sb_names[2]), &stat_mode);
1377
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[3], strlen(stat_sb_names[3]), &stat_nlink);
1378
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[4], strlen(stat_sb_names[4]), &stat_uid);
1379
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[5], strlen(stat_sb_names[5]), &stat_gid);
1380
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[6], strlen(stat_sb_names[6]), &stat_rdev);
1381
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[7], strlen(stat_sb_names[7]), &stat_size);
1382
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[8], strlen(stat_sb_names[8]), &stat_atime);
1383
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[9], strlen(stat_sb_names[9]), &stat_mtime);
1384
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[10], strlen(stat_sb_names[10]), &stat_ctime);
1385
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[11], strlen(stat_sb_names[11]), &stat_blksize);
1386
0
  zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[12], strlen(stat_sb_names[12]), &stat_blocks);
1387
0
}
1388
1389
/* {{{ Stat() on a filehandle */
1390
PHP_FUNCTION(fstat)
1391
0
{
1392
0
  php_stream *stream;
1393
1394
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
1395
0
    PHP_Z_PARAM_STREAM(stream)
1396
0
  ZEND_PARSE_PARAMETERS_END();
1397
1398
0
  php_fstat(stream, return_value);
1399
0
}
1400
/* }}} */
1401
1402
/* {{{ Copy a file */
1403
PHP_FUNCTION(copy)
1404
0
{
1405
0
  char *source, *target;
1406
0
  size_t source_len, target_len;
1407
0
  zval *zcontext = NULL;
1408
0
  php_stream_context *context;
1409
1410
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
1411
0
    Z_PARAM_PATH(source, source_len)
1412
0
    Z_PARAM_PATH(target, target_len)
1413
0
    Z_PARAM_OPTIONAL
1414
0
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
1415
0
  ZEND_PARSE_PARAMETERS_END();
1416
1417
0
  if (php_stream_locate_url_wrapper(source, NULL, 0) == &php_plain_files_wrapper && php_check_open_basedir(source)) {
1418
0
    RETURN_FALSE;
1419
0
  }
1420
1421
0
  context = php_stream_context_from_zval(zcontext, 0);
1422
1423
0
  RETURN_BOOL(php_copy_file_ctx(source, target, 0, context) == SUCCESS);
1424
0
}
1425
/* }}} */
1426
1427
/* {{{ php_copy_file */
1428
PHPAPI zend_result php_copy_file(const char *src, const char *dest)
1429
0
{
1430
0
  return php_copy_file_ctx(src, dest, 0, NULL);
1431
0
}
1432
/* }}} */
1433
1434
/* {{{ php_copy_file_ex */
1435
PHPAPI zend_result php_copy_file_ex(const char *src, const char *dest, int src_flags)
1436
0
{
1437
0
  return php_copy_file_ctx(src, dest, src_flags, NULL);
1438
0
}
1439
/* }}} */
1440
1441
/* {{{ php_copy_file_ctx */
1442
PHPAPI zend_result php_copy_file_ctx(const char *src, const char *dest, int src_flags, php_stream_context *ctx)
1443
0
{
1444
0
  php_stream *srcstream = NULL, *deststream = NULL;
1445
0
  zend_result ret = FAILURE;
1446
0
  php_stream_statbuf src_s, dest_s;
1447
0
  int src_stat_flags = (src_flags & STREAM_DISABLE_OPEN_BASEDIR) ? PHP_STREAM_URL_STAT_IGNORE_OPEN_BASEDIR : 0;
1448
1449
0
  switch (php_stream_stat_path_ex(src, src_stat_flags, &src_s, ctx)) {
1450
0
    case -1:
1451
      /* non-statable stream */
1452
0
      goto safe_to_copy;
1453
0
      break;
1454
0
    case 0:
1455
0
      break;
1456
0
    default: /* failed to stat file, does not exist? */
1457
0
      return ret;
1458
0
  }
1459
0
  if (S_ISDIR(src_s.sb.st_mode)) {
1460
0
    php_error_docref(NULL, E_WARNING, "The first argument to copy() function cannot be a directory");
1461
0
    return FAILURE;
1462
0
  }
1463
1464
0
  switch (php_stream_stat_path_ex(dest, PHP_STREAM_URL_STAT_QUIET, &dest_s, ctx)) {
1465
0
    case -1:
1466
      /* non-statable stream */
1467
0
      goto safe_to_copy;
1468
0
      break;
1469
0
    case 0:
1470
0
      break;
1471
0
    default: /* failed to stat file, does not exist? */
1472
0
      return ret;
1473
0
  }
1474
0
  if (S_ISDIR(dest_s.sb.st_mode)) {
1475
0
    php_error_docref(NULL, E_WARNING, "The second argument to copy() function cannot be a directory");
1476
0
    return FAILURE;
1477
0
  }
1478
0
  if (!src_s.sb.st_ino || !dest_s.sb.st_ino) {
1479
0
    goto no_stat;
1480
0
  }
1481
0
  if (src_s.sb.st_ino == dest_s.sb.st_ino && src_s.sb.st_dev == dest_s.sb.st_dev) {
1482
0
    return ret;
1483
0
  } else {
1484
0
    goto safe_to_copy;
1485
0
  }
1486
0
no_stat:
1487
0
  {
1488
0
    char *sp, *dp;
1489
0
    int res;
1490
1491
0
    if ((sp = expand_filepath(src, NULL)) == NULL) {
1492
0
      return ret;
1493
0
    }
1494
0
    if ((dp = expand_filepath(dest, NULL)) == NULL) {
1495
0
      efree(sp);
1496
0
      goto safe_to_copy;
1497
0
    }
1498
1499
0
    res =
1500
0
#ifndef PHP_WIN32
1501
0
      !strcmp(sp, dp);
1502
#else
1503
      !strcasecmp(sp, dp);
1504
#endif
1505
1506
0
    efree(sp);
1507
0
    efree(dp);
1508
0
    if (res) {
1509
0
      return ret;
1510
0
    }
1511
0
  }
1512
0
safe_to_copy:
1513
1514
0
  srcstream = php_stream_open_wrapper_ex(src, "rb", src_flags | REPORT_ERRORS, NULL, ctx);
1515
1516
0
  if (!srcstream) {
1517
0
    return ret;
1518
0
  }
1519
1520
0
  deststream = php_stream_open_wrapper_ex(dest, "wb", REPORT_ERRORS, NULL, ctx);
1521
1522
0
  if (deststream) {
1523
0
    ret = php_stream_copy_to_stream_ex(srcstream, deststream, PHP_STREAM_COPY_ALL, NULL);
1524
0
  }
1525
0
  php_stream_close(srcstream);
1526
0
  if (deststream) {
1527
0
    php_stream_close(deststream);
1528
0
  }
1529
0
  return ret;
1530
0
}
1531
/* }}} */
1532
1533
/* {{{ Binary-safe file read */
1534
PHPAPI PHP_FUNCTION(fread)
1535
0
{
1536
0
  zend_long len;
1537
0
  php_stream *stream;
1538
0
  zend_string *str;
1539
1540
0
  ZEND_PARSE_PARAMETERS_START(2, 2)
1541
0
    PHP_Z_PARAM_STREAM(stream)
1542
0
    Z_PARAM_LONG(len)
1543
0
  ZEND_PARSE_PARAMETERS_END();
1544
1545
0
  if (len <= 0) {
1546
0
    zend_argument_value_error(2, "must be greater than 0");
1547
0
    RETURN_THROWS();
1548
0
  }
1549
1550
0
  str = php_stream_read_to_str(stream, len);
1551
0
  if (!str) {
1552
0
    RETURN_FALSE;
1553
0
  }
1554
1555
0
  RETURN_STR(str);
1556
0
}
1557
/* }}} */
1558
1559
static const char *php_fgetcsv_lookup_trailing_spaces(const char *ptr, size_t len) /* {{{ */
1560
5.84k
{
1561
5.84k
  int inc_len;
1562
5.84k
  unsigned char last_chars[2] = { 0, 0 };
1563
1564
106k
  while (len > 0) {
1565
101k
    inc_len = (*ptr == '\0' ? 1 : php_mblen(ptr, len));
1566
101k
    switch (inc_len) {
1567
93
      case -2:
1568
24.1k
      case -1:
1569
24.1k
        inc_len = 1;
1570
24.1k
        php_mb_reset();
1571
24.1k
        break;
1572
0
      case 0:
1573
0
        goto quit_loop;
1574
76.4k
      case 1:
1575
76.9k
      default:
1576
76.9k
        last_chars[0] = last_chars[1];
1577
76.9k
        last_chars[1] = *ptr;
1578
76.9k
        break;
1579
101k
    }
1580
101k
    ptr += inc_len;
1581
101k
    len -= inc_len;
1582
101k
  }
1583
5.84k
quit_loop:
1584
5.84k
  switch (last_chars[1]) {
1585
96
    case '\n':
1586
96
      if (last_chars[0] == '\r') {
1587
0
        return ptr - 2;
1588
0
      }
1589
96
      ZEND_FALLTHROUGH;
1590
105
    case '\r':
1591
105
      return ptr - 1;
1592
5.84k
  }
1593
5.74k
  return ptr;
1594
5.84k
}
1595
/* }}} */
1596
1597
PHPAPI int php_csv_handle_escape_argument(const zend_string *escape_str, uint32_t arg_num)
1598
99
{
1599
99
  if (escape_str != NULL) {
1600
0
    if (ZSTR_LEN(escape_str) > 1) {
1601
0
      zend_argument_value_error(arg_num, "must be empty or a single character");
1602
0
      return PHP_CSV_ESCAPE_ERROR;
1603
0
    }
1604
0
    if (ZSTR_LEN(escape_str) < 1) {
1605
0
      return PHP_CSV_NO_ESCAPE;
1606
0
    } else {
1607
      /* use first character from string */
1608
0
      return (unsigned char) ZSTR_VAL(escape_str)[0];
1609
0
    }
1610
99
  } else {
1611
99
    php_error_docref(NULL, E_DEPRECATED, "the $escape parameter must be provided as its default value will change");
1612
99
    if (UNEXPECTED(EG(exception))) {
1613
0
      return PHP_CSV_ESCAPE_ERROR;
1614
0
    }
1615
99
    return (unsigned char) '\\';
1616
99
  }
1617
99
}
1618
1619
0
#define FPUTCSV_FLD_CHK(c) memchr(ZSTR_VAL(field_str), c, ZSTR_LEN(field_str))
1620
1621
/* {{{ Format line as CSV and write to file pointer */
1622
PHP_FUNCTION(fputcsv)
1623
0
{
1624
0
  char delimiter = ',';         /* allow this to be set as parameter */
1625
0
  char enclosure = '"';         /* allow this to be set as parameter */
1626
0
  php_stream *stream;
1627
0
  zval *fields = NULL;
1628
0
  ssize_t ret;
1629
0
  char *delimiter_str = NULL, *enclosure_str = NULL;
1630
0
  zend_string *escape_str = NULL;
1631
0
  size_t delimiter_str_len = 0, enclosure_str_len = 0;
1632
0
  zend_string *eol_str = NULL;
1633
1634
0
  ZEND_PARSE_PARAMETERS_START(2, 6)
1635
0
    PHP_Z_PARAM_STREAM(stream)
1636
0
    Z_PARAM_ARRAY(fields)
1637
0
    Z_PARAM_OPTIONAL
1638
0
    Z_PARAM_STRING(delimiter_str, delimiter_str_len)
1639
0
    Z_PARAM_STRING(enclosure_str, enclosure_str_len)
1640
0
    Z_PARAM_STR(escape_str)
1641
0
    Z_PARAM_STR_OR_NULL(eol_str)
1642
0
  ZEND_PARSE_PARAMETERS_END();
1643
1644
0
  if (delimiter_str != NULL) {
1645
    /* Make sure that there is at least one character in string */
1646
0
    if (delimiter_str_len != 1) {
1647
0
      zend_argument_value_error(3, "must be a single character");
1648
0
      RETURN_THROWS();
1649
0
    }
1650
1651
    /* use first character from string */
1652
0
    delimiter = *delimiter_str;
1653
0
  }
1654
1655
0
  if (enclosure_str != NULL) {
1656
0
    if (enclosure_str_len != 1) {
1657
0
      zend_argument_value_error(4, "must be a single character");
1658
0
      RETURN_THROWS();
1659
0
    }
1660
    /* use first character from string */
1661
0
    enclosure = *enclosure_str;
1662
0
  }
1663
1664
0
  int escape_char = php_csv_handle_escape_argument(escape_str, 5);
1665
0
  if (escape_char == PHP_CSV_ESCAPE_ERROR) {
1666
0
    RETURN_THROWS();
1667
0
  }
1668
1669
0
  ret = php_fputcsv(stream, fields, delimiter, enclosure, escape_char, eol_str);
1670
0
  if (ret < 0) {
1671
0
    RETURN_FALSE;
1672
0
  }
1673
0
  RETURN_LONG(ret);
1674
0
}
1675
/* }}} */
1676
1677
/* {{{ PHPAPI size_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, int escape_char, zend_string *eol_str) */
1678
PHPAPI ssize_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, int escape_char, zend_string *eol_str)
1679
0
{
1680
0
  uint32_t count, i = 0;
1681
0
  size_t ret;
1682
0
  zval *field_tmp;
1683
0
  smart_str csvline = {0};
1684
1685
0
  ZEND_ASSERT((escape_char >= 0 && escape_char <= UCHAR_MAX) || escape_char == PHP_CSV_NO_ESCAPE);
1686
0
  count = zend_hash_num_elements(Z_ARRVAL_P(fields));
1687
0
  ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(fields), field_tmp) {
1688
0
    zend_string *tmp_field_str;
1689
0
    zend_string *field_str = zval_get_tmp_string(field_tmp, &tmp_field_str);
1690
1691
    /* enclose a field that contains a delimiter, an enclosure character, or a newline */
1692
0
    if (FPUTCSV_FLD_CHK(delimiter) ||
1693
0
      FPUTCSV_FLD_CHK(enclosure) ||
1694
0
      (escape_char != PHP_CSV_NO_ESCAPE && FPUTCSV_FLD_CHK(escape_char)) ||
1695
0
      FPUTCSV_FLD_CHK('\n') ||
1696
0
      FPUTCSV_FLD_CHK('\r') ||
1697
0
      FPUTCSV_FLD_CHK('\t') ||
1698
0
      FPUTCSV_FLD_CHK(' ')
1699
0
    ) {
1700
0
      char *ch = ZSTR_VAL(field_str);
1701
0
      char *end = ch + ZSTR_LEN(field_str);
1702
0
      int escaped = 0;
1703
1704
0
      smart_str_appendc(&csvline, enclosure);
1705
0
      while (ch < end) {
1706
0
        if (escape_char != PHP_CSV_NO_ESCAPE && *ch == escape_char) {
1707
0
          escaped = 1;
1708
0
        } else if (!escaped && *ch == enclosure) {
1709
0
          smart_str_appendc(&csvline, enclosure);
1710
0
        } else {
1711
0
          escaped = 0;
1712
0
        }
1713
0
        smart_str_appendc(&csvline, *ch);
1714
0
        ch++;
1715
0
      }
1716
0
      smart_str_appendc(&csvline, enclosure);
1717
0
    } else {
1718
0
      smart_str_append(&csvline, field_str);
1719
0
    }
1720
1721
0
    if (++i != count) {
1722
0
      smart_str_appendl(&csvline, &delimiter, 1);
1723
0
    }
1724
0
    zend_tmp_string_release(tmp_field_str);
1725
0
  } ZEND_HASH_FOREACH_END();
1726
1727
0
  if (eol_str) {
1728
0
    smart_str_append(&csvline, eol_str);
1729
0
  } else {
1730
0
    smart_str_appendc(&csvline, '\n');
1731
0
  }
1732
0
  smart_str_0(&csvline);
1733
1734
0
  ret = php_stream_write(stream, ZSTR_VAL(csvline.s), ZSTR_LEN(csvline.s));
1735
1736
0
  smart_str_free(&csvline);
1737
1738
0
  return ret;
1739
0
}
1740
/* }}} */
1741
1742
/* {{{ Get line from file pointer and parse for CSV fields */
1743
PHP_FUNCTION(fgetcsv)
1744
0
{
1745
0
  char delimiter = ','; /* allow this to be set as parameter */
1746
0
  char enclosure = '"'; /* allow this to be set as parameter */
1747
1748
0
  zend_long len = 0;
1749
0
  size_t buf_len;
1750
0
  char *buf;
1751
0
  php_stream *stream;
1752
1753
0
  bool len_is_null = 1;
1754
0
  char *delimiter_str = NULL;
1755
0
  size_t delimiter_str_len = 0;
1756
0
  char *enclosure_str = NULL;
1757
0
  size_t enclosure_str_len = 0;
1758
0
  zend_string *escape_str = NULL;
1759
1760
0
  ZEND_PARSE_PARAMETERS_START(1, 5)
1761
0
    PHP_Z_PARAM_STREAM(stream)
1762
0
    Z_PARAM_OPTIONAL
1763
0
    Z_PARAM_LONG_OR_NULL(len, len_is_null)
1764
0
    Z_PARAM_STRING(delimiter_str, delimiter_str_len)
1765
0
    Z_PARAM_STRING(enclosure_str, enclosure_str_len)
1766
0
    Z_PARAM_STR(escape_str)
1767
0
  ZEND_PARSE_PARAMETERS_END();
1768
1769
0
  if (delimiter_str != NULL) {
1770
    /* Make sure that there is at least one character in string */
1771
0
    if (delimiter_str_len != 1) {
1772
0
      zend_argument_value_error(3, "must be a single character");
1773
0
      RETURN_THROWS();
1774
0
    }
1775
1776
    /* use first character from string */
1777
0
    delimiter = delimiter_str[0];
1778
0
  }
1779
1780
0
  if (enclosure_str != NULL) {
1781
0
    if (enclosure_str_len != 1) {
1782
0
      zend_argument_value_error(4, "must be a single character");
1783
0
      RETURN_THROWS();
1784
0
    }
1785
1786
    /* use first character from string */
1787
0
    enclosure = enclosure_str[0];
1788
0
  }
1789
1790
0
  int escape_char = php_csv_handle_escape_argument(escape_str, 5);
1791
0
  if (escape_char == PHP_CSV_ESCAPE_ERROR) {
1792
0
    RETURN_THROWS();
1793
0
  }
1794
1795
0
  if (len_is_null || len == 0) {
1796
0
    len = -1;
1797
0
  } else if (len < 0 || len > (ZEND_LONG_MAX - 1)) {
1798
0
    zend_argument_value_error(2, "must be between 0 and " ZEND_LONG_FMT, (ZEND_LONG_MAX - 1));
1799
0
    RETURN_THROWS();
1800
0
  }
1801
1802
0
  if (len < 0) {
1803
0
    if ((buf = php_stream_get_line(stream, NULL, 0, &buf_len)) == NULL) {
1804
0
      RETURN_FALSE;
1805
0
    }
1806
0
  } else {
1807
0
    buf = emalloc(len + 1);
1808
0
    if (php_stream_get_line(stream, buf, len + 1, &buf_len) == NULL) {
1809
0
      efree(buf);
1810
0
      RETURN_FALSE;
1811
0
    }
1812
0
  }
1813
1814
0
  HashTable *values = php_fgetcsv(stream, delimiter, enclosure, escape_char, buf_len, buf);
1815
0
  if (values == NULL) {
1816
0
    values = php_bc_fgetcsv_empty_line();
1817
0
  }
1818
0
  RETURN_ARR(values);
1819
0
}
1820
/* }}} */
1821
1822
PHPAPI HashTable *php_bc_fgetcsv_empty_line(void)
1823
0
{
1824
0
  HashTable *values = zend_new_array(1);
1825
0
  zval tmp;
1826
0
  ZVAL_NULL(&tmp);
1827
0
  zend_hash_next_index_insert(values, &tmp);
1828
0
  return values;
1829
0
}
1830
1831
PHPAPI HashTable *php_fgetcsv(php_stream *stream, char delimiter, char enclosure, int escape_char, size_t buf_len, char *buf) /* {{{ */
1832
99
{
1833
99
  char *temp, *bptr, *line_end, *limit;
1834
99
  size_t temp_len, line_end_len;
1835
99
  int inc_len;
1836
99
  bool first_field = true;
1837
1838
99
  ZEND_ASSERT((escape_char >= 0 && escape_char <= UCHAR_MAX) || escape_char == PHP_CSV_NO_ESCAPE);
1839
1840
  /* initialize internal state */
1841
99
  php_mb_reset();
1842
1843
  /* Now into new section that parses buf for delimiter/enclosure fields */
1844
1845
  /* Strip trailing space from buf, saving end of line in case required for enclosure field */
1846
1847
99
  bptr = buf;
1848
99
  line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len);
1849
99
  line_end_len = buf_len - (size_t)(limit - buf);
1850
1851
  /* reserve workspace for building each individual field */
1852
99
  temp_len = buf_len;
1853
99
  temp = emalloc(temp_len + line_end_len + 1);
1854
1855
  /* Initialize values HashTable */
1856
99
  HashTable *values = zend_new_array(0);
1857
1858
  /* Main loop to read CSV fields */
1859
  /* NB this routine will return NULL for a blank line */
1860
7.29k
  do {
1861
7.29k
    char *comp_end, *hunk_begin;
1862
7.29k
    char *tptr = temp;
1863
1864
7.29k
    inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
1865
7.29k
    if (inc_len == 1) {
1866
6.75k
      char *tmp = bptr;
1867
7.04k
      while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) {
1868
291
        tmp++;
1869
291
      }
1870
6.75k
      if (*tmp == enclosure && tmp < limit) {
1871
1.54k
        bptr = tmp;
1872
1.54k
      }
1873
6.75k
    }
1874
1875
7.29k
    if (first_field && bptr == line_end) {
1876
0
      zend_array_destroy(values);
1877
0
      values = NULL;
1878
0
      break;
1879
0
    }
1880
7.29k
    first_field = false;
1881
    /* 2. Read field, leaving bptr pointing at start of next field */
1882
7.29k
    if (inc_len != 0 && *bptr == enclosure) {
1883
1.54k
      int state = 0;
1884
1885
1.54k
      bptr++; /* move on to first character in field */
1886
1.54k
      hunk_begin = bptr;
1887
1888
      /* 2A. handle enclosure delimited field */
1889
36.2k
      for (;;) {
1890
36.2k
        switch (inc_len) {
1891
12
          case 0:
1892
12
            switch (state) {
1893
6
              case 2:
1894
6
                tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin - 1));
1895
6
                hunk_begin = bptr;
1896
6
                goto quit_loop_2;
1897
1898
0
              case 1:
1899
0
                tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin));
1900
0
                hunk_begin = bptr;
1901
0
                ZEND_FALLTHROUGH;
1902
1903
6
              case 0: {
1904
6
                if (hunk_begin != line_end) {
1905
3
                  tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin));
1906
3
                  hunk_begin = bptr;
1907
3
                }
1908
1909
                /* add the embedded line end to the field */
1910
6
                tptr = zend_mempcpy(tptr, line_end, line_end_len);
1911
1912
                /* nothing can be fetched if stream is NULL (e.g. str_getcsv()) */
1913
6
                if (stream == NULL) {
1914
                  /* the enclosure is unterminated */
1915
6
                  if (bptr > limit) {
1916
                    /* if the line ends with enclosure, we need to go back by
1917
                     * one character so the \0 character is not copied. */
1918
0
                    if (hunk_begin == bptr) {
1919
0
                      --hunk_begin;
1920
0
                    }
1921
0
                    --bptr;
1922
0
                  }
1923
6
                  goto quit_loop_2;
1924
6
                }
1925
1926
0
                size_t new_len;
1927
0
                char *new_buf = php_stream_get_line(stream, NULL, 0, &new_len);
1928
0
                if (!new_buf) {
1929
                  /* we've got an unterminated enclosure,
1930
                   * assign all the data from the start of
1931
                   * the enclosure to end of data to the
1932
                   * last element */
1933
0
                  if (bptr > limit) {
1934
                    /* if the line ends with enclosure, we need to go back by
1935
                     * one character so the \0 character is not copied. */
1936
0
                    if (hunk_begin == bptr) {
1937
0
                      --hunk_begin;
1938
0
                    }
1939
0
                    --bptr;
1940
0
                  }
1941
0
                  goto quit_loop_2;
1942
0
                }
1943
1944
0
                temp_len += new_len;
1945
0
                char *new_temp = erealloc(temp, temp_len);
1946
0
                tptr = new_temp + (size_t)(tptr - temp);
1947
0
                temp = new_temp;
1948
1949
0
                efree(buf);
1950
0
                buf_len = new_len;
1951
0
                bptr = buf = new_buf;
1952
0
                hunk_begin = buf;
1953
1954
0
                line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len);
1955
0
                line_end_len = buf_len - (size_t)(limit - buf);
1956
1957
0
                state = 0;
1958
0
              } break;
1959
12
            }
1960
0
            break;
1961
1962
0
          case -2:
1963
3.49k
          case -1:
1964
3.49k
            php_mb_reset();
1965
3.49k
            ZEND_FALLTHROUGH;
1966
35.9k
          case 1:
1967
            /* we need to determine if the enclosure is
1968
             * 'real' or is it escaped */
1969
35.9k
            switch (state) {
1970
81
              case 1: /* escaped */
1971
81
                bptr++;
1972
81
                state = 0;
1973
81
                break;
1974
13.0k
              case 2: /* embedded enclosure ? let's check it */
1975
13.0k
                if (*bptr != enclosure) {
1976
                  /* real enclosure */
1977
1.19k
                  tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
1978
1.19k
                  hunk_begin = bptr;
1979
1.19k
                  goto quit_loop_2;
1980
1.19k
                }
1981
11.8k
                tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
1982
11.8k
                bptr++;
1983
11.8k
                hunk_begin = bptr;
1984
11.8k
                state = 0;
1985
11.8k
                break;
1986
22.8k
              default:
1987
22.8k
                if (*bptr == enclosure) {
1988
13.3k
                  state = 2;
1989
13.3k
                } else if (escape_char != PHP_CSV_NO_ESCAPE && *bptr == escape_char) {
1990
99
                  state = 1;
1991
99
                }
1992
22.8k
                bptr++;
1993
22.8k
                break;
1994
35.9k
            }
1995
34.7k
            break;
1996
1997
34.7k
          default:
1998
360
            switch (state) {
1999
336
              case 2:
2000
                /* real enclosure */
2001
336
                tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2002
336
                hunk_begin = bptr;
2003
336
                goto quit_loop_2;
2004
18
              case 1:
2005
18
                bptr += inc_len;
2006
18
                tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2007
18
                hunk_begin = bptr;
2008
18
                state = 0;
2009
18
                break;
2010
6
              default:
2011
6
                bptr += inc_len;
2012
6
                break;
2013
360
            }
2014
24
            break;
2015
36.2k
        }
2016
34.7k
        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2017
34.7k
      }
2018
2019
1.54k
    quit_loop_2:
2020
      /* look up for a delimiter */
2021
19.6k
      for (;;) {
2022
19.6k
        switch (inc_len) {
2023
12
          case 0:
2024
12
            goto quit_loop_3;
2025
2026
0
          case -2:
2027
6.93k
          case -1:
2028
6.93k
            inc_len = 1;
2029
6.93k
            php_mb_reset();
2030
6.93k
            ZEND_FALLTHROUGH;
2031
19.3k
          case 1:
2032
19.3k
            if (*bptr == delimiter) {
2033
1.53k
              goto quit_loop_3;
2034
1.53k
            }
2035
17.7k
            break;
2036
17.7k
          default:
2037
339
            break;
2038
19.6k
        }
2039
18.1k
        bptr += inc_len;
2040
18.1k
        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2041
18.1k
      }
2042
2043
1.54k
    quit_loop_3:
2044
1.54k
      tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2045
1.54k
      bptr += inc_len;
2046
1.54k
      comp_end = tptr;
2047
5.74k
    } else {
2048
      /* 2B. Handle non-enclosure field */
2049
2050
5.74k
      hunk_begin = bptr;
2051
2052
25.4k
      for (;;) {
2053
25.4k
        switch (inc_len) {
2054
87
          case 0:
2055
87
            goto quit_loop_4;
2056
3
          case -2:
2057
7.02k
          case -1:
2058
7.02k
            inc_len = 1;
2059
7.02k
            php_mb_reset();
2060
7.02k
            ZEND_FALLTHROUGH;
2061
25.3k
          case 1:
2062
25.3k
            if (*bptr == delimiter) {
2063
5.65k
              goto quit_loop_4;
2064
5.65k
            }
2065
19.6k
            break;
2066
19.6k
          default:
2067
41
            break;
2068
25.4k
        }
2069
19.7k
        bptr += inc_len;
2070
19.7k
        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2071
19.7k
      }
2072
5.74k
    quit_loop_4:
2073
5.74k
      tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2074
2075
5.74k
      comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp);
2076
5.74k
      if (*bptr == delimiter) {
2077
5.71k
        bptr++;
2078
5.71k
      }
2079
5.74k
    }
2080
2081
    /* 3. Now pass our field back to php */
2082
7.29k
    *comp_end = '\0';
2083
2084
7.29k
    zval z_tmp;
2085
7.29k
    ZVAL_STRINGL(&z_tmp, temp, comp_end - temp);
2086
7.29k
    zend_hash_next_index_insert(values, &z_tmp);
2087
7.29k
  } while (inc_len > 0);
2088
2089
99
  efree(temp);
2090
99
  if (stream) {
2091
0
    efree(buf);
2092
0
  }
2093
2094
99
  return values;
2095
99
}
2096
/* }}} */
2097
2098
/* {{{ Return the resolved path */
2099
PHP_FUNCTION(realpath)
2100
0
{
2101
0
  char *filename;
2102
0
  size_t filename_len;
2103
0
  char resolved_path_buff[MAXPATHLEN];
2104
2105
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
2106
0
    Z_PARAM_PATH(filename, filename_len)
2107
0
  ZEND_PARSE_PARAMETERS_END();
2108
2109
0
  if (VCWD_REALPATH(filename, resolved_path_buff)) {
2110
0
    if (php_check_open_basedir(resolved_path_buff)) {
2111
0
      RETURN_FALSE;
2112
0
    }
2113
2114
#ifdef ZTS
2115
    if (VCWD_ACCESS(resolved_path_buff, F_OK)) {
2116
      RETURN_FALSE;
2117
    }
2118
#endif
2119
0
    RETURN_STRING(resolved_path_buff);
2120
0
  } else {
2121
0
    RETURN_FALSE;
2122
0
  }
2123
0
}
2124
/* }}} */
2125
2126
/* See http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 */
2127
0
#define PHP_META_HTML401_CHARS "-_.:"
2128
2129
/* {{{ php_next_meta_token
2130
   Tokenizes an HTML file for get_meta_tags */
2131
php_meta_tags_token php_next_meta_token(php_meta_tags_data *md)
2132
0
{
2133
0
  int ch = 0, compliment;
2134
0
  char buff[META_DEF_BUFSIZE + 1];
2135
2136
0
  memset((void *)buff, 0, META_DEF_BUFSIZE + 1);
2137
2138
0
  while (md->ulc || (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)))) {
2139
0
    if (php_stream_eof(md->stream)) {
2140
0
      break;
2141
0
    }
2142
2143
0
    if (md->ulc) {
2144
0
      ch = md->lc;
2145
0
      md->ulc = 0;
2146
0
    }
2147
2148
0
    switch (ch) {
2149
0
      case '<':
2150
0
        return TOK_OPENTAG;
2151
0
        break;
2152
2153
0
      case '>':
2154
0
        return TOK_CLOSETAG;
2155
0
        break;
2156
2157
0
      case '=':
2158
0
        return TOK_EQUAL;
2159
0
        break;
2160
0
      case '/':
2161
0
        return TOK_SLASH;
2162
0
        break;
2163
2164
0
      case '\'':
2165
0
      case '"':
2166
0
        compliment = ch;
2167
0
        md->token_len = 0;
2168
0
        while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && ch != compliment && ch != '<' && ch != '>') {
2169
0
          buff[(md->token_len)++] = ch;
2170
2171
0
          if (md->token_len == META_DEF_BUFSIZE) {
2172
0
            break;
2173
0
          }
2174
0
        }
2175
2176
0
        if (ch == '<' || ch == '>') {
2177
          /* Was just an apostrophe */
2178
0
          md->ulc = 1;
2179
0
          md->lc = ch;
2180
0
        }
2181
2182
        /* We don't need to alloc unless we are in a meta tag */
2183
0
        if (md->in_meta) {
2184
0
          md->token_data = (char *) emalloc(md->token_len + 1);
2185
0
          memcpy(md->token_data, buff, md->token_len+1);
2186
0
        }
2187
2188
0
        return TOK_STRING;
2189
0
        break;
2190
2191
0
      case '\n':
2192
0
      case '\r':
2193
0
      case '\t':
2194
0
        break;
2195
2196
0
      case ' ':
2197
0
        return TOK_SPACE;
2198
0
        break;
2199
2200
0
      default:
2201
0
        if (isalnum(ch)) {
2202
0
          md->token_len = 0;
2203
0
          buff[(md->token_len)++] = ch;
2204
0
          while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && (isalnum(ch) || strchr(PHP_META_HTML401_CHARS, ch))) {
2205
0
            buff[(md->token_len)++] = ch;
2206
2207
0
            if (md->token_len == META_DEF_BUFSIZE) {
2208
0
              break;
2209
0
            }
2210
0
          }
2211
2212
          /* This is ugly, but we have to replace ungetc */
2213
0
          if (!isalpha(ch) && ch != '-') {
2214
0
            md->ulc = 1;
2215
0
            md->lc = ch;
2216
0
          }
2217
2218
0
          md->token_data = (char *) emalloc(md->token_len + 1);
2219
0
          memcpy(md->token_data, buff, md->token_len+1);
2220
2221
0
          return TOK_ID;
2222
0
        } else {
2223
0
          return TOK_OTHER;
2224
0
        }
2225
0
        break;
2226
0
    }
2227
0
  }
2228
2229
0
  return TOK_EOF;
2230
0
}
2231
/* }}} */
2232
2233
#ifdef HAVE_FNMATCH
2234
/* {{{ Match filename against pattern */
2235
PHP_FUNCTION(fnmatch)
2236
0
{
2237
0
  char *pattern, *filename;
2238
0
  size_t pattern_len, filename_len;
2239
0
  zend_long flags = 0;
2240
2241
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
2242
0
    Z_PARAM_PATH(pattern, pattern_len)
2243
0
    Z_PARAM_PATH(filename, filename_len)
2244
0
    Z_PARAM_OPTIONAL
2245
0
    Z_PARAM_LONG(flags)
2246
0
  ZEND_PARSE_PARAMETERS_END();
2247
2248
0
  if (filename_len >= MAXPATHLEN) {
2249
0
    php_error_docref(NULL, E_WARNING, "Filename exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2250
0
    RETURN_FALSE;
2251
0
  }
2252
0
  if (pattern_len >= MAXPATHLEN) {
2253
0
    php_error_docref(NULL, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2254
0
    RETURN_FALSE;
2255
0
  }
2256
2257
0
  RETURN_BOOL( ! fnmatch( pattern, filename, (int)flags ));
2258
0
}
2259
/* }}} */
2260
#endif
2261
2262
/* {{{ Returns directory path used for temporary files */
2263
PHP_FUNCTION(sys_get_temp_dir)
2264
0
{
2265
0
  ZEND_PARSE_PARAMETERS_NONE();
2266
2267
0
  RETURN_STRING((char *)php_get_temporary_directory());
2268
0
}
2269
/* }}} */