Coverage Report

Created: 2026-04-01 06:49

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
36
{
113
36
  return le_stream_context;
114
36
}
115
/* }}} */
116
117
/* {{{ Module-Stuff */
118
static ZEND_RSRC_DTOR_FUNC(file_context_dtor)
119
36
{
120
36
  php_stream_context *context = (php_stream_context*)res->ptr;
121
36
  if (Z_TYPE(context->options) != IS_UNDEF) {
122
36
    zval_ptr_dtor(&context->options);
123
36
    ZVAL_UNDEF(&context->options);
124
36
  }
125
36
  php_stream_context_free(context);
126
36
}
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
8
{
379
8
  char *filename;
380
8
  size_t filename_len;
381
8
  bool use_include_path = 0;
382
8
  php_stream *stream;
383
8
  zend_long offset = 0;
384
8
  zend_long maxlen;
385
8
  bool maxlen_is_null = 1;
386
8
  zval *zcontext = NULL;
387
8
  php_stream_context *context = NULL;
388
8
  zend_string *contents;
389
390
  /* Parse arguments */
391
24
  ZEND_PARSE_PARAMETERS_START(1, 5)
392
32
    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
8
  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
10
{
583
10
  char *filename;
584
10
  size_t filename_len;
585
10
  char *p, *s, *e;
586
10
  int i = 0;
587
10
  char eol_marker = '\n';
588
10
  zend_long flags = 0;
589
10
  bool use_include_path;
590
10
  bool include_new_line;
591
10
  bool skip_blank_lines;
592
10
  php_stream *stream;
593
10
  zval *zcontext = NULL;
594
10
  php_stream_context *context = NULL;
595
10
  zend_string *target_buf;
596
597
  /* Parse arguments */
598
28
  ZEND_PARSE_PARAMETERS_START(1, 3)
599
32
    Z_PARAM_PATH(filename, filename_len)
600
8
    Z_PARAM_OPTIONAL
601
20
    Z_PARAM_LONG(flags)
602
5
    Z_PARAM_RESOURCE_OR_NULL(zcontext)
603
10
  ZEND_PARSE_PARAMETERS_END();
604
605
6
  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
6
  use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
611
6
  include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES);
612
6
  skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES;
613
614
6
  context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
615
616
6
  stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
617
6
  if (!stream) {
618
0
    RETURN_FALSE;
619
0
  }
620
621
  /* Initialize return array */
622
6
  array_init(return_value);
623
624
6
  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
6
  php_stream_close(stream);
671
6
}
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
9
{
846
9
  php_stream *stream;
847
848
27
  ZEND_PARSE_PARAMETERS_START(1, 1)
849
36
    PHP_Z_PARAM_STREAM(stream)
850
9
  ZEND_PARSE_PARAMETERS_END();
851
852
6
  if (php_stream_eof(stream)) {
853
6
    RETURN_TRUE;
854
6
  } else {
855
0
    RETURN_FALSE;
856
0
  }
857
6
}
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
    case 0:
1454
0
      break;
1455
0
    default: /* failed to stat file, does not exist? */
1456
0
      return ret;
1457
0
  }
1458
0
  if (S_ISDIR(src_s.sb.st_mode)) {
1459
0
    php_error_docref(NULL, E_WARNING, "The first argument to copy() function cannot be a directory");
1460
0
    return FAILURE;
1461
0
  }
1462
1463
0
  switch (php_stream_stat_path_ex(dest, PHP_STREAM_URL_STAT_QUIET, &dest_s, ctx)) {
1464
0
    case -1:
1465
      /* non-statable stream */
1466
0
      goto safe_to_copy;
1467
0
    case 0:
1468
0
      break;
1469
0
    default: /* failed to stat file, does not exist? */
1470
0
      return ret;
1471
0
  }
1472
0
  if (S_ISDIR(dest_s.sb.st_mode)) {
1473
0
    php_error_docref(NULL, E_WARNING, "The second argument to copy() function cannot be a directory");
1474
0
    return FAILURE;
1475
0
  }
1476
0
  if (!src_s.sb.st_ino || !dest_s.sb.st_ino) {
1477
0
    goto no_stat;
1478
0
  }
1479
0
  if (src_s.sb.st_ino == dest_s.sb.st_ino && src_s.sb.st_dev == dest_s.sb.st_dev) {
1480
0
    return ret;
1481
0
  } else {
1482
0
    goto safe_to_copy;
1483
0
  }
1484
0
no_stat:
1485
0
  {
1486
0
    char *sp, *dp;
1487
0
    int res;
1488
1489
0
    if ((sp = expand_filepath(src, NULL)) == NULL) {
1490
0
      return ret;
1491
0
    }
1492
0
    if ((dp = expand_filepath(dest, NULL)) == NULL) {
1493
0
      efree(sp);
1494
0
      goto safe_to_copy;
1495
0
    }
1496
1497
0
    res =
1498
0
#ifndef PHP_WIN32
1499
0
      !strcmp(sp, dp);
1500
#else
1501
      !strcasecmp(sp, dp);
1502
#endif
1503
1504
0
    efree(sp);
1505
0
    efree(dp);
1506
0
    if (res) {
1507
0
      return ret;
1508
0
    }
1509
0
  }
1510
0
safe_to_copy:
1511
1512
0
  srcstream = php_stream_open_wrapper_ex(src, "rb", src_flags | REPORT_ERRORS, NULL, ctx);
1513
1514
0
  if (!srcstream) {
1515
0
    return ret;
1516
0
  }
1517
1518
0
  deststream = php_stream_open_wrapper_ex(dest, "wb", REPORT_ERRORS, NULL, ctx);
1519
1520
0
  if (deststream) {
1521
0
    ret = php_stream_copy_to_stream_ex(srcstream, deststream, PHP_STREAM_COPY_ALL, NULL);
1522
0
  }
1523
0
  php_stream_close(srcstream);
1524
0
  if (deststream) {
1525
0
    php_stream_close(deststream);
1526
0
  }
1527
0
  return ret;
1528
0
}
1529
/* }}} */
1530
1531
/* {{{ Binary-safe file read */
1532
PHPAPI PHP_FUNCTION(fread)
1533
0
{
1534
0
  zend_long len;
1535
0
  php_stream *stream;
1536
0
  zend_string *str;
1537
1538
0
  ZEND_PARSE_PARAMETERS_START(2, 2)
1539
0
    PHP_Z_PARAM_STREAM(stream)
1540
0
    Z_PARAM_LONG(len)
1541
0
  ZEND_PARSE_PARAMETERS_END();
1542
1543
0
  if (len <= 0) {
1544
0
    zend_argument_value_error(2, "must be greater than 0");
1545
0
    RETURN_THROWS();
1546
0
  }
1547
1548
0
  str = php_stream_read_to_str(stream, len);
1549
0
  if (!str) {
1550
0
    RETURN_FALSE;
1551
0
  }
1552
1553
0
  RETURN_STR(str);
1554
0
}
1555
/* }}} */
1556
1557
static const char *php_fgetcsv_lookup_trailing_spaces(const char *ptr, size_t len) /* {{{ */
1558
6.30k
{
1559
6.30k
  int inc_len;
1560
6.30k
  unsigned char last_chars[2] = { 0, 0 };
1561
1562
147k
  while (len > 0) {
1563
141k
    inc_len = (*ptr == '\0' ? 1 : php_mblen(ptr, len));
1564
141k
    switch (inc_len) {
1565
110
      case -2:
1566
34.2k
      case -1:
1567
34.2k
        inc_len = 1;
1568
34.2k
        php_mb_reset();
1569
34.2k
        break;
1570
0
      case 0:
1571
0
        goto quit_loop;
1572
106k
      case 1:
1573
106k
      default:
1574
106k
        last_chars[0] = last_chars[1];
1575
106k
        last_chars[1] = *ptr;
1576
106k
        break;
1577
141k
    }
1578
141k
    ptr += inc_len;
1579
141k
    len -= inc_len;
1580
141k
  }
1581
6.30k
quit_loop:
1582
6.30k
  switch (last_chars[1]) {
1583
108
    case '\n':
1584
108
      if (last_chars[0] == '\r') {
1585
0
        return ptr - 2;
1586
0
      }
1587
108
      ZEND_FALLTHROUGH;
1588
117
    case '\r':
1589
117
      return ptr - 1;
1590
6.30k
  }
1591
6.18k
  return ptr;
1592
6.30k
}
1593
/* }}} */
1594
1595
PHPAPI int php_csv_handle_escape_argument(const zend_string *escape_str, uint32_t arg_num)
1596
125
{
1597
125
  if (escape_str != NULL) {
1598
0
    if (ZSTR_LEN(escape_str) > 1) {
1599
0
      zend_argument_value_error(arg_num, "must be empty or a single character");
1600
0
      return PHP_CSV_ESCAPE_ERROR;
1601
0
    }
1602
0
    if (ZSTR_LEN(escape_str) < 1) {
1603
0
      return PHP_CSV_NO_ESCAPE;
1604
0
    } else {
1605
      /* use first character from string */
1606
0
      return (unsigned char) ZSTR_VAL(escape_str)[0];
1607
0
    }
1608
125
  } else {
1609
125
    php_error_docref(NULL, E_DEPRECATED, "the $escape parameter must be provided as its default value will change");
1610
125
    if (UNEXPECTED(EG(exception))) {
1611
0
      return PHP_CSV_ESCAPE_ERROR;
1612
0
    }
1613
125
    return (unsigned char) '\\';
1614
125
  }
1615
125
}
1616
1617
0
#define FPUTCSV_FLD_CHK(c) memchr(ZSTR_VAL(field_str), c, ZSTR_LEN(field_str))
1618
1619
/* {{{ Format line as CSV and write to file pointer */
1620
PHP_FUNCTION(fputcsv)
1621
0
{
1622
0
  char delimiter = ',';         /* allow this to be set as parameter */
1623
0
  char enclosure = '"';         /* allow this to be set as parameter */
1624
0
  php_stream *stream;
1625
0
  zval *fields = NULL;
1626
0
  ssize_t ret;
1627
0
  char *delimiter_str = NULL, *enclosure_str = NULL;
1628
0
  zend_string *escape_str = NULL;
1629
0
  size_t delimiter_str_len = 0, enclosure_str_len = 0;
1630
0
  zend_string *eol_str = NULL;
1631
1632
0
  ZEND_PARSE_PARAMETERS_START(2, 6)
1633
0
    PHP_Z_PARAM_STREAM(stream)
1634
0
    Z_PARAM_ARRAY(fields)
1635
0
    Z_PARAM_OPTIONAL
1636
0
    Z_PARAM_STRING(delimiter_str, delimiter_str_len)
1637
0
    Z_PARAM_STRING(enclosure_str, enclosure_str_len)
1638
0
    Z_PARAM_STR(escape_str)
1639
0
    Z_PARAM_STR_OR_NULL(eol_str)
1640
0
  ZEND_PARSE_PARAMETERS_END();
1641
1642
0
  if (delimiter_str != NULL) {
1643
    /* Make sure that there is at least one character in string */
1644
0
    if (delimiter_str_len != 1) {
1645
0
      zend_argument_value_error(3, "must be a single character");
1646
0
      RETURN_THROWS();
1647
0
    }
1648
1649
    /* use first character from string */
1650
0
    delimiter = *delimiter_str;
1651
0
  }
1652
1653
0
  if (enclosure_str != NULL) {
1654
0
    if (enclosure_str_len != 1) {
1655
0
      zend_argument_value_error(4, "must be a single character");
1656
0
      RETURN_THROWS();
1657
0
    }
1658
    /* use first character from string */
1659
0
    enclosure = *enclosure_str;
1660
0
  }
1661
1662
0
  int escape_char = php_csv_handle_escape_argument(escape_str, 5);
1663
0
  if (escape_char == PHP_CSV_ESCAPE_ERROR) {
1664
0
    RETURN_THROWS();
1665
0
  }
1666
1667
0
  ret = php_fputcsv(stream, fields, delimiter, enclosure, escape_char, eol_str);
1668
0
  if (ret < 0) {
1669
0
    RETURN_FALSE;
1670
0
  }
1671
0
  RETURN_LONG(ret);
1672
0
}
1673
/* }}} */
1674
1675
/* {{{ PHPAPI size_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, int escape_char, zend_string *eol_str) */
1676
PHPAPI ssize_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, int escape_char, zend_string *eol_str)
1677
0
{
1678
0
  uint32_t count, i = 0;
1679
0
  size_t ret;
1680
0
  zval *field_tmp;
1681
0
  smart_str csvline = {0};
1682
1683
0
  ZEND_ASSERT((escape_char >= 0 && escape_char <= UCHAR_MAX) || escape_char == PHP_CSV_NO_ESCAPE);
1684
0
  count = zend_hash_num_elements(Z_ARRVAL_P(fields));
1685
0
  ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(fields), field_tmp) {
1686
0
    zend_string *tmp_field_str;
1687
0
    zend_string *field_str = zval_get_tmp_string(field_tmp, &tmp_field_str);
1688
1689
    /* enclose a field that contains a delimiter, an enclosure character, or a newline */
1690
0
    if (FPUTCSV_FLD_CHK(delimiter) ||
1691
0
      FPUTCSV_FLD_CHK(enclosure) ||
1692
0
      (escape_char != PHP_CSV_NO_ESCAPE && FPUTCSV_FLD_CHK(escape_char)) ||
1693
0
      FPUTCSV_FLD_CHK('\n') ||
1694
0
      FPUTCSV_FLD_CHK('\r') ||
1695
0
      FPUTCSV_FLD_CHK('\t') ||
1696
0
      FPUTCSV_FLD_CHK(' ')
1697
0
    ) {
1698
0
      char *ch = ZSTR_VAL(field_str);
1699
0
      char *end = ch + ZSTR_LEN(field_str);
1700
0
      int escaped = 0;
1701
1702
0
      smart_str_appendc(&csvline, enclosure);
1703
0
      while (ch < end) {
1704
0
        if (escape_char != PHP_CSV_NO_ESCAPE && *ch == escape_char) {
1705
0
          escaped = 1;
1706
0
        } else if (!escaped && *ch == enclosure) {
1707
0
          smart_str_appendc(&csvline, enclosure);
1708
0
        } else {
1709
0
          escaped = 0;
1710
0
        }
1711
0
        smart_str_appendc(&csvline, *ch);
1712
0
        ch++;
1713
0
      }
1714
0
      smart_str_appendc(&csvline, enclosure);
1715
0
    } else {
1716
0
      smart_str_append(&csvline, field_str);
1717
0
    }
1718
1719
0
    if (++i != count) {
1720
0
      smart_str_appendl(&csvline, &delimiter, 1);
1721
0
    }
1722
0
    zend_tmp_string_release(tmp_field_str);
1723
0
  } ZEND_HASH_FOREACH_END();
1724
1725
0
  if (eol_str) {
1726
0
    smart_str_append(&csvline, eol_str);
1727
0
  } else {
1728
0
    smart_str_appendc(&csvline, '\n');
1729
0
  }
1730
0
  smart_str_0(&csvline);
1731
1732
0
  ret = php_stream_write(stream, ZSTR_VAL(csvline.s), ZSTR_LEN(csvline.s));
1733
1734
0
  smart_str_free(&csvline);
1735
1736
0
  return ret;
1737
0
}
1738
/* }}} */
1739
1740
/* {{{ Get line from file pointer and parse for CSV fields */
1741
PHP_FUNCTION(fgetcsv)
1742
0
{
1743
0
  char delimiter = ','; /* allow this to be set as parameter */
1744
0
  char enclosure = '"'; /* allow this to be set as parameter */
1745
1746
0
  zend_long len = 0;
1747
0
  size_t buf_len;
1748
0
  char *buf;
1749
0
  php_stream *stream;
1750
1751
0
  bool len_is_null = 1;
1752
0
  char *delimiter_str = NULL;
1753
0
  size_t delimiter_str_len = 0;
1754
0
  char *enclosure_str = NULL;
1755
0
  size_t enclosure_str_len = 0;
1756
0
  zend_string *escape_str = NULL;
1757
1758
0
  ZEND_PARSE_PARAMETERS_START(1, 5)
1759
0
    PHP_Z_PARAM_STREAM(stream)
1760
0
    Z_PARAM_OPTIONAL
1761
0
    Z_PARAM_LONG_OR_NULL(len, len_is_null)
1762
0
    Z_PARAM_STRING(delimiter_str, delimiter_str_len)
1763
0
    Z_PARAM_STRING(enclosure_str, enclosure_str_len)
1764
0
    Z_PARAM_STR(escape_str)
1765
0
  ZEND_PARSE_PARAMETERS_END();
1766
1767
0
  if (delimiter_str != NULL) {
1768
    /* Make sure that there is at least one character in string */
1769
0
    if (delimiter_str_len != 1) {
1770
0
      zend_argument_value_error(3, "must be a single character");
1771
0
      RETURN_THROWS();
1772
0
    }
1773
1774
    /* use first character from string */
1775
0
    delimiter = delimiter_str[0];
1776
0
  }
1777
1778
0
  if (enclosure_str != NULL) {
1779
0
    if (enclosure_str_len != 1) {
1780
0
      zend_argument_value_error(4, "must be a single character");
1781
0
      RETURN_THROWS();
1782
0
    }
1783
1784
    /* use first character from string */
1785
0
    enclosure = enclosure_str[0];
1786
0
  }
1787
1788
0
  int escape_char = php_csv_handle_escape_argument(escape_str, 5);
1789
0
  if (escape_char == PHP_CSV_ESCAPE_ERROR) {
1790
0
    RETURN_THROWS();
1791
0
  }
1792
1793
0
  if (len_is_null || len == 0) {
1794
0
    len = -1;
1795
0
  } else if (len < 0 || len > (ZEND_LONG_MAX - 1)) {
1796
0
    zend_argument_value_error(2, "must be between 0 and " ZEND_LONG_FMT, (ZEND_LONG_MAX - 1));
1797
0
    RETURN_THROWS();
1798
0
  }
1799
1800
0
  if (len < 0) {
1801
0
    if ((buf = php_stream_get_line(stream, NULL, 0, &buf_len)) == NULL) {
1802
0
      RETURN_FALSE;
1803
0
    }
1804
0
  } else {
1805
0
    buf = emalloc(len + 1);
1806
0
    if (php_stream_get_line(stream, buf, len + 1, &buf_len) == NULL) {
1807
0
      efree(buf);
1808
0
      RETURN_FALSE;
1809
0
    }
1810
0
  }
1811
1812
0
  HashTable *values = php_fgetcsv(stream, delimiter, enclosure, escape_char, buf_len, buf);
1813
0
  if (values == NULL) {
1814
0
    values = php_bc_fgetcsv_empty_line();
1815
0
  }
1816
0
  RETURN_ARR(values);
1817
0
}
1818
/* }}} */
1819
1820
PHPAPI HashTable *php_bc_fgetcsv_empty_line(void)
1821
0
{
1822
0
  HashTable *values = zend_new_array(1);
1823
0
  zval tmp;
1824
0
  ZVAL_NULL(&tmp);
1825
0
  zend_hash_next_index_insert(values, &tmp);
1826
0
  return values;
1827
0
}
1828
1829
PHPAPI HashTable *php_fgetcsv(php_stream *stream, char delimiter, char enclosure, int escape_char, size_t buf_len, char *buf) /* {{{ */
1830
125
{
1831
125
  char *temp, *bptr, *line_end, *limit;
1832
125
  size_t temp_len, line_end_len;
1833
125
  int inc_len;
1834
125
  bool first_field = true;
1835
1836
125
  ZEND_ASSERT((escape_char >= 0 && escape_char <= UCHAR_MAX) || escape_char == PHP_CSV_NO_ESCAPE);
1837
1838
  /* initialize internal state */
1839
125
  php_mb_reset();
1840
1841
  /* Now into new section that parses buf for delimiter/enclosure fields */
1842
1843
  /* Strip trailing space from buf, saving end of line in case required for enclosure field */
1844
1845
125
  bptr = buf;
1846
125
  line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len);
1847
125
  line_end_len = buf_len - (size_t)(limit - buf);
1848
1849
  /* reserve workspace for building each individual field */
1850
125
  temp_len = buf_len;
1851
125
  temp = emalloc(temp_len + line_end_len + 1);
1852
1853
  /* Initialize values HashTable */
1854
125
  HashTable *values = zend_new_array(0);
1855
1856
  /* Main loop to read CSV fields */
1857
  /* NB this routine will return NULL for a blank line */
1858
8.11k
  do {
1859
8.11k
    char *comp_end, *hunk_begin;
1860
8.11k
    char *tptr = temp;
1861
1862
8.11k
    inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
1863
8.11k
    if (inc_len == 1) {
1864
7.49k
      char *tmp = bptr;
1865
7.87k
      while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) {
1866
381
        tmp++;
1867
381
      }
1868
7.49k
      if (*tmp == enclosure && tmp < limit) {
1869
1.94k
        bptr = tmp;
1870
1.94k
      }
1871
7.49k
    }
1872
1873
8.11k
    if (first_field && bptr == line_end) {
1874
0
      zend_array_destroy(values);
1875
0
      values = NULL;
1876
0
      break;
1877
0
    }
1878
8.11k
    first_field = false;
1879
    /* 2. Read field, leaving bptr pointing at start of next field */
1880
8.11k
    if (inc_len != 0 && *bptr == enclosure) {
1881
1.94k
      int state = 0;
1882
1883
1.94k
      bptr++; /* move on to first character in field */
1884
1.94k
      hunk_begin = bptr;
1885
1886
      /* 2A. handle enclosure delimited field */
1887
50.6k
      for (;;) {
1888
50.6k
        switch (inc_len) {
1889
17
          case 0:
1890
17
            switch (state) {
1891
9
              case 2:
1892
9
                tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin - 1));
1893
9
                hunk_begin = bptr;
1894
9
                goto quit_loop_2;
1895
1896
0
              case 1:
1897
0
                tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin));
1898
0
                hunk_begin = bptr;
1899
0
                ZEND_FALLTHROUGH;
1900
1901
8
              case 0: {
1902
8
                if (hunk_begin != line_end) {
1903
2
                  tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin));
1904
2
                  hunk_begin = bptr;
1905
2
                }
1906
1907
                /* add the embedded line end to the field */
1908
8
                tptr = zend_mempcpy(tptr, line_end, line_end_len);
1909
1910
                /* nothing can be fetched if stream is NULL (e.g. str_getcsv()) */
1911
8
                if (stream == NULL) {
1912
                  /* the enclosure is unterminated */
1913
8
                  if (bptr > limit) {
1914
                    /* if the line ends with enclosure, we need to go back by
1915
                     * one character so the \0 character is not copied. */
1916
0
                    if (hunk_begin == bptr) {
1917
0
                      --hunk_begin;
1918
0
                    }
1919
0
                    --bptr;
1920
0
                  }
1921
8
                  goto quit_loop_2;
1922
8
                }
1923
1924
0
                size_t new_len;
1925
0
                char *new_buf = php_stream_get_line(stream, NULL, 0, &new_len);
1926
0
                if (!new_buf) {
1927
                  /* we've got an unterminated enclosure,
1928
                   * assign all the data from the start of
1929
                   * the enclosure to end of data to the
1930
                   * last element */
1931
0
                  if (bptr > limit) {
1932
                    /* if the line ends with enclosure, we need to go back by
1933
                     * one character so the \0 character is not copied. */
1934
0
                    if (hunk_begin == bptr) {
1935
0
                      --hunk_begin;
1936
0
                    }
1937
0
                    --bptr;
1938
0
                  }
1939
0
                  goto quit_loop_2;
1940
0
                }
1941
1942
0
                temp_len += new_len;
1943
0
                char *new_temp = erealloc(temp, temp_len);
1944
0
                tptr = new_temp + (size_t)(tptr - temp);
1945
0
                temp = new_temp;
1946
1947
0
                efree(buf);
1948
0
                buf_len = new_len;
1949
0
                bptr = buf = new_buf;
1950
0
                hunk_begin = buf;
1951
1952
0
                line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len);
1953
0
                line_end_len = buf_len - (size_t)(limit - buf);
1954
1955
0
                state = 0;
1956
0
              } break;
1957
17
            }
1958
0
            break;
1959
1960
0
          case -2:
1961
5.80k
          case -1:
1962
5.80k
            php_mb_reset();
1963
5.80k
            ZEND_FALLTHROUGH;
1964
50.1k
          case 1:
1965
            /* we need to determine if the enclosure is
1966
             * 'real' or is it escaped */
1967
50.1k
            switch (state) {
1968
135
              case 1: /* escaped */
1969
135
                bptr++;
1970
135
                state = 0;
1971
135
                break;
1972
17.4k
              case 2: /* embedded enclosure ? let's check it */
1973
17.4k
                if (*bptr != enclosure) {
1974
                  /* real enclosure */
1975
1.50k
                  tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
1976
1.50k
                  hunk_begin = bptr;
1977
1.50k
                  goto quit_loop_2;
1978
1.50k
                }
1979
15.9k
                tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
1980
15.9k
                bptr++;
1981
15.9k
                hunk_begin = bptr;
1982
15.9k
                state = 0;
1983
15.9k
                break;
1984
32.5k
              default:
1985
32.5k
                if (*bptr == enclosure) {
1986
17.8k
                  state = 2;
1987
17.8k
                } else if (escape_char != PHP_CSV_NO_ESCAPE && *bptr == escape_char) {
1988
174
                  state = 1;
1989
174
                }
1990
32.5k
                bptr++;
1991
32.5k
                break;
1992
50.1k
            }
1993
48.5k
            break;
1994
1995
48.5k
          default:
1996
484
            switch (state) {
1997
417
              case 2:
1998
                /* real enclosure */
1999
417
                tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2000
417
                hunk_begin = bptr;
2001
417
                goto quit_loop_2;
2002
39
              case 1:
2003
39
                bptr += inc_len;
2004
39
                tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2005
39
                hunk_begin = bptr;
2006
39
                state = 0;
2007
39
                break;
2008
28
              default:
2009
28
                bptr += inc_len;
2010
28
                break;
2011
484
            }
2012
67
            break;
2013
50.6k
        }
2014
48.6k
        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2015
48.6k
      }
2016
2017
1.94k
    quit_loop_2:
2018
      /* look up for a delimiter */
2019
23.6k
      for (;;) {
2020
23.6k
        switch (inc_len) {
2021
17
          case 0:
2022
17
            goto quit_loop_3;
2023
2024
0
          case -2:
2025
7.71k
          case -1:
2026
7.71k
            inc_len = 1;
2027
7.71k
            php_mb_reset();
2028
7.71k
            ZEND_FALLTHROUGH;
2029
23.2k
          case 1:
2030
23.2k
            if (*bptr == delimiter) {
2031
1.92k
              goto quit_loop_3;
2032
1.92k
            }
2033
21.3k
            break;
2034
21.3k
          default:
2035
424
            break;
2036
23.6k
        }
2037
21.7k
        bptr += inc_len;
2038
21.7k
        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2039
21.7k
      }
2040
2041
1.94k
    quit_loop_3:
2042
1.94k
      tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2043
1.94k
      bptr += inc_len;
2044
1.94k
      comp_end = tptr;
2045
6.17k
    } else {
2046
      /* 2B. Handle non-enclosure field */
2047
2048
6.17k
      hunk_begin = bptr;
2049
2050
36.5k
      for (;;) {
2051
36.5k
        switch (inc_len) {
2052
108
          case 0:
2053
108
            goto quit_loop_4;
2054
3
          case -2:
2055
10.5k
          case -1:
2056
10.5k
            inc_len = 1;
2057
10.5k
            php_mb_reset();
2058
10.5k
            ZEND_FALLTHROUGH;
2059
36.3k
          case 1:
2060
36.3k
            if (*bptr == delimiter) {
2061
6.06k
              goto quit_loop_4;
2062
6.06k
            }
2063
30.3k
            break;
2064
30.3k
          default:
2065
79
            break;
2066
36.5k
        }
2067
30.3k
        bptr += inc_len;
2068
30.3k
        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2069
30.3k
      }
2070
6.17k
    quit_loop_4:
2071
6.17k
      tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2072
2073
6.17k
      comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp);
2074
6.17k
      if (*bptr == delimiter) {
2075
6.13k
        bptr++;
2076
6.13k
      }
2077
6.17k
    }
2078
2079
    /* 3. Now pass our field back to php */
2080
8.11k
    *comp_end = '\0';
2081
2082
8.11k
    zval z_tmp;
2083
8.11k
    ZVAL_STRINGL(&z_tmp, temp, comp_end - temp);
2084
8.11k
    zend_hash_next_index_insert(values, &z_tmp);
2085
8.11k
  } while (inc_len > 0);
2086
2087
125
  efree(temp);
2088
125
  if (stream) {
2089
0
    efree(buf);
2090
0
  }
2091
2092
125
  return values;
2093
125
}
2094
/* }}} */
2095
2096
/* {{{ Return the resolved path */
2097
PHP_FUNCTION(realpath)
2098
0
{
2099
0
  char *filename;
2100
0
  size_t filename_len;
2101
0
  char resolved_path_buff[MAXPATHLEN];
2102
2103
0
  ZEND_PARSE_PARAMETERS_START(1, 1)
2104
0
    Z_PARAM_PATH(filename, filename_len)
2105
0
  ZEND_PARSE_PARAMETERS_END();
2106
2107
0
  if (VCWD_REALPATH(filename, resolved_path_buff)) {
2108
0
    if (php_check_open_basedir(resolved_path_buff)) {
2109
0
      RETURN_FALSE;
2110
0
    }
2111
2112
#ifdef ZTS
2113
    if (VCWD_ACCESS(resolved_path_buff, F_OK)) {
2114
      RETURN_FALSE;
2115
    }
2116
#endif
2117
0
    RETURN_STRING(resolved_path_buff);
2118
0
  } else {
2119
0
    RETURN_FALSE;
2120
0
  }
2121
0
}
2122
/* }}} */
2123
2124
/* See http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 */
2125
0
#define PHP_META_HTML401_CHARS "-_.:"
2126
2127
/* {{{ php_next_meta_token
2128
   Tokenizes an HTML file for get_meta_tags */
2129
php_meta_tags_token php_next_meta_token(php_meta_tags_data *md)
2130
0
{
2131
0
  int ch = 0, compliment;
2132
0
  char buff[META_DEF_BUFSIZE + 1];
2133
2134
0
  memset((void *)buff, 0, META_DEF_BUFSIZE + 1);
2135
2136
0
  while (md->ulc || (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)))) {
2137
0
    if (php_stream_eof(md->stream)) {
2138
0
      break;
2139
0
    }
2140
2141
0
    if (md->ulc) {
2142
0
      ch = md->lc;
2143
0
      md->ulc = 0;
2144
0
    }
2145
2146
0
    switch (ch) {
2147
0
      case '<':
2148
0
        return TOK_OPENTAG;
2149
2150
0
      case '>':
2151
0
        return TOK_CLOSETAG;
2152
2153
0
      case '=':
2154
0
        return TOK_EQUAL;
2155
0
      case '/':
2156
0
        return TOK_SLASH;
2157
2158
0
      case '\'':
2159
0
      case '"':
2160
0
        compliment = ch;
2161
0
        md->token_len = 0;
2162
0
        while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && ch != compliment && ch != '<' && ch != '>') {
2163
0
          buff[(md->token_len)++] = ch;
2164
2165
0
          if (md->token_len == META_DEF_BUFSIZE) {
2166
0
            break;
2167
0
          }
2168
0
        }
2169
2170
0
        if (ch == '<' || ch == '>') {
2171
          /* Was just an apostrophe */
2172
0
          md->ulc = 1;
2173
0
          md->lc = ch;
2174
0
        }
2175
2176
        /* We don't need to alloc unless we are in a meta tag */
2177
0
        if (md->in_meta) {
2178
0
          md->token_data = (char *) emalloc(md->token_len + 1);
2179
0
          memcpy(md->token_data, buff, md->token_len+1);
2180
0
        }
2181
2182
0
        return TOK_STRING;
2183
2184
0
      case '\n':
2185
0
      case '\r':
2186
0
      case '\t':
2187
0
        break;
2188
2189
0
      case ' ':
2190
0
        return TOK_SPACE;
2191
2192
0
      default:
2193
0
        if (isalnum(ch)) {
2194
0
          md->token_len = 0;
2195
0
          buff[(md->token_len)++] = ch;
2196
0
          while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && (isalnum(ch) || strchr(PHP_META_HTML401_CHARS, ch))) {
2197
0
            buff[(md->token_len)++] = ch;
2198
2199
0
            if (md->token_len == META_DEF_BUFSIZE) {
2200
0
              break;
2201
0
            }
2202
0
          }
2203
2204
          /* This is ugly, but we have to replace ungetc */
2205
0
          if (!isalpha(ch) && ch != '-') {
2206
0
            md->ulc = 1;
2207
0
            md->lc = ch;
2208
0
          }
2209
2210
0
          md->token_data = (char *) emalloc(md->token_len + 1);
2211
0
          memcpy(md->token_data, buff, md->token_len+1);
2212
2213
0
          return TOK_ID;
2214
0
        } else {
2215
0
          return TOK_OTHER;
2216
0
        }
2217
0
        break;
2218
0
    }
2219
0
  }
2220
2221
0
  return TOK_EOF;
2222
0
}
2223
/* }}} */
2224
2225
#ifdef HAVE_FNMATCH
2226
/* {{{ Match filename against pattern */
2227
PHP_FUNCTION(fnmatch)
2228
0
{
2229
0
  char *pattern, *filename;
2230
0
  size_t pattern_len, filename_len;
2231
0
  zend_long flags = 0;
2232
2233
0
  ZEND_PARSE_PARAMETERS_START(2, 3)
2234
0
    Z_PARAM_PATH(pattern, pattern_len)
2235
0
    Z_PARAM_PATH(filename, filename_len)
2236
0
    Z_PARAM_OPTIONAL
2237
0
    Z_PARAM_LONG(flags)
2238
0
  ZEND_PARSE_PARAMETERS_END();
2239
2240
0
  if (filename_len >= MAXPATHLEN) {
2241
0
    php_error_docref(NULL, E_WARNING, "Filename exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2242
0
    RETURN_FALSE;
2243
0
  }
2244
0
  if (pattern_len >= MAXPATHLEN) {
2245
0
    php_error_docref(NULL, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2246
0
    RETURN_FALSE;
2247
0
  }
2248
2249
0
  RETURN_BOOL( ! fnmatch( pattern, filename, (int)flags ));
2250
0
}
2251
/* }}} */
2252
#endif
2253
2254
/* {{{ Returns directory path used for temporary files */
2255
PHP_FUNCTION(sys_get_temp_dir)
2256
0
{
2257
0
  ZEND_PARSE_PARAMETERS_NONE();
2258
2259
0
  RETURN_STRING((char *)php_get_temporary_directory());
2260
0
}
2261
/* }}} */