repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
php-src
|
php-src-master/ext/dba/libinifile/inifile.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id: bb00b98fa4a14dfc9555fb285175d1c7acbaac4f $ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_globals.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "inifile.h"
/* ret = -1 means that database was opened for read-only
* ret = 0 success
* ret = 1 key already exists - nothing done
*/
/* {{{ inifile_version */
const char *inifile_version(void)
{
return "1.0, $Id: bb00b98fa4a14dfc9555fb285175d1c7acbaac4f $";
}
/* }}} */
/* {{{ inifile_free_key */
void inifile_key_free(key_type *key)
{
if (key->group) {
efree(key->group);
}
if (key->name) {
efree(key->name);
}
memset(key, 0, sizeof(key_type));
}
/* }}} */
/* {{{ inifile_free_val */
void inifile_val_free(val_type *val)
{
if (val->value) {
efree(val->value);
}
memset(val, 0, sizeof(val_type));
}
/* }}} */
/* {{{ inifile_free_val */
void inifile_line_free(line_type *ln)
{
inifile_key_free(&ln->key);
inifile_val_free(&ln->val);
ln->pos = 0;
}
/* }}} */
/* {{{ inifile_alloc */
inifile * inifile_alloc(php_stream *fp, int readonly, int persistent)
{
inifile *dba;
if (!readonly) {
if (!php_stream_truncate_supported(fp)) {
php_error_docref(NULL, E_WARNING, "Can't truncate this stream");
return NULL;
}
}
dba = pemalloc(sizeof(inifile), persistent);
memset(dba, 0, sizeof(inifile));
dba->fp = fp;
dba->readonly = readonly;
return dba;
}
/* }}} */
/* {{{ inifile_free */
void inifile_free(inifile *dba, int persistent)
{
if (dba) {
inifile_line_free(&dba->curr);
inifile_line_free(&dba->next);
pefree(dba, persistent);
}
}
/* }}} */
/* {{{ inifile_key_split */
key_type inifile_key_split(const char *group_name)
{
key_type key;
char *name;
if (group_name[0] == '[' && (name = strchr(group_name, ']')) != NULL) {
key.group = estrndup(group_name+1, name - (group_name + 1));
key.name = estrdup(name+1);
} else {
key.group = estrdup("");
key.name = estrdup(group_name);
}
return key;
}
/* }}} */
/* {{{ inifile_key_string */
char * inifile_key_string(const key_type *key)
{
if (key->group && *key->group) {
char *result;
spprintf(&result, 0, "[%s]%s", key->group, key->name ? key->name : "");
return result;
} else if (key->name) {
return estrdup(key->name);
} else {
return NULL;
}
}
/* }}} */
/* {{{ etrim */
static char *etrim(const char *str)
{
char *val;
size_t l;
if (!str) {
return NULL;
}
val = (char*)str;
while (*val && strchr(" \t\r\n", *val)) {
val++;
}
l = strlen(val);
while (l && (strchr(" \t\r\n", val[l-1]))) {
l--;
}
return estrndup(val, l);
}
/* }}} */
/* {{{ inifile_findkey */
static int inifile_read(inifile *dba, line_type *ln) {
char *fline;
char *pos;
inifile_val_free(&ln->val);
while ((fline = php_stream_gets(dba->fp, NULL, 0)) != NULL) {
if (fline) {
if (fline[0] == '[') {
/* A value name cannot start with '['
* So either we find a ']' or we found an error
*/
pos = strchr(fline+1, ']');
if (pos) {
*pos = '\0';
inifile_key_free(&ln->key);
ln->key.group = etrim(fline+1);
ln->key.name = estrdup("");
ln->pos = php_stream_tell(dba->fp);
efree(fline);
return 1;
} else {
efree(fline);
continue;
}
} else {
pos = strchr(fline, '=');
if (pos) {
*pos = '\0';
/* keep group or make empty if not existent */
if (!ln->key.group) {
ln->key.group = estrdup("");
}
if (ln->key.name) {
efree(ln->key.name);
}
ln->key.name = etrim(fline);
ln->val.value = etrim(pos+1);
ln->pos = php_stream_tell(dba->fp);
efree(fline);
return 1;
} else {
/* simply ignore lines without '='
* those should be comments
*/
efree(fline);
continue;
}
}
}
}
inifile_line_free(ln);
return 0;
}
/* }}} */
/* {{{ inifile_key_cmp */
/* 0 = EQUAL
* 1 = GROUP-EQUAL,NAME-DIFFERENT
* 2 = DIFFERENT
*/
static int inifile_key_cmp(const key_type *k1, const key_type *k2)
{
assert(k1->group && k1->name && k2->group && k2->name);
if (!strcasecmp(k1->group, k2->group)) {
if (!strcasecmp(k1->name, k2->name)) {
return 0;
} else {
return 1;
}
} else {
return 2;
}
}
/* }}} */
/* {{{ inifile_fetch */
val_type inifile_fetch(inifile *dba, const key_type *key, int skip) {
line_type ln = {{NULL,NULL},{NULL},0};
val_type val;
int res, grp_eq = 0;
if (skip == -1 && dba->next.key.group && dba->next.key.name && !inifile_key_cmp(&dba->next.key, key)) {
/* we got position already from last fetch */
php_stream_seek(dba->fp, dba->next.pos, SEEK_SET);
ln.key.group = estrdup(dba->next.key.group);
} else {
/* specific instance or not same key -> restart search */
/* the slow way: restart and seacrch */
php_stream_rewind(dba->fp);
inifile_line_free(&dba->next);
}
if (skip == -1) {
skip = 0;
}
while(inifile_read(dba, &ln)) {
if (!(res=inifile_key_cmp(&ln.key, key))) {
if (!skip) {
val.value = estrdup(ln.val.value ? ln.val.value : "");
/* allow faster access by updating key read into next */
inifile_line_free(&dba->next);
dba->next = ln;
dba->next.pos = php_stream_tell(dba->fp);
return val;
}
skip--;
} else if (res == 1) {
grp_eq = 1;
} else if (grp_eq) {
/* we are leaving group now: that means we cannot find the key */
break;
}
}
inifile_line_free(&ln);
dba->next.pos = php_stream_tell(dba->fp);
return ln.val;
}
/* }}} */
/* {{{ inifile_firstkey */
int inifile_firstkey(inifile *dba) {
inifile_line_free(&dba->curr);
dba->curr.pos = 0;
return inifile_nextkey(dba);
}
/* }}} */
/* {{{ inifile_nextkey */
int inifile_nextkey(inifile *dba) {
line_type ln = {{NULL,NULL},{NULL},0};
/*inifile_line_free(&dba->next); ??? */
php_stream_seek(dba->fp, dba->curr.pos, SEEK_SET);
ln.key.group = estrdup(dba->curr.key.group ? dba->curr.key.group : "");
inifile_read(dba, &ln);
inifile_line_free(&dba->curr);
dba->curr = ln;
return ln.key.group || ln.key.name;
}
/* }}} */
/* {{{ inifile_truncate */
static int inifile_truncate(inifile *dba, size_t size)
{
int res;
if ((res=php_stream_truncate_set_size(dba->fp, size)) != 0) {
php_error_docref(NULL, E_WARNING, "Error in ftruncate: %d", res);
return FAILURE;
}
php_stream_seek(dba->fp, size, SEEK_SET);
return SUCCESS;
}
/* }}} */
/* {{{ inifile_find_group
* if found pos_grp_start points to "[group_name]"
*/
static int inifile_find_group(inifile *dba, const key_type *key, size_t *pos_grp_start)
{
int ret = FAILURE;
php_stream_flush(dba->fp);
php_stream_seek(dba->fp, 0, SEEK_SET);
inifile_line_free(&dba->curr);
inifile_line_free(&dba->next);
if (key->group && strlen(key->group)) {
int res;
line_type ln = {{NULL,NULL},{NULL},0};
res = 1;
while(inifile_read(dba, &ln)) {
if ((res=inifile_key_cmp(&ln.key, key)) < 2) {
ret = SUCCESS;
break;
}
*pos_grp_start = php_stream_tell(dba->fp);
}
inifile_line_free(&ln);
} else {
*pos_grp_start = 0;
ret = SUCCESS;
}
if (ret == FAILURE) {
*pos_grp_start = php_stream_tell(dba->fp);
}
return ret;
}
/* }}} */
/* {{{ inifile_next_group
* only valid after a call to inifile_find_group
* if any next group is found pos_grp_start points to "[group_name]" or whitespace before that
*/
static int inifile_next_group(inifile *dba, const key_type *key, size_t *pos_grp_start)
{
int ret = FAILURE;
line_type ln = {{NULL,NULL},{NULL},0};
*pos_grp_start = php_stream_tell(dba->fp);
ln.key.group = estrdup(key->group);
while(inifile_read(dba, &ln)) {
if (inifile_key_cmp(&ln.key, key) == 2) {
ret = SUCCESS;
break;
}
*pos_grp_start = php_stream_tell(dba->fp);
}
inifile_line_free(&ln);
return ret;
}
/* }}} */
/* {{{ inifile_copy_to */
static int inifile_copy_to(inifile *dba, size_t pos_start, size_t pos_end, inifile **ini_copy)
{
php_stream *fp;
if (pos_start == pos_end) {
*ini_copy = NULL;
return SUCCESS;
}
if ((fp = php_stream_temp_create(0, 64 * 1024)) == NULL) {
php_error_docref(NULL, E_WARNING, "Could not create temporary stream");
*ini_copy = NULL;
return FAILURE;
}
if ((*ini_copy = inifile_alloc(fp, 1, 0)) == NULL) {
/* writes error */
return FAILURE;
}
php_stream_seek(dba->fp, pos_start, SEEK_SET);
if (SUCCESS != php_stream_copy_to_stream_ex(dba->fp, fp, pos_end - pos_start, NULL)) {
php_error_docref(NULL, E_WARNING, "Could not copy group [%zu - %zu] to temporary stream", pos_start, pos_end);
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* {{{ inifile_filter
* copy from to dba while ignoring key name (group must equal)
*/
static int inifile_filter(inifile *dba, inifile *from, const key_type *key, bool *found)
{
size_t pos_start = 0, pos_next = 0, pos_curr;
int ret = SUCCESS;
line_type ln = {{NULL,NULL},{NULL},0};
php_stream_seek(from->fp, 0, SEEK_SET);
php_stream_seek(dba->fp, 0, SEEK_END);
while(inifile_read(from, &ln)) {
switch(inifile_key_cmp(&ln.key, key)) {
case 0:
if (found) {
*found = (bool) 1;
}
pos_curr = php_stream_tell(from->fp);
if (pos_start != pos_next) {
php_stream_seek(from->fp, pos_start, SEEK_SET);
if (SUCCESS != php_stream_copy_to_stream_ex(from->fp, dba->fp, pos_next - pos_start, NULL)) {
php_error_docref(NULL, E_WARNING, "Could not copy [%zu - %zu] from temporary stream", pos_next, pos_start);
ret = FAILURE;
}
php_stream_seek(from->fp, pos_curr, SEEK_SET);
}
pos_next = pos_start = pos_curr;
break;
case 1:
pos_next = php_stream_tell(from->fp);
break;
case 2:
/* the function is meant to process only entries from same group */
assert(0);
break;
}
}
if (pos_start != pos_next) {
php_stream_seek(from->fp, pos_start, SEEK_SET);
if (SUCCESS != php_stream_copy_to_stream_ex(from->fp, dba->fp, pos_next - pos_start, NULL)) {
php_error_docref(NULL, E_WARNING, "Could not copy [%zu - %zu] from temporary stream", pos_next, pos_start);
ret = FAILURE;
}
}
inifile_line_free(&ln);
return ret;
}
/* }}} */
/* {{{ inifile_delete_replace_append */
static int inifile_delete_replace_append(inifile *dba, const key_type *key, const val_type *value, int append, bool *found)
{
size_t pos_grp_start=0, pos_grp_next;
inifile *ini_tmp = NULL;
php_stream *fp_tmp = NULL;
int ret;
/* 1) Search group start
* 2) Search next group
* 3) If not append: Copy group to ini_tmp
* 4) Open temp_stream and copy remainder
* 5) Truncate stream
* 6) If not append AND key.name given: Filtered copy back from ini_tmp
* to stream. Otherwise the user wanted to delete the group.
* 7) Append value if given
* 8) Append temporary stream
*/
assert(!append || (key->name && value)); /* missuse */
/* 1 - 3 */
inifile_find_group(dba, key, &pos_grp_start);
inifile_next_group(dba, key, &pos_grp_next);
if (append) {
ret = SUCCESS;
} else {
ret = inifile_copy_to(dba, pos_grp_start, pos_grp_next, &ini_tmp);
}
/* 4 */
if (ret == SUCCESS) {
fp_tmp = php_stream_temp_create(0, 64 * 1024);
if (!fp_tmp) {
php_error_docref(NULL, E_WARNING, "Could not create temporary stream");
ret = FAILURE;
} else {
php_stream_seek(dba->fp, 0, SEEK_END);
if (pos_grp_next != (size_t)php_stream_tell(dba->fp)) {
php_stream_seek(dba->fp, pos_grp_next, SEEK_SET);
if (SUCCESS != php_stream_copy_to_stream_ex(dba->fp, fp_tmp, PHP_STREAM_COPY_ALL, NULL)) {
php_error_docref(NULL, E_WARNING, "Could not copy remainder to temporary stream");
ret = FAILURE;
}
}
}
}
/* 5 */
if (ret == SUCCESS) {
if (!value || (key->name && strlen(key->name))) {
ret = inifile_truncate(dba, append ? pos_grp_next : pos_grp_start); /* writes error on fail */
}
}
if (ret == SUCCESS) {
if (key->name && strlen(key->name)) {
/* 6 */
if (!append && ini_tmp) {
ret = inifile_filter(dba, ini_tmp, key, found);
}
/* 7 */
/* important: do not query ret==SUCCESS again: inifile_filter might fail but
* however next operation must be done.
*/
if (value) {
if (pos_grp_start == pos_grp_next && key->group && strlen(key->group)) {
php_stream_printf(dba->fp, "[%s]\n", key->group);
}
php_stream_printf(dba->fp, "%s=%s\n", key->name, value->value ? value->value : "");
}
}
/* 8 */
/* important: do not query ret==SUCCESS again: inifile_filter might fail but
* however next operation must be done.
*/
if (fp_tmp && php_stream_tell(fp_tmp)) {
php_stream_seek(fp_tmp, 0, SEEK_SET);
php_stream_seek(dba->fp, 0, SEEK_END);
if (SUCCESS != php_stream_copy_to_stream_ex(fp_tmp, dba->fp, PHP_STREAM_COPY_ALL, NULL)) {
zend_throw_error(NULL, "Could not copy from temporary stream - ini file truncated");
ret = FAILURE;
}
}
}
if (ini_tmp) {
php_stream_close(ini_tmp->fp);
inifile_free(ini_tmp, 0);
}
if (fp_tmp) {
php_stream_close(fp_tmp);
}
php_stream_flush(dba->fp);
php_stream_seek(dba->fp, 0, SEEK_SET);
return ret;
}
/* }}} */
/* {{{ inifile_delete */
int inifile_delete(inifile *dba, const key_type *key)
{
return inifile_delete_replace_append(dba, key, NULL, 0, NULL);
}
/* }}} */
/* {{{ inifile_delete_ex */
int inifile_delete_ex(inifile *dba, const key_type *key, bool *found)
{
return inifile_delete_replace_append(dba, key, NULL, 0, found);
}
/* }}} */
/* {{{ inifile_relace */
int inifile_replace(inifile *dba, const key_type *key, const val_type *value)
{
return inifile_delete_replace_append(dba, key, value, 0, NULL);
}
/* }}} */
/* {{{ inifile_replace_ex */
int inifile_replace_ex(inifile *dba, const key_type *key, const val_type *value, bool *found)
{
return inifile_delete_replace_append(dba, key, value, 0, found);
}
/* }}} */
/* {{{ inifile_append */
int inifile_append(inifile *dba, const key_type *key, const val_type *value)
{
return inifile_delete_replace_append(dba, key, value, 1, NULL);
}
/* }}} */
| 14,868 | 24.159052 | 123 |
c
|
php-src
|
php-src-master/ext/dba/libinifile/inifile.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_LIB_INIFILE_H
#define PHP_LIB_INIFILE_H
typedef struct {
char *group;
char *name;
} key_type;
typedef struct {
char *value;
} val_type;
typedef struct {
key_type key;
val_type val;
size_t pos;
} line_type;
typedef struct {
char *lockfn;
int lockfd;
php_stream *fp;
int readonly;
line_type curr;
line_type next;
} inifile;
val_type inifile_fetch(inifile *dba, const key_type *key, int skip);
int inifile_firstkey(inifile *dba);
int inifile_nextkey(inifile *dba);
int inifile_delete(inifile *dba, const key_type *key);
int inifile_delete_ex(inifile *dba, const key_type *key, bool *found);
int inifile_replace(inifile *dba, const key_type *key, const val_type *val);
int inifile_replace_ex(inifile *dba, const key_type *key, const val_type *val, bool *found);
int inifile_append(inifile *dba, const key_type *key, const val_type *val);
const char *inifile_version(void);
key_type inifile_key_split(const char *group_name);
char * inifile_key_string(const key_type *key);
void inifile_key_free(key_type *key);
void inifile_val_free(val_type *val);
void inifile_line_free(line_type *ln);
inifile * inifile_alloc(php_stream *fp, int readonly, int persistent);
void inifile_free(inifile *dba, int persistent);
#endif
| 2,240 | 33.476923 | 92 |
h
|
php-src
|
php-src-master/ext/dl_test/dl_test_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 547ddbc21e9aa853b491cb17e902bbbb9cc2df00 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dl_test_test1, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dl_test_test2, 0, 0, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, str, IS_STRING, 0, "\"\"")
ZEND_END_ARG_INFO()
ZEND_FUNCTION(dl_test_test1);
ZEND_FUNCTION(dl_test_test2);
static const zend_function_entry ext_functions[] = {
ZEND_FE(dl_test_test1, arginfo_dl_test_test1)
ZEND_FE(dl_test_test2, arginfo_dl_test_test2)
ZEND_FE_END
};
| 622 | 28.666667 | 82 |
h
|
php-src
|
php-src-master/ext/dl_test/php_dl_test.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
#ifndef PHP_DL_TEST_H
# define PHP_DL_TEST_H
extern zend_module_entry dl_test_module_entry;
# define phpext_dl_test_ptr &dl_test_module_entry
# define PHP_DL_TEST_VERSION PHP_VERSION
# if defined(ZTS) && defined(COMPILE_DL_DL_TEST)
ZEND_TSRMLS_CACHE_EXTERN()
# endif
ZEND_BEGIN_MODULE_GLOBALS(dl_test)
zend_long long_value;
char *string_value;
ZEND_END_MODULE_GLOBALS(dl_test);
#define DT_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(dl_test, v)
#endif /* PHP_DL_TEST_H */
| 1,452 | 38.27027 | 74 |
h
|
php-src
|
php-src-master/ext/dom/attr.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMAttr extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-637646024
* Since:
*/
/* {{{ */
PHP_METHOD(DOMAttr, __construct)
{
xmlAttrPtr nodep = NULL;
xmlNodePtr oldnode = NULL;
dom_object *intern;
char *name, *value = NULL;
size_t name_len, value_len, name_valid;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &name, &name_len, &value, &value_len) == FAILURE) {
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
name_valid = xmlValidateName((xmlChar *) name, 0);
if (name_valid != 0) {
php_dom_throw_error(INVALID_CHARACTER_ERR, 1);
RETURN_THROWS();
}
nodep = xmlNewProp(NULL, (xmlChar *) name, (xmlChar *) value);
if (!nodep) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)nodep, (void *)intern);
}
/* }}} end DOMAttr::__construct */
/* {{{ name string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-1112119403
Since:
*/
int dom_attr_name_read(dom_object *obj, zval *retval)
{
xmlAttrPtr attrp;
attrp = (xmlAttrPtr) dom_object_get_node(obj);
if (attrp == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
ZVAL_STRING(retval, (char *) attrp->name);
return SUCCESS;
}
/* }}} */
/* {{{ specified boolean
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-862529273
Since:
*/
int dom_attr_specified_read(dom_object *obj, zval *retval)
{
/* TODO */
ZVAL_TRUE(retval);
return SUCCESS;
}
/* }}} */
/* {{{ value string
readonly=no
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-221662474
Since:
*/
int dom_attr_value_read(dom_object *obj, zval *retval)
{
xmlAttrPtr attrp = (xmlAttrPtr) dom_object_get_node(obj);
xmlChar *content;
if (attrp == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
/* Can't avoid a content copy because it's an attribute node */
if ((content = xmlNodeGetContent((xmlNodePtr) attrp)) != NULL) {
ZVAL_STRING(retval, (char *) content);
xmlFree(content);
} else {
ZVAL_EMPTY_STRING(retval);
}
return SUCCESS;
}
int dom_attr_value_write(dom_object *obj, zval *newval)
{
zend_string *str;
xmlAttrPtr attrp = (xmlAttrPtr) dom_object_get_node(obj);
if (attrp == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
str = zval_try_get_string(newval);
if (UNEXPECTED(!str)) {
return FAILURE;
}
dom_remove_all_children((xmlNodePtr) attrp);
xmlNodeSetContentLen((xmlNodePtr) attrp, (xmlChar *) ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release_ex(str, 0);
return SUCCESS;
}
/* }}} */
/* {{{ ownerElement DOMElement
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Attr-ownerElement
Since: DOM Level 2
*/
int dom_attr_owner_element_read(dom_object *obj, zval *retval)
{
xmlNodePtr nodep, nodeparent;
nodep = dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
nodeparent = nodep->parent;
if (!nodeparent) {
ZVAL_NULL(retval);
return SUCCESS;
}
php_dom_create_object(nodeparent, retval, obj);
return SUCCESS;
}
/* }}} */
/* {{{ schemaTypeInfo DOMTypeInfo
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Attr-schemaTypeInfo
Since: DOM Level 3
*/
int dom_attr_schema_type_info_read(dom_object *obj, zval *retval)
{
/* TODO */
ZVAL_NULL(retval);
return SUCCESS;
}
/* }}} */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Attr-isId
Since: DOM Level 3
*/
PHP_METHOD(DOMAttr, isId)
{
zval *id;
dom_object *intern;
xmlAttrPtr attrp;
id = ZEND_THIS;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(attrp, id, xmlAttrPtr, intern);
if (attrp->atype == XML_ATTRIBUTE_ID) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} end dom_attr_is_id */
#endif
| 5,342 | 22.434211 | 102 |
c
|
php-src
|
php-src-master/ext/dom/cdatasection.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMCdataSection extends DOMText
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-667469212
* Since:
*/
/* {{{ */
PHP_METHOD(DOMCdataSection, __construct)
{
xmlNodePtr nodep = NULL, oldnode = NULL;
dom_object *intern;
char *value = NULL;
size_t value_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &value, &value_len) == FAILURE) {
RETURN_THROWS();
}
nodep = xmlNewCDataBlock(NULL, (xmlChar *) value, value_len);
if (!nodep) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, nodep, (void *)intern);
}
/* }}} end DOMCdataSection::__construct */
#endif
| 2,049 | 32.064516 | 90 |
c
|
php-src
|
php-src-master/ext/dom/characterdata.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMCharacterData extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-FF21A306
* Since:
*/
/* {{{ data string
readonly=no
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-72AB8359
Since:
*/
int dom_characterdata_data_read(dom_object *obj, zval *retval)
{
xmlNodePtr nodep = dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
php_dom_get_content_into_zval(nodep, retval, false);
return SUCCESS;
}
int dom_characterdata_data_write(dom_object *obj, zval *newval)
{
xmlNode *nodep = dom_object_get_node(obj);
zend_string *str;
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
str = zval_try_get_string(newval);
if (UNEXPECTED(!str)) {
return FAILURE;
}
xmlNodeSetContentLen(nodep, (xmlChar *) ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release_ex(str, 0);
return SUCCESS;
}
/* }}} */
/* {{{ length long
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-7D61178C
Since:
*/
int dom_characterdata_length_read(dom_object *obj, zval *retval)
{
xmlNodePtr nodep = dom_object_get_node(obj);
long length = 0;
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (nodep->content) {
length = xmlUTF8Strlen(nodep->content);
}
ZVAL_LONG(retval, length);
return SUCCESS;
}
/* }}} */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6531BCCF
Since:
*/
PHP_METHOD(DOMCharacterData, substringData)
{
zval *id;
xmlChar *cur;
xmlChar *substring;
xmlNodePtr node;
zend_long offset, count;
int length;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll", &offset, &count) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(node, id, xmlNodePtr, intern);
cur = node->content;
if (cur == NULL) {
RETURN_FALSE;
}
length = xmlUTF8Strlen(cur);
if (offset < 0 || count < 0 || ZEND_LONG_INT_OVFL(offset) || ZEND_LONG_INT_OVFL(count) || offset > length) {
php_dom_throw_error(INDEX_SIZE_ERR, dom_get_strict_error(intern->document));
RETURN_FALSE;
}
if ((offset + count) > length) {
count = length - offset;
}
substring = xmlUTF8Strsub(cur, (int)offset, (int)count);
if (substring) {
RETVAL_STRING((char *) substring);
xmlFree(substring);
} else {
RETVAL_EMPTY_STRING();
}
}
/* }}} end dom_characterdata_substring_data */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-32791A2F
Since:
*/
PHP_METHOD(DOMCharacterData, appendData)
{
zval *id;
xmlNode *nodep;
dom_object *intern;
char *arg;
size_t arg_len;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(nodep, id, xmlNodePtr, intern);
xmlTextConcat(nodep, (xmlChar *) arg, arg_len);
RETURN_TRUE;
}
/* }}} end dom_characterdata_append_data */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3EDB695F
Since:
*/
PHP_METHOD(DOMCharacterData, insertData)
{
zval *id;
xmlChar *cur, *first, *second;
xmlNodePtr node;
char *arg;
zend_long offset;
int length;
size_t arg_len;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ls", &offset, &arg, &arg_len) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(node, id, xmlNodePtr, intern);
cur = node->content;
if (cur == NULL) {
RETURN_FALSE;
}
length = xmlUTF8Strlen(cur);
if (offset < 0 || ZEND_LONG_INT_OVFL(offset) || offset > length) {
php_dom_throw_error(INDEX_SIZE_ERR, dom_get_strict_error(intern->document));
RETURN_FALSE;
}
first = xmlUTF8Strndup(cur, (int)offset);
second = xmlUTF8Strsub(cur, (int)offset, length - (int)offset);
xmlNodeSetContent(node, first);
xmlNodeAddContent(node, (xmlChar *) arg);
xmlNodeAddContent(node, second);
xmlFree(first);
xmlFree(second);
RETURN_TRUE;
}
/* }}} end dom_characterdata_insert_data */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-7C603781
Since:
*/
PHP_METHOD(DOMCharacterData, deleteData)
{
zval *id;
xmlChar *cur, *substring, *second;
xmlNodePtr node;
zend_long offset, count;
int length;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll", &offset, &count) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(node, id, xmlNodePtr, intern);
cur = node->content;
if (cur == NULL) {
RETURN_FALSE;
}
length = xmlUTF8Strlen(cur);
if (offset < 0 || count < 0 || ZEND_LONG_INT_OVFL(offset) || ZEND_LONG_INT_OVFL(count) || offset > length) {
php_dom_throw_error(INDEX_SIZE_ERR, dom_get_strict_error(intern->document));
RETURN_FALSE;
}
if (offset > 0) {
substring = xmlUTF8Strsub(cur, 0, (int)offset);
} else {
substring = NULL;
}
if ((offset + count) > length) {
count = length - offset;
}
second = xmlUTF8Strsub(cur, (int)offset + (int)count, length - (int)offset);
substring = xmlStrcat(substring, second);
xmlNodeSetContent(node, substring);
xmlFree(second);
xmlFree(substring);
RETURN_TRUE;
}
/* }}} end dom_characterdata_delete_data */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-E5CBA7FB
Since:
*/
PHP_METHOD(DOMCharacterData, replaceData)
{
zval *id;
xmlChar *cur, *substring, *second = NULL;
xmlNodePtr node;
char *arg;
zend_long offset, count;
int length;
size_t arg_len;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "lls", &offset, &count, &arg, &arg_len) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(node, id, xmlNodePtr, intern);
cur = node->content;
if (cur == NULL) {
RETURN_FALSE;
}
length = xmlUTF8Strlen(cur);
if (offset < 0 || count < 0 || ZEND_LONG_INT_OVFL(offset) || ZEND_LONG_INT_OVFL(count) || offset > length) {
php_dom_throw_error(INDEX_SIZE_ERR, dom_get_strict_error(intern->document));
RETURN_FALSE;
}
if (offset > 0) {
substring = xmlUTF8Strsub(cur, 0, (int)offset);
} else {
substring = NULL;
}
if ((offset + count) > length) {
count = length - offset;
}
if (offset < length) {
second = xmlUTF8Strsub(cur, (int)offset + count, length - (int)offset);
}
substring = xmlStrcat(substring, (xmlChar *) arg);
substring = xmlStrcat(substring, second);
xmlNodeSetContent(node, substring);
if (second) {
xmlFree(second);
}
xmlFree(substring);
RETURN_TRUE;
}
/* }}} end dom_characterdata_replace_data */
PHP_METHOD(DOMCharacterData, remove)
{
dom_object *intern;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_child_node_remove(intern);
RETURN_NULL();
}
PHP_METHOD(DOMCharacterData, after)
{
uint32_t argc;
zval *args;
dom_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_parent_node_after(intern, args, argc);
}
PHP_METHOD(DOMCharacterData, before)
{
uint32_t argc;
zval *args;
dom_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_parent_node_before(intern, args, argc);
}
PHP_METHOD(DOMCharacterData, replaceWith)
{
uint32_t argc;
zval *args;
dom_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_parent_node_after(intern, args, argc);
dom_child_node_remove(intern);
}
#endif
| 8,926 | 21.772959 | 109 |
c
|
php-src
|
php-src-master/ext/dom/comment.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMComment extends DOMCharacterData
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-1728279322
* Since:
*/
/* {{{ */
PHP_METHOD(DOMComment, __construct)
{
xmlNodePtr nodep = NULL, oldnode = NULL;
dom_object *intern;
char *value = NULL;
size_t value_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &value, &value_len) == FAILURE) {
RETURN_THROWS();
}
nodep = xmlNewComment((xmlChar *) value);
if (!nodep) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
if (intern != NULL) {
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)nodep, (void *)intern);
}
}
/* }}} end DOMComment::__construct */
#endif
| 2,068 | 31.328125 | 101 |
c
|
php-src
|
php-src-master/ext/dom/documentfragment.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMDocumentFragment extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-B63ED1A3
* Since:
*/
/* {{{ */
PHP_METHOD(DOMDocumentFragment, __construct)
{
xmlNodePtr nodep = NULL, oldnode = NULL;
dom_object *intern;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
nodep = xmlNewDocFragment(NULL);
if (!nodep) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
/* php_dom_set_object(intern, nodep); */
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, nodep, (void *)intern);
}
/* }}} end DOMDocumentFragment::__construct */
/* {{{ */
PHP_METHOD(DOMDocumentFragment, appendXML) {
zval *id;
xmlNode *nodep;
dom_object *intern;
char *data = NULL;
size_t data_len = 0;
int err;
xmlNodePtr lst;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &data, &data_len) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(nodep, id, xmlNodePtr, intern);
if (dom_node_is_read_only(nodep) == SUCCESS) {
php_dom_throw_error(NO_MODIFICATION_ALLOWED_ERR, dom_get_strict_error(intern->document));
RETURN_FALSE;
}
if (data) {
err = xmlParseBalancedChunkMemory(nodep->doc, NULL, NULL, 0, (xmlChar *) data, &lst);
if (err != 0) {
RETURN_FALSE;
}
xmlAddChildList(nodep,lst);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ URL: https://dom.spec.whatwg.org/#dom-parentnode-append
Since: DOM Living Standard (DOM4)
*/
PHP_METHOD(DOMDocumentFragment, append)
{
uint32_t argc;
zval *args;
dom_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_parent_node_append(intern, args, argc);
}
/* }}} */
/* {{{ URL: https://dom.spec.whatwg.org/#dom-parentnode-prepend
Since: DOM Living Standard (DOM4)
*/
PHP_METHOD(DOMDocumentFragment, prepend)
{
uint32_t argc;
zval *args;
dom_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_parent_node_prepend(intern, args, argc);
}
/* }}} */
/* {{{ URL: https://dom.spec.whatwg.org/#dom-parentnode-replacechildren
Since:
*/
PHP_METHOD(DOMDocumentFragment, replaceChildren)
{
uint32_t argc = 0;
zval *args;
dom_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "*", &args, &argc) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_THIS_INTERN(intern);
dom_parent_node_replace_children(intern, args, argc);
}
/* }}} */
#endif
| 3,855 | 24.202614 | 91 |
c
|
php-src
|
php-src-master/ext/dom/documenttype.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/* {{{ name string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1844763134
Since:
*/
int dom_documenttype_name_read(dom_object *obj, zval *retval)
{
xmlDtdPtr dtdptr = (xmlDtdPtr) dom_object_get_node(obj);
if (dtdptr == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
ZVAL_STRING(retval, dtdptr->name ? (char *) (dtdptr->name) : "");
return SUCCESS;
}
/* }}} */
/* {{{ entities DOMNamedNodeMap
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1788794630
Since:
*/
int dom_documenttype_entities_read(dom_object *obj, zval *retval)
{
xmlDtdPtr doctypep = (xmlDtdPtr) dom_object_get_node(obj);
xmlHashTable *entityht;
dom_object *intern;
if (doctypep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
php_dom_create_iterator(retval, DOM_NAMEDNODEMAP);
entityht = (xmlHashTable *) doctypep->entities;
intern = Z_DOMOBJ_P(retval);
dom_namednode_iter(obj, XML_ENTITY_NODE, intern, entityht, NULL, 0, NULL, 0);
return SUCCESS;
}
/* }}} */
/* {{{ notations DOMNamedNodeMap
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D46829EF
Since:
*/
int dom_documenttype_notations_read(dom_object *obj, zval *retval)
{
xmlDtdPtr doctypep = (xmlDtdPtr) dom_object_get_node(obj);
xmlHashTable *notationht;
dom_object *intern;
if (doctypep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
php_dom_create_iterator(retval, DOM_NAMEDNODEMAP);
notationht = (xmlHashTable *) doctypep->notations;
intern = Z_DOMOBJ_P(retval);
dom_namednode_iter(obj, XML_NOTATION_NODE, intern, notationht, NULL, 0, NULL, 0);
return SUCCESS;
}
/* }}} */
/* {{{ publicId string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-Core-DocType-publicId
Since: DOM Level 2
*/
int dom_documenttype_public_id_read(dom_object *obj, zval *retval)
{
xmlDtdPtr dtdptr = (xmlDtdPtr) dom_object_get_node(obj);
if (dtdptr == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (dtdptr->ExternalID) {
ZVAL_STRING(retval, (char *) (dtdptr->ExternalID));
} else {
ZVAL_EMPTY_STRING(retval);
}
return SUCCESS;
}
/* }}} */
/* {{{ systemId string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-Core-DocType-systemId
Since: DOM Level 2
*/
int dom_documenttype_system_id_read(dom_object *obj, zval *retval)
{
xmlDtdPtr dtdptr = (xmlDtdPtr) dom_object_get_node(obj);
if (dtdptr == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (dtdptr->SystemID) {
ZVAL_STRING(retval, (char *) (dtdptr->SystemID));
} else {
ZVAL_EMPTY_STRING(retval);
}
return SUCCESS;
}
/* }}} */
/* {{{ internalSubset string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-Core-DocType-internalSubset
Since: DOM Level 2
*/
int dom_documenttype_internal_subset_read(dom_object *obj, zval *retval)
{
xmlDtdPtr dtdptr = (xmlDtdPtr) dom_object_get_node(obj);
xmlDtdPtr intsubset;
if (dtdptr == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (dtdptr->doc != NULL && ((intsubset = xmlGetIntSubset(dtdptr->doc)) != NULL)) {
smart_str ret_buf = {0};
xmlNodePtr cur = intsubset->children;
while (cur != NULL) {
xmlOutputBuffer *buff = xmlAllocOutputBuffer(NULL);
if (buff != NULL) {
xmlNodeDumpOutput (buff, NULL, cur, 0, 0, NULL);
xmlOutputBufferFlush(buff);
#ifdef LIBXML2_NEW_BUFFER
smart_str_appendl(&ret_buf, (const char *) xmlOutputBufferGetContent(buff), xmlOutputBufferGetSize(buff));
#else
smart_str_appendl(&ret_buf, (char *) buff->buffer->content, buff->buffer->use);
#endif
(void)xmlOutputBufferClose(buff);
}
cur = cur->next;
}
if (ret_buf.s) {
ZVAL_STR(retval, smart_str_extract(&ret_buf));
return SUCCESS;
}
}
ZVAL_NULL(retval);
return SUCCESS;
}
/* }}} */
#endif
| 5,271 | 24.717073 | 110 |
c
|
php-src
|
php-src-master/ext/dom/dom_ce.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef DOM_CE_H
#define DOM_CE_H
extern PHP_DOM_EXPORT zend_class_entry *dom_node_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_domexception_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_domimplementation_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_documentfragment_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_document_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_nodelist_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_namednodemap_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_characterdata_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_attr_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_element_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_text_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_comment_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_cdatasection_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_documenttype_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_notation_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_entity_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_entityreference_class_entry;
extern PHP_DOM_EXPORT zend_class_entry *dom_processinginstruction_class_entry;
#ifdef LIBXML_XPATH_ENABLED
extern PHP_DOM_EXPORT zend_class_entry *dom_xpath_class_entry;
#endif
extern PHP_DOM_EXPORT zend_class_entry *dom_namespace_node_class_entry;
#endif /* DOM_CE_H */
| 2,529 | 55.222222 | 78 |
h
|
php-src
|
php-src-master/ext/dom/dom_iterators.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
#include "dom_ce.h"
typedef struct _nodeIterator nodeIterator;
struct _nodeIterator {
int cur;
int index;
xmlNode *node;
};
typedef struct _notationIterator notationIterator;
struct _notationIterator {
int cur;
int index;
xmlNotation *notation;
};
#if LIBXML_VERSION >= 20908
static void itemHashScanner (void *payload, void *data, const xmlChar *name) /* {{{ */
#else
static void itemHashScanner (void *payload, void *data, xmlChar *name)
#endif
{
nodeIterator *priv = (nodeIterator *)data;
if(priv->cur < priv->index) {
priv->cur++;
} else {
if(priv->node == NULL) {
priv->node = (xmlNode *)payload;
}
}
}
/* }}} */
xmlNodePtr create_notation(const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) /* {{{ */
{
xmlEntityPtr ret;
ret = (xmlEntityPtr) xmlMalloc(sizeof(xmlEntity));
memset(ret, 0, sizeof(xmlEntity));
ret->type = XML_NOTATION_NODE;
ret->name = xmlStrdup(name);
ret->ExternalID = xmlStrdup(ExternalID);
ret->SystemID = xmlStrdup(SystemID);
ret->length = 0;
ret->content = NULL;
ret->URI = NULL;
ret->orig = NULL;
ret->children = NULL;
ret->parent = NULL;
ret->doc = NULL;
ret->_private = NULL;
ret->last = NULL;
ret->prev = NULL;
return((xmlNodePtr) ret);
}
/* }}} */
xmlNode *php_dom_libxml_hash_iter(xmlHashTable *ht, int index) /* {{{ */
{
xmlNode *nodep = NULL;
nodeIterator *iter;
int htsize;
if ((htsize = xmlHashSize(ht)) > 0 && index < htsize) {
iter = emalloc(sizeof(nodeIterator));
iter->cur = 0;
iter->index = index;
iter->node = NULL;
xmlHashScan(ht, itemHashScanner, iter);
nodep = iter->node;
efree(iter);
return nodep;
} else {
return NULL;
}
}
/* }}} */
xmlNode *php_dom_libxml_notation_iter(xmlHashTable *ht, int index) /* {{{ */
{
notationIterator *iter;
xmlNotation *notep = NULL;
int htsize;
if ((htsize = xmlHashSize(ht)) > 0 && index < htsize) {
iter = emalloc(sizeof(notationIterator));
iter->cur = 0;
iter->index = index;
iter->notation = NULL;
xmlHashScan(ht, itemHashScanner, iter);
notep = iter->notation;
efree(iter);
return create_notation(notep->name, notep->PublicID, notep->SystemID);
} else {
return NULL;
}
}
/* }}} */
static void php_dom_iterator_dtor(zend_object_iterator *iter) /* {{{ */
{
php_dom_iterator *iterator = (php_dom_iterator *)iter;
zval_ptr_dtor(&iterator->intern.data);
zval_ptr_dtor(&iterator->curobj);
}
/* }}} */
static int php_dom_iterator_valid(zend_object_iterator *iter) /* {{{ */
{
php_dom_iterator *iterator = (php_dom_iterator *)iter;
if (Z_TYPE(iterator->curobj) != IS_UNDEF) {
return SUCCESS;
} else {
return FAILURE;
}
}
/* }}} */
zval *php_dom_iterator_current_data(zend_object_iterator *iter) /* {{{ */
{
php_dom_iterator *iterator = (php_dom_iterator *)iter;
return &iterator->curobj;
}
/* }}} */
static void php_dom_iterator_current_key(zend_object_iterator *iter, zval *key) /* {{{ */
{
php_dom_iterator *iterator = (php_dom_iterator *)iter;
zval *object = &iterator->intern.data;
if (instanceof_function(Z_OBJCE_P(object), dom_nodelist_class_entry)) {
ZVAL_LONG(key, iter->index);
} else {
dom_object *intern = Z_DOMOBJ_P(&iterator->curobj);
if (intern != NULL && intern->ptr != NULL) {
xmlNodePtr curnode = (xmlNodePtr)((php_libxml_node_ptr *)intern->ptr)->node;
ZVAL_STRINGL(key, (char *) curnode->name, xmlStrlen(curnode->name));
} else {
ZVAL_NULL(key);
}
}
}
/* }}} */
static void php_dom_iterator_move_forward(zend_object_iterator *iter) /* {{{ */
{
zval *object;
xmlNodePtr curnode = NULL, basenode;
dom_object *intern;
dom_object *nnmap;
dom_nnodemap_object *objmap;
int previndex;
HashTable *nodeht;
zval *entry;
bool do_curobj_undef = 1;
php_dom_iterator *iterator = (php_dom_iterator *)iter;
object = &iterator->intern.data;
nnmap = Z_DOMOBJ_P(object);
objmap = (dom_nnodemap_object *)nnmap->ptr;
intern = Z_DOMOBJ_P(&iterator->curobj);
if (intern != NULL && intern->ptr != NULL) {
if (objmap->nodetype != XML_ENTITY_NODE &&
objmap->nodetype != XML_NOTATION_NODE) {
if (objmap->nodetype == DOM_NODESET) {
nodeht = HASH_OF(&objmap->baseobj_zv);
zend_hash_move_forward_ex(nodeht, &iterator->pos);
if ((entry = zend_hash_get_current_data_ex(nodeht, &iterator->pos))) {
zval_ptr_dtor(&iterator->curobj);
ZVAL_UNDEF(&iterator->curobj);
ZVAL_COPY(&iterator->curobj, entry);
do_curobj_undef = 0;
}
} else {
if (objmap->nodetype == XML_ATTRIBUTE_NODE ||
objmap->nodetype == XML_ELEMENT_NODE) {
curnode = (xmlNodePtr)((php_libxml_node_ptr *)intern->ptr)->node;
curnode = curnode->next;
} else {
/* The collection is live, we nav the tree from the base object if we cannot
* use the cache to restart from the last point. */
basenode = dom_object_get_node(objmap->baseobj);
if (UNEXPECTED(!basenode)) {
goto err;
}
if (php_dom_is_cache_tag_stale_from_node(&iterator->cache_tag, basenode)) {
php_dom_mark_cache_tag_up_to_date_from_node(&iterator->cache_tag, basenode);
previndex = 0;
if (basenode->type == XML_DOCUMENT_NODE || basenode->type == XML_HTML_DOCUMENT_NODE) {
curnode = xmlDocGetRootElement((xmlDoc *) basenode);
} else {
curnode = basenode->children;
}
} else {
previndex = iter->index - 1;
curnode = (xmlNodePtr)((php_libxml_node_ptr *)intern->ptr)->node;
}
curnode = dom_get_elements_by_tag_name_ns_raw(
basenode, curnode, (char *) objmap->ns, (char *) objmap->local, &previndex, iter->index);
}
}
} else {
if (objmap->nodetype == XML_ENTITY_NODE) {
curnode = php_dom_libxml_hash_iter(objmap->ht, iter->index);
} else {
curnode = php_dom_libxml_notation_iter(objmap->ht, iter->index);
}
}
}
err:
if (do_curobj_undef) {
zval_ptr_dtor(&iterator->curobj);
ZVAL_UNDEF(&iterator->curobj);
}
if (curnode) {
php_dom_create_object(curnode, &iterator->curobj, objmap->baseobj);
}
}
/* }}} */
static const zend_object_iterator_funcs php_dom_iterator_funcs = {
php_dom_iterator_dtor,
php_dom_iterator_valid,
php_dom_iterator_current_data,
php_dom_iterator_current_key,
php_dom_iterator_move_forward,
NULL,
NULL,
NULL, /* get_gc */
};
zend_object_iterator *php_dom_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
{
dom_object *intern;
dom_nnodemap_object *objmap;
xmlNodePtr curnode=NULL;
int curindex = 0;
HashTable *nodeht;
zval *entry;
php_dom_iterator *iterator;
if (by_ref) {
zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
return NULL;
}
iterator = emalloc(sizeof(php_dom_iterator));
zend_iterator_init(&iterator->intern);
iterator->cache_tag.modification_nr = 0;
ZVAL_OBJ_COPY(&iterator->intern.data, Z_OBJ_P(object));
iterator->intern.funcs = &php_dom_iterator_funcs;
ZVAL_UNDEF(&iterator->curobj);
intern = Z_DOMOBJ_P(object);
objmap = (dom_nnodemap_object *)intern->ptr;
if (objmap != NULL) {
if (objmap->nodetype != XML_ENTITY_NODE &&
objmap->nodetype != XML_NOTATION_NODE) {
if (objmap->nodetype == DOM_NODESET) {
nodeht = HASH_OF(&objmap->baseobj_zv);
zend_hash_internal_pointer_reset_ex(nodeht, &iterator->pos);
if ((entry = zend_hash_get_current_data_ex(nodeht, &iterator->pos))) {
ZVAL_COPY(&iterator->curobj, entry);
}
} else {
xmlNodePtr basep = (xmlNode *)dom_object_get_node(objmap->baseobj);
if (!basep) {
goto err;
}
if (objmap->nodetype == XML_ATTRIBUTE_NODE || objmap->nodetype == XML_ELEMENT_NODE) {
if (objmap->nodetype == XML_ATTRIBUTE_NODE) {
curnode = (xmlNodePtr) basep->properties;
} else {
curnode = (xmlNodePtr) basep->children;
}
} else {
xmlNodePtr nodep = basep;
if (nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_HTML_DOCUMENT_NODE) {
nodep = xmlDocGetRootElement((xmlDoc *) nodep);
} else {
nodep = nodep->children;
}
curnode = dom_get_elements_by_tag_name_ns_raw(
basep, nodep, (char *) objmap->ns, (char *) objmap->local, &curindex, 0);
}
}
} else {
if (objmap->nodetype == XML_ENTITY_NODE) {
curnode = php_dom_libxml_hash_iter(objmap->ht, 0);
} else {
curnode = php_dom_libxml_notation_iter(objmap->ht, 0);
}
}
}
err:
if (curnode) {
php_dom_create_object(curnode, &iterator->curobj, objmap->baseobj);
}
return &iterator->intern;
}
/* }}} */
#endif
| 9,643 | 27.448378 | 109 |
c
|
php-src
|
php-src-master/ext/dom/dom_properties.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef DOM_PROPERTIES_H
#define DOM_PROPERTIES_H
/* attr properties */
int dom_attr_name_read(dom_object *obj, zval *retval);
int dom_attr_specified_read(dom_object *obj, zval *retval);
int dom_attr_value_read(dom_object *obj, zval *retval);
int dom_attr_value_write(dom_object *obj, zval *newval);
int dom_attr_owner_element_read(dom_object *obj, zval *retval);
int dom_attr_schema_type_info_read(dom_object *obj, zval *retval);
/* characterdata properties */
int dom_characterdata_data_read(dom_object *obj, zval *retval);
int dom_characterdata_data_write(dom_object *obj, zval *newval);
int dom_characterdata_length_read(dom_object *obj, zval *retval);
/* document properties */
int dom_document_doctype_read(dom_object *obj, zval *retval);
int dom_document_implementation_read(dom_object *obj, zval *retval);
int dom_document_document_element_read(dom_object *obj, zval *retval);
int dom_document_actual_encoding_read(dom_object *obj, zval *retval);
int dom_document_actual_encoding_write(dom_object *obj, zval *newval);
int dom_document_encoding_read(dom_object *obj, zval *retval);
int dom_document_encoding_write(dom_object *obj, zval *newval);
int dom_document_standalone_read(dom_object *obj, zval *retval);
int dom_document_standalone_write(dom_object *obj, zval *newval);
int dom_document_version_read(dom_object *obj, zval *retval);
int dom_document_version_write(dom_object *obj, zval *newval);
int dom_document_strict_error_checking_read(dom_object *obj, zval *retval);
int dom_document_strict_error_checking_write(dom_object *obj, zval *newval);
int dom_document_document_uri_read(dom_object *obj, zval *retval);
int dom_document_document_uri_write(dom_object *obj, zval *newval);
int dom_document_config_read(dom_object *obj, zval *retval);
int dom_document_format_output_read(dom_object *obj, zval *retval);
int dom_document_format_output_write(dom_object *obj, zval *newval);
int dom_document_validate_on_parse_read(dom_object *obj, zval *retval);
int dom_document_validate_on_parse_write(dom_object *obj, zval *newval);
int dom_document_resolve_externals_read(dom_object *obj, zval *retval);
int dom_document_resolve_externals_write(dom_object *obj, zval *newval);
int dom_document_preserve_whitespace_read(dom_object *obj, zval *retval);
int dom_document_preserve_whitespace_write(dom_object *obj, zval *newval);
int dom_document_recover_read(dom_object *obj, zval *retval);
int dom_document_recover_write(dom_object *obj, zval *newval);
int dom_document_substitue_entities_read(dom_object *obj, zval *retval);
int dom_document_substitue_entities_write(dom_object *obj, zval *newval);
/* documenttype properties */
int dom_documenttype_name_read(dom_object *obj, zval *retval);
int dom_documenttype_entities_read(dom_object *obj, zval *retval);
int dom_documenttype_notations_read(dom_object *obj, zval *retval);
int dom_documenttype_public_id_read(dom_object *obj, zval *retval);
int dom_documenttype_system_id_read(dom_object *obj, zval *retval);
int dom_documenttype_internal_subset_read(dom_object *obj, zval *retval);
/* element properties */
int dom_element_tag_name_read(dom_object *obj, zval *retval);
int dom_element_class_name_read(dom_object *obj, zval *retval);
int dom_element_class_name_write(dom_object *obj, zval *newval);
int dom_element_id_read(dom_object *obj, zval *retval);
int dom_element_id_write(dom_object *obj, zval *newval);
int dom_element_schema_type_info_read(dom_object *obj, zval *retval);
/* entity properties */
int dom_entity_public_id_read(dom_object *obj, zval *retval);
int dom_entity_system_id_read(dom_object *obj, zval *retval);
int dom_entity_notation_name_read(dom_object *obj, zval *retval);
int dom_entity_actual_encoding_read(dom_object *obj, zval *retval);
int dom_entity_encoding_read(dom_object *obj, zval *retval);
int dom_entity_version_read(dom_object *obj, zval *retval);
/* namednodemap properties */
int dom_namednodemap_length_read(dom_object *obj, zval *retval);
/* parent node properties */
int dom_parent_node_first_element_child_read(dom_object *obj, zval *retval);
int dom_parent_node_last_element_child_read(dom_object *obj, zval *retval);
int dom_parent_node_child_element_count(dom_object *obj, zval *retval);
/* node properties */
int dom_node_node_name_read(dom_object *obj, zval *retval);
int dom_node_node_value_read(dom_object *obj, zval *retval);
int dom_node_node_value_write(dom_object *obj, zval *newval);
int dom_node_node_type_read(dom_object *obj, zval *retval);
int dom_node_parent_node_read(dom_object *obj, zval *retval);
int dom_node_parent_element_read(dom_object *obj, zval *retval);
int dom_node_child_nodes_read(dom_object *obj, zval *retval);
int dom_node_first_child_read(dom_object *obj, zval *retval);
int dom_node_last_child_read(dom_object *obj, zval *retval);
int dom_node_previous_sibling_read(dom_object *obj, zval *retval);
int dom_node_next_sibling_read(dom_object *obj, zval *retval);
int dom_node_previous_element_sibling_read(dom_object *obj, zval *retval);
int dom_node_next_element_sibling_read(dom_object *obj, zval *retval);
int dom_node_attributes_read(dom_object *obj, zval *retval);
int dom_node_is_connected_read(dom_object *obj, zval *retval);
int dom_node_owner_document_read(dom_object *obj, zval *retval);
int dom_node_namespace_uri_read(dom_object *obj, zval *retval);
int dom_node_prefix_read(dom_object *obj, zval *retval);
int dom_node_prefix_write(dom_object *obj, zval *newval);
int dom_node_local_name_read(dom_object *obj, zval *retval);
int dom_node_base_uri_read(dom_object *obj, zval *retval);
int dom_node_text_content_read(dom_object *obj, zval *retval);
int dom_node_text_content_write(dom_object *obj, zval *newval);
/* nodelist properties */
int dom_nodelist_length_read(dom_object *obj, zval *retval);
xmlNodePtr dom_nodelist_xml_item(dom_nnodemap_object *objmap, long index);
xmlNodePtr dom_nodelist_baseobj_item(dom_nnodemap_object *objmap, long index);
/* notation properties */
int dom_notation_public_id_read(dom_object *obj, zval *retval);
int dom_notation_system_id_read(dom_object *obj, zval *retval);
/* processinginstruction properties */
int dom_processinginstruction_target_read(dom_object *obj, zval *retval);
int dom_processinginstruction_data_read(dom_object *obj, zval *retval);
int dom_processinginstruction_data_write(dom_object *obj, zval *newval);
/* text properties */
int dom_text_whole_text_read(dom_object *obj, zval *retval);
#ifdef LIBXML_XPATH_ENABLED
/* xpath properties */
int dom_xpath_document_read(dom_object *obj, zval *retval);
int dom_xpath_register_node_ns_read(dom_object *obj, zval *retval);
int dom_xpath_register_node_ns_write(dom_object *obj, zval *newval);
#endif
#endif /* DOM_PROPERTIES_H */
| 7,770 | 52.226027 | 78 |
h
|
php-src
|
php-src-master/ext/dom/domexception.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMException
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-17189187
* Since:
*/
extern zend_class_entry *dom_domexception_class_entry;
void php_dom_throw_error_with_message(int error_code, char *error_message, int strict_error) /* {{{ */
{
if (strict_error == 1) {
zend_throw_exception(dom_domexception_class_entry, error_message, error_code);
} else {
php_libxml_issue_error(E_WARNING, error_message);
}
}
/* }}} */
/* {{{ php_dom_throw_error */
void php_dom_throw_error(int error_code, int strict_error)
{
char *error_message;
switch (error_code)
{
case INDEX_SIZE_ERR:
error_message = "Index Size Error";
break;
case DOMSTRING_SIZE_ERR:
error_message = "DOM String Size Error";
break;
case HIERARCHY_REQUEST_ERR:
error_message = "Hierarchy Request Error";
break;
case WRONG_DOCUMENT_ERR:
error_message = "Wrong Document Error";
break;
case INVALID_CHARACTER_ERR:
error_message = "Invalid Character Error";
break;
case NO_DATA_ALLOWED_ERR:
error_message = "No Data Allowed Error";
break;
case NO_MODIFICATION_ALLOWED_ERR:
error_message = "No Modification Allowed Error";
break;
case NOT_FOUND_ERR:
error_message = "Not Found Error";
break;
case NOT_SUPPORTED_ERR:
error_message = "Not Supported Error";
break;
case INUSE_ATTRIBUTE_ERR:
error_message = "Inuse Attribute Error";
break;
case INVALID_STATE_ERR:
error_message = "Invalid State Error";
break;
case SYNTAX_ERR:
error_message = "Syntax Error";
break;
case INVALID_MODIFICATION_ERR:
error_message = "Invalid Modification Error";
break;
case NAMESPACE_ERR:
error_message = "Namespace Error";
break;
case INVALID_ACCESS_ERR:
error_message = "Invalid Access Error";
break;
case VALIDATION_ERR:
error_message = "Validation Error";
break;
default:
error_message = "Unhandled Error";
}
php_dom_throw_error_with_message(error_code, error_message, strict_error);
}
/* }}} end php_dom_throw_error */
#endif /* HAVE_LIBXML && HAVE_DOM */
| 3,297 | 29.256881 | 102 |
c
|
php-src
|
php-src-master/ext/dom/domexception.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef DOM_EXCEPTION_H
#define DOM_EXCEPTION_H
/* domexception errors */
typedef enum {
/* PHP_ERR is non-spec code for PHP errors: */
PHP_ERR = 0,
INDEX_SIZE_ERR = 1,
DOMSTRING_SIZE_ERR = 2,
HIERARCHY_REQUEST_ERR = 3,
WRONG_DOCUMENT_ERR = 4,
INVALID_CHARACTER_ERR = 5,
NO_DATA_ALLOWED_ERR = 6,
NO_MODIFICATION_ALLOWED_ERR = 7,
NOT_FOUND_ERR = 8,
NOT_SUPPORTED_ERR = 9,
INUSE_ATTRIBUTE_ERR = 10,
/* Introduced in DOM Level 2: */
INVALID_STATE_ERR = 11,
/* Introduced in DOM Level 2: */
SYNTAX_ERR = 12,
/* Introduced in DOM Level 2: */
INVALID_MODIFICATION_ERR = 13,
/* Introduced in DOM Level 2: */
NAMESPACE_ERR = 14,
/* Introduced in DOM Level 2: */
INVALID_ACCESS_ERR = 15,
/* Introduced in DOM Level 3: */
VALIDATION_ERR = 16
} dom_exception_code;
#endif /* DOM_EXCEPTION_H */
| 2,093 | 40.88 | 75 |
h
|
php-src
|
php-src-master/ext/dom/entity.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMEntity extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-527DCFF2
* Since:
*/
/* {{{ publicId string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-D7303025
Since:
*/
int dom_entity_public_id_read(dom_object *obj, zval *retval)
{
xmlEntity *nodep = (xmlEntity *) dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (nodep->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
ZVAL_NULL(retval);
} else {
ZVAL_STRING(retval, (char *) (nodep->ExternalID));
}
return SUCCESS;
}
/* }}} */
/* {{{ systemId string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-D7C29F3E
Since:
*/
int dom_entity_system_id_read(dom_object *obj, zval *retval)
{
xmlEntity *nodep = (xmlEntity *) dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (nodep->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
ZVAL_NULL(retval);
} else {
ZVAL_STRING(retval, (char *) (nodep->SystemID));
}
return SUCCESS;
}
/* }}} */
/* {{{ notationName string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-6ABAEB38
Since:
*/
int dom_entity_notation_name_read(dom_object *obj, zval *retval)
{
xmlEntity *nodep = (xmlEntity *) dom_object_get_node(obj);
char *content;
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (nodep->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
ZVAL_NULL(retval);
} else {
content = (char *) xmlNodeGetContent((xmlNodePtr) nodep);
ZVAL_STRING(retval, content);
xmlFree(content);
}
return SUCCESS;
}
/* }}} */
/* {{{ actualEncoding string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Entity3-actualEncoding
Since: DOM Level 3
*/
int dom_entity_actual_encoding_read(dom_object *obj, zval *retval)
{
ZVAL_NULL(retval);
return SUCCESS;
}
/* }}} */
/* {{{ encoding string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Entity3-encoding
Since: DOM Level 3
*/
int dom_entity_encoding_read(dom_object *obj, zval *retval)
{
ZVAL_NULL(retval);
return SUCCESS;
}
/* }}} */
/* {{{ version string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Entity3-version
Since: DOM Level 3
*/
int dom_entity_version_read(dom_object *obj, zval *retval)
{
ZVAL_NULL(retval);
return SUCCESS;
}
/* }}} */
#endif
| 3,819 | 24.131579 | 97 |
c
|
php-src
|
php-src-master/ext/dom/entityreference.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMEntityReference extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-11C98490
* Since:
*/
/* {{{ */
PHP_METHOD(DOMEntityReference, __construct)
{
xmlNode *node;
xmlNodePtr oldnode = NULL;
dom_object *intern;
char *name;
size_t name_len, name_valid;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, &name_len) == FAILURE) {
RETURN_THROWS();
}
name_valid = xmlValidateName((xmlChar *) name, 0);
if (name_valid != 0) {
php_dom_throw_error(INVALID_CHARACTER_ERR, 1);
RETURN_THROWS();
}
node = xmlNewReference(NULL, (xmlChar *) name);
if (!node) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
if (intern != NULL) {
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, node, (void *)intern);
}
}
/* }}} end DOMEntityReference::__construct */
#endif
| 2,223 | 30.323944 | 89 |
c
|
php-src
|
php-src-master/ext/dom/namednodemap.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
#include "zend_interfaces.h"
/*
* class DOMNamedNodeMap
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1780488922
* Since:
*/
int php_dom_get_namednodemap_length(dom_object *obj)
{
dom_nnodemap_object *objmap = (dom_nnodemap_object *) obj->ptr;
if (!objmap) {
return 0;
}
if (objmap->nodetype == XML_NOTATION_NODE || objmap->nodetype == XML_ENTITY_NODE) {
return objmap->ht ? xmlHashSize(objmap->ht) : 0;
}
int count = 0;
xmlNodePtr nodep = dom_object_get_node(objmap->baseobj);
if (nodep) {
xmlAttrPtr curnode = nodep->properties;
if (curnode) {
count++;
while (curnode->next != NULL) {
count++;
curnode = curnode->next;
}
}
}
return count;
}
/* {{{ length int
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6D0FB19E
Since:
*/
int dom_namednodemap_length_read(dom_object *obj, zval *retval)
{
ZVAL_LONG(retval, php_dom_get_namednodemap_length(obj));
return SUCCESS;
}
/* }}} */
xmlNodePtr php_dom_named_node_map_get_named_item(dom_nnodemap_object *objmap, const char *named, bool may_transform)
{
xmlNodePtr itemnode = NULL;
if (objmap != NULL) {
if ((objmap->nodetype == XML_NOTATION_NODE) ||
objmap->nodetype == XML_ENTITY_NODE) {
if (objmap->ht) {
if (objmap->nodetype == XML_ENTITY_NODE) {
itemnode = (xmlNodePtr)xmlHashLookup(objmap->ht, (const xmlChar *) named);
} else {
xmlNotationPtr notep = xmlHashLookup(objmap->ht, (const xmlChar *) named);
if (notep) {
if (may_transform) {
itemnode = create_notation(notep->name, notep->PublicID, notep->SystemID);
} else {
itemnode = (xmlNodePtr) notep;
}
}
}
}
} else {
xmlNodePtr nodep = dom_object_get_node(objmap->baseobj);
if (nodep) {
itemnode = (xmlNodePtr)xmlHasProp(nodep, (const xmlChar *) named);
}
}
}
return itemnode;
}
void php_dom_named_node_map_get_named_item_into_zval(dom_nnodemap_object *objmap, const char *named, zval *return_value)
{
int ret;
xmlNodePtr itemnode = php_dom_named_node_map_get_named_item(objmap, named, true);
if (itemnode) {
DOM_RET_OBJ(itemnode, &ret, objmap->baseobj);
} else {
RETURN_NULL();
}
}
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1074577549
Since:
*/
PHP_METHOD(DOMNamedNodeMap, getNamedItem)
{
size_t namedlen;
char *named;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &named, &namedlen) == FAILURE) {
RETURN_THROWS();
}
zval *id = ZEND_THIS;
dom_nnodemap_object *objmap = Z_DOMOBJ_P(id)->ptr;
php_dom_named_node_map_get_named_item_into_zval(objmap, named, return_value);
}
/* }}} end dom_namednodemap_get_named_item */
xmlNodePtr php_dom_named_node_map_get_item(dom_nnodemap_object *objmap, zend_long index)
{
xmlNodePtr itemnode = NULL;
if (objmap != NULL) {
if ((objmap->nodetype == XML_NOTATION_NODE) ||
objmap->nodetype == XML_ENTITY_NODE) {
if (objmap->ht) {
if (objmap->nodetype == XML_ENTITY_NODE) {
itemnode = php_dom_libxml_hash_iter(objmap->ht, index);
} else {
itemnode = php_dom_libxml_notation_iter(objmap->ht, index);
}
}
} else {
xmlNodePtr nodep = dom_object_get_node(objmap->baseobj);
if (nodep) {
xmlNodePtr curnode = (xmlNodePtr)nodep->properties;
zend_long count = 0;
while (count < index && curnode != NULL) {
count++;
curnode = (xmlNodePtr)curnode->next;
}
itemnode = curnode;
}
}
}
return itemnode;
}
void php_dom_named_node_map_get_item_into_zval(dom_nnodemap_object *objmap, zend_long index, zval *return_value)
{
int ret;
xmlNodePtr itemnode = php_dom_named_node_map_get_item(objmap, index);
if (itemnode) {
DOM_RET_OBJ(itemnode, &ret, objmap->baseobj);
} else {
RETURN_NULL();
}
}
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-349467F9
Since:
*/
PHP_METHOD(DOMNamedNodeMap, item)
{
zend_long index;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(index)
ZEND_PARSE_PARAMETERS_END();
if (index < 0 || ZEND_LONG_INT_OVFL(index)) {
zend_argument_value_error(1, "must be between 0 and %d", INT_MAX);
RETURN_THROWS();
}
zval *id = ZEND_THIS;
dom_object *intern = Z_DOMOBJ_P(id);
dom_nnodemap_object *objmap = intern->ptr;
php_dom_named_node_map_get_item_into_zval(objmap, index, return_value);
}
/* }}} end dom_namednodemap_item */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getNamedItemNS
Since: DOM Level 2
*/
PHP_METHOD(DOMNamedNodeMap, getNamedItemNS)
{
zval *id;
int ret;
size_t namedlen=0, urilen=0;
dom_object *intern;
xmlNodePtr itemnode = NULL;
char *uri, *named;
dom_nnodemap_object *objmap;
xmlNodePtr nodep;
xmlNotation *notep = NULL;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s!s", &uri, &urilen, &named, &namedlen) == FAILURE) {
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(id);
objmap = (dom_nnodemap_object *)intern->ptr;
if (objmap != NULL) {
if ((objmap->nodetype == XML_NOTATION_NODE) ||
objmap->nodetype == XML_ENTITY_NODE) {
if (objmap->ht) {
if (objmap->nodetype == XML_ENTITY_NODE) {
itemnode = (xmlNodePtr)xmlHashLookup(objmap->ht, (xmlChar *) named);
} else {
notep = (xmlNotation *)xmlHashLookup(objmap->ht, (xmlChar *) named);
if (notep) {
itemnode = create_notation(notep->name, notep->PublicID, notep->SystemID);
}
}
}
} else {
nodep = dom_object_get_node(objmap->baseobj);
if (nodep) {
itemnode = (xmlNodePtr)xmlHasNsProp(nodep, (xmlChar *) named, (xmlChar *) uri);
}
}
}
if (itemnode) {
DOM_RET_OBJ(itemnode, &ret, objmap->baseobj);
return;
} else {
RETVAL_NULL();
}
}
/* }}} end dom_namednodemap_get_named_item_ns */
/* {{{ */
PHP_METHOD(DOMNamedNodeMap, count)
{
zval *id;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(id);
RETURN_LONG(php_dom_get_namednodemap_length(intern));
}
/* }}} end dom_namednodemap_count */
PHP_METHOD(DOMNamedNodeMap, getIterator)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_create_internal_iterator_zval(return_value, ZEND_THIS);
}
#endif
| 7,458 | 26.123636 | 120 |
c
|
php-src
|
php-src-master/ext/dom/notation.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMNotation extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-5431D1B9
* Since:
*/
/* {{{ attribute protos, not implemented yet */
/* {{{ publicId string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-54F2B4D0
Since:
*/
int dom_notation_public_id_read(dom_object *obj, zval *retval)
{
xmlEntityPtr nodep = (xmlEntityPtr) dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (nodep->ExternalID) {
ZVAL_STRING(retval, (char *) (nodep->ExternalID));
} else {
ZVAL_EMPTY_STRING(retval);
}
return SUCCESS;
}
/* }}} */
/* {{{ systemId string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-E8AAB1D0
Since:
*/
int dom_notation_system_id_read(dom_object *obj, zval *retval)
{
xmlEntityPtr nodep = (xmlEntityPtr) dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
if (nodep->SystemID) {
ZVAL_STRING(retval, (char *) (nodep->SystemID));
} else {
ZVAL_EMPTY_STRING(retval);
}
return SUCCESS;
}
/* }}} */
/* }}} */
#endif
| 2,420 | 26.511364 | 89 |
c
|
php-src
|
php-src-master/ext/dom/processinginstruction.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
/*
* class DOMProcessingInstruction extends DOMNode
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-1004215813
* Since:
*/
/* {{{ */
PHP_METHOD(DOMProcessingInstruction, __construct)
{
xmlNodePtr nodep = NULL, oldnode = NULL;
dom_object *intern;
char *name, *value = NULL;
size_t name_len, value_len;
int name_valid;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &name, &name_len, &value, &value_len) == FAILURE) {
RETURN_THROWS();
}
name_valid = xmlValidateName((xmlChar *) name, 0);
if (name_valid != 0) {
php_dom_throw_error(INVALID_CHARACTER_ERR, 1);
RETURN_THROWS();
}
nodep = xmlNewPI((xmlChar *) name, (xmlChar *) value);
if (!nodep) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, nodep, (void *)intern);
}
/* }}} end DOMProcessingInstruction::__construct */
/* {{{ target string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-1478689192
Since:
*/
int dom_processinginstruction_target_read(dom_object *obj, zval *retval)
{
xmlNodePtr nodep = dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
ZVAL_STRING(retval, (char *) (nodep->name));
return SUCCESS;
}
/* }}} */
/* {{{ data string
readonly=no
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-837822393
Since:
*/
int dom_processinginstruction_data_read(dom_object *obj, zval *retval)
{
xmlNodePtr nodep = dom_object_get_node(obj);
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
php_dom_get_content_into_zval(nodep, retval, false);
return SUCCESS;
}
int dom_processinginstruction_data_write(dom_object *obj, zval *newval)
{
xmlNode *nodep = dom_object_get_node(obj);
zend_string *str;
if (nodep == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
str = zval_try_get_string(newval);
if (UNEXPECTED(!str)) {
return FAILURE;
}
php_libxml_invalidate_node_list_cache_from_doc(nodep->doc);
xmlNodeSetContentLen(nodep, (xmlChar *) ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release_ex(str, 0);
return SUCCESS;
}
/* }}} */
#endif
| 3,616 | 25.992537 | 102 |
c
|
php-src
|
php-src-master/ext/dom/text.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if defined(HAVE_LIBXML) && defined(HAVE_DOM)
#include "php_dom.h"
#include "dom_ce.h"
/*
* class DOMText extends DOMCharacterData
*
* URL: https://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-1312295772
* Since:
*/
/* {{{ */
PHP_METHOD(DOMText, __construct)
{
xmlNodePtr nodep = NULL, oldnode = NULL;
dom_object *intern;
char *value = NULL;
size_t value_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &value, &value_len) == FAILURE) {
RETURN_THROWS();
}
nodep = xmlNewText((xmlChar *) value);
if (!nodep) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
RETURN_THROWS();
}
intern = Z_DOMOBJ_P(ZEND_THIS);
if (intern != NULL) {
oldnode = dom_object_get_node(intern);
if (oldnode != NULL) {
php_libxml_node_free_resource(oldnode );
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, nodep, (void *)intern);
}
}
/* }}} end DOMText::__construct */
/* {{{ wholeText string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-wholeText
Since: DOM Level 3
*/
int dom_text_whole_text_read(dom_object *obj, zval *retval)
{
xmlNodePtr node;
xmlChar *wholetext = NULL;
node = dom_object_get_node(obj);
if (node == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 1);
return FAILURE;
}
/* Find starting text node */
while (node->prev && ((node->prev->type == XML_TEXT_NODE) || (node->prev->type == XML_CDATA_SECTION_NODE))) {
node = node->prev;
}
/* concatenate all adjacent text and cdata nodes */
while (node && ((node->type == XML_TEXT_NODE) || (node->type == XML_CDATA_SECTION_NODE))) {
wholetext = xmlStrcat(wholetext, node->content);
node = node->next;
}
if (wholetext != NULL) {
ZVAL_STRING(retval, (char *) wholetext);
xmlFree(wholetext);
} else {
ZVAL_EMPTY_STRING(retval);
}
return SUCCESS;
}
/* }}} */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-38853C1D
Since:
*/
PHP_METHOD(DOMText, splitText)
{
zval *id;
xmlChar *cur;
xmlChar *first;
xmlChar *second;
xmlNodePtr node;
xmlNodePtr nnode;
zend_long offset;
int length;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &offset) == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(node, id, xmlNodePtr, intern);
if (offset < 0) {
zend_argument_value_error(1, "must be greater than or equal to 0");
RETURN_THROWS();
}
if (node->type != XML_TEXT_NODE && node->type != XML_CDATA_SECTION_NODE) {
/* TODO Add warning? */
RETURN_FALSE;
}
cur = node->content;
if (cur == NULL) {
/* TODO Add warning? */
RETURN_FALSE;
}
length = xmlUTF8Strlen(cur);
if (ZEND_LONG_INT_OVFL(offset) || (int)offset > length) {
/* TODO Add warning? */
RETURN_FALSE;
}
first = xmlUTF8Strndup(cur, (int)offset);
second = xmlUTF8Strsub(cur, (int)offset, (int)(length - offset));
xmlNodeSetContent(node, first);
nnode = xmlNewDocText(node->doc, second);
xmlFree(first);
xmlFree(second);
if (nnode == NULL) {
/* TODO Add warning? */
RETURN_FALSE;
}
if (node->parent != NULL) {
nnode->type = XML_ELEMENT_NODE;
xmlAddNextSibling(node, nnode);
nnode->type = XML_TEXT_NODE;
}
php_dom_create_object(nnode, return_value, intern);
}
/* }}} end dom_text_split_text */
/* {{{ URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-isWhitespaceInElementContent
Since: DOM Level 3
*/
PHP_METHOD(DOMText, isWhitespaceInElementContent)
{
zval *id;
xmlNodePtr node;
dom_object *intern;
id = ZEND_THIS;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
DOM_GET_OBJ(node, id, xmlNodePtr, intern);
if (xmlIsBlankNode(node)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} end dom_text_is_whitespace_in_element_content */
#endif
| 4,976 | 24.523077 | 121 |
c
|
php-src
|
php-src-master/ext/dom/xml_common.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <[email protected]> |
| Rob Richards <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_XML_COMMON_H
#define PHP_XML_COMMON_H
#include "ext/libxml/php_libxml.h"
typedef libxml_doc_props *dom_doc_propsptr;
typedef struct _dom_object {
void *ptr;
php_libxml_ref_obj *document;
HashTable *prop_handler;
zend_object std;
} dom_object;
static inline dom_object *php_dom_obj_from_obj(zend_object *obj) {
return (dom_object*)((char*)(obj) - XtOffsetOf(dom_object, std));
}
#define Z_DOMOBJ_P(zv) php_dom_obj_from_obj(Z_OBJ_P((zv)))
#ifdef PHP_WIN32
# ifdef DOM_EXPORTS
# define PHP_DOM_EXPORT __declspec(dllexport)
# elif !defined(DOM_LOCAL_DEFINES) /* Allow to counteract LNK4049 warning. */
# define PHP_DOM_EXPORT __declspec(dllimport)
# else
# define PHP_DOM_EXPORT
# endif /* DOM_EXPORTS */
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_DOM_EXPORT __attribute__ ((visibility("default")))
#elif defined(PHPAPI)
# define PHP_DOM_EXPORT PHPAPI
#else
# define PHP_DOM_EXPORT
#endif
PHP_DOM_EXPORT extern zend_class_entry *dom_node_class_entry;
PHP_DOM_EXPORT dom_object *php_dom_object_get_data(xmlNodePtr obj);
PHP_DOM_EXPORT bool php_dom_create_object(xmlNodePtr obj, zval* return_value, dom_object *domobj);
PHP_DOM_EXPORT xmlNodePtr dom_object_get_node(dom_object *obj);
#define DOM_XMLNS_NAMESPACE \
(const xmlChar *) "http://www.w3.org/2000/xmlns/"
#define NODE_GET_OBJ(__ptr, __id, __prtype, __intern) { \
__intern = Z_LIBXML_NODE_P(__id); \
if (UNEXPECTED(__intern->node == NULL)) { \
php_error_docref(NULL, E_WARNING, "Couldn't fetch %s", \
ZSTR_VAL(__intern->std.ce->name));\
RETURN_NULL();\
} \
__ptr = (__prtype)__intern->node->node; \
}
#define DOC_GET_OBJ(__ptr, __id, __prtype, __intern) { \
__intern = Z_LIBXML_NODE_P(__id); \
if (EXPECTED(__intern->document != NULL)) { \
__ptr = (__prtype)__intern->document->ptr); \
} \
}
#define DOM_RET_OBJ(obj, ret, domobject) \
*ret = php_dom_create_object(obj, return_value, domobject)
#define DOM_GET_THIS_OBJ(__ptr, __id, __prtype, __intern) \
__id = ZEND_THIS; \
DOM_GET_OBJ(__ptr, __id, __prtype, __intern);
#endif
| 3,110 | 34.758621 | 98 |
h
|
php-src
|
php-src-master/ext/enchant/enchant_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 42bb5a4488d254e87d763c75ccff62e283e63335 */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_enchant_broker_init, 0, 0, EnchantBroker, MAY_BE_FALSE)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_broker_free, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_enchant_broker_get_error, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_broker_set_dict_path, 0, 3, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_ARG_TYPE_INFO(0, type, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, path, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_enchant_broker_get_dict_path, 0, 2, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_ARG_TYPE_INFO(0, type, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_broker_list_dicts, 0, 1, IS_ARRAY, 0)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_enchant_broker_request_dict, 0, 2, EnchantDictionary, MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_ARG_TYPE_INFO(0, tag, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_enchant_broker_request_pwl_dict, 0, 2, EnchantDictionary, MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_broker_free_dict, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_broker_dict_exists, 0, 2, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_ARG_TYPE_INFO(0, tag, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_broker_set_ordering, 0, 3, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, broker, EnchantBroker, 0)
ZEND_ARG_TYPE_INFO(0, tag, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, ordering, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_enchant_broker_describe arginfo_enchant_broker_list_dicts
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_dict_quick_check, 0, 2, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_ARG_TYPE_INFO(0, word, IS_STRING, 0)
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, suggestions, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_dict_check, 0, 2, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_ARG_TYPE_INFO(0, word, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_dict_suggest, 0, 2, IS_ARRAY, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_ARG_TYPE_INFO(0, word, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_dict_add, 0, 2, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_ARG_TYPE_INFO(0, word, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_enchant_dict_add_to_personal arginfo_enchant_dict_add
#define arginfo_enchant_dict_add_to_session arginfo_enchant_dict_add
#define arginfo_enchant_dict_is_added arginfo_enchant_dict_check
#define arginfo_enchant_dict_is_in_session arginfo_enchant_dict_check
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_dict_store_replacement, 0, 3, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_ARG_TYPE_INFO(0, misspelled, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, correct, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_enchant_dict_get_error, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_enchant_dict_describe, 0, 1, IS_ARRAY, 0)
ZEND_ARG_OBJ_INFO(0, dictionary, EnchantDictionary, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(enchant_broker_init);
ZEND_FUNCTION(enchant_broker_free);
ZEND_FUNCTION(enchant_broker_get_error);
ZEND_FUNCTION(enchant_broker_set_dict_path);
ZEND_FUNCTION(enchant_broker_get_dict_path);
ZEND_FUNCTION(enchant_broker_list_dicts);
ZEND_FUNCTION(enchant_broker_request_dict);
ZEND_FUNCTION(enchant_broker_request_pwl_dict);
ZEND_FUNCTION(enchant_broker_free_dict);
ZEND_FUNCTION(enchant_broker_dict_exists);
ZEND_FUNCTION(enchant_broker_set_ordering);
ZEND_FUNCTION(enchant_broker_describe);
ZEND_FUNCTION(enchant_dict_quick_check);
ZEND_FUNCTION(enchant_dict_check);
ZEND_FUNCTION(enchant_dict_suggest);
ZEND_FUNCTION(enchant_dict_add);
ZEND_FUNCTION(enchant_dict_add_to_session);
ZEND_FUNCTION(enchant_dict_is_added);
ZEND_FUNCTION(enchant_dict_store_replacement);
ZEND_FUNCTION(enchant_dict_get_error);
ZEND_FUNCTION(enchant_dict_describe);
static const zend_function_entry ext_functions[] = {
ZEND_FE(enchant_broker_init, arginfo_enchant_broker_init)
ZEND_DEP_FE(enchant_broker_free, arginfo_enchant_broker_free)
ZEND_FE(enchant_broker_get_error, arginfo_enchant_broker_get_error)
ZEND_DEP_FE(enchant_broker_set_dict_path, arginfo_enchant_broker_set_dict_path)
ZEND_DEP_FE(enchant_broker_get_dict_path, arginfo_enchant_broker_get_dict_path)
ZEND_FE(enchant_broker_list_dicts, arginfo_enchant_broker_list_dicts)
ZEND_FE(enchant_broker_request_dict, arginfo_enchant_broker_request_dict)
ZEND_FE(enchant_broker_request_pwl_dict, arginfo_enchant_broker_request_pwl_dict)
ZEND_DEP_FE(enchant_broker_free_dict, arginfo_enchant_broker_free_dict)
ZEND_FE(enchant_broker_dict_exists, arginfo_enchant_broker_dict_exists)
ZEND_FE(enchant_broker_set_ordering, arginfo_enchant_broker_set_ordering)
ZEND_FE(enchant_broker_describe, arginfo_enchant_broker_describe)
ZEND_FE(enchant_dict_quick_check, arginfo_enchant_dict_quick_check)
ZEND_FE(enchant_dict_check, arginfo_enchant_dict_check)
ZEND_FE(enchant_dict_suggest, arginfo_enchant_dict_suggest)
ZEND_FE(enchant_dict_add, arginfo_enchant_dict_add)
ZEND_DEP_FALIAS(enchant_dict_add_to_personal, enchant_dict_add, arginfo_enchant_dict_add_to_personal)
ZEND_FE(enchant_dict_add_to_session, arginfo_enchant_dict_add_to_session)
ZEND_FE(enchant_dict_is_added, arginfo_enchant_dict_is_added)
ZEND_DEP_FALIAS(enchant_dict_is_in_session, enchant_dict_is_added, arginfo_enchant_dict_is_in_session)
ZEND_FE(enchant_dict_store_replacement, arginfo_enchant_dict_store_replacement)
ZEND_FE(enchant_dict_get_error, arginfo_enchant_dict_get_error)
ZEND_FE(enchant_dict_describe, arginfo_enchant_dict_describe)
ZEND_FE_END
};
static const zend_function_entry class_EnchantBroker_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_EnchantDictionary_methods[] = {
ZEND_FE_END
};
static void register_enchant_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("ENCHANT_MYSPELL", PHP_ENCHANT_MYSPELL, CONST_PERSISTENT | CONST_DEPRECATED);
REGISTER_LONG_CONSTANT("ENCHANT_ISPELL", PHP_ENCHANT_ISPELL, CONST_PERSISTENT | CONST_DEPRECATED);
#if defined(HAVE_ENCHANT_GET_VERSION)
REGISTER_STRING_CONSTANT("LIBENCHANT_VERSION", PHP_ENCHANT_GET_VERSION, CONST_PERSISTENT);
#endif
}
static zend_class_entry *register_class_EnchantBroker(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "EnchantBroker", class_EnchantBroker_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NO_DYNAMIC_PROPERTIES|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
static zend_class_entry *register_class_EnchantDictionary(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "EnchantDictionary", class_EnchantDictionary_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NO_DYNAMIC_PROPERTIES|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
| 8,065 | 41.230366 | 123 |
h
|
php-src
|
php-src-master/ext/enchant/php_enchant.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Pierre-Alain Joye <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_ENCHANT_H
#define PHP_ENCHANT_H
extern zend_module_entry enchant_module_entry;
#define phpext_enchant_ptr &enchant_module_entry
#define PHP_ENCHANT_VERSION PHP_VERSION
#ifdef PHP_WIN32
#define PHP_ENCHANT_API __declspec(dllexport)
#else
#define PHP_ENCHANT_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
PHP_MINIT_FUNCTION(enchant);
PHP_MSHUTDOWN_FUNCTION(enchant);
PHP_MINFO_FUNCTION(enchant);
#endif /* PHP_ENCHANT_H */
| 1,422 | 34.575 | 74 |
h
|
php-src
|
php-src-master/ext/exif/exif_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 633b2db018fa1453845a854a6361f11f107f4653 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_exif_tagname, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_exif_read_data, 0, 1, MAY_BE_ARRAY|MAY_BE_FALSE)
ZEND_ARG_INFO(0, file)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, required_sections, IS_STRING, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, as_arrays, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, read_thumbnail, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_exif_thumbnail, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_INFO(0, file)
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, width, "null")
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, height, "null")
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(1, image_type, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_exif_imagetype, 0, 1, MAY_BE_LONG|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(exif_tagname);
ZEND_FUNCTION(exif_read_data);
ZEND_FUNCTION(exif_thumbnail);
ZEND_FUNCTION(exif_imagetype);
static const zend_function_entry ext_functions[] = {
ZEND_FE(exif_tagname, arginfo_exif_tagname)
ZEND_FE(exif_read_data, arginfo_exif_read_data)
ZEND_FE(exif_thumbnail, arginfo_exif_thumbnail)
ZEND_FE(exif_imagetype, arginfo_exif_imagetype)
ZEND_FE_END
};
static void register_exif_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", USE_MBSTRING, CONST_PERSISTENT);
}
| 1,651 | 35.711111 | 97 |
h
|
php-src
|
php-src-master/ext/exif/php_exif.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <[email protected]> |
| Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_version.h"
#define PHP_EXIF_VERSION PHP_VERSION
extern zend_module_entry exif_module_entry;
#define phpext_exif_ptr &exif_module_entry
| 1,222 | 52.173913 | 75 |
h
|
php-src
|
php-src-master/ext/fileinfo/fileinfo_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 94697d59958fb55a431bfa4786158b5db3c1ae0e */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_finfo_open, 0, 0, finfo, MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, magic_database, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_finfo_close, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, finfo, finfo, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_finfo_set_flags, 0, 2, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, finfo, finfo, 0)
ZEND_ARG_TYPE_INFO(0, flags, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_finfo_file, 0, 2, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, finfo, finfo, 0)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(0, context, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_finfo_buffer, 0, 2, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_OBJ_INFO(0, finfo, finfo, 0)
ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(0, context, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_mime_content_type, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_finfo___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, magic_database, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_TYPE_MASK_EX(arginfo_class_finfo_file, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, filename, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(0, context, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_TYPE_MASK_EX(arginfo_class_finfo_buffer, 0, 1, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, string, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "FILEINFO_NONE")
ZEND_ARG_INFO_WITH_DEFAULT_VALUE(0, context, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_finfo_set_flags, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, flags, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(finfo_open);
ZEND_FUNCTION(finfo_close);
ZEND_FUNCTION(finfo_set_flags);
ZEND_FUNCTION(finfo_file);
ZEND_FUNCTION(finfo_buffer);
ZEND_FUNCTION(mime_content_type);
static const zend_function_entry ext_functions[] = {
ZEND_FE(finfo_open, arginfo_finfo_open)
ZEND_FE(finfo_close, arginfo_finfo_close)
ZEND_FE(finfo_set_flags, arginfo_finfo_set_flags)
ZEND_FE(finfo_file, arginfo_finfo_file)
ZEND_FE(finfo_buffer, arginfo_finfo_buffer)
ZEND_FE(mime_content_type, arginfo_mime_content_type)
ZEND_FE_END
};
static const zend_function_entry class_finfo_methods[] = {
ZEND_ME_MAPPING(__construct, finfo_open, arginfo_class_finfo___construct, ZEND_ACC_PUBLIC)
ZEND_ME_MAPPING(file, finfo_file, arginfo_class_finfo_file, ZEND_ACC_PUBLIC)
ZEND_ME_MAPPING(buffer, finfo_buffer, arginfo_class_finfo_buffer, ZEND_ACC_PUBLIC)
ZEND_ME_MAPPING(set_flags, finfo_set_flags, arginfo_class_finfo_set_flags, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static void register_fileinfo_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("FILEINFO_NONE", MAGIC_NONE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_SYMLINK", MAGIC_SYMLINK, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_MIME", MAGIC_MIME, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_MIME_TYPE", MAGIC_MIME_TYPE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_MIME_ENCODING", MAGIC_MIME_ENCODING, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_DEVICES", MAGIC_DEVICES, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_CONTINUE", MAGIC_CONTINUE, CONST_PERSISTENT);
#if defined(MAGIC_PRESERVE_ATIME)
REGISTER_LONG_CONSTANT("FILEINFO_PRESERVE_ATIME", MAGIC_PRESERVE_ATIME, CONST_PERSISTENT);
#endif
#if defined(MAGIC_RAW)
REGISTER_LONG_CONSTANT("FILEINFO_RAW", MAGIC_RAW, CONST_PERSISTENT);
#endif
REGISTER_LONG_CONSTANT("FILEINFO_APPLE", MAGIC_APPLE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILEINFO_EXTENSION", MAGIC_EXTENSION, CONST_PERSISTENT);
}
static zend_class_entry *register_class_finfo(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "finfo", class_finfo_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
| 4,756 | 40.72807 | 111 |
h
|
php-src
|
php-src-master/ext/fileinfo/php_fileinfo.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Ilia Alshanetsky <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_FILEINFO_H
#define PHP_FILEINFO_H
extern zend_module_entry fileinfo_module_entry;
#define phpext_fileinfo_ptr &fileinfo_module_entry
#define PHP_FILEINFO_VERSION PHP_VERSION
#ifdef PHP_WIN32
#define PHP_FILEINFO_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
#define PHP_FILEINFO_API __attribute__((visibility("default")))
#else
#define PHP_FILEINFO_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
PHP_MINFO_FUNCTION(fileinfo);
#endif /* PHP_FILEINFO_H */
| 1,475 | 35.9 | 74 |
h
|
php-src
|
php-src-master/ext/fileinfo/php_libmagic.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_libmagic.h"
zend_string* convert_libmagic_pattern(const char *val, size_t len, uint32_t options)
{
int i, j;
zend_string *t;
for (i = j = 0; i < len; i++) {
switch (val[i]) {
case '~':
j += 2;
break;
case '\0':
j += 4;
break;
default:
j++;
break;
}
}
t = zend_string_alloc(j + 4, 0);
j = 0;
ZSTR_VAL(t)[j++] = '~';
for (i = 0; i < len; i++, j++) {
switch (val[i]) {
case '~':
ZSTR_VAL(t)[j++] = '\\';
ZSTR_VAL(t)[j] = '~';
break;
case '\0':
ZSTR_VAL(t)[j++] = '\\';
ZSTR_VAL(t)[j++] = 'x';
ZSTR_VAL(t)[j++] = '0';
ZSTR_VAL(t)[j] = '0';
break;
default:
ZSTR_VAL(t)[j] = val[i];
break;
}
}
ZSTR_VAL(t)[j++] = '~';
if (options & PCRE2_CASELESS)
ZSTR_VAL(t)[j++] = 'i';
if (options & PCRE2_MULTILINE)
ZSTR_VAL(t)[j++] = 'm';
ZSTR_VAL(t)[j]='\0';
ZSTR_LEN(t) = j;
return t;
}
| 1,904 | 24.065789 | 84 |
c
|
php-src
|
php-src-master/ext/fileinfo/php_libmagic.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_LIBMAGIC_H
#define PHP_LIBMAGIC_H
#include "php_fileinfo.h"
#include "main/php_network.h"
#include "ext/standard/php_string.h"
#include "ext/pcre/php_pcre.h"
#ifdef PHP_WIN32
#include "win32/param.h"
#include "win32/unistd.h"
#ifdef _WIN64
#define FINFO_LSEEK_FUNC _lseeki64
#else
#define FINFO_LSEEK_FUNC _lseek
#endif
#define FINFO_READ_FUNC _read
#define strtoull _strtoui64
#define HAVE_ASCTIME_R 1
#define asctime_r php_asctime_r
#define HAVE_CTIME_R 1
#define ctime_r php_ctime_r
#else
#define FINFO_LSEEK_FUNC lseek
#define FINFO_READ_FUNC read
#endif
#if defined(__hpux) && !defined(HAVE_STRTOULL)
#if SIZEOF_LONG == 8
# define strtoull strtoul
#else
# define strtoull __strtoull
#endif
#endif
#ifndef offsetof
#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
#endif
#ifndef UINT32_MAX
# define UINT32_MAX (0xffffffff)
#endif
#ifndef PREG_OFFSET_CAPTURE
# define PREG_OFFSET_CAPTURE (1<<8)
#endif
#define abort() zend_error_noreturn(E_ERROR, "fatal libmagic error")
zend_string* convert_libmagic_pattern(const char *val, size_t len, uint32_t options);
#endif /* PHP_LIBMAGIC_H */
| 2,138 | 27.52 | 85 |
h
|
php-src
|
php-src-master/ext/fileinfo/libmagic/apptype.c
|
/*
* Adapted from: apptype.c, Written by Eberhard Mattes and put into the
* public domain
*
* Notes: 1. Qualify the filename so that DosQueryAppType does not do extraneous
* searches.
*
* 2. DosQueryAppType will return FAPPTYP_DOS on a file ending with ".com"
* (other than an OS/2 exe or Win exe with this name). Eberhard Mattes
* remarks Tue, 6 Apr 93: Moreover, it reports the type of the (new and very
* bug ridden) Win Emacs as "OS/2 executable".
*
* 3. apptype() uses the filename if given, otherwise a tmp file is created with
* the contents of buf. If buf is not the complete file, apptype can
* incorrectly identify the exe type. The "-z" option of "file" is the reason
* for this ugly code.
*/
/*
* amai: Darrel Hankerson did the changes described here.
*
* It remains to check the validity of comments (2.) since it's referred to an
* "old" OS/2 version.
*
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: apptype.c,v 1.14 2018/09/09 20:33:28 christos Exp $")
#endif /* lint */
#include <stdlib.h>
#include <string.h>
#ifdef __EMX__
#include <io.h>
#define INCL_DOSSESMGR
#define INCL_DOSERRORS
#define INCL_DOSFILEMGR
#include <os2.h>
typedef ULONG APPTYPE;
protected int
file_os2_apptype(struct magic_set *ms, const char *fn, const void *buf,
size_t nb)
{
APPTYPE rc, type;
char path[_MAX_PATH], drive[_MAX_DRIVE], dir[_MAX_DIR],
fname[_MAX_FNAME], ext[_MAX_EXT];
char *filename;
FILE *fp;
if (fn)
filename = strdup(fn);
else if ((filename = tempnam("./", "tmp")) == NULL) {
file_error(ms, errno, "cannot create tempnam");
return -1;
}
/* qualify the filename to prevent extraneous searches */
_splitpath(filename, drive, dir, fname, ext);
(void)sprintf(path, "%s%s%s%s", drive,
(*dir == '\0') ? "./" : dir,
fname,
(*ext == '\0') ? "." : ext);
if (fn == NULL) {
if ((fp = fopen(path, "wb")) == NULL) {
file_error(ms, errno, "cannot open tmp file `%s'", path);
return -1;
}
if (fwrite(buf, 1, nb, fp) != nb) {
file_error(ms, errno, "cannot write tmp file `%s'",
path);
(void)fclose(fp);
return -1;
}
(void)fclose(fp);
}
rc = DosQueryAppType((unsigned char *)path, &type);
if (fn == NULL) {
unlink(path);
free(filename);
}
#if 0
if (rc == ERROR_INVALID_EXE_SIGNATURE)
printf("%s: not an executable file\n", fname);
else if (rc == ERROR_FILE_NOT_FOUND)
printf("%s: not found\n", fname);
else if (rc == ERROR_ACCESS_DENIED)
printf("%s: access denied\n", fname);
else if (rc != 0)
printf("%s: error code = %lu\n", fname, rc);
else
#else
/*
* for our purpose here it's sufficient to just ignore the error and
* return w/o success (=0)
*/
if (rc)
return (0);
#endif
if (type & FAPPTYP_32BIT)
if (file_printf(ms, "32-bit ") == -1)
return -1;
if (type & FAPPTYP_PHYSDRV) {
if (file_printf(ms, "physical device driver") == -1)
return -1;
} else if (type & FAPPTYP_VIRTDRV) {
if (file_printf(ms, "virtual device driver") == -1)
return -1;
} else if (type & FAPPTYP_DLL) {
if (type & FAPPTYP_PROTDLL)
if (file_printf(ms, "protected ") == -1)
return -1;
if (file_printf(ms, "DLL") == -1)
return -1;
} else if (type & (FAPPTYP_WINDOWSREAL | FAPPTYP_WINDOWSPROT)) {
if (file_printf(ms, "Windows executable") == -1)
return -1;
} else if (type & FAPPTYP_DOS) {
/*
* The API routine is partially broken on filenames ending
* ".com".
*/
if (stricmp(ext, ".com") == 0)
if (strncmp((const char *)buf, "MZ", 2))
return (0);
if (file_printf(ms, "DOS executable") == -1)
return -1;
/* ---------------------------------------- */
/* Might learn more from the magic(4) entry */
if (file_printf(ms, ", magic(4)-> ") == -1)
return -1;
return (0);
/* ---------------------------------------- */
} else if (type & FAPPTYP_BOUND) {
if (file_printf(ms, "bound executable") == -1)
return -1;
} else if ((type & 7) == FAPPTYP_WINDOWAPI) {
if (file_printf(ms, "PM executable") == -1)
return -1;
} else if (file_printf(ms, "OS/2 executable") == -1)
return -1;
switch (type & (FAPPTYP_NOTWINDOWCOMPAT |
FAPPTYP_WINDOWCOMPAT |
FAPPTYP_WINDOWAPI)) {
case FAPPTYP_NOTWINDOWCOMPAT:
if (file_printf(ms, " [NOTWINDOWCOMPAT]") == -1)
return -1;
break;
case FAPPTYP_WINDOWCOMPAT:
if (file_printf(ms, " [WINDOWCOMPAT]") == -1)
return -1;
break;
case FAPPTYP_WINDOWAPI:
if (file_printf(ms, " [WINDOWAPI]") == -1)
return -1;
break;
}
return 1;
}
#endif
| 4,522 | 25.605882 | 80 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/ascmagic.c
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* ASCII magic -- try to detect text encoding.
*
* Extensively modified by Eric Fischer <[email protected]> in July, 2000,
* to handle character codes other than ASCII on a unified basis.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: ascmagic.c,v 1.110 2021/12/06 15:33:00 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#define MAXLINELEN 300 /* longest sane line length */
#define ISSPC(x) ((x) == ' ' || (x) == '\t' || (x) == '\r' || (x) == '\n' \
|| (x) == 0x85 || (x) == '\f')
private unsigned char *encode_utf8(unsigned char *, size_t, file_unichar_t *,
size_t);
private size_t trim_nuls(const unsigned char *, size_t);
/*
* Undo the NUL-termination kindly provided by process()
* but leave at least one byte to look at
*/
private size_t
trim_nuls(const unsigned char *buf, size_t nbytes)
{
while (nbytes > 1 && buf[nbytes - 1] == '\0')
nbytes--;
return nbytes;
}
protected int
file_ascmagic(struct magic_set *ms, const struct buffer *b, int text)
{
file_unichar_t *ubuf = NULL;
size_t ulen = 0;
int rv = 1;
struct buffer bb;
const char *code = NULL;
const char *code_mime = NULL;
const char *type = NULL;
bb = *b;
bb.flen = trim_nuls(CAST(const unsigned char *, b->fbuf), b->flen);
/*
* Avoid trimming at an odd byte if the original buffer was evenly
* sized; this avoids losing the last character on UTF-16 LE text
*/
if ((bb.flen & 1) && !(b->flen & 1))
bb.flen++;
/* If file doesn't look like any sort of text, give up. */
if (file_encoding(ms, &bb, &ubuf, &ulen, &code, &code_mime,
&type) == 0)
rv = 0;
else
rv = file_ascmagic_with_encoding(ms, &bb,
ubuf, ulen, code, type, text);
efree(ubuf);
return rv;
}
protected int
file_ascmagic_with_encoding(struct magic_set *ms, const struct buffer *b,
file_unichar_t *ubuf, size_t ulen, const char *code, const char *type,
int text)
{
struct buffer bb;
const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
size_t nbytes = b->flen;
unsigned char *utf8_buf = NULL, *utf8_end;
size_t mlen, i, len;
int rv = -1;
int mime = ms->flags & MAGIC_MIME;
int need_separator = 0;
const char *subtype = NULL;
int has_escapes = 0;
int has_backspace = 0;
int seen_cr = 0;
int n_crlf = 0;
int n_lf = 0;
int n_cr = 0;
int n_nel = 0;
int executable = 0;
size_t last_line_end = CAST(size_t, -1);
size_t has_long_lines = 0;
nbytes = trim_nuls(buf, nbytes);
/* If we have fewer than 2 bytes, give up. */
if (nbytes <= 1) {
rv = 0;
goto done;
}
if (ulen > 0 && (ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
/* Convert ubuf to UTF-8 and try text soft magic */
/* malloc size is a conservative overestimate; could be
improved, or at least realloced after conversion. */
mlen = ulen * 6;
if ((utf8_buf = CAST(unsigned char *, emalloc(mlen))) == NULL) {
file_oomem(ms, mlen);
goto done;
}
if ((utf8_end = encode_utf8(utf8_buf, mlen, ubuf, ulen))
== NULL)
goto done;
buffer_init(&bb, b->fd, &b->st, utf8_buf,
CAST(size_t, utf8_end - utf8_buf));
if ((rv = file_softmagic(ms, &bb, NULL, NULL,
TEXTTEST, text)) == 0)
rv = -1;
else
need_separator = 1;
buffer_fini(&bb);
if ((ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION))) {
rv = rv == -1 ? 0 : 1;
goto done;
}
}
if ((ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION))) {
rv = 0;
goto done;
}
/* Now try to discover other details about the file. */
for (i = 0; i < ulen; i++) {
if (ubuf[i] == '\n') {
if (seen_cr)
n_crlf++;
else
n_lf++;
last_line_end = i;
} else if (seen_cr)
n_cr++;
seen_cr = (ubuf[i] == '\r');
if (seen_cr)
last_line_end = i;
if (ubuf[i] == 0x85) { /* X3.64/ECMA-43 "next line" character */
n_nel++;
last_line_end = i;
}
/* If this line is _longer_ than MAXLINELEN, remember it. */
if (i > last_line_end + MAXLINELEN) {
size_t ll = i - last_line_end;
if (ll > has_long_lines)
has_long_lines = ll;
}
if (ubuf[i] == '\033')
has_escapes = 1;
if (ubuf[i] == '\b')
has_backspace = 1;
}
/* Beware, if the data has been truncated, the final CR could have
been followed by a LF. If we have ms->bytes_max bytes, it indicates
that the data might have been truncated, probably even before
this function was called. */
if (seen_cr && nbytes < ms->bytes_max)
n_cr++;
if (strcmp(type, "binary") == 0) {
rv = 0;
goto done;
}
len = file_printedlen(ms);
if (mime) {
if ((mime & MAGIC_MIME_TYPE) != 0) {
if (len) {
/*
* Softmagic printed something, we
* are either done, or we need a separator
*/
if ((ms->flags & MAGIC_CONTINUE) == 0) {
rv = 1;
goto done;
}
if (need_separator && file_separator(ms) == -1)
goto done;
} else {
if (file_printf(ms, "text/plain") == -1)
goto done;
}
}
} else {
if (len) {
switch (file_replace(ms, " text$", ", ")) {
case 0:
switch (file_replace(ms, " text executable$",
", ")) {
case 0:
if (file_printf(ms, ", ") == -1)
goto done;
break;
case -1:
goto done;
default:
executable = 1;
break;
}
break;
case -1:
goto done;
default:
break;
}
}
if (file_printf(ms, "%s", code) == -1)
goto done;
if (subtype) {
if (file_printf(ms, " %s", subtype) == -1)
goto done;
}
if (file_printf(ms, " %s", type) == -1)
goto done;
if (executable)
if (file_printf(ms, " executable") == -1)
goto done;
if (has_long_lines)
if (file_printf(ms, ", with very long lines (%zu)",
has_long_lines) == -1)
goto done;
/*
* Only report line terminators if we find one other than LF,
* or if we find none at all.
*/
if ((n_crlf == 0 && n_cr == 0 && n_nel == 0 && n_lf == 0) ||
(n_crlf != 0 || n_cr != 0 || n_nel != 0)) {
if (file_printf(ms, ", with") == -1)
goto done;
if (n_crlf == 0 && n_cr == 0 &&
n_nel == 0 && n_lf == 0) {
if (file_printf(ms, " no") == -1)
goto done;
} else {
if (n_crlf) {
if (file_printf(ms, " CRLF") == -1)
goto done;
if (n_cr || n_lf || n_nel)
if (file_printf(ms, ",") == -1)
goto done;
}
if (n_cr) {
if (file_printf(ms, " CR") == -1)
goto done;
if (n_lf || n_nel)
if (file_printf(ms, ",") == -1)
goto done;
}
if (n_lf) {
if (file_printf(ms, " LF") == -1)
goto done;
if (n_nel)
if (file_printf(ms, ",") == -1)
goto done;
}
if (n_nel)
if (file_printf(ms, " NEL") == -1)
goto done;
}
if (file_printf(ms, " line terminators") == -1)
goto done;
}
if (has_escapes)
if (file_printf(ms, ", with escape sequences") == -1)
goto done;
if (has_backspace)
if (file_printf(ms, ", with overstriking") == -1)
goto done;
}
rv = 1;
done:
if (utf8_buf)
efree(utf8_buf);
return rv;
}
/*
* Encode Unicode string as UTF-8, returning pointer to character
* after end of string, or NULL if an invalid character is found.
*/
private unsigned char *
encode_utf8(unsigned char *buf, size_t len, file_unichar_t *ubuf, size_t ulen)
{
size_t i;
unsigned char *end = buf + len;
for (i = 0; i < ulen; i++) {
if (ubuf[i] <= 0x7f) {
if (end - buf < 1)
return NULL;
*buf++ = CAST(unsigned char, ubuf[i]);
continue;
}
if (ubuf[i] <= 0x7ff) {
if (end - buf < 2)
return NULL;
*buf++ = CAST(unsigned char, (ubuf[i] >> 6) + 0xc0);
goto out1;
}
if (ubuf[i] <= 0xffff) {
if (end - buf < 3)
return NULL;
*buf++ = CAST(unsigned char, (ubuf[i] >> 12) + 0xe0);
goto out2;
}
if (ubuf[i] <= 0x1fffff) {
if (end - buf < 4)
return NULL;
*buf++ = CAST(unsigned char, (ubuf[i] >> 18) + 0xf0);
goto out3;
}
if (ubuf[i] <= 0x3ffffff) {
if (end - buf < 5)
return NULL;
*buf++ = CAST(unsigned char, (ubuf[i] >> 24) + 0xf8);
goto out4;
}
if (ubuf[i] <= 0x7fffffff) {
if (end - buf < 6)
return NULL;
*buf++ = CAST(unsigned char, (ubuf[i] >> 30) + 0xfc);
goto out5;
}
/* Invalid character */
return NULL;
out5: *buf++ = CAST(unsigned char, ((ubuf[i] >> 24) & 0x3f) + 0x80);
out4: *buf++ = CAST(unsigned char, ((ubuf[i] >> 18) & 0x3f) + 0x80);
out3: *buf++ = CAST(unsigned char, ((ubuf[i] >> 12) & 0x3f) + 0x80);
out2: *buf++ = CAST(unsigned char, ((ubuf[i] >> 6) & 0x3f) + 0x80);
out1: *buf++ = CAST(unsigned char, ((ubuf[i] >> 0) & 0x3f) + 0x80);
}
return buf;
}
| 10,086 | 24.40806 | 78 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/buffer.c
|
/*
* Copyright (c) Christos Zoulas 2017.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: buffer.c,v 1.8 2020/02/16 15:52:49 christos Exp $")
#endif /* lint */
#include "magic.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
void
buffer_init(struct buffer *b, int fd, const zend_stat_t *st, const void *data,
size_t len)
{
b->fd = fd;
if (st)
memcpy(&b->st, st, sizeof(b->st));
else if (b->fd == -1 || zend_fstat(b->fd, &b->st) == -1)
memset(&b->st, 0, sizeof(b->st));
b->fbuf = data;
b->flen = len;
b->eoff = 0;
b->ebuf = NULL;
b->elen = 0;
}
void
buffer_fini(struct buffer *b)
{
efree(b->ebuf);
}
int
buffer_fill(const struct buffer *bb)
{
struct buffer *b = CCAST(struct buffer *, bb);
if (b->elen != 0)
return b->elen == FILE_BADSIZE ? -1 : 0;
if (!S_ISREG(b->st.st_mode))
goto out;
b->elen = CAST(size_t, b->st.st_size) < b->flen ?
CAST(size_t, b->st.st_size) : b->flen;
if ((b->ebuf = emalloc(b->elen)) == NULL)
goto out;
b->eoff = b->st.st_size - b->elen;
if (FINFO_LSEEK_FUNC(b->fd, b->eoff, SEEK_SET) == (zend_off_t)-1 ||
FINFO_READ_FUNC(b->fd, b->ebuf, b->elen) != (ssize_t)b->elen)
{
efree(b->ebuf);
b->ebuf = NULL;
goto out;
}
return 0;
out:
b->elen = FILE_BADSIZE;
return -1;
}
| 2,704 | 28.086022 | 78 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/cdf.h
|
/*-
* Copyright (c) 2008 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Parse Composite Document Files, the format used in Microsoft Office
* document files before they switched to zipped XML.
* Info from: http://sc.openoffice.org/compdocfileformat.pdf
*
* N.B. This is the "Composite Document File" format, and not the
* "Compound Document Format", nor the "Channel Definition Format".
*/
#ifndef _H_CDF_
#define _H_CDF_
#ifdef WIN32
#include <winsock2.h>
#endif
#ifdef __DJGPP__
#define timespec timeval
#define tv_nsec tv_usec
#endif
typedef int32_t cdf_secid_t;
#define CDF_LOOP_LIMIT 10000
#define CDF_ELEMENT_LIMIT 100000
#define CDF_SECID_NULL 0
#define CDF_SECID_FREE -1
#define CDF_SECID_END_OF_CHAIN -2
#define CDF_SECID_SECTOR_ALLOCATION_TABLE -3
#define CDF_SECID_MASTER_SECTOR_ALLOCATION_TABLE -4
typedef struct {
uint64_t h_magic;
#define CDF_MAGIC 0xE11AB1A1E011CFD0LL
uint64_t h_uuid[2];
uint16_t h_revision;
uint16_t h_version;
uint16_t h_byte_order;
uint16_t h_sec_size_p2;
uint16_t h_short_sec_size_p2;
uint8_t h_unused0[10];
uint32_t h_num_sectors_in_sat;
uint32_t h_secid_first_directory;
uint8_t h_unused1[4];
uint32_t h_min_size_standard_stream;
cdf_secid_t h_secid_first_sector_in_short_sat;
uint32_t h_num_sectors_in_short_sat;
cdf_secid_t h_secid_first_sector_in_master_sat;
uint32_t h_num_sectors_in_master_sat;
cdf_secid_t h_master_sat[436/4];
} cdf_header_t;
#define CDF_SEC_SIZE(h) CAST(size_t, 1 << (h)->h_sec_size_p2)
#define CDF_SEC_POS(h, secid) (CDF_SEC_SIZE(h) + (secid) * CDF_SEC_SIZE(h))
#define CDF_SHORT_SEC_SIZE(h) CAST(size_t, 1 << (h)->h_short_sec_size_p2)
#define CDF_SHORT_SEC_POS(h, secid) ((secid) * CDF_SHORT_SEC_SIZE(h))
typedef int32_t cdf_dirid_t;
#define CDF_DIRID_NULL -1
typedef int64_t cdf_timestamp_t;
#define CDF_BASE_YEAR 1601
#define CDF_TIME_PREC 10000000
typedef struct {
uint16_t d_name[32];
uint16_t d_namelen;
uint8_t d_type;
#define CDF_DIR_TYPE_EMPTY 0
#define CDF_DIR_TYPE_USER_STORAGE 1
#define CDF_DIR_TYPE_USER_STREAM 2
#define CDF_DIR_TYPE_LOCKBYTES 3
#define CDF_DIR_TYPE_PROPERTY 4
#define CDF_DIR_TYPE_ROOT_STORAGE 5
uint8_t d_color;
#define CDF_DIR_COLOR_READ 0
#define CDF_DIR_COLOR_BLACK 1
cdf_dirid_t d_left_child;
cdf_dirid_t d_right_child;
cdf_dirid_t d_storage;
uint64_t d_storage_uuid[2];
uint32_t d_flags;
cdf_timestamp_t d_created;
cdf_timestamp_t d_modified;
cdf_secid_t d_stream_first_sector;
uint32_t d_size;
uint32_t d_unused0;
} cdf_directory_t;
#define CDF_DIRECTORY_SIZE 128
typedef struct {
cdf_secid_t *sat_tab;
size_t sat_len;
} cdf_sat_t;
typedef struct {
cdf_directory_t *dir_tab;
size_t dir_len;
} cdf_dir_t;
typedef struct {
void *sst_tab;
size_t sst_len; /* Number of sectors */
size_t sst_dirlen; /* Directory sector size */
size_t sst_ss; /* Sector size */
} cdf_stream_t;
typedef struct {
uint32_t cl_dword;
uint16_t cl_word[2];
uint8_t cl_two[2];
uint8_t cl_six[6];
} cdf_classid_t;
typedef struct {
uint16_t si_byte_order;
uint16_t si_zero;
uint16_t si_os_version;
uint16_t si_os;
cdf_classid_t si_class;
uint32_t si_count;
} cdf_summary_info_header_t;
#define CDF_SECTION_DECLARATION_OFFSET 0x1c
typedef struct {
cdf_classid_t sd_class;
uint32_t sd_offset;
} cdf_section_declaration_t;
typedef struct {
uint32_t sh_len;
uint32_t sh_properties;
} cdf_section_header_t;
typedef struct {
uint32_t pi_id;
uint32_t pi_type;
union {
uint16_t _pi_u16;
int16_t _pi_s16;
uint32_t _pi_u32;
int32_t _pi_s32;
uint64_t _pi_u64;
int64_t _pi_s64;
cdf_timestamp_t _pi_tp;
float _pi_f;
double _pi_d;
struct {
uint32_t s_len;
const char *s_buf;
} _pi_str;
} pi_val;
#define pi_u64 pi_val._pi_u64
#define pi_s64 pi_val._pi_s64
#define pi_u32 pi_val._pi_u32
#define pi_s32 pi_val._pi_s32
#define pi_u16 pi_val._pi_u16
#define pi_s16 pi_val._pi_s16
#define pi_f pi_val._pi_f
#define pi_d pi_val._pi_d
#define pi_tp pi_val._pi_tp
#define pi_str pi_val._pi_str
} cdf_property_info_t;
#define CDF_ROUND(val, by) (((val) + (by) - 1) & ~((by) - 1))
/* Variant type definitions */
#define CDF_EMPTY 0x00000000
#define CDF_NULL 0x00000001
#define CDF_SIGNED16 0x00000002
#define CDF_SIGNED32 0x00000003
#define CDF_FLOAT 0x00000004
#define CDF_DOUBLE 0x00000005
#define CDF_CY 0x00000006
#define CDF_DATE 0x00000007
#define CDF_BSTR 0x00000008
#define CDF_DISPATCH 0x00000009
#define CDF_ERROR 0x0000000a
#define CDF_BOOL 0x0000000b
#define CDF_VARIANT 0x0000000c
#define CDF_UNKNOWN 0x0000000d
#define CDF_DECIMAL 0x0000000e
#define CDF_SIGNED8 0x00000010
#define CDF_UNSIGNED8 0x00000011
#define CDF_UNSIGNED16 0x00000012
#define CDF_UNSIGNED32 0x00000013
#define CDF_SIGNED64 0x00000014
#define CDF_UNSIGNED64 0x00000015
#define CDF_INT 0x00000016
#define CDF_UINT 0x00000017
#define CDF_VOID 0x00000018
#define CDF_HRESULT 0x00000019
#define CDF_PTR 0x0000001a
#define CDF_SAFEARRAY 0x0000001b
#define CDF_CARRAY 0x0000001c
#define CDF_USERDEFINED 0x0000001d
#define CDF_LENGTH32_STRING 0x0000001e
#define CDF_LENGTH32_WSTRING 0x0000001f
#define CDF_FILETIME 0x00000040
#define CDF_BLOB 0x00000041
#define CDF_STREAM 0x00000042
#define CDF_STORAGE 0x00000043
#define CDF_STREAMED_OBJECT 0x00000044
#define CDF_STORED_OBJECT 0x00000045
#define CDF_BLOB_OBJECT 0x00000046
#define CDF_CLIPBOARD 0x00000047
#define CDF_CLSID 0x00000048
#define CDF_VECTOR 0x00001000
#define CDF_ARRAY 0x00002000
#define CDF_BYREF 0x00004000
#define CDF_RESERVED 0x00008000
#define CDF_ILLEGAL 0x0000ffff
#define CDF_ILLEGALMASKED 0x00000fff
#define CDF_TYPEMASK 0x00000fff
#define CDF_PROPERTY_CODE_PAGE 0x00000001
#define CDF_PROPERTY_TITLE 0x00000002
#define CDF_PROPERTY_SUBJECT 0x00000003
#define CDF_PROPERTY_AUTHOR 0x00000004
#define CDF_PROPERTY_KEYWORDS 0x00000005
#define CDF_PROPERTY_COMMENTS 0x00000006
#define CDF_PROPERTY_TEMPLATE 0x00000007
#define CDF_PROPERTY_LAST_SAVED_BY 0x00000008
#define CDF_PROPERTY_REVISION_NUMBER 0x00000009
#define CDF_PROPERTY_TOTAL_EDITING_TIME 0x0000000a
#define CDF_PROPERTY_LAST_PRINTED 0X0000000b
#define CDF_PROPERTY_CREATE_TIME 0x0000000c
#define CDF_PROPERTY_LAST_SAVED_TIME 0x0000000d
#define CDF_PROPERTY_NUMBER_OF_PAGES 0x0000000e
#define CDF_PROPERTY_NUMBER_OF_WORDS 0x0000000f
#define CDF_PROPERTY_NUMBER_OF_CHARACTERS 0x00000010
#define CDF_PROPERTY_THUMBNAIL 0x00000011
#define CDF_PROPERTY_NAME_OF_APPLICATION 0x00000012
#define CDF_PROPERTY_SECURITY 0x00000013
#define CDF_PROPERTY_LOCALE_ID 0x80000000
typedef struct {
int i_fd;
const unsigned char *i_buf;
size_t i_len;
} cdf_info_t;
typedef struct {
uint16_t ce_namlen;
uint32_t ce_num;
uint64_t ce_timestamp;
uint16_t ce_name[256];
} cdf_catalog_entry_t;
typedef struct {
size_t cat_num;
cdf_catalog_entry_t cat_e[1];
} cdf_catalog_t;
struct timespec;
int cdf_timestamp_to_timespec(struct timespec *, cdf_timestamp_t);
int cdf_timespec_to_timestamp(cdf_timestamp_t *, const struct timespec *);
int cdf_read_header(const cdf_info_t *, cdf_header_t *);
void cdf_swap_header(cdf_header_t *);
void cdf_unpack_header(cdf_header_t *, char *);
void cdf_swap_dir(cdf_directory_t *);
void cdf_unpack_dir(cdf_directory_t *, char *);
void cdf_swap_class(cdf_classid_t *);
ssize_t cdf_read_sector(const cdf_info_t *, void *, size_t, size_t,
const cdf_header_t *, cdf_secid_t);
ssize_t cdf_read_short_sector(const cdf_stream_t *, void *, size_t, size_t,
const cdf_header_t *, cdf_secid_t);
int cdf_read_sat(const cdf_info_t *, cdf_header_t *, cdf_sat_t *);
size_t cdf_count_chain(const cdf_sat_t *, cdf_secid_t, size_t);
int cdf_read_long_sector_chain(const cdf_info_t *, const cdf_header_t *,
const cdf_sat_t *, cdf_secid_t, size_t, cdf_stream_t *);
int cdf_read_short_sector_chain(const cdf_header_t *, const cdf_sat_t *,
const cdf_stream_t *, cdf_secid_t, size_t, cdf_stream_t *);
int cdf_read_sector_chain(const cdf_info_t *, const cdf_header_t *,
const cdf_sat_t *, const cdf_sat_t *, const cdf_stream_t *, cdf_secid_t,
size_t, cdf_stream_t *);
int cdf_read_dir(const cdf_info_t *, const cdf_header_t *, const cdf_sat_t *,
cdf_dir_t *);
int cdf_read_ssat(const cdf_info_t *, const cdf_header_t *, const cdf_sat_t *,
cdf_sat_t *);
int cdf_read_short_stream(const cdf_info_t *, const cdf_header_t *,
const cdf_sat_t *, const cdf_dir_t *, cdf_stream_t *,
const cdf_directory_t **);
int cdf_read_property_info(const cdf_stream_t *, const cdf_header_t *, uint32_t,
cdf_property_info_t **, size_t *, size_t *);
int cdf_read_user_stream(const cdf_info_t *, const cdf_header_t *,
const cdf_sat_t *, const cdf_sat_t *, const cdf_stream_t *,
const cdf_dir_t *, const char *, cdf_stream_t *);
int cdf_find_stream(const cdf_dir_t *, const char *, int);
int cdf_zero_stream(cdf_stream_t *);
int cdf_read_doc_summary_info(const cdf_info_t *, const cdf_header_t *,
const cdf_sat_t *, const cdf_sat_t *, const cdf_stream_t *,
const cdf_dir_t *, cdf_stream_t *);
int cdf_read_summary_info(const cdf_info_t *, const cdf_header_t *,
const cdf_sat_t *, const cdf_sat_t *, const cdf_stream_t *,
const cdf_dir_t *, cdf_stream_t *);
int cdf_unpack_summary_info(const cdf_stream_t *, const cdf_header_t *,
cdf_summary_info_header_t *, cdf_property_info_t **, size_t *);
int cdf_unpack_catalog(const cdf_header_t *, const cdf_stream_t *,
cdf_catalog_t **);
int cdf_print_classid(char *, size_t, const cdf_classid_t *);
int cdf_print_property_name(char *, size_t, uint32_t);
int cdf_print_elapsed_time(char *, size_t, cdf_timestamp_t);
uint16_t cdf_tole2(uint16_t);
uint32_t cdf_tole4(uint32_t);
uint64_t cdf_tole8(uint64_t);
char *cdf_ctime(const time_t *, char *);
char *cdf_u16tos8(char *, size_t, const uint16_t *);
#ifdef CDF_DEBUG
void cdf_dump_header(const cdf_header_t *);
void cdf_dump_sat(const char *, const cdf_sat_t *, size_t);
void cdf_dump(const void *, size_t);
void cdf_dump_stream(const cdf_stream_t *);
void cdf_dump_dir(const cdf_info_t *, const cdf_header_t *, const cdf_sat_t *,
const cdf_sat_t *, const cdf_stream_t *, const cdf_dir_t *);
void cdf_dump_property_info(const cdf_property_info_t *, size_t);
void cdf_dump_summary_info(const cdf_header_t *, const cdf_stream_t *);
void cdf_dump_catalog(const cdf_header_t *, const cdf_stream_t *);
#endif
#endif /* _H_CDF_ */
| 11,670 | 32.15625 | 80 |
h
|
php-src
|
php-src-master/ext/fileinfo/libmagic/cdf_time.c
|
/*-
* Copyright (c) 2008 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: cdf_time.c,v 1.20 2021/12/06 15:33:00 christos Exp $")
#endif
#include <time.h>
#ifdef TEST
#include <err.h>
#endif
#include <string.h>
#include "cdf.h"
#define isleap(y) ((((y) % 4) == 0) && \
((((y) % 100) != 0) || (((y) % 400) == 0)))
static const int mdays[] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
/*
* Return the number of days between jan 01 1601 and jan 01 of year.
*/
static int
cdf_getdays(int year)
{
int days = 0;
int y;
for (y = CDF_BASE_YEAR; y < year; y++)
days += isleap(y) + 365;
return days;
}
/*
* Return the day within the month
*/
static int
cdf_getday(int year, int days)
{
size_t m;
for (m = 0; m < __arraycount(mdays); m++) {
int sub = mdays[m] + (m == 1 && isleap(year));
if (days < sub)
return days;
days -= sub;
}
return days;
}
/*
* Return the 0...11 month number.
*/
static int
cdf_getmonth(int year, int days)
{
size_t m;
for (m = 0; m < __arraycount(mdays); m++) {
days -= mdays[m];
if (m == 1 && isleap(year))
days--;
if (days <= 0)
return CAST(int, m);
}
return CAST(int, m);
}
int
cdf_timestamp_to_timespec(struct timespec *ts, cdf_timestamp_t t)
{
struct tm tm;
#ifdef HAVE_STRUCT_TM_TM_ZONE
static char UTC[] = "UTC";
#endif
int rdays;
/* Unit is 100's of nanoseconds */
ts->tv_nsec = (t % CDF_TIME_PREC) * 100;
t /= CDF_TIME_PREC;
tm.tm_sec = CAST(int, t % 60);
t /= 60;
tm.tm_min = CAST(int, t % 60);
t /= 60;
tm.tm_hour = CAST(int, t % 24);
t /= 24;
/* XXX: Approx */
tm.tm_year = CAST(int, CDF_BASE_YEAR + (t / 365));
rdays = cdf_getdays(tm.tm_year);
t -= rdays - 1;
tm.tm_mday = cdf_getday(tm.tm_year, CAST(int, t));
tm.tm_mon = cdf_getmonth(tm.tm_year, CAST(int, t));
tm.tm_wday = 0;
tm.tm_yday = 0;
tm.tm_isdst = 0;
#ifdef HAVE_STRUCT_TM_TM_GMTOFF
tm.tm_gmtoff = 0;
#endif
#ifdef HAVE_STRUCT_TM_TM_ZONE
tm.tm_zone = UTC;
#endif
tm.tm_year -= 1900;
ts->tv_sec = mktime(&tm);
if (ts->tv_sec == -1) {
errno = EINVAL;
return -1;
}
return 0;
}
int
/*ARGSUSED*/
cdf_timespec_to_timestamp(cdf_timestamp_t *t, const struct timespec *ts)
{
#ifndef __lint__
(void)&t;
(void)&ts;
#endif
#ifdef notyet
struct tm tm;
if (gmtime_r(&ts->ts_sec, &tm) == NULL) {
errno = EINVAL;
return -1;
}
*t = (ts->ts_nsec / 100) * CDF_TIME_PREC;
*t = tm.tm_sec;
*t += tm.tm_min * 60;
*t += tm.tm_hour * 60 * 60;
*t += tm.tm_mday * 60 * 60 * 24;
#endif
return 0;
}
char *
cdf_ctime(const time_t *sec, char *buf)
{
char *ptr = ctime_r(sec, buf);
if (ptr != NULL)
return buf;
#ifdef WIN32
(void)snprintf(buf, 26, "*Bad* 0x%16.16I64x\n",
CAST(long long, *sec));
#else
(void)snprintf(buf, 26, "*Bad* %#16.16" INT64_T_FORMAT "x\n",
CAST(long long, *sec));
#endif
return buf;
}
#ifdef TEST_TIME
int
main(int argc, char *argv[])
{
struct timespec ts;
char buf[25];
static const cdf_timestamp_t tst = 0x01A5E403C2D59C00ULL;
static const char *ref = "Sat Apr 23 01:30:00 1977";
char *p, *q;
cdf_timestamp_to_timespec(&ts, tst);
p = cdf_ctime(&ts.tv_sec, buf);
if ((q = strchr(p, '\n')) != NULL)
*q = '\0';
if (strcmp(ref, p) != 0)
errx(1, "Error date %s != %s\n", ref, p);
return 0;
}
#endif
| 4,594 | 21.52451 | 78 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/der.c
|
/*-
* Copyright (c) 2016 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* DER (Distinguished Encoding Rules) Parser
*
* Sources:
* https://en.wikipedia.org/wiki/X.690
* http://fm4dd.com/openssl/certexamples.htm
* http://blog.engelke.com/2014/10/17/parsing-ber-and-der-encoded-asn-1-objects/
*/
#ifndef TEST_DER
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: der.c,v 1.24 2022/07/30 18:08:36 christos Exp $")
#endif
#else
#define SIZE_T_FORMAT "z"
#define CAST(a, b) ((a)(b))
#endif
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifndef TEST_DER
#include "magic.h"
#include "der.h"
#else
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#include <sys/stat.h>
#include <err.h>
#endif
#define DER_BAD CAST(uint32_t, -1)
#define DER_CLASS_UNIVERSAL 0
#define DER_CLASS_APPLICATION 1
#define DER_CLASS_CONTEXT 2
#define DER_CLASS_PRIVATE 3
#if defined(DEBUG_DER) || defined(TEST_DER)
static const char der_class[] = "UACP";
#endif
#define DER_TYPE_PRIMITIVE 0
#define DER_TYPE_CONSTRUCTED 1
#if defined(DEBUG_DER) || defined(TEST_DER)
static const char der_type[] = "PC";
#endif
#define DER_TAG_EOC 0x00
#define DER_TAG_BOOLEAN 0x01
#define DER_TAG_INTEGER 0x02
#define DER_TAG_BIT STRING 0x03
#define DER_TAG_OCTET_STRING 0x04
#define DER_TAG_NULL 0x05
#define DER_TAG_OBJECT_IDENTIFIER 0x06
#define DER_TAG_OBJECT_DESCRIPTOR 0x07
#define DER_TAG_EXTERNAL 0x08
#define DER_TAG_REAL 0x09
#define DER_TAG_ENUMERATED 0x0a
#define DER_TAG_EMBEDDED_PDV 0x0b
#define DER_TAG_UTF8_STRING 0x0c
#define DER_TAG_RELATIVE_OID 0x0d
#define DER_TAG_TIME 0x0e
#define DER_TAG_RESERVED_2 0x0f
#define DER_TAG_SEQUENCE 0x10
#define DER_TAG_SET 0x11
#define DER_TAG_NUMERIC_STRING 0x12
#define DER_TAG_PRINTABLE_STRING 0x13
#define DER_TAG_T61_STRING 0x14
#define DER_TAG_VIDEOTEX_STRING 0x15
#define DER_TAG_IA5_STRING 0x16
#define DER_TAG_UTCTIME 0x17
#define DER_TAG_GENERALIZED_TIME 0x18
#define DER_TAG_GRAPHIC_STRING 0x19
#define DER_TAG_VISIBLE_STRING 0x1a
#define DER_TAG_GENERAL_STRING 0x1b
#define DER_TAG_UNIVERSAL_STRING 0x1c
#define DER_TAG_CHARACTER_STRING 0x1d
#define DER_TAG_BMP_STRING 0x1e
#define DER_TAG_DATE 0x1f
#define DER_TAG_TIME_OF_DAY 0x20
#define DER_TAG_DATE_TIME 0x21
#define DER_TAG_DURATION 0x22
#define DER_TAG_OID_IRI 0x23
#define DER_TAG_RELATIVE_OID_IRI 0x24
#define DER_TAG_LAST 0x25
static const char *der__tag[] = {
"eoc", "bool", "int", "bit_str", "octet_str",
"null", "obj_id", "obj_desc", "ext", "real",
"enum", "embed", "utf8_str", "rel_oid", "time",
"res2", "seq", "set", "num_str", "prt_str",
"t61_str", "vid_str", "ia5_str", "utc_time", "gen_time",
"gr_str", "vis_str", "gen_str", "univ_str", "char_str",
"bmp_str", "date", "tod", "datetime", "duration",
"oid-iri", "rel-oid-iri",
};
#ifdef DEBUG_DER
#define DPRINTF(a) printf a
#else
#define DPRINTF(a)
#endif
#ifdef TEST_DER
static uint8_t
getclass(uint8_t c)
{
return c >> 6;
}
static uint8_t
gettype(uint8_t c)
{
return (c >> 5) & 1;
}
#endif
static uint32_t
gettag(const uint8_t *c, size_t *p, size_t l)
{
uint32_t tag;
if (*p >= l)
return DER_BAD;
tag = c[(*p)++] & 0x1f;
if (tag != 0x1f)
return tag;
if (*p >= l)
return DER_BAD;
while (c[*p] >= 0x80) {
tag = tag * 128 + c[(*p)++] - 0x80;
if (*p >= l)
return DER_BAD;
}
return tag;
}
/*
* Read the length of a DER tag from the input.
*
* `c` is the input, `p` is an output parameter that specifies how much of the
* input we consumed, and `l` is the maximum input length.
*
* Returns the length, or DER_BAD if the end of the input is reached or the
* length exceeds the remaining input.
*/
static uint32_t
getlength(const uint8_t *c, size_t *p, size_t l)
{
uint8_t digits, i;
size_t len;
int is_onebyte_result;
if (*p >= l) {
DPRINTF(("%s:[1] %zu >= %zu\n", __func__, *p, l));
return DER_BAD;
}
/*
* Digits can either be 0b0 followed by the result, or 0b1
* followed by the number of digits of the result. In either case,
* we verify that we can read so many bytes from the input.
*/
is_onebyte_result = (c[*p] & 0x80) == 0;
digits = c[(*p)++] & 0x7f;
if (*p + digits >= l) {
DPRINTF(("%s:[2] %zu + %u >= %zu\n", __func__, *p, digits, l));
return DER_BAD;
}
if (is_onebyte_result)
return digits;
/*
* Decode len. We've already verified that we're allowed to read
* `digits` bytes.
*/
len = 0;
for (i = 0; i < digits; i++)
len = (len << 8) | c[(*p)++];
if (len > UINT32_MAX - *p || *p + len > l) {
DPRINTF(("%s:[3] bad len %zu + %zu >= %zu\n",
__func__, *p, len, l));
return DER_BAD;
}
return CAST(uint32_t, len);
}
static const char *
der_tag(char *buf, size_t len, uint32_t tag)
{
if (tag < DER_TAG_LAST)
strlcpy(buf, der__tag[tag], len);
else
snprintf(buf, len, "%#x", tag);
return buf;
}
#ifndef TEST_DER
static int
der_data(char *buf, size_t blen, uint32_t tag, const void *q, uint32_t len)
{
uint32_t i;
const uint8_t *d = CAST(const uint8_t *, q);
switch (tag) {
case DER_TAG_PRINTABLE_STRING:
case DER_TAG_UTF8_STRING:
case DER_TAG_IA5_STRING:
return snprintf(buf, blen, "%.*s", len, RCAST(const char *, q));
case DER_TAG_UTCTIME:
if (len < 12)
break;
return snprintf(buf, blen,
"20%c%c-%c%c-%c%c %c%c:%c%c:%c%c GMT", d[0], d[1], d[2],
d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10], d[11]);
default:
break;
}
for (i = 0; i < len; i++) {
uint32_t z = i << 1;
if (z < blen - 2)
snprintf(buf + z, blen - z, "%.2x", d[i]);
}
return len * 2;
}
int32_t
der_offs(struct magic_set *ms, struct magic *m, size_t nbytes)
{
const uint8_t *b = RCAST(const uint8_t *, ms->search.s);
size_t offs = 0, len = ms->search.s_len ? ms->search.s_len : nbytes;
if (gettag(b, &offs, len) == DER_BAD) {
DPRINTF(("%s: bad tag 1\n", __func__));
return -1;
}
DPRINTF(("%s1: %d %" SIZE_T_FORMAT "u %u\n", __func__, ms->offset,
offs, m->offset));
uint32_t tlen = getlength(b, &offs, len);
if (tlen == DER_BAD) {
DPRINTF(("%s: bad tag 2\n", __func__));
return -1;
}
DPRINTF(("%s2: %d %" SIZE_T_FORMAT "u %u\n", __func__, ms->offset,
offs, tlen));
offs += ms->offset + m->offset;
DPRINTF(("cont_level = %d\n", m->cont_level));
#ifdef DEBUG_DER
size_t i;
for (i = 0; i < m->cont_level; i++)
printf("cont_level[%" SIZE_T_FORMAT "u] = %u\n", i,
ms->c.li[i].off);
#endif
if (m->cont_level != 0) {
if (offs + tlen > nbytes)
return -1;
ms->c.li[m->cont_level - 1].off = CAST(int, offs + tlen);
DPRINTF(("cont_level[%u] = %u\n", m->cont_level - 1,
ms->c.li[m->cont_level - 1].off));
}
return CAST(int32_t, offs);
}
int
der_cmp(struct magic_set *ms, struct magic *m)
{
const uint8_t *b = RCAST(const uint8_t *, ms->search.s);
const char *s = m->value.s;
size_t offs = 0, len = ms->search.s_len;
uint32_t tag, tlen;
char buf[128];
DPRINTF(("%s: compare %zu bytes\n", __func__, len));
tag = gettag(b, &offs, len);
if (tag == DER_BAD) {
DPRINTF(("%s: bad tag 1\n", __func__));
return -1;
}
DPRINTF(("%s1: %d %" SIZE_T_FORMAT "u %u\n", __func__, ms->offset,
offs, m->offset));
tlen = getlength(b, &offs, len);
if (tlen == DER_BAD) {
DPRINTF(("%s: bad tag 2\n", __func__));
return -1;
}
der_tag(buf, sizeof(buf), tag);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "%s: tag %p got=%s exp=%s\n", __func__, b,
buf, s);
size_t slen = strlen(buf);
if (strncmp(buf, s, slen) != 0) {
DPRINTF(("%s: no string match %s != %s\n", __func__, buf, s));
return 0;
}
s += slen;
again:
switch (*s) {
case '\0':
DPRINTF(("%s: EOF match\n", __func__));
return 1;
case '=':
s++;
goto val;
default:
if (!isdigit(CAST(unsigned char, *s))) {
DPRINTF(("%s: no digit %c\n", __func__, *s));
return 0;
}
slen = 0;
do
slen = slen * 10 + *s - '0';
while (isdigit(CAST(unsigned char, *++s)));
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "%s: len %" SIZE_T_FORMAT "u %u\n",
__func__, slen, tlen);
if (tlen != slen) {
DPRINTF(("%s: len %u != %zu\n", __func__, tlen, slen));
return 0;
}
goto again;
}
val:
DPRINTF(("%s: before data %" SIZE_T_FORMAT "u %u\n", __func__, offs,
tlen));
der_data(buf, sizeof(buf), tag, b + offs, tlen);
if ((ms->flags & MAGIC_DEBUG) != 0)
fprintf(stderr, "%s: data %s %s\n", __func__, buf, s);
if (strcmp(buf, s) != 0 && strcmp("x", s) != 0) {
DPRINTF(("%s: no string match %s != %s\n", __func__, buf, s));
return 0;
}
strlcpy(ms->ms_value.s, buf, sizeof(ms->ms_value.s));
DPRINTF(("%s: complete match\n", __func__));
return 1;
}
#endif
#ifdef TEST_DER
static void
printtag(uint32_t tag, const void *q, uint32_t len)
{
const uint8_t *d = q;
switch (tag) {
case DER_TAG_PRINTABLE_STRING:
case DER_TAG_UTF8_STRING:
case DER_TAG_IA5_STRING:
case DER_TAG_UTCTIME:
printf("%.*s\n", len, (const char *)q);
return;
default:
break;
}
for (uint32_t i = 0; i < len; i++)
printf("%.2x", d[i]);
printf("\n");
}
static void
printdata(size_t level, const void *v, size_t x, size_t l)
{
const uint8_t *p = v, *ep = p + l;
size_t ox;
char buf[128];
while (p + x < ep) {
const uint8_t *q;
uint8_t c = getclass(p[x]);
uint8_t t = gettype(p[x]);
ox = x;
// if (x != 0)
// printf("%.2x %.2x %.2x\n", p[x - 1], p[x], p[x + 1]);
uint32_t tag = gettag(p, &x, ep - p + x);
if (p + x >= ep)
break;
uint32_t len = getlength(p, &x, ep - p + x);
printf("%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u-%"
SIZE_T_FORMAT "u %c,%c,%s,%u:", level, ox, x,
der_class[c], der_type[t],
der_tag(buf, sizeof(buf), tag), len);
q = p + x;
if (p + len > ep)
errx(EXIT_FAILURE, "corrupt der");
printtag(tag, q, len);
if (t != DER_TYPE_PRIMITIVE)
printdata(level + 1, p, x, len + x);
x += len;
}
}
int
main(int argc, char *argv[])
{
int fd;
struct stat st;
size_t l;
void *p;
if ((fd = open(argv[1], O_RDONLY)) == -1)
err(EXIT_FAILURE, "open `%s'", argv[1]);
if (fstat(fd, &st) == -1)
err(EXIT_FAILURE, "stat `%s'", argv[1]);
l = (size_t)st.st_size;
if ((p = mmap(NULL, l, PROT_READ, MAP_FILE, fd, 0)) == MAP_FAILED)
err(EXIT_FAILURE, "mmap `%s'", argv[1]);
printdata(0, p, 0, l);
munmap(p, l);
return 0;
}
#endif
| 11,574 | 24.10846 | 80 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/der.h
|
/*-
* Copyright (c) 2016 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
extern int der_offs(struct magic_set *, struct magic *, size_t);
extern int der_cmp(struct magic_set *, struct magic *);
| 1,500 | 50.758621 | 78 |
h
|
php-src
|
php-src-master/ext/fileinfo/libmagic/elfclass.h
|
/*
* Copyright (c) Christos Zoulas 2008.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
if (nbytes <= sizeof(elfhdr))
return 0;
u.l = 1;
(void)memcpy(&elfhdr, buf, sizeof elfhdr);
swap = (u.c[sizeof(int32_t) - 1] + 1) != elfhdr.e_ident[EI_DATA];
type = elf_getu16(swap, elfhdr.e_type);
notecount = ms->elf_notes_max;
switch (type) {
#ifdef ELFCORE
case ET_CORE:
phnum = elf_getu16(swap, elfhdr.e_phnum);
if (phnum > ms->elf_phnum_max)
return toomany(ms, "program headers", phnum);
flags |= FLAGS_IS_CORE;
if (dophn_core(ms, clazz, swap, fd,
CAST(zend_off_t, elf_getu(swap, elfhdr.e_phoff)), phnum,
CAST(size_t, elf_getu16(swap, elfhdr.e_phentsize)),
fsize, &flags, ¬ecount) == -1)
return -1;
break;
#endif
case ET_EXEC:
case ET_DYN:
phnum = elf_getu16(swap, elfhdr.e_phnum);
if (phnum > ms->elf_phnum_max)
return toomany(ms, "program", phnum);
shnum = elf_getu16(swap, elfhdr.e_shnum);
if (shnum > ms->elf_shnum_max)
return toomany(ms, "section", shnum);
if (dophn_exec(ms, clazz, swap, fd,
CAST(zend_off_t, elf_getu(swap, elfhdr.e_phoff)), phnum,
CAST(size_t, elf_getu16(swap, elfhdr.e_phentsize)),
fsize, shnum, &flags, ¬ecount) == -1)
return -1;
/*FALLTHROUGH*/
case ET_REL:
shnum = elf_getu16(swap, elfhdr.e_shnum);
if (shnum > ms->elf_shnum_max)
return toomany(ms, "section headers", shnum);
if (doshn(ms, clazz, swap, fd,
CAST(zend_off_t, elf_getu(swap, elfhdr.e_shoff)), shnum,
CAST(size_t, elf_getu16(swap, elfhdr.e_shentsize)),
fsize, elf_getu16(swap, elfhdr.e_machine),
CAST(int, elf_getu16(swap, elfhdr.e_shstrndx)),
&flags, ¬ecount) == -1)
return -1;
break;
default:
break;
}
if (notecount == 0)
return toomany(ms, "notes", ms->elf_notes_max);
return 1;
| 3,154 | 37.012048 | 77 |
h
|
php-src
|
php-src-master/ext/fileinfo/libmagic/encoding.c
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Encoding -- determine the character encoding of a text file.
*
* Joerg Wunsch <[email protected]> wrote the original support for 8-bit
* international characters.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: encoding.c,v 1.39 2022/09/13 18:46:07 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <string.h>
#include <stdlib.h>
private int looks_ascii(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private int looks_utf8_with_BOM(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private int looks_utf7(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private int looks_ucs16(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private int looks_ucs32(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private int looks_latin1(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private int looks_extended(const unsigned char *, size_t, file_unichar_t *,
size_t *);
private void from_ebcdic(const unsigned char *, size_t, unsigned char *);
#ifdef DEBUG_ENCODING
#define DPRINTF(a) printf a
#else
#define DPRINTF(a)
#endif
/*
* Try to determine whether text is in some character code we can
* identify. Each of these tests, if it succeeds, will leave
* the text converted into one-file_unichar_t-per-character Unicode in
* ubuf, and the number of characters converted in ulen.
*/
protected int
file_encoding(struct magic_set *ms, const struct buffer *b,
file_unichar_t **ubuf, size_t *ulen, const char **code,
const char **code_mime, const char **type)
{
const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
size_t nbytes = b->flen;
size_t mlen;
int rv = 1, ucs_type;
file_unichar_t *udefbuf;
size_t udeflen;
if (ubuf == NULL)
ubuf = &udefbuf;
if (ulen == NULL)
ulen = &udeflen;
*type = "text";
*ulen = 0;
*code = "unknown";
*code_mime = "binary";
if (nbytes > ms->encoding_max)
nbytes = ms->encoding_max;
mlen = (nbytes + 1) * sizeof((*ubuf)[0]);
*ubuf = CAST(file_unichar_t *, ecalloc(CAST(size_t, 1), mlen));
if (*ubuf == NULL) {
file_oomem(ms, mlen);
goto done;
}
if (looks_ascii(buf, nbytes, *ubuf, ulen)) {
if (looks_utf7(buf, nbytes, *ubuf, ulen) > 0) {
DPRINTF(("utf-7 %" SIZE_T_FORMAT "u\n", *ulen));
*code = "Unicode text, UTF-7";
*code_mime = "utf-7";
} else {
DPRINTF(("ascii %" SIZE_T_FORMAT "u\n", *ulen));
*code = "ASCII";
*code_mime = "us-ascii";
}
} else if (looks_utf8_with_BOM(buf, nbytes, *ubuf, ulen) > 0) {
DPRINTF(("utf8/bom %" SIZE_T_FORMAT "u\n", *ulen));
*code = "Unicode text, UTF-8 (with BOM)";
*code_mime = "utf-8";
} else if (file_looks_utf8(buf, nbytes, *ubuf, ulen) > 1) {
DPRINTF(("utf8 %" SIZE_T_FORMAT "u\n", *ulen));
*code = "Unicode text, UTF-8";
*code_mime = "utf-8";
} else if ((ucs_type = looks_ucs32(buf, nbytes, *ubuf, ulen)) != 0) {
if (ucs_type == 1) {
*code = "Unicode text, UTF-32, little-endian";
*code_mime = "utf-32le";
} else {
*code = "Unicode text, UTF-32, big-endian";
*code_mime = "utf-32be";
}
DPRINTF(("ucs32 %" SIZE_T_FORMAT "u\n", *ulen));
} else if ((ucs_type = looks_ucs16(buf, nbytes, *ubuf, ulen)) != 0) {
if (ucs_type == 1) {
*code = "Unicode text, UTF-16, little-endian";
*code_mime = "utf-16le";
} else {
*code = "Unicode text, UTF-16, big-endian";
*code_mime = "utf-16be";
}
DPRINTF(("ucs16 %" SIZE_T_FORMAT "u\n", *ulen));
} else if (looks_latin1(buf, nbytes, *ubuf, ulen)) {
DPRINTF(("latin1 %" SIZE_T_FORMAT "u\n", *ulen));
*code = "ISO-8859";
*code_mime = "iso-8859-1";
} else if (looks_extended(buf, nbytes, *ubuf, ulen)) {
DPRINTF(("extended %" SIZE_T_FORMAT "u\n", *ulen));
*code = "Non-ISO extended-ASCII";
*code_mime = "unknown-8bit";
} else {
unsigned char *nbuf;
mlen = (nbytes + 1) * sizeof(nbuf[0]);
if ((nbuf = CAST(unsigned char *, emalloc(mlen))) == NULL) {
file_oomem(ms, mlen);
goto done;
}
from_ebcdic(buf, nbytes, nbuf);
if (looks_ascii(nbuf, nbytes, *ubuf, ulen)) {
DPRINTF(("ebcdic %" SIZE_T_FORMAT "u\n", *ulen));
*code = "EBCDIC";
*code_mime = "ebcdic";
} else if (looks_latin1(nbuf, nbytes, *ubuf, ulen)) {
DPRINTF(("ebcdic/international %" SIZE_T_FORMAT "u\n",
*ulen));
*code = "International EBCDIC";
*code_mime = "ebcdic";
} else { /* Doesn't look like text at all */
DPRINTF(("binary\n"));
rv = 0;
*type = "binary";
}
efree(nbuf);
}
done:
if (ubuf == &udefbuf)
efree(udefbuf);
return rv;
}
/*
* This table reflects a particular philosophy about what constitutes
* "text," and there is room for disagreement about it.
*
* Version 3.31 of the file command considered a file to be ASCII if
* each of its characters was approved by either the isascii() or
* isalpha() function. On most systems, this would mean that any
* file consisting only of characters in the range 0x00 ... 0x7F
* would be called ASCII text, but many systems might reasonably
* consider some characters outside this range to be alphabetic,
* so the file command would call such characters ASCII. It might
* have been more accurate to call this "considered textual on the
* local system" than "ASCII."
*
* It considered a file to be "International language text" if each
* of its characters was either an ASCII printing character (according
* to the real ASCII standard, not the above test), a character in
* the range 0x80 ... 0xFF, or one of the following control characters:
* backspace, tab, line feed, vertical tab, form feed, carriage return,
* escape. No attempt was made to determine the language in which files
* of this type were written.
*
*
* The table below considers a file to be ASCII if all of its characters
* are either ASCII printing characters (again, according to the X3.4
* standard, not isascii()) or any of the following controls: bell,
* backspace, tab, line feed, form feed, carriage return, esc, nextline.
*
* I include bell because some programs (particularly shell scripts)
* use it literally, even though it is rare in normal text. I exclude
* vertical tab because it never seems to be used in real text. I also
* include, with hesitation, the X3.64/ECMA-43 control nextline (0x85),
* because that's what the dd EBCDIC->ASCII table maps the EBCDIC newline
* character to. It might be more appropriate to include it in the 8859
* set instead of the ASCII set, but it's got to be included in *something*
* we recognize or EBCDIC files aren't going to be considered textual.
* Some old Unix source files use SO/SI (^N/^O) to shift between Greek
* and Latin characters, so these should possibly be allowed. But they
* make a real mess on VT100-style displays if they're not paired properly,
* so we are probably better off not calling them text.
*
* A file is considered to be ISO-8859 text if its characters are all
* either ASCII, according to the above definition, or printing characters
* from the ISO-8859 8-bit extension, characters 0xA0 ... 0xFF.
*
* Finally, a file is considered to be international text from some other
* character code if its characters are all either ISO-8859 (according to
* the above definition) or characters in the range 0x80 ... 0x9F, which
* ISO-8859 considers to be control characters but the IBM PC and Macintosh
* consider to be printing characters.
*/
#define F 0 /* character never appears in text */
#define T 1 /* character appears in plain ASCII text */
#define I 2 /* character appears in ISO-8859 text */
#define X 3 /* character appears in non-ISO extended ASCII (Mac, IBM PC) */
private char text_chars[256] = {
/* BEL BS HT LF VT FF CR */
F, F, F, F, F, F, F, T, T, T, T, T, T, T, F, F, /* 0x0X */
/* ESC */
F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, F, /* 0x1X */
T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x2X */
T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x3X */
T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x4X */
T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x5X */
T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x6X */
T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, /* 0x7X */
/* NEL */
X, X, X, X, X, T, X, X, X, X, X, X, X, X, X, X, /* 0x8X */
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 0x9X */
I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xaX */
I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xbX */
I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xcX */
I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xdX */
I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xeX */
I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I /* 0xfX */
};
#define LOOKS(NAME, COND) \
private int \
looks_ ## NAME(const unsigned char *buf, size_t nbytes, file_unichar_t *ubuf, \
size_t *ulen) \
{ \
size_t i; \
\
*ulen = 0; \
\
for (i = 0; i < nbytes; i++) { \
int t = text_chars[buf[i]]; \
\
if (COND) \
return 0; \
\
ubuf[(*ulen)++] = buf[i]; \
} \
return 1; \
}
LOOKS(ascii, t != T)
LOOKS(latin1, t != T && t != I)
LOOKS(extended, t != T && t != I && t != X)
/*
* Decide whether some text looks like UTF-8. Returns:
*
* -1: invalid UTF-8
* 0: uses odd control characters, so doesn't look like text
* 1: 7-bit text
* 2: definitely UTF-8 text (valid high-bit set bytes)
*
* If ubuf is non-NULL on entry, text is decoded into ubuf, *ulen;
* ubuf must be big enough!
*/
// from: https://golang.org/src/unicode/utf8/utf8.go
#define XX 0xF1 // invalid: size 1
#define AS 0xF0 // ASCII: size 1
#define S1 0x02 // accept 0, size 2
#define S2 0x13 // accept 1, size 3
#define S3 0x03 // accept 0, size 3
#define S4 0x23 // accept 2, size 3
#define S5 0x34 // accept 3, size 4
#define S6 0x04 // accept 0, size 4
#define S7 0x44 // accept 4, size 4
#define LOCB 0x80
#define HICB 0xBF
// first is information about the first byte in a UTF-8 sequence.
static const uint8_t first[] = {
// 1 2 3 4 5 6 7 8 9 A B C D E F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x00-0x0F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x10-0x1F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x20-0x2F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x30-0x3F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x40-0x4F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x50-0x5F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x60-0x6F
AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, AS, // 0x70-0x7F
// 1 2 3 4 5 6 7 8 9 A B C D E F
XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0x80-0x8F
XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0x90-0x9F
XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0xA0-0xAF
XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0xB0-0xBF
XX, XX, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, // 0xC0-0xCF
S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, S1, // 0xD0-0xDF
S2, S3, S3, S3, S3, S3, S3, S3, S3, S3, S3, S3, S3, S4, S3, S3, // 0xE0-0xEF
S5, S6, S6, S6, S7, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, XX, // 0xF0-0xFF
};
// acceptRange gives the range of valid values for the second byte in a UTF-8
// sequence.
struct accept_range {
uint8_t lo; // lowest value for second byte.
uint8_t hi; // highest value for second byte.
} accept_ranges[16] = {
// acceptRanges has size 16 to avoid bounds checks in the code that uses it.
{ LOCB, HICB },
{ 0xA0, HICB },
{ LOCB, 0x9F },
{ 0x90, HICB },
{ LOCB, 0x8F },
};
protected int
file_looks_utf8(const unsigned char *buf, size_t nbytes, file_unichar_t *ubuf,
size_t *ulen)
{
size_t i;
int n;
file_unichar_t c;
int gotone = 0, ctrl = 0;
if (ubuf)
*ulen = 0;
for (i = 0; i < nbytes; i++) {
if ((buf[i] & 0x80) == 0) { /* 0xxxxxxx is plain ASCII */
/*
* Even if the whole file is valid UTF-8 sequences,
* still reject it if it uses weird control characters.
*/
if (text_chars[buf[i]] != T)
ctrl = 1;
if (ubuf)
ubuf[(*ulen)++] = buf[i];
} else if ((buf[i] & 0x40) == 0) { /* 10xxxxxx never 1st byte */
return -1;
} else { /* 11xxxxxx begins UTF-8 */
int following;
uint8_t x = first[buf[i]];
const struct accept_range *ar =
&accept_ranges[(unsigned int)x >> 4];
if (x == XX)
return -1;
if ((buf[i] & 0x20) == 0) { /* 110xxxxx */
c = buf[i] & 0x1f;
following = 1;
} else if ((buf[i] & 0x10) == 0) { /* 1110xxxx */
c = buf[i] & 0x0f;
following = 2;
} else if ((buf[i] & 0x08) == 0) { /* 11110xxx */
c = buf[i] & 0x07;
following = 3;
} else if ((buf[i] & 0x04) == 0) { /* 111110xx */
c = buf[i] & 0x03;
following = 4;
} else if ((buf[i] & 0x02) == 0) { /* 1111110x */
c = buf[i] & 0x01;
following = 5;
} else
return -1;
for (n = 0; n < following; n++) {
i++;
if (i >= nbytes)
goto done;
if (n == 0 &&
(buf[i] < ar->lo || buf[i] > ar->hi))
return -1;
if ((buf[i] & 0x80) == 0 || (buf[i] & 0x40))
return -1;
c = (c << 6) + (buf[i] & 0x3f);
}
if (ubuf)
ubuf[(*ulen)++] = c;
gotone = 1;
}
}
done:
return ctrl ? 0 : (gotone ? 2 : 1);
}
/*
* Decide whether some text looks like UTF-8 with BOM. If there is no
* BOM, return -1; otherwise return the result of looks_utf8 on the
* rest of the text.
*/
private int
looks_utf8_with_BOM(const unsigned char *buf, size_t nbytes,
file_unichar_t *ubuf, size_t *ulen)
{
if (nbytes > 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf)
return file_looks_utf8(buf + 3, nbytes - 3, ubuf, ulen);
else
return -1;
}
private int
looks_utf7(const unsigned char *buf, size_t nbytes, file_unichar_t *ubuf,
size_t *ulen)
{
if (nbytes > 4 && buf[0] == '+' && buf[1] == '/' && buf[2] == 'v')
switch (buf[3]) {
case '8':
case '9':
case '+':
case '/':
if (ubuf)
*ulen = 0;
return 1;
default:
return -1;
}
else
return -1;
}
#define UCS16_NOCHAR(c) ((c) >= 0xfdd0 && (c) <= 0xfdef)
#define UCS16_HISURR(c) ((c) >= 0xd800 && (c) <= 0xdbff)
#define UCS16_LOSURR(c) ((c) >= 0xdc00 && (c) <= 0xdfff)
private int
looks_ucs16(const unsigned char *bf, size_t nbytes, file_unichar_t *ubf,
size_t *ulen)
{
int bigend;
uint32_t hi;
size_t i;
if (nbytes < 2)
return 0;
if (bf[0] == 0xff && bf[1] == 0xfe)
bigend = 0;
else if (bf[0] == 0xfe && bf[1] == 0xff)
bigend = 1;
else
return 0;
*ulen = 0;
hi = 0;
for (i = 2; i + 1 < nbytes; i += 2) {
uint32_t uc;
if (bigend)
uc = CAST(uint32_t,
bf[i + 1] | (CAST(file_unichar_t, bf[i]) << 8));
else
uc = CAST(uint32_t,
bf[i] | (CAST(file_unichar_t, bf[i + 1]) << 8));
uc &= 0xffff;
switch (uc) {
case 0xfffe:
case 0xffff:
return 0;
default:
if (UCS16_NOCHAR(uc))
return 0;
break;
}
if (hi) {
if (!UCS16_LOSURR(uc))
return 0;
uc = 0x10000 + 0x400 * (hi - 1) + (uc - 0xdc00);
hi = 0;
}
if (uc < 128 && text_chars[CAST(size_t, uc)] != T)
return 0;
ubf[(*ulen)++] = uc;
if (UCS16_HISURR(uc))
hi = uc - 0xd800 + 1;
if (UCS16_LOSURR(uc))
return 0;
}
return 1 + bigend;
}
private int
looks_ucs32(const unsigned char *bf, size_t nbytes, file_unichar_t *ubf,
size_t *ulen)
{
int bigend;
size_t i;
if (nbytes < 4)
return 0;
if (bf[0] == 0xff && bf[1] == 0xfe && bf[2] == 0 && bf[3] == 0)
bigend = 0;
else if (bf[0] == 0 && bf[1] == 0 && bf[2] == 0xfe && bf[3] == 0xff)
bigend = 1;
else
return 0;
*ulen = 0;
for (i = 4; i + 3 < nbytes; i += 4) {
/* XXX fix to properly handle chars > 65536 */
if (bigend)
ubf[(*ulen)++] = CAST(file_unichar_t, bf[i + 3])
| (CAST(file_unichar_t, bf[i + 2]) << 8)
| (CAST(file_unichar_t, bf[i + 1]) << 16)
| (CAST(file_unichar_t, bf[i]) << 24);
else
ubf[(*ulen)++] = CAST(file_unichar_t, bf[i + 0])
| (CAST(file_unichar_t, bf[i + 1]) << 8)
| (CAST(file_unichar_t, bf[i + 2]) << 16)
| (CAST(file_unichar_t, bf[i + 3]) << 24);
if (ubf[*ulen - 1] == 0xfffe)
return 0;
if (ubf[*ulen - 1] < 128 &&
text_chars[CAST(size_t, ubf[*ulen - 1])] != T)
return 0;
}
return 1 + bigend;
}
#undef F
#undef T
#undef I
#undef X
/*
* This table maps each EBCDIC character to an (8-bit extended) ASCII
* character, as specified in the rationale for the dd(1) command in
* draft 11.2 (September, 1991) of the POSIX P1003.2 standard.
*
* Unfortunately it does not seem to correspond exactly to any of the
* five variants of EBCDIC documented in IBM's _Enterprise Systems
* Architecture/390: Principles of Operation_, SA22-7201-06, Seventh
* Edition, July, 1999, pp. I-1 - I-4.
*
* Fortunately, though, all versions of EBCDIC, including this one, agree
* on most of the printing characters that also appear in (7-bit) ASCII.
* Of these, only '|', '!', '~', '^', '[', and ']' are in question at all.
*
* Fortunately too, there is general agreement that codes 0x00 through
* 0x3F represent control characters, 0x41 a nonbreaking space, and the
* remainder printing characters.
*
* This is sufficient to allow us to identify EBCDIC text and to distinguish
* between old-style and internationalized examples of text.
*/
private unsigned char ebcdic_to_ascii[] = {
0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15,
16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31,
128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7,
144, 145, 22, 147, 148, 149, 150, 4, 152, 153, 154, 155, 20, 21, 158, 26,
' ', 160, 161, 162, 163, 164, 165, 166, 167, 168, 213, '.', '<', '(', '+', '|',
'&', 169, 170, 171, 172, 173, 174, 175, 176, 177, '!', '$', '*', ')', ';', '~',
'-', '/', 178, 179, 180, 181, 182, 183, 184, 185, 203, ',', '%', '_', '>', '?',
186, 187, 188, 189, 190, 191, 192, 193, 194, '`', ':', '#', '@', '\'','=', '"',
195, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 196, 197, 198, 199, 200, 201,
202, 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', '^', 204, 205, 206, 207, 208,
209, 229, 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 210, 211, 212, '[', 214, 215,
216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, ']', 230, 231,
'{', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 232, 233, 234, 235, 236, 237,
'}', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 238, 239, 240, 241, 242, 243,
'\\',159, 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 244, 245, 246, 247, 248, 249,
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 250, 251, 252, 253, 254, 255
};
#ifdef notdef
/*
* The following EBCDIC-to-ASCII table may relate more closely to reality,
* or at least to modern reality. It comes from
*
* http://ftp.s390.ibm.com/products/oe/bpxqp9.html
*
* and maps the characters of EBCDIC code page 1047 (the code used for
* Unix-derived software on IBM's 390 systems) to the corresponding
* characters from ISO 8859-1.
*
* If this table is used instead of the above one, some of the special
* cases for the NEL character can be taken out of the code.
*/
private unsigned char ebcdic_1047_to_8859[] = {
0x00,0x01,0x02,0x03,0x9C,0x09,0x86,0x7F,0x97,0x8D,0x8E,0x0B,0x0C,0x0D,0x0E,0x0F,
0x10,0x11,0x12,0x13,0x9D,0x0A,0x08,0x87,0x18,0x19,0x92,0x8F,0x1C,0x1D,0x1E,0x1F,
0x80,0x81,0x82,0x83,0x84,0x85,0x17,0x1B,0x88,0x89,0x8A,0x8B,0x8C,0x05,0x06,0x07,
0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9A,0x9B,0x14,0x15,0x9E,0x1A,
0x20,0xA0,0xE2,0xE4,0xE0,0xE1,0xE3,0xE5,0xE7,0xF1,0xA2,0x2E,0x3C,0x28,0x2B,0x7C,
0x26,0xE9,0xEA,0xEB,0xE8,0xED,0xEE,0xEF,0xEC,0xDF,0x21,0x24,0x2A,0x29,0x3B,0x5E,
0x2D,0x2F,0xC2,0xC4,0xC0,0xC1,0xC3,0xC5,0xC7,0xD1,0xA6,0x2C,0x25,0x5F,0x3E,0x3F,
0xF8,0xC9,0xCA,0xCB,0xC8,0xCD,0xCE,0xCF,0xCC,0x60,0x3A,0x23,0x40,0x27,0x3D,0x22,
0xD8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xAB,0xBB,0xF0,0xFD,0xFE,0xB1,
0xB0,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,0xAA,0xBA,0xE6,0xB8,0xC6,0xA4,
0xB5,0x7E,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0xA1,0xBF,0xD0,0x5B,0xDE,0xAE,
0xAC,0xA3,0xA5,0xB7,0xA9,0xA7,0xB6,0xBC,0xBD,0xBE,0xDD,0xA8,0xAF,0x5D,0xB4,0xD7,
0x7B,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xAD,0xF4,0xF6,0xF2,0xF3,0xF5,
0x7D,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x51,0x52,0xB9,0xFB,0xFC,0xF9,0xFA,0xFF,
0x5C,0xF7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0xB2,0xD4,0xD6,0xD2,0xD3,0xD5,
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xB3,0xDB,0xDC,0xD9,0xDA,0x9F
};
#endif
/*
* Copy buf[0 ... nbytes-1] into out[], translating EBCDIC to ASCII.
*/
private void
from_ebcdic(const unsigned char *buf, size_t nbytes, unsigned char *out)
{
size_t i;
for (i = 0; i < nbytes; i++) {
out[i] = ebcdic_to_ascii[buf[i]];
}
}
| 22,551 | 33.221548 | 80 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/file.h
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* file.h - definitions for file(1) program
* @(#)$File: file.h,v 1.237 2022/09/10 13:21:42 christos Exp $
*/
#ifndef __file_h__
#define __file_h__
#include "config.h"
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifdef _WIN32
# ifdef PRIu32
# ifdef _WIN64
# define SIZE_T_FORMAT PRIu64
# else
# define SIZE_T_FORMAT PRIu32
# endif
# define INT64_T_FORMAT PRIi64
# define INTMAX_T_FORMAT PRIiMAX
# else
# ifdef _WIN64
# define SIZE_T_FORMAT "I64"
# else
# define SIZE_T_FORMAT ""
# endif
# define INT64_T_FORMAT "I64"
# define INTMAX_T_FORMAT "I64"
# endif
#else
# define SIZE_T_FORMAT "z"
# define INT64_T_FORMAT "ll"
# define INTMAX_T_FORMAT "j"
#endif
#include <stdio.h> /* Include that here, to make sure __P gets defined */
#include <errno.h>
#include <fcntl.h> /* For open and flags */
#include <sys/types.h>
#ifndef WIN32
#include <sys/param.h>
#endif
/* Do this here and now, because struct stat gets re-defined on solaris */
#include <sys/stat.h>
#include <stdarg.h>
#define ENABLE_CONDITIONALS
#ifndef MAGIC
#define MAGIC "/etc/magic"
#endif
#if defined(__EMX__) || defined (WIN32)
#define PATHSEP ';'
#else
#define PATHSEP ':'
#endif
#define private static
#if HAVE_VISIBILITY && !defined(WIN32)
#define public __attribute__ ((__visibility__("default")))
#ifndef protected
#define protected __attribute__ ((__visibility__("hidden")))
#endif
#else
#define public
#ifndef protected
#define protected
#endif
#endif
#ifndef __arraycount
#define __arraycount(a) (sizeof(a) / sizeof(a[0]))
#endif
#ifndef __GNUC_PREREQ__
#ifdef __GNUC__
#define __GNUC_PREREQ__(x, y) \
((__GNUC__ == (x) && __GNUC_MINOR__ >= (y)) || \
(__GNUC__ > (x)))
#else
#define __GNUC_PREREQ__(x, y) 0
#endif
#endif
#ifndef __GNUC__
#ifndef __attribute__
#define __attribute__(a)
#endif
#endif
#ifndef MIN
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef O_CLOEXEC
# define O_CLOEXEC 0
#endif
#ifndef FD_CLOEXEC
# define FD_CLOEXEC 1
#endif
#define FILE_BADSIZE CAST(size_t, ~0ul)
#define MAXDESC 64 /* max len of text description/MIME type */
#define MAXMIME 80 /* max len of text MIME type */
#define MAXstring 128 /* max len of "string" types */
#define MAGICNO 0xF11E041C
#define VERSIONNO 18
#define FILE_MAGICSIZE 376
#define FILE_GUID_SIZE sizeof("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
#define FILE_LOAD 0
#define FILE_CHECK 1
#define FILE_COMPILE 2
#define FILE_LIST 3
struct buffer {
int fd;
zend_stat_t st;
const void *fbuf;
size_t flen;
zend_off_t eoff;
void *ebuf;
size_t elen;
};
union VALUETYPE {
uint8_t b;
uint16_t h;
uint32_t l;
uint64_t q;
uint8_t hs[2]; /* 2 bytes of a fixed-endian "short" */
uint8_t hl[4]; /* 4 bytes of a fixed-endian "long" */
uint8_t hq[8]; /* 8 bytes of a fixed-endian "quad" */
char s[MAXstring]; /* the search string or regex pattern */
unsigned char us[MAXstring];
uint64_t guid[2];
float f;
double d;
};
struct magic {
/* Word 1 */
uint16_t cont_level; /* level of ">" */
uint8_t flag;
#define INDIR 0x01 /* if '(...)' appears */
#define OFFADD 0x02 /* if '>&' or '>...(&' appears */
#define INDIROFFADD 0x04 /* if '>&(' appears */
#define UNSIGNED 0x08 /* comparison is unsigned */
#define NOSPACE 0x10 /* suppress space character before output */
#define BINTEST 0x20 /* test is for a binary type (set only
for top-level tests) */
#define TEXTTEST 0x40 /* for passing to file_softmagic */
#define OFFNEGATIVE 0x80 /* relative to the end of file */
uint8_t factor;
/* Word 2 */
uint8_t reln; /* relation (0=eq, '>'=gt, etc) */
uint8_t vallen; /* length of string value, if any */
uint8_t type; /* comparison type (FILE_*) */
uint8_t in_type; /* type of indirection */
#define FILE_INVALID 0
#define FILE_BYTE 1
#define FILE_SHORT 2
#define FILE_DEFAULT 3
#define FILE_LONG 4
#define FILE_STRING 5
#define FILE_DATE 6
#define FILE_BESHORT 7
#define FILE_BELONG 8
#define FILE_BEDATE 9
#define FILE_LESHORT 10
#define FILE_LELONG 11
#define FILE_LEDATE 12
#define FILE_PSTRING 13
#define FILE_LDATE 14
#define FILE_BELDATE 15
#define FILE_LELDATE 16
#define FILE_REGEX 17
#define FILE_BESTRING16 18
#define FILE_LESTRING16 19
#define FILE_SEARCH 20
#define FILE_MEDATE 21
#define FILE_MELDATE 22
#define FILE_MELONG 23
#define FILE_QUAD 24
#define FILE_LEQUAD 25
#define FILE_BEQUAD 26
#define FILE_QDATE 27
#define FILE_LEQDATE 28
#define FILE_BEQDATE 29
#define FILE_QLDATE 30
#define FILE_LEQLDATE 31
#define FILE_BEQLDATE 32
#define FILE_FLOAT 33
#define FILE_BEFLOAT 34
#define FILE_LEFLOAT 35
#define FILE_DOUBLE 36
#define FILE_BEDOUBLE 37
#define FILE_LEDOUBLE 38
#define FILE_BEID3 39
#define FILE_LEID3 40
#define FILE_INDIRECT 41
#define FILE_QWDATE 42
#define FILE_LEQWDATE 43
#define FILE_BEQWDATE 44
#define FILE_NAME 45
#define FILE_USE 46
#define FILE_CLEAR 47
#define FILE_DER 48
#define FILE_GUID 49
#define FILE_OFFSET 50
#define FILE_BEVARINT 51
#define FILE_LEVARINT 52
#define FILE_MSDOSDATE 53
#define FILE_LEMSDOSDATE 54
#define FILE_BEMSDOSDATE 55
#define FILE_MSDOSTIME 56
#define FILE_LEMSDOSTIME 57
#define FILE_BEMSDOSTIME 58
#define FILE_OCTAL 59
#define FILE_NAMES_SIZE 60 /* size of array to contain all names */
#define IS_LIBMAGIC_STRING(t) \
((t) == FILE_STRING || \
(t) == FILE_PSTRING || \
(t) == FILE_BESTRING16 || \
(t) == FILE_LESTRING16 || \
(t) == FILE_REGEX || \
(t) == FILE_SEARCH || \
(t) == FILE_INDIRECT || \
(t) == FILE_NAME || \
(t) == FILE_USE || \
(t) == FILE_OCTAL)
#define FILE_FMT_NONE 0
#define FILE_FMT_NUM 1 /* "cduxXi" */
#define FILE_FMT_STR 2 /* "s" */
#define FILE_FMT_QUAD 3 /* "ll" */
#define FILE_FMT_FLOAT 4 /* "eEfFgG" */
#define FILE_FMT_DOUBLE 5 /* "eEfFgG" */
/* Word 3 */
uint8_t in_op; /* operator for indirection */
uint8_t mask_op; /* operator for mask */
#ifdef ENABLE_CONDITIONALS
uint8_t cond; /* conditional type */
#else
uint8_t dummy;
#endif
uint8_t factor_op;
#define FILE_FACTOR_OP_PLUS '+'
#define FILE_FACTOR_OP_MINUS '-'
#define FILE_FACTOR_OP_TIMES '*'
#define FILE_FACTOR_OP_DIV '/'
#define FILE_FACTOR_OP_NONE '\0'
#define FILE_OPS "&|^+-*/%"
#define FILE_OPAND 0
#define FILE_OPOR 1
#define FILE_OPXOR 2
#define FILE_OPADD 3
#define FILE_OPMINUS 4
#define FILE_OPMULTIPLY 5
#define FILE_OPDIVIDE 6
#define FILE_OPMODULO 7
#define FILE_OPS_MASK 0x07 /* mask for above ops */
#define FILE_UNUSED_1 0x08
#define FILE_UNUSED_2 0x10
#define FILE_OPSIGNED 0x20
#define FILE_OPINVERSE 0x40
#define FILE_OPINDIRECT 0x80
#ifdef ENABLE_CONDITIONALS
#define COND_NONE 0
#define COND_IF 1
#define COND_ELIF 2
#define COND_ELSE 3
#endif /* ENABLE_CONDITIONALS */
/* Word 4 */
int32_t offset; /* offset to magic number */
/* Word 5 */
int32_t in_offset; /* offset from indirection */
/* Word 6 */
uint32_t lineno; /* line number in magic file */
/* Word 7,8 */
union {
uint64_t _mask; /* for use with numeric and date types */
struct {
uint32_t _count; /* repeat/line count */
uint32_t _flags; /* modifier flags */
} _s; /* for use with string types */
} _u;
#define num_mask _u._mask
#define str_range _u._s._count
#define str_flags _u._s._flags
/* Words 9-24 */
union VALUETYPE value; /* either number or string */
/* Words 25-40 */
char desc[MAXDESC]; /* description */
/* Words 41-60 */
char mimetype[MAXMIME]; /* MIME type */
/* Words 61-62 */
char apple[8]; /* APPLE CREATOR/TYPE */
/* Words 63-78 */
char ext[64]; /* Popular extensions */
};
#define BIT(A) (1 << (A))
#define STRING_COMPACT_WHITESPACE BIT(0)
#define STRING_COMPACT_OPTIONAL_WHITESPACE BIT(1)
#define STRING_IGNORE_LOWERCASE BIT(2)
#define STRING_IGNORE_UPPERCASE BIT(3)
#define REGEX_OFFSET_START BIT(4)
#define STRING_TEXTTEST BIT(5)
#define STRING_BINTEST BIT(6)
#define PSTRING_1_BE BIT(7)
#define PSTRING_1_LE BIT(7)
#define PSTRING_2_BE BIT(8)
#define PSTRING_2_LE BIT(9)
#define PSTRING_4_BE BIT(10)
#define PSTRING_4_LE BIT(11)
#define REGEX_LINE_COUNT BIT(11)
#define PSTRING_LEN \
(PSTRING_1_BE|PSTRING_2_LE|PSTRING_2_BE|PSTRING_4_LE|PSTRING_4_BE)
#define PSTRING_LENGTH_INCLUDES_ITSELF BIT(12)
#define STRING_TRIM BIT(13)
#define STRING_FULL_WORD BIT(14)
#define CHAR_COMPACT_WHITESPACE 'W'
#define CHAR_COMPACT_OPTIONAL_WHITESPACE 'w'
#define CHAR_IGNORE_LOWERCASE 'c'
#define CHAR_IGNORE_UPPERCASE 'C'
#define CHAR_REGEX_OFFSET_START 's'
#define CHAR_TEXTTEST 't'
#define CHAR_TRIM 'T'
#define CHAR_FULL_WORD 'f'
#define CHAR_BINTEST 'b'
#define CHAR_PSTRING_1_BE 'B'
#define CHAR_PSTRING_1_LE 'B'
#define CHAR_PSTRING_2_BE 'H'
#define CHAR_PSTRING_2_LE 'h'
#define CHAR_PSTRING_4_BE 'L'
#define CHAR_PSTRING_4_LE 'l'
#define CHAR_PSTRING_LENGTH_INCLUDES_ITSELF 'J'
#define STRING_IGNORE_CASE (STRING_IGNORE_LOWERCASE|STRING_IGNORE_UPPERCASE)
#define STRING_DEFAULT_RANGE 100
#define INDIRECT_RELATIVE BIT(0)
#define CHAR_INDIRECT_RELATIVE 'r'
/* list of magic entries */
struct mlist {
struct magic *magic; /* array of magic entries */
size_t nmagic; /* number of entries in array */
void *map; /* internal resources used by entry */
struct mlist *next, *prev;
};
#ifdef __cplusplus
#define CAST(T, b) static_cast<T>(b)
#define RCAST(T, b) reinterpret_cast<T>(b)
#define CCAST(T, b) const_cast<T>(b)
#else
#define CAST(T, b) ((T)(b))
#define RCAST(T, b) ((T)(uintptr_t)(b))
#define CCAST(T, b) ((T)(uintptr_t)(b))
#endif
struct level_info {
int32_t off;
int got_match;
#ifdef ENABLE_CONDITIONALS
int last_match;
int last_cond; /* used for error checking by parse() */
#endif
};
struct cont {
size_t len;
struct level_info *li;
};
#define MAGIC_SETS 2
struct magic_set {
struct mlist *mlist[MAGIC_SETS]; /* list of regular entries */
struct cont c;
struct out {
char *buf; /* Accumulation buffer */
size_t blen; /* Length of buffer */
char *pbuf; /* Printable buffer */
} o;
uint32_t offset; /* a copy of m->offset while we */
/* are working on the magic entry */
uint32_t eoffset; /* offset from end of file */
int error;
int flags; /* Control magic tests. */
int event_flags; /* Note things that happened. */
#define EVENT_HAD_ERR 0x01
const char *file;
size_t line; /* current magic line number */
mode_t mode; /* copy of current stat mode */
/* data for searches */
struct {
const char *s; /* start of search in original source */
size_t s_len; /* length of search region */
size_t offset; /* starting offset in source: XXX - should this be off_t? */
size_t rm_len; /* match length */
} search;
/* FIXME: Make the string dynamically allocated so that e.g.
strings matched in files can be longer than MAXstring */
union VALUETYPE ms_value; /* either number or string */
uint16_t indir_max;
uint16_t name_max;
uint16_t elf_shnum_max;
uint16_t elf_phnum_max;
uint16_t elf_notes_max;
uint16_t regex_max;
size_t bytes_max; /* number of bytes to read from file */
size_t encoding_max; /* bytes to look for encoding */
#ifndef FILE_BYTES_MAX
# define FILE_BYTES_MAX (1024 * 1024) /* how much of the file to look at */
#endif
#define FILE_ELF_NOTES_MAX 256
#define FILE_ELF_PHNUM_MAX 2048
#define FILE_ELF_SHNUM_MAX 32768
#define FILE_INDIR_MAX 50
#define FILE_NAME_MAX 50
#define FILE_REGEX_MAX 8192
#define FILE_ENCODING_MAX (64 * 1024)
#if defined(HAVE_NEWLOCALE) && defined(HAVE_USELOCALE) && defined(HAVE_FREELOCALE)
#define USE_C_LOCALE
locale_t c_lc_ctype;
#define file_locale_used
#else
#define file_locale_used __attribute__((__unused__))
#endif
};
/* Type for Unicode characters */
typedef unsigned long file_unichar_t;
struct stat;
#define FILE_T_LOCAL 1
#define FILE_T_WINDOWS 2
protected const char *file_fmtdatetime(char *, size_t, uint64_t, int);
protected const char *file_fmtdate(char *, size_t, uint16_t);
protected const char *file_fmttime(char *, size_t, uint16_t);
protected const char *file_fmtvarint(char *, size_t, const unsigned char *,
int);
protected const char *file_fmtnum(char *, size_t, const char *, int);
protected struct magic_set *file_ms_alloc(int);
protected void file_ms_free(struct magic_set *);
protected int file_buffer(struct magic_set *, php_stream *, zend_stat_t *, const char *, const void *,
size_t);
protected int file_fsmagic(struct magic_set *, const char *, zend_stat_t *);
protected int file_pipe2file(struct magic_set *, int, const void *, size_t);
protected int file_vprintf(struct magic_set *, const char *, va_list)
__attribute__((__format__(__printf__, 2, 0)));
protected int file_separator(struct magic_set *);
protected char *file_copystr(char *, size_t, size_t, const char *);
protected int file_checkfmt(char *, size_t, const char *);
protected size_t file_printedlen(const struct magic_set *);
protected int file_print_guid(char *, size_t, const uint64_t *);
protected int file_parse_guid(const char *, uint64_t *);
protected int file_replace(struct magic_set *, const char *, const char *);
protected int file_printf(struct magic_set *, const char *, ...)
__attribute__((__format__(__printf__, 2, 3)));
protected int file_reset(struct magic_set *, int);
protected int file_tryelf(struct magic_set *, const struct buffer *);
protected int file_trycdf(struct magic_set *, const struct buffer *);
#ifdef PHP_FILEINFO_UNCOMPRESS
protected int file_zmagic(struct magic_set *, const struct buffer *,
const char *);
#endif
protected int file_ascmagic(struct magic_set *, const struct buffer *,
int);
protected int file_ascmagic_with_encoding(struct magic_set *,
const struct buffer *, file_unichar_t *, size_t, const char *, const char *, int);
protected int file_encoding(struct magic_set *, const struct buffer *,
file_unichar_t **, size_t *, const char **, const char **, const char **);
protected int file_is_json(struct magic_set *, const struct buffer *);
protected int file_is_csv(struct magic_set *, const struct buffer *, int);
protected int file_is_tar(struct magic_set *, const struct buffer *);
protected int file_softmagic(struct magic_set *, const struct buffer *,
uint16_t *, uint16_t *, int, int);
protected int file_apprentice(struct magic_set *, const char *, int);
protected int buffer_apprentice(struct magic_set *, struct magic **,
size_t *, size_t);
protected int file_magicfind(struct magic_set *, const char *, struct mlist *);
protected uint64_t file_signextend(struct magic_set *, struct magic *,
uint64_t);
protected uintmax_t file_varint2uintmax_t(const unsigned char *, int, size_t *);
protected void file_badread(struct magic_set *);
protected void file_badseek(struct magic_set *);
protected void file_oomem(struct magic_set *, size_t);
protected void file_error(struct magic_set *, int, const char *, ...)
__attribute__((__format__(__printf__, 3, 4)));
protected void file_magerror(struct magic_set *, const char *, ...)
__attribute__((__format__(__printf__, 2, 3)));
protected void file_magwarn(struct magic_set *, const char *, ...)
__attribute__((__format__(__printf__, 2, 3)));
protected void file_mdump(struct magic *);
protected void file_showstr(FILE *, const char *, size_t);
protected size_t file_mbswidth(struct magic_set *, const char *);
protected const char *file_getbuffer(struct magic_set *);
protected ssize_t sread(int, void *, size_t, int);
protected int file_check_mem(struct magic_set *, unsigned int);
protected int file_looks_utf8(const unsigned char *, size_t, file_unichar_t *,
size_t *);
protected size_t file_pstring_length_size(struct magic_set *,
const struct magic *);
protected size_t file_pstring_get_length(struct magic_set *,
const struct magic *, const char *);
protected char * file_printable(struct magic_set *, char *, size_t,
const char *, size_t);
#ifdef __EMX__
protected int file_os2_apptype(struct magic_set *, const char *, const void *,
size_t);
#endif /* __EMX__ */
protected int file_pipe_closexec(int *);
protected int file_clear_closexec(int);
protected char *file_strtrim(char *);
protected void buffer_init(struct buffer *, int, const zend_stat_t *,
const void *, size_t);
protected void buffer_fini(struct buffer *);
protected int buffer_fill(const struct buffer *);
typedef struct {
char *buf;
size_t blen;
uint32_t offset;
} file_pushbuf_t;
protected file_pushbuf_t *file_push_buffer(struct magic_set *);
protected char *file_pop_buffer(struct magic_set *, file_pushbuf_t *);
#ifndef COMPILE_ONLY
extern const char *file_names[];
extern const size_t file_nnames;
#endif
#ifndef strlcpy
size_t strlcpy(char *, const char *, size_t);
#endif
#ifndef strlcat
size_t strlcat(char *, const char *, size_t);
#endif
#ifndef HAVE_STRCASESTR
char *strcasestr(const char *, const char *);
#endif
#ifndef HAVE_GETLINE
ssize_t getline(char **, size_t *, FILE *);
ssize_t getdelim(char **, size_t *, int, FILE *);
#endif
#ifndef HAVE_CTIME_R
char *ctime_r(const time_t *, char *);
#endif
#ifndef HAVE_ASCTIME_R
char *asctime_r(const struct tm *, char *);
#endif
#if defined(HAVE_MMAP) && defined(HAVE_SYS_MMAN_H) && !defined(QUICK)
#define QUICK
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_NONBLOCK
#define O_NONBLOCK 0
#endif
#ifndef __cplusplus
#if defined(__GNUC__) && (__GNUC__ >= 3)
#define FILE_RCSID(id) \
static const char rcsid[] __attribute__((__used__)) = id;
#else
#define FILE_RCSID(id) \
static const char *rcsid(const char *p) { \
return rcsid(p = id); \
}
#endif
#else
#define FILE_RCSID(id)
#endif
#ifndef __RCSID
#define __RCSID(a)
#endif
#endif /* __file_h__ */
| 19,544 | 29.162037 | 102 |
h
|
php-src
|
php-src-master/ext/fileinfo/libmagic/fsmagic.c
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* fsmagic - magic based on filesystem info - directory, special files, etc.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: fsmagic.c,v 1.82 2022/04/11 18:14:41 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
/* Since major is a function on SVR4, we cannot use `ifndef major'. */
#ifdef MAJOR_IN_MKDEV
# include <sys/mkdev.h>
# define HAVE_MAJOR
#endif
#ifdef HAVE_SYS_SYSMACROS_H
# include <sys/sysmacros.h>
#endif
#ifdef MAJOR_IN_SYSMACROS
# define HAVE_MAJOR
#endif
#if defined(major) && !defined(HAVE_MAJOR)
/* Might be defined in sys/types.h. */
# define HAVE_MAJOR
#endif
#ifdef WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
#ifndef HAVE_MAJOR
# define major(dev) (((dev) >> 8) & 0xff)
# define minor(dev) ((dev) & 0xff)
#endif
#undef HAVE_MAJOR
#ifdef PHP_WIN32
# undef S_IFIFO
#endif
private int
handle_mime(struct magic_set *ms, int mime, const char *str)
{
if ((mime & MAGIC_MIME_TYPE)) {
if (file_printf(ms, "inode/%s", str) == -1)
return -1;
if ((mime & MAGIC_MIME_ENCODING) && file_printf(ms,
"; charset=") == -1)
return -1;
}
if ((mime & MAGIC_MIME_ENCODING) && file_printf(ms, "binary") == -1)
return -1;
return 0;
}
protected int
file_fsmagic(struct magic_set *ms, const char *fn, zend_stat_t *sb)
{
int ret, did = 0;
int mime = ms->flags & MAGIC_MIME;
int silent = ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION);
if (fn == NULL)
return 0;
#define COMMA (did++ ? ", " : "")
ret = php_sys_stat(fn, sb);
if (ret) {
if (ms->flags & MAGIC_ERROR) {
file_error(ms, errno, "cannot stat `%s'", fn);
return -1;
}
if (file_printf(ms, "cannot open `%s' (%s)",
fn, strerror(errno)) == -1)
return -1;
return 0;
}
ret = 1;
if (!mime && !silent) {
#ifdef S_ISUID
if (sb->st_mode & S_ISUID)
if (file_printf(ms, "%ssetuid", COMMA) == -1)
return -1;
#endif
#ifdef S_ISGID
if (sb->st_mode & S_ISGID)
if (file_printf(ms, "%ssetgid", COMMA) == -1)
return -1;
#endif
#ifdef S_ISVTX
if (sb->st_mode & S_ISVTX)
if (file_printf(ms, "%ssticky", COMMA) == -1)
return -1;
#endif
}
switch (sb->st_mode & S_IFMT) {
#ifndef PHP_WIN32
# ifdef S_IFCHR
case S_IFCHR:
/*
* If -s has been specified, treat character special files
* like ordinary files. Otherwise, just report that they
* are block special files and go on to the next file.
*/
if ((ms->flags & MAGIC_DEVICES) != 0) {
ret = 0;
break;
}
if (mime) {
if (handle_mime(ms, mime, "chardevice") == -1)
return -1;
} else {
# ifdef HAVE_STAT_ST_RDEV
# ifdef dv_unit
if (file_printf(ms, "%scharacter special (%d/%d/%d)",
COMMA, major(sb->st_rdev), dv_unit(sb->st_rdev),
dv_subunit(sb->st_rdev)) == -1)
return -1;
# else
if (file_printf(ms, "%scharacter special (%ld/%ld)",
COMMA, (long)major(sb->st_rdev),
(long)minor(sb->st_rdev)) == -1)
return -1;
# endif
#else
if (file_printf(ms, "%scharacter special", COMMA) == -1)
return -1;
#endif
}
return 1;
# endif
#endif
#ifdef S_IFIFO
case S_IFIFO:
if((ms->flags & MAGIC_DEVICES) != 0)
break;
if (mime) {
if (handle_mime(ms, mime, "fifo") == -1)
return -1;
} else if (silent) {
} else if (file_printf(ms, "%sfifo (named pipe)", COMMA) == -1)
return -1;
break;
#endif
#ifdef S_IFDOOR
case S_IFDOOR:
if (mime) {
if (handle_mime(ms, mime, "door") == -1)
return -1;
} else if (silent) {
} else if (file_printf(ms, "%sdoor", COMMA) == -1)
return -1;
break;
#endif
#ifdef S_IFLNK
case S_IFLNK:
/* stat is used, if it made here then the link is broken */
if (ms->flags & MAGIC_ERROR) {
file_error(ms, errno, "unreadable symlink `%s'", fn);
return -1;
}
return 1;
#endif
#ifdef S_IFSOCK
#ifndef __COHERENT__
case S_IFSOCK:
if (mime) {
if (handle_mime(ms, mime, "socket") == -1)
return -1;
} else if (silent) {
} else if (file_printf(ms, "%ssocket", COMMA) == -1)
return -1;
break;
#endif
#endif
case S_IFREG:
/*
* regular file, check next possibility
*
* If stat() tells us the file has zero length, report here that
* the file is empty, so we can skip all the work of opening and
* reading the file.
* But if the -s option has been given, we skip this
* optimization, since on some systems, stat() reports zero
* size for raw disk partitions. (If the block special device
* really has zero length, the fact that it is empty will be
* detected and reported correctly when we read the file.)
*/
if ((ms->flags & MAGIC_DEVICES) == 0 && sb->st_size == 0) {
if (mime) {
if (handle_mime(ms, mime, "x-empty") == -1)
return -1;
} else if (silent) {
} else if (file_printf(ms, "%sempty", COMMA) == -1)
return -1;
break;
}
ret = 0;
break;
default:
file_error(ms, 0, "invalid mode 0%o", sb->st_mode);
return -1;
/*NOTREACHED*/
}
if (!silent && !mime && did && ret == 0) {
if (file_printf(ms, " ") == -1)
return -1;
}
/*
* If we were looking for extensions or apple (silent) it is not our
* job to print here, so don't count this as a match.
*/
if (ret == 1 && silent)
return 0;
return ret;
}
| 6,785 | 25.404669 | 77 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/funcs.c
|
/*
* Copyright (c) Christos Zoulas 2003.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: funcs.c,v 1.131 2022/09/13 18:46:07 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <assert.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> /* for pipe2() */
#endif
#if defined(HAVE_WCHAR_H)
#include <wchar.h>
#endif
#if defined(HAVE_WCTYPE_H)
#include <wctype.h>
#endif
#include <limits.h>
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)~0)
#endif
protected char *
file_copystr(char *buf, size_t blen, size_t width, const char *str)
{
if (blen == 0)
return buf;
if (width >= blen)
width = blen - 1;
memcpy(buf, str, width);
buf[width] = '\0';
return buf;
}
private void
file_clearbuf(struct magic_set *ms)
{
efree(ms->o.buf);
ms->o.buf = NULL;
ms->o.blen = 0;
}
private int
file_checkfield(char *msg, size_t mlen, const char *what, const char **pp)
{
const char *p = *pp;
int fw = 0;
while (*p && isdigit((unsigned char)*p))
fw = fw * 10 + (*p++ - '0');
*pp = p;
if (fw < 1024)
return 1;
if (msg)
snprintf(msg, mlen, "field %s too large: %d", what, fw);
return 0;
}
protected int
file_checkfmt(char *msg, size_t mlen, const char *fmt)
{
const char *p;
for (p = fmt; *p; p++) {
if (*p != '%')
continue;
if (*++p == '%')
continue;
// Skip uninteresting.
while (strchr("#0.'+- ", *p) != NULL)
p++;
if (*p == '*') {
if (msg)
snprintf(msg, mlen, "* not allowed in format");
return -1;
}
if (!file_checkfield(msg, mlen, "width", &p))
return -1;
if (*p == '.') {
p++;
if (!file_checkfield(msg, mlen, "precision", &p))
return -1;
}
if (!isalpha((unsigned char)*p)) {
if (msg)
snprintf(msg, mlen, "bad format char: %c", *p);
return -1;
}
}
return 0;
}
/*
* Like printf, only we append to a buffer.
*/
protected int
file_vprintf(struct magic_set *ms, const char *fmt, va_list ap)
{
size_t len;
char *buf, *newstr;
char tbuf[1024];
if (ms->event_flags & EVENT_HAD_ERR)
return 0;
if (file_checkfmt(tbuf, sizeof(tbuf), fmt)) {
file_clearbuf(ms);
file_error(ms, 0, "Bad magic format `%s' (%s)", fmt, tbuf);
return -1;
}
len = vspprintf(&buf, 0, fmt, ap);
if (len > 1024 || len + ms->o.blen > 1024 * 1024) {
size_t blen = ms->o.blen;
if (buf) efree(buf);
file_clearbuf(ms);
file_error(ms, 0, "Output buffer space exceeded %" SIZE_T_FORMAT "u+%"
SIZE_T_FORMAT "u", len, blen);
return -1;
}
if (ms->o.buf != NULL) {
len = spprintf(&newstr, 0, "%s%s", ms->o.buf, buf);
efree(buf);
efree(ms->o.buf);
buf = newstr;
}
ms->o.buf = buf;
ms->o.blen = len;
return 0;
}
protected int
file_printf(struct magic_set *ms, const char *fmt, ...)
{
int rv;
va_list ap;
va_start(ap, fmt);
rv = file_vprintf(ms, fmt, ap);
va_end(ap);
return rv;
}
/*
* error - print best error message possible
*/
/*VARARGS*/
__attribute__((__format__(__printf__, 3, 0)))
private void
file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
size_t lineno)
{
/* Only the first error is ok */
if (ms->event_flags & EVENT_HAD_ERR)
return;
if (lineno != 0) {
file_clearbuf(ms);
(void)file_printf(ms, "line %" SIZE_T_FORMAT "u:", lineno);
}
if (ms->o.buf && *ms->o.buf)
(void)file_printf(ms, " ");
(void)file_vprintf(ms, f, va);
if (error > 0)
(void)file_printf(ms, " (%s)", strerror(error));
ms->event_flags |= EVENT_HAD_ERR;
ms->error = error;
}
/*VARARGS*/
protected void
file_error(struct magic_set *ms, int error, const char *f, ...)
{
va_list va;
va_start(va, f);
file_error_core(ms, error, f, va, 0);
va_end(va);
}
/*
* Print an error with magic line number.
*/
/*VARARGS*/
protected void
file_magerror(struct magic_set *ms, const char *f, ...)
{
va_list va;
va_start(va, f);
file_error_core(ms, 0, f, va, ms->line);
va_end(va);
}
protected void
file_oomem(struct magic_set *ms, size_t len)
{
file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
len);
}
protected void
file_badseek(struct magic_set *ms)
{
file_error(ms, errno, "error seeking");
}
protected void
file_badread(struct magic_set *ms)
{
file_error(ms, errno, "error reading");
}
#ifndef COMPILE_ONLY
#define FILE_SEPARATOR "\n- "
protected int
file_separator(struct magic_set *ms)
{
return file_printf(ms, FILE_SEPARATOR);
}
static void
trim_separator(struct magic_set *ms)
{
size_t l;
if (ms->o.buf == NULL)
return;
l = strlen(ms->o.buf);
if (l < sizeof(FILE_SEPARATOR))
return;
l -= sizeof(FILE_SEPARATOR) - 1;
if (strcmp(ms->o.buf + l, FILE_SEPARATOR) != 0)
return;
ms->o.buf[l] = '\0';
}
static int
checkdone(struct magic_set *ms, int *rv)
{
if ((ms->flags & MAGIC_CONTINUE) == 0)
return 1;
if (file_separator(ms) == -1)
*rv = -1;
return 0;
}
protected int
file_default(struct magic_set *ms, size_t nb)
{
if (ms->flags & MAGIC_MIME) {
if ((ms->flags & MAGIC_MIME_TYPE) &&
file_printf(ms, "application/%s",
nb ? "octet-stream" : "x-empty") == -1)
return -1;
return 1;
}
if (ms->flags & MAGIC_APPLE) {
if (file_printf(ms, "UNKNUNKN") == -1)
return -1;
return 1;
}
if (ms->flags & MAGIC_EXTENSION) {
if (file_printf(ms, "???") == -1)
return -1;
return 1;
}
return 0;
}
/*
* The magic detection functions return:
* 1: found
* 0: not found
* -1: error
*/
/*ARGSUSED*/
protected int
file_buffer(struct magic_set *ms, php_stream *stream, zend_stat_t *st,
const char *inname,
const void *buf, size_t nb)
{
int m = 0, rv = 0, looks_text = 0;
const char *code = NULL;
const char *code_mime = "binary";
const char *def = "data";
const char *ftype = NULL;
char *rbuf = NULL;
struct buffer b;
int fd = -1;
if (stream) {
#ifdef _WIN64
php_socket_t _fd = fd;
#else
int _fd;
#endif
int _ret = php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&_fd, 0);
if (SUCCESS == _ret) {
fd = (int)_fd;
}
}
buffer_init(&b, fd, st, buf, nb);
ms->mode = b.st.st_mode;
if (nb == 0) {
def = "empty";
goto simple;
} else if (nb == 1) {
def = "very short file (no magic)";
goto simple;
}
if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
looks_text = file_encoding(ms, &b, NULL, 0,
&code, &code_mime, &ftype);
}
#ifdef __EMX__
if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
m = file_os2_apptype(ms, inname, &b);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try os2_apptype %d]\n", m);
switch (m) {
case -1:
return -1;
case 0:
break;
default:
return 1;
}
}
#endif
#if PHP_FILEINFO_UNCOMPRESS
/* try compression stuff */
if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0) {
m = file_zmagic(ms, &b, inname);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try zmagic %d]\n", m);
if (m) {
goto done_encoding;
}
}
#endif
/* Check if we have a tar file */
if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0) {
m = file_is_tar(ms, &b);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try tar %d]\n", m);
if (m) {
if (checkdone(ms, &rv))
goto done;
}
}
/* Check if we have a JSON file */
if ((ms->flags & MAGIC_NO_CHECK_JSON) == 0) {
m = file_is_json(ms, &b);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try json %d]\n", m);
if (m) {
if (checkdone(ms, &rv))
goto done;
}
}
/* Check if we have a CSV file */
if ((ms->flags & MAGIC_NO_CHECK_CSV) == 0) {
m = file_is_csv(ms, &b, looks_text);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try csv %d]\n", m);
if (m) {
if (checkdone(ms, &rv))
goto done;
}
}
/* Check if we have a CDF file */
if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
m = file_trycdf(ms, &b);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try cdf %d]\n", m);
if (m) {
if (checkdone(ms, &rv))
goto done;
}
}
#ifdef BUILTIN_ELF
if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && nb > 5 && fd != -1) {
file_pushbuf_t *pb;
/*
* We matched something in the file, so this
* *might* be an ELF file, and the file is at
* least 5 bytes long, so if it's an ELF file
* it has at least one byte past the ELF magic
* number - try extracting information from the
* ELF headers that cannot easily be extracted
* with rules in the magic file. We we don't
* print the information yet.
*/
if ((pb = file_push_buffer(ms)) == NULL)
return -1;
rv = file_tryelf(ms, &b);
rbuf = file_pop_buffer(ms, pb);
if (rv == -1) {
free(rbuf);
rbuf = NULL;
}
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try elf %d]\n", m);
}
#endif
/* try soft magic tests */
if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
m = file_softmagic(ms, &b, NULL, NULL, BINTEST, looks_text);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try softmagic %d]\n", m);
if (m == 1 && rbuf) {
if (file_printf(ms, "%s", rbuf) == -1)
goto done;
}
if (m) {
if (checkdone(ms, &rv))
goto done;
}
}
/* try text properties */
if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
m = file_ascmagic(ms, &b, looks_text);
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "[try ascmagic %d]\n", m);
if (m) {
goto done;
}
}
simple:
/* give up */
if (m == 0) {
m = 1;
rv = file_default(ms, nb);
if (rv == 0)
if (file_printf(ms, "%s", def) == -1)
rv = -1;
}
done:
trim_separator(ms);
if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
if (ms->flags & MAGIC_MIME_TYPE)
if (file_printf(ms, "; charset=") == -1)
rv = -1;
if (file_printf(ms, "%s", code_mime) == -1)
rv = -1;
}
#if PHP_FILEINFO_UNCOMPRESS
done_encoding:
#endif
efree(rbuf);
buffer_fini(&b);
if (rv)
return rv;
return m;
}
#endif
protected int
file_reset(struct magic_set *ms, int checkloaded)
{
if (checkloaded && ms->mlist[0] == NULL) {
file_error(ms, 0, "no magic files loaded");
return -1;
}
file_clearbuf(ms);
if (ms->o.pbuf) {
efree(ms->o.pbuf);
ms->o.pbuf = NULL;
}
ms->event_flags &= ~EVENT_HAD_ERR;
ms->error = -1;
return 0;
}
#define OCTALIFY(n, o) \
/*LINTED*/ \
(void)(*(n)++ = '\\', \
*(n)++ = ((CAST(uint32_t, *(o)) >> 6) & 3) + '0', \
*(n)++ = ((CAST(uint32_t, *(o)) >> 3) & 7) + '0', \
*(n)++ = ((CAST(uint32_t, *(o)) >> 0) & 7) + '0', \
(o)++)
protected const char *
file_getbuffer(struct magic_set *ms)
{
char *pbuf, *op, *np;
size_t psize, len;
if (ms->event_flags & EVENT_HAD_ERR)
return NULL;
if (ms->flags & MAGIC_RAW)
return ms->o.buf;
if (ms->o.buf == NULL)
return NULL;
/* * 4 is for octal representation, + 1 is for NUL */
len = strlen(ms->o.buf);
if (len > (SIZE_MAX - 1) / 4) {
file_oomem(ms, len);
return NULL;
}
psize = len * 4 + 1;
if ((pbuf = CAST(char *, erealloc(ms->o.pbuf, psize))) == NULL) {
file_oomem(ms, psize);
return NULL;
}
ms->o.pbuf = pbuf;
#if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
{
mbstate_t state;
wchar_t nextchar;
int mb_conv = 1;
size_t bytesconsumed;
char *eop;
(void)memset(&state, 0, sizeof(mbstate_t));
np = ms->o.pbuf;
op = ms->o.buf;
eop = op + len;
while (op < eop) {
bytesconsumed = mbrtowc(&nextchar, op,
CAST(size_t, eop - op), &state);
if (bytesconsumed == CAST(size_t, -1) ||
bytesconsumed == CAST(size_t, -2)) {
mb_conv = 0;
break;
}
if (iswprint(nextchar)) {
(void)memcpy(np, op, bytesconsumed);
op += bytesconsumed;
np += bytesconsumed;
} else {
while (bytesconsumed-- > 0)
OCTALIFY(np, op);
}
}
*np = '\0';
/* Parsing succeeded as a multi-byte sequence */
if (mb_conv != 0)
return ms->o.pbuf;
}
#endif
for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
if (isprint(CAST(unsigned char, *op))) {
*np++ = *op++;
} else {
OCTALIFY(np, op);
}
}
*np = '\0';
return ms->o.pbuf;
}
protected int
file_check_mem(struct magic_set *ms, unsigned int level)
{
size_t len;
if (level >= ms->c.len) {
len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
emalloc(len) :
erealloc(ms->c.li, len));
if (ms->c.li == NULL) {
file_oomem(ms, len);
return -1;
}
}
ms->c.li[level].got_match = 0;
#ifdef ENABLE_CONDITIONALS
ms->c.li[level].last_match = 0;
ms->c.li[level].last_cond = COND_NONE;
#endif /* ENABLE_CONDITIONALS */
return 0;
}
protected size_t
file_printedlen(const struct magic_set *ms)
{
return ms->o.blen;
}
protected int
file_replace(struct magic_set *ms, const char *pat, const char *rep)
{
zend_string *pattern;
uint32_t opts = 0;
pcre_cache_entry *pce;
zend_string *res;
zend_string *repl;
size_t rep_cnt = 0;
opts |= PCRE2_MULTILINE;
pattern = convert_libmagic_pattern((char*)pat, strlen(pat), opts);
if ((pce = pcre_get_compiled_regex_cache_ex(pattern, 0)) == NULL) {
zend_string_release(pattern);
rep_cnt = -1;
goto out;
}
zend_string_release(pattern);
repl = zend_string_init(rep, strlen(rep), 0);
res = php_pcre_replace_impl(pce, NULL, ms->o.buf, strlen(ms->o.buf), repl, -1, &rep_cnt);
zend_string_release_ex(repl, 0);
if (NULL == res) {
rep_cnt = -1;
goto out;
}
strncpy(ms->o.buf, ZSTR_VAL(res), ZSTR_LEN(res));
ms->o.buf[ZSTR_LEN(res)] = '\0';
zend_string_release_ex(res, 0);
out:
return rep_cnt;
}
protected file_pushbuf_t *
file_push_buffer(struct magic_set *ms)
{
file_pushbuf_t *pb;
if (ms->event_flags & EVENT_HAD_ERR)
return NULL;
if ((pb = (CAST(file_pushbuf_t *, emalloc(sizeof(*pb))))) == NULL)
return NULL;
pb->buf = ms->o.buf;
pb->blen = ms->o.blen;
pb->offset = ms->offset;
ms->o.buf = NULL;
ms->o.blen = 0;
ms->offset = 0;
return pb;
}
protected char *
file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
{
char *rbuf;
if (ms->event_flags & EVENT_HAD_ERR) {
efree(pb->buf);
efree(pb);
return NULL;
}
rbuf = ms->o.buf;
ms->o.buf = pb->buf;
ms->o.blen = pb->blen;
ms->offset = pb->offset;
efree(pb);
return rbuf;
}
/*
* convert string to ascii printable format.
*/
protected char *
file_printable(struct magic_set *ms, char *buf, size_t bufsiz,
const char *str, size_t slen)
{
char *ptr, *eptr = buf + bufsiz - 1;
const unsigned char *s = RCAST(const unsigned char *, str);
const unsigned char *es = s + slen;
for (ptr = buf; ptr < eptr && s < es && *s; s++) {
if ((ms->flags & MAGIC_RAW) != 0 || isprint(*s)) {
*ptr++ = *s;
continue;
}
if (ptr >= eptr - 3)
break;
*ptr++ = '\\';
*ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
*ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
*ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
}
*ptr = '\0';
return buf;
}
struct guid {
uint32_t data1;
uint16_t data2;
uint16_t data3;
uint8_t data4[8];
};
protected int
file_parse_guid(const char *s, uint64_t *guid)
{
struct guid *g = CAST(struct guid *, CAST(void *, guid));
#ifndef WIN32
return sscanf(s,
"%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
&g->data1, &g->data2, &g->data3, &g->data4[0], &g->data4[1],
&g->data4[2], &g->data4[3], &g->data4[4], &g->data4[5],
&g->data4[6], &g->data4[7]) == 11 ? 0 : -1;
#else
/* MS-Windows runtime doesn't support %hhx, except under
non-default __USE_MINGW_ANSI_STDIO. */
uint16_t data16[8];
int rv = sscanf(s, "%8x-%4hx-%4hx-%2hx%2hx-%2hx%2hx%2hx%2hx%2hx%2hx",
&g->data1, &g->data2, &g->data3, &data16[0], &data16[1],
&data16[2], &data16[3], &data16[4], &data16[5],
&data16[6], &data16[7]) == 11 ? 0 : -1;
int i;
for (i = 0; i < 8; i++)
g->data4[i] = data16[i];
return rv;
#endif
}
protected int
file_print_guid(char *str, size_t len, const uint64_t *guid)
{
const struct guid *g = CAST(const struct guid *,
CAST(const void *, guid));
#ifndef WIN32
return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hhX%.2hhX-"
"%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX",
g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
g->data4[2], g->data4[3], g->data4[4], g->data4[5],
g->data4[6], g->data4[7]);
#else
return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hX%.2hX-"
"%.2hX%.2hX%.2hX%.2hX%.2hX%.2hX",
g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
g->data4[2], g->data4[3], g->data4[4], g->data4[5],
g->data4[6], g->data4[7]);
#endif
}
#if 0
protected int
file_pipe_closexec(int *fds)
{
#ifdef HAVE_PIPE2
return pipe2(fds, O_CLOEXEC);
#else
if (pipe(fds) == -1)
return -1;
# ifdef F_SETFD
(void)fcntl(fds[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(fds[1], F_SETFD, FD_CLOEXEC);
# endif
return 0;
#endif
}
#endif
protected int
file_clear_closexec(int fd) {
#ifdef F_SETFD
return fcntl(fd, F_SETFD, 0);
#else
return 0;
#endif
}
protected char *
file_strtrim(char *str)
{
char *last;
while (isspace(CAST(unsigned char, *str)))
str++;
last = str;
while (*last)
last++;
--last;
while (isspace(CAST(unsigned char, *last)))
last--;
*++last = '\0';
return str;
}
| 18,333 | 20.671395 | 90 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/is_csv.c
|
/*-
* Copyright (c) 2019 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Parse CSV object serialization format (RFC-4180, RFC-7111)
*/
#ifndef TEST
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: is_csv.c,v 1.7 2022/05/28 00:44:22 christos Exp $")
#endif
#include <string.h>
#include "magic.h"
#else
#include <sys/types.h>
#endif
#ifdef DEBUG
#include <stdio.h>
#define DPRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
#else
#define DPRINTF(fmt, ...)
#endif
/*
* if CSV_LINES == 0:
* check all the lines in the buffer
* otherwise:
* check only up-to the number of lines specified
*
* the last line count is always ignored if it does not end in CRLF
*/
#ifndef CSV_LINES
#define CSV_LINES 10
#endif
static int csv_parse(const unsigned char *, const unsigned char *);
static const unsigned char *
eatquote(const unsigned char *uc, const unsigned char *ue)
{
int quote = 0;
while (uc < ue) {
unsigned char c = *uc++;
if (c != '"') {
// We already got one, done.
if (quote) {
return --uc;
}
continue;
}
if (quote) {
// quote-quote escapes
quote = 0;
continue;
}
// first quote
quote = 1;
}
return ue;
}
static int
csv_parse(const unsigned char *uc, const unsigned char *ue)
{
size_t nf = 0, tf = 0, nl = 0;
while (uc < ue) {
switch (*uc++) {
case '"':
// Eat until the matching quote
uc = eatquote(uc, ue);
break;
case ',':
nf++;
break;
case '\n':
DPRINTF("%zu %zu %zu\n", nl, nf, tf);
nl++;
#if CSV_LINES
if (nl == CSV_LINES)
return tf != 0 && tf == nf;
#endif
if (tf == 0) {
// First time and no fields, give up
if (nf == 0)
return 0;
// First time, set the number of fields
tf = nf;
} else if (tf != nf) {
// Field number mismatch, we are done.
return 0;
}
nf = 0;
break;
default:
break;
}
}
return tf && nl > 2;
}
#ifndef TEST
int
file_is_csv(struct magic_set *ms, const struct buffer *b, int looks_text)
{
const unsigned char *uc = CAST(const unsigned char *, b->fbuf);
const unsigned char *ue = uc + b->flen;
int mime = ms->flags & MAGIC_MIME;
if (!looks_text)
return 0;
if ((ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION)) != 0)
return 0;
if (!csv_parse(uc, ue))
return 0;
if (mime == MAGIC_MIME_ENCODING)
return 1;
if (mime) {
if (file_printf(ms, "text/csv") == -1)
return -1;
return 1;
}
if (file_printf(ms, "CSV text") == -1)
return -1;
return 1;
}
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <err.h>
int
main(int argc, char *argv[])
{
int fd, rv;
struct stat st;
unsigned char *p;
if ((fd = open(argv[1], O_RDONLY)) == -1)
err(EXIT_FAILURE, "Can't open `%s'", argv[1]);
if (fstat(fd, &st) == -1)
err(EXIT_FAILURE, "Can't stat `%s'", argv[1]);
if ((p = CAST(char *, malloc(st.st_size))) == NULL)
err(EXIT_FAILURE, "Can't allocate %jd bytes",
(intmax_t)st.st_size);
if (read(fd, p, st.st_size) != st.st_size)
err(EXIT_FAILURE, "Can't read %jd bytes",
(intmax_t)st.st_size);
printf("is csv %d\n", csv_parse(p, p + st.st_size));
return 0;
}
#endif
| 4,497 | 21.832487 | 78 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/is_tar.c
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* is_tar() -- figure out whether file is a tar archive.
*
* Stolen (by the author!) from the public domain tar program:
* Public Domain version written 26 Aug 1985 John Gilmore (ihnp4!hoptoad!gnu).
*
* @(#)list.c 1.18 9/23/86 Public Domain - gnu
*
* Comments changed and some code/comments reformatted
* for file command by Ian Darwin.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: is_tar.c,v 1.47 2022/09/13 18:46:07 christos Exp $")
#endif
#include "magic.h"
#include <string.h>
#include <ctype.h>
#include "tar.h"
#define isodigit(c) ( ((c) >= '0') && ((c) <= '7') )
private int is_tar(const unsigned char *, size_t);
private int from_oct(const char *, size_t); /* Decode octal number */
static const char tartype[][32] = { /* should be equal to messages */
"tar archive", /* found in ../magic/Magdir/archive */
"POSIX tar archive",
"POSIX tar archive (GNU)", /* */
};
protected int
file_is_tar(struct magic_set *ms, const struct buffer *b)
{
const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
size_t nbytes = b->flen;
/*
* Do the tar test first, because if the first file in the tar
* archive starts with a dot, we can confuse it with an nroff file.
*/
int tar;
int mime = ms->flags & MAGIC_MIME;
if ((ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION)) != 0)
return 0;
tar = is_tar(buf, nbytes);
if (tar < 1 || tar > 3)
return 0;
if (mime == MAGIC_MIME_ENCODING)
return 1;
if (file_printf(ms, "%s", mime ? "application/x-tar" :
tartype[tar - 1]) == -1)
return -1;
return 1;
}
/*
* Return
* 0 if the checksum is bad (i.e., probably not a tar archive),
* 1 for old UNIX tar file,
* 2 for Unix Std (POSIX) tar file,
* 3 for GNU tar file.
*/
private int
is_tar(const unsigned char *buf, size_t nbytes)
{
static const char gpkg_match[] = "/gpkg-1";
const union record *header = RCAST(const union record *,
RCAST(const void *, buf));
size_t i;
int sum, recsum;
const unsigned char *p, *ep;
const char *nulp;
if (nbytes < sizeof(*header))
return 0;
/* If the file looks like Gentoo GLEP 78 binary package (GPKG),
* don't waste time on further checks and fall back to magic rules.
*/
nulp = CAST(const char *,
memchr(header->header.name, 0, sizeof(header->header.name)));
if (nulp != NULL && nulp >= header->header.name + sizeof(gpkg_match) &&
memcmp(nulp - sizeof(gpkg_match) + 1, gpkg_match,
sizeof(gpkg_match)) == 0)
return 0;
recsum = from_oct(header->header.chksum, sizeof(header->header.chksum));
sum = 0;
p = header->charptr;
ep = header->charptr + sizeof(*header);
while (p < ep)
sum += *p++;
/* Adjust checksum to count the "chksum" field as blanks. */
for (i = 0; i < sizeof(header->header.chksum); i++)
sum -= header->header.chksum[i];
sum += ' ' * sizeof(header->header.chksum);
if (sum != recsum)
return 0; /* Not a tar archive */
if (strncmp(header->header.magic, GNUTMAGIC,
sizeof(header->header.magic)) == 0)
return 3; /* GNU Unix Standard tar archive */
if (strncmp(header->header.magic, TMAGIC,
sizeof(header->header.magic)) == 0)
return 2; /* Unix Standard tar archive */
return 1; /* Old fashioned tar archive */
}
/*
* Quick and dirty octal conversion.
*
* Result is -1 if the field is invalid (all blank, or non-octal).
*/
private int
from_oct(const char *where, size_t digs)
{
int value;
if (digs == 0)
return -1;
while (isspace(CAST(unsigned char, *where))) { /* Skip spaces */
where++;
if (digs-- == 0)
return -1; /* All blank field */
}
value = 0;
while (digs > 0 && isodigit(*where)) { /* Scan til non-octal */
value = (value << 3) | (*where++ - '0');
digs--;
}
if (digs > 0 && *where && !isspace(CAST(unsigned char, *where)))
return -1; /* Ended on non-(space/NUL) */
return value;
}
| 5,329 | 28.611111 | 78 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/magic.c
|
/*
* Copyright (c) Christos Zoulas 2003.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: magic.c,v 1.117 2021/12/06 15:33:00 christos Exp $")
#endif /* lint */
#include "magic.h"
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#ifdef QUICK
#include <sys/mman.h>
#endif
#include <limits.h> /* for PIPE_BUF */
#if defined(HAVE_UTIMES)
# include <sys/time.h>
#elif defined(HAVE_UTIME)
# if defined(HAVE_SYS_UTIME_H)
# include <sys/utime.h>
# elif defined(HAVE_UTIME_H)
# include <utime.h>
# endif
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h> /* for read() */
#endif
#ifndef PIPE_BUF
/* Get the PIPE_BUF from pathconf */
#ifdef _PC_PIPE_BUF
#define PIPE_BUF pathconf(".", _PC_PIPE_BUF)
#else
#define PIPE_BUF 512
#endif
#endif
#ifdef PHP_WIN32
# undef S_IFLNK
# undef S_IFIFO
#endif
private int unreadable_info(struct magic_set *, mode_t, const char *);
private const char *file_or_stream(struct magic_set *, const char *, php_stream *);
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
public struct magic_set *
magic_open(int flags)
{
return file_ms_alloc(flags);
}
private int
unreadable_info(struct magic_set *ms, mode_t md, const char *file)
{
if (file) {
/* We cannot open it, but we were able to stat it. */
if (access(file, W_OK) == 0)
if (file_printf(ms, "writable, ") == -1)
return -1;
#ifndef WIN32
if (access(file, X_OK) == 0)
if (file_printf(ms, "executable, ") == -1)
return -1;
#else
/* X_OK doesn't work well on MS-Windows */
{
const char *p = strrchr(file, '.');
if (p && (stricmp(p, ".exe")
|| stricmp(p, ".dll")
|| stricmp(p, ".bat")
|| stricmp(p, ".cmd")))
if (file_printf(ms, "writable, ") == -1)
return -1;
}
#endif
}
if (S_ISREG(md))
if (file_printf(ms, "regular file, ") == -1)
return -1;
if (file_printf(ms, "no read permission") == -1)
return -1;
return 0;
}
public void
magic_close(struct magic_set *ms)
{
if (ms == NULL)
return;
file_ms_free(ms);
}
/*
* load a magic file
*/
public int
magic_load(struct magic_set *ms, const char *magicfile)
{
if (ms == NULL)
return -1;
return file_apprentice(ms, magicfile, FILE_LOAD);
}
public int
magic_compile(struct magic_set *ms, const char *magicfile)
{
if (ms == NULL)
return -1;
return file_apprentice(ms, magicfile, FILE_COMPILE);
}
public int
magic_check(struct magic_set *ms, const char *magicfile)
{
if (ms == NULL)
return -1;
return file_apprentice(ms, magicfile, FILE_CHECK);
}
public int
magic_list(struct magic_set *ms, const char *magicfile)
{
if (ms == NULL)
return -1;
return file_apprentice(ms, magicfile, FILE_LIST);
}
#ifndef COMPILE_ONLY
/*
* find type of descriptor
*/
public const char *
magic_descriptor(struct magic_set *ms, int fd)
{
if (ms == NULL)
return NULL;
return file_or_stream(ms, NULL, NULL);
}
/*
* find type of named file
*/
public const char *
magic_file(struct magic_set *ms, const char *inname)
{
if (ms == NULL)
return NULL;
return file_or_stream(ms, inname, NULL);
}
public const char *
magic_stream(struct magic_set *ms, php_stream *stream)
{
if (ms == NULL)
return NULL;
return file_or_stream(ms, NULL, stream);
}
private const char *
file_or_stream(struct magic_set *ms, const char *inname, php_stream *stream)
{
int rv = -1;
unsigned char *buf;
zend_stat_t sb = {0};
ssize_t nbytes = 0; /* number of bytes read from a datafile */
int no_in_stream = 0;
if (file_reset(ms, 1) == -1)
goto out;
/*
* one extra for terminating '\0', and
* some overlapping space for matches near EOF
*/
#define SLOP (1 + sizeof(union VALUETYPE))
if ((buf = CAST(unsigned char *, emalloc(ms->bytes_max + SLOP))) == NULL)
return NULL;
switch (file_fsmagic(ms, inname, &sb)) {
case -1: /* error */
goto done;
case 0: /* nothing found */
break;
default: /* matched it and printed type */
rv = 0;
goto done;
}
errno = 0;
if (inname && !stream) {
no_in_stream = 1;
stream = php_stream_open_wrapper((char *)inname, "rb", REPORT_ERRORS, NULL);
if (!stream) {
if (unreadable_info(ms, sb.st_mode, inname) == -1)
goto done;
rv = -1;
goto done;
}
}
php_stream_statbuf ssb;
if (php_stream_stat(stream, &ssb) < 0) {
if (ms->flags & MAGIC_ERROR) {
file_error(ms, errno, "cannot stat `%s'", inname);
rv = -1;
goto done;
}
}
memcpy(&sb, &ssb.sb, sizeof(zend_stat_t));
/*
* try looking at the first ms->bytes_max bytes
*/
if ((nbytes = php_stream_read(stream, (char *)buf, ms->bytes_max - nbytes)) < 0) {
file_error(ms, errno, "cannot read `%s'", inname);
goto done;
}
(void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
if (file_buffer(ms, stream, &sb, inname, buf, CAST(size_t, nbytes)) == -1)
goto done;
rv = 0;
done:
efree(buf);
if (no_in_stream && stream) {
php_stream_close(stream);
}
out:
return rv == 0 ? file_getbuffer(ms) : NULL;
}
public const char *
magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
{
if (ms == NULL)
return NULL;
if (file_reset(ms, 1) == -1)
return NULL;
/*
* The main work is done here!
* We have the file name and/or the data buffer to be identified.
*/
if (file_buffer(ms, NULL, NULL, NULL, buf, nb) == -1) {
return NULL;
}
return file_getbuffer(ms);
}
#endif
public const char *
magic_error(struct magic_set *ms)
{
if (ms == NULL)
return "Magic database is not open";
return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
}
public int
magic_errno(struct magic_set *ms)
{
if (ms == NULL)
return EINVAL;
return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
}
public int
magic_getflags(struct magic_set *ms)
{
if (ms == NULL)
return -1;
return ms->flags;
}
public int
magic_setflags(struct magic_set *ms, int flags)
{
if (ms == NULL)
return -1;
#if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
if (flags & MAGIC_PRESERVE_ATIME)
return -1;
#endif
ms->flags = flags;
return 0;
}
public int
magic_version(void)
{
return MAGIC_VERSION;
}
public int
magic_setparam(struct magic_set *ms, int param, const void *val)
{
if (ms == NULL)
return -1;
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = CAST(uint16_t, *CAST(const size_t *, val));
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = CAST(uint16_t, *CAST(const size_t *, val));
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = CAST(uint16_t, *CAST(const size_t *, val));
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = CAST(uint16_t, *CAST(const size_t *, val));
return 0;
case MAGIC_PARAM_ELF_NOTES_MAX:
ms->elf_notes_max = CAST(uint16_t, *CAST(const size_t *, val));
return 0;
case MAGIC_PARAM_REGEX_MAX:
ms->regex_max = CAST(uint16_t, *CAST(const size_t *, val));
return 0;
case MAGIC_PARAM_BYTES_MAX:
ms->bytes_max = *CAST(const size_t *, val);
return 0;
case MAGIC_PARAM_ENCODING_MAX:
ms->encoding_max = *CAST(const size_t *, val);
return 0;
default:
errno = EINVAL;
return -1;
}
}
public int
magic_getparam(struct magic_set *ms, int param, void *val)
{
if (ms == NULL)
return -1;
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
*CAST(size_t *, val) = ms->indir_max;
return 0;
case MAGIC_PARAM_NAME_MAX:
*CAST(size_t *, val) = ms->name_max;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
*CAST(size_t *, val) = ms->elf_phnum_max;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
*CAST(size_t *, val) = ms->elf_shnum_max;
return 0;
case MAGIC_PARAM_ELF_NOTES_MAX:
*CAST(size_t *, val) = ms->elf_notes_max;
return 0;
case MAGIC_PARAM_REGEX_MAX:
*CAST(size_t *, val) = ms->regex_max;
return 0;
case MAGIC_PARAM_BYTES_MAX:
*CAST(size_t *, val) = ms->bytes_max;
return 0;
case MAGIC_PARAM_ENCODING_MAX:
*CAST(size_t *, val) = ms->encoding_max;
return 0;
default:
errno = EINVAL;
return -1;
}
}
| 9,225 | 21.836634 | 83 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/magic.h
|
/*
* Copyright (c) Christos Zoulas 2003.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _MAGIC_H
#define _MAGIC_H
#include <sys/types.h>
#define MAGIC_NONE 0x0000000 /* No flags */
#define MAGIC_DEBUG 0x0000001 /* Turn on debugging */
#define MAGIC_SYMLINK 0x0000002 /* Follow symlinks */
#define MAGIC_COMPRESS 0x0000004 /* Check inside compressed files */
#define MAGIC_DEVICES 0x0000008 /* Look at the contents of devices */
#define MAGIC_MIME_TYPE 0x0000010 /* Return the MIME type */
#define MAGIC_CONTINUE 0x0000020 /* Return all matches */
#define MAGIC_CHECK 0x0000040 /* Print warnings to stderr */
#define MAGIC_PRESERVE_ATIME 0x0000080 /* Restore access time on exit */
#define MAGIC_RAW 0x0000100 /* Don't convert unprintable chars */
#define MAGIC_ERROR 0x0000200 /* Handle ENOENT etc as real errors */
#define MAGIC_MIME_ENCODING 0x0000400 /* Return the MIME encoding */
#define MAGIC_MIME (MAGIC_MIME_TYPE|MAGIC_MIME_ENCODING)
#define MAGIC_APPLE 0x0000800 /* Return the Apple creator/type */
#define MAGIC_EXTENSION 0x1000000 /* Return a /-separated list of
* extensions */
#define MAGIC_COMPRESS_TRANSP 0x2000000 /* Check inside compressed files
* but not report compression */
#define MAGIC_NODESC (MAGIC_EXTENSION|MAGIC_MIME|MAGIC_APPLE)
#define MAGIC_NO_CHECK_COMPRESS 0x0001000 /* Don't check for compressed files */
#define MAGIC_NO_CHECK_TAR 0x0002000 /* Don't check for tar files */
#define MAGIC_NO_CHECK_SOFT 0x0004000 /* Don't check magic entries */
#define MAGIC_NO_CHECK_APPTYPE 0x0008000 /* Don't check application type */
#define MAGIC_NO_CHECK_ELF 0x0010000 /* Don't check for elf details */
#define MAGIC_NO_CHECK_TEXT 0x0020000 /* Don't check for text files */
#define MAGIC_NO_CHECK_CDF 0x0040000 /* Don't check for cdf files */
#define MAGIC_NO_CHECK_CSV 0x0080000 /* Don't check for CSV files */
#define MAGIC_NO_CHECK_TOKENS 0x0100000 /* Don't check tokens */
#define MAGIC_NO_CHECK_ENCODING 0x0200000 /* Don't check text encodings */
#define MAGIC_NO_CHECK_JSON 0x0400000 /* Don't check for JSON files */
/* No built-in tests; only consult the magic file */
#define MAGIC_NO_CHECK_BUILTIN ( \
MAGIC_NO_CHECK_COMPRESS | \
MAGIC_NO_CHECK_TAR | \
/* MAGIC_NO_CHECK_SOFT | */ \
MAGIC_NO_CHECK_APPTYPE | \
MAGIC_NO_CHECK_ELF | \
MAGIC_NO_CHECK_TEXT | \
MAGIC_NO_CHECK_CSV | \
MAGIC_NO_CHECK_CDF | \
MAGIC_NO_CHECK_TOKENS | \
MAGIC_NO_CHECK_ENCODING | \
MAGIC_NO_CHECK_JSON | \
0 \
)
#define MAGIC_SNPRINTB "\177\020\
b\0debug\0\
b\1symlink\0\
b\2compress\0\
b\3devices\0\
b\4mime_type\0\
b\5continue\0\
b\6check\0\
b\7preserve_atime\0\
b\10raw\0\
b\11error\0\
b\12mime_encoding\0\
b\13apple\0\
b\14no_check_compress\0\
b\15no_check_tar\0\
b\16no_check_soft\0\
b\17no_check_sapptype\0\
b\20no_check_elf\0\
b\21no_check_text\0\
b\22no_check_cdf\0\
b\23no_check_reserved0\0\
b\24no_check_tokens\0\
b\25no_check_encoding\0\
b\26no_check_json\0\
b\27no_check_reserved2\0\
b\30extension\0\
b\31transp_compression\0\
"
/* Defined for backwards compatibility (renamed) */
#define MAGIC_NO_CHECK_ASCII MAGIC_NO_CHECK_TEXT
/* Defined for backwards compatibility; do nothing */
#define MAGIC_NO_CHECK_FORTRAN 0x000000 /* Don't check ascii/fortran */
#define MAGIC_NO_CHECK_TROFF 0x000000 /* Don't check ascii/troff */
#define MAGIC_VERSION 543 /* This implementation */
#ifdef __cplusplus
extern "C" {
#endif
typedef struct magic_set *magic_t;
magic_t magic_open(int);
void magic_close(magic_t);
const char *magic_getpath(const char *, int);
const char *magic_file(magic_t, const char *);
const char *magic_stream(magic_t, php_stream *);
const char *magic_descriptor(magic_t, int);
const char *magic_buffer(magic_t, const void *, size_t);
const char *magic_error(magic_t);
int magic_getflags(magic_t);
int magic_setflags(magic_t, int);
int magic_version(void);
int magic_load(magic_t, const char *);
int magic_load_buffers(magic_t, void **, size_t *, size_t);
int magic_compile(magic_t, const char *);
int magic_check(magic_t, const char *);
int magic_list(magic_t, const char *);
int magic_errno(magic_t);
#define MAGIC_PARAM_INDIR_MAX 0
#define MAGIC_PARAM_NAME_MAX 1
#define MAGIC_PARAM_ELF_PHNUM_MAX 2
#define MAGIC_PARAM_ELF_SHNUM_MAX 3
#define MAGIC_PARAM_ELF_NOTES_MAX 4
#define MAGIC_PARAM_REGEX_MAX 5
#define MAGIC_PARAM_BYTES_MAX 6
#define MAGIC_PARAM_ENCODING_MAX 7
int magic_setparam(magic_t, int, const void *);
int magic_getparam(magic_t, int, void *);
#ifdef __cplusplus
};
#endif
#endif /* _MAGIC_H */
| 5,856 | 34.932515 | 80 |
h
|
php-src
|
php-src-master/ext/fileinfo/libmagic/print.c
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* print.c - debugging printout routines
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: print.c,v 1.92 2022/09/10 13:21:42 christos Exp $")
#endif /* lint */
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <time.h>
#include "cdf.h"
#ifndef COMPILE_ONLY
protected void
file_mdump(struct magic *m)
{
static const char optyp[] = { FILE_OPS };
char tbuf[256];
(void) fprintf(stderr, "%u: %.*s %u", m->lineno,
(m->cont_level & 7) + 1, ">>>>>>>>", m->offset);
if (m->flag & INDIR) {
(void) fprintf(stderr, "(%s,",
/* Note: type is unsigned */
(m->in_type < file_nnames) ? file_names[m->in_type] :
"*bad in_type*");
if (m->in_op & FILE_OPINVERSE)
(void) fputc('~', stderr);
(void) fprintf(stderr, "%c%u),",
(CAST(size_t, m->in_op & FILE_OPS_MASK) <
__arraycount(optyp)) ?
optyp[m->in_op & FILE_OPS_MASK] : '?', m->in_offset);
}
(void) fprintf(stderr, " %s%s", (m->flag & UNSIGNED) ? "u" : "",
/* Note: type is unsigned */
(m->type < file_nnames) ? file_names[m->type] : "*bad type");
if (m->mask_op & FILE_OPINVERSE)
(void) fputc('~', stderr);
if (IS_LIBMAGIC_STRING(m->type)) {
if (m->str_flags) {
(void) fputc('/', stderr);
if (m->str_flags & STRING_COMPACT_WHITESPACE)
(void) fputc(CHAR_COMPACT_WHITESPACE, stderr);
if (m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE)
(void) fputc(CHAR_COMPACT_OPTIONAL_WHITESPACE,
stderr);
if (m->str_flags & STRING_IGNORE_LOWERCASE)
(void) fputc(CHAR_IGNORE_LOWERCASE, stderr);
if (m->str_flags & STRING_IGNORE_UPPERCASE)
(void) fputc(CHAR_IGNORE_UPPERCASE, stderr);
if (m->str_flags & REGEX_OFFSET_START)
(void) fputc(CHAR_REGEX_OFFSET_START, stderr);
if (m->str_flags & STRING_TEXTTEST)
(void) fputc(CHAR_TEXTTEST, stderr);
if (m->str_flags & STRING_BINTEST)
(void) fputc(CHAR_BINTEST, stderr);
if (m->str_flags & PSTRING_1_BE)
(void) fputc(CHAR_PSTRING_1_BE, stderr);
if (m->str_flags & PSTRING_2_BE)
(void) fputc(CHAR_PSTRING_2_BE, stderr);
if (m->str_flags & PSTRING_2_LE)
(void) fputc(CHAR_PSTRING_2_LE, stderr);
if (m->str_flags & PSTRING_4_BE)
(void) fputc(CHAR_PSTRING_4_BE, stderr);
if (m->str_flags & PSTRING_4_LE)
(void) fputc(CHAR_PSTRING_4_LE, stderr);
if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
(void) fputc(
CHAR_PSTRING_LENGTH_INCLUDES_ITSELF,
stderr);
}
if (m->str_range)
(void) fprintf(stderr, "/%u", m->str_range);
}
else {
if (CAST(size_t, m->mask_op & FILE_OPS_MASK) <
__arraycount(optyp))
(void) fputc(optyp[m->mask_op & FILE_OPS_MASK], stderr);
else
(void) fputc('?', stderr);
if (m->num_mask) {
(void) fprintf(stderr, "%.8llx",
CAST(unsigned long long, m->num_mask));
}
}
(void) fprintf(stderr, ",%c", m->reln);
if (m->reln != 'x') {
switch (m->type) {
case FILE_BYTE:
case FILE_SHORT:
case FILE_LONG:
case FILE_LESHORT:
case FILE_LELONG:
case FILE_MELONG:
case FILE_BESHORT:
case FILE_BELONG:
case FILE_INDIRECT:
(void) fprintf(stderr, "%d", m->value.l);
break;
case FILE_BEQUAD:
case FILE_LEQUAD:
case FILE_QUAD:
case FILE_OFFSET:
(void) fprintf(stderr, "%" INT64_T_FORMAT "d",
CAST(long long, m->value.q));
break;
case FILE_PSTRING:
case FILE_STRING:
case FILE_REGEX:
case FILE_BESTRING16:
case FILE_LESTRING16:
case FILE_SEARCH:
file_showstr(stderr, m->value.s,
CAST(size_t, m->vallen));
break;
case FILE_DATE:
case FILE_LEDATE:
case FILE_BEDATE:
case FILE_MEDATE:
(void)fprintf(stderr, "%s,",
file_fmtdatetime(tbuf, sizeof(tbuf), m->value.l, 0));
break;
case FILE_LDATE:
case FILE_LELDATE:
case FILE_BELDATE:
case FILE_MELDATE:
(void)fprintf(stderr, "%s,",
file_fmtdatetime(tbuf, sizeof(tbuf), m->value.l,
FILE_T_LOCAL));
break;
case FILE_QDATE:
case FILE_LEQDATE:
case FILE_BEQDATE:
(void)fprintf(stderr, "%s,",
file_fmtdatetime(tbuf, sizeof(tbuf), m->value.q, 0));
break;
case FILE_QLDATE:
case FILE_LEQLDATE:
case FILE_BEQLDATE:
(void)fprintf(stderr, "%s,",
file_fmtdatetime(tbuf, sizeof(tbuf), m->value.q,
FILE_T_LOCAL));
break;
case FILE_QWDATE:
case FILE_LEQWDATE:
case FILE_BEQWDATE:
(void)fprintf(stderr, "%s,",
file_fmtdatetime(tbuf, sizeof(tbuf), m->value.q,
FILE_T_WINDOWS));
break;
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
(void) fprintf(stderr, "%G", m->value.f);
break;
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
(void) fprintf(stderr, "%G", m->value.d);
break;
case FILE_LEVARINT:
case FILE_BEVARINT:
(void)fprintf(stderr, "%s", file_fmtvarint(
tbuf, sizeof(tbuf), m->value.us, m->type));
break;
case FILE_MSDOSDATE:
case FILE_BEMSDOSDATE:
case FILE_LEMSDOSDATE:
(void)fprintf(stderr, "%s,",
file_fmtdate(tbuf, sizeof(tbuf), m->value.h));
break;
case FILE_MSDOSTIME:
case FILE_BEMSDOSTIME:
case FILE_LEMSDOSTIME:
(void)fprintf(stderr, "%s,",
file_fmttime(tbuf, sizeof(tbuf), m->value.h));
break;
case FILE_OCTAL:
(void)fprintf(stderr, "%s",
file_fmtnum(tbuf, sizeof(tbuf), m->value.s, 8));
break;
case FILE_DEFAULT:
/* XXX - do anything here? */
break;
case FILE_USE:
case FILE_NAME:
case FILE_DER:
(void) fprintf(stderr, "'%s'", m->value.s);
break;
case FILE_GUID:
(void) file_print_guid(tbuf, sizeof(tbuf),
m->value.guid);
(void) fprintf(stderr, "%s", tbuf);
break;
default:
(void) fprintf(stderr, "*bad type %d*", m->type);
break;
}
}
(void) fprintf(stderr, ",\"%s\"]\n", m->desc);
}
#endif
/*VARARGS*/
protected void
file_magwarn(struct magic_set *ms, const char *f, ...)
{
va_list va;
char *expanded_format = NULL;
int expanded_len;
va_start(va, f);
expanded_len = vasprintf(&expanded_format, f, va);
va_end(va);
if (expanded_len >= 0 && expanded_format) {
php_error_docref(NULL, E_WARNING, "%s", expanded_format);
free(expanded_format);
}
}
protected const char *
file_fmtvarint(char *buf, size_t blen, const unsigned char *us, int t)
{
snprintf(buf, blen, "%jd", file_varint2uintmax_t(us, t, NULL));
return buf;
}
protected const char *
file_fmtdatetime(char *buf, size_t bsize, uint64_t v, int flags)
{
char *pp;
time_t t;
struct tm *tm, tmz;
if (flags & FILE_T_WINDOWS) {
struct timespec ts;
cdf_timestamp_to_timespec(&ts, CAST(cdf_timestamp_t, v));
t = ts.tv_sec;
} else {
// XXX: perhaps detect and print something if overflow
// on 32 bit time_t?
t = CAST(time_t, v);
}
if (flags & FILE_T_LOCAL) {
tm = php_localtime_r(&t, &tmz);
} else {
tm = php_gmtime_r(&t, &tmz);
}
if (tm == NULL)
goto out;
pp = php_asctime_r(tm, buf);
if (pp == NULL)
goto out;
pp[strcspn(pp, "\n")] = '\0';
return pp;
out:
strlcpy(buf, "*Invalid datetime*", bsize);
return buf;
}
/*
* https://docs.microsoft.com/en-us/windows/win32/api/winbase/\
* nf-winbase-dosdatetimetofiletime?redirectedfrom=MSDN
*/
protected const char *
file_fmtdate(char *buf, size_t bsize, uint16_t v)
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_mday = v & 0x1f;
tm.tm_mon = ((v >> 5) & 0xf) - 1;
tm.tm_year = (v >> 9) + 80;
if (strftime(buf, bsize, "%a, %b %d %Y", &tm) == 0)
goto out;
return buf;
out:
strlcpy(buf, "*Invalid date*", bsize);
return buf;
}
protected const char *
file_fmttime(char *buf, size_t bsize, uint16_t v)
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_sec = (v & 0x1f) * 2;
tm.tm_min = ((v >> 5) & 0x3f);
tm.tm_hour = (v >> 11);
if (strftime(buf, bsize, "%T", &tm) == 0)
goto out;
return buf;
out:
strlcpy(buf, "*Invalid time*", bsize);
return buf;
}
protected const char *
file_fmtnum(char *buf, size_t blen, const char *us, int base)
{
char *endptr;
unsigned long long val;
errno = 0;
val = strtoull(us, &endptr, base);
if (*endptr || errno) {
bad: strlcpy(buf, "*Invalid number*", blen);
return buf;
}
if (snprintf(buf, blen, "%llu", val) < 0)
goto bad;
return buf;
}
| 9,667 | 25.487671 | 77 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/readcdf.c
|
/*-
* Copyright (c) 2008, 2016 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: readcdf.c,v 1.76 2022/01/17 16:59:01 christos Exp $")
#endif
#include <assert.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <time.h>
#include <ctype.h>
#include "cdf.h"
#include "magic.h"
#define NOTMIME(ms) (((ms)->flags & MAGIC_MIME) == 0)
static const struct nv {
const char *pattern;
const char *mime;
} app2mime[] = {
{ "Word", "msword", },
{ "Excel", "vnd.ms-excel", },
{ "Powerpoint", "vnd.ms-powerpoint", },
{ "Crystal Reports", "x-rpt", },
{ "Advanced Installer", "vnd.ms-msi", },
{ "InstallShield", "vnd.ms-msi", },
{ "Microsoft Patch Compiler", "vnd.ms-msi", },
{ "NAnt", "vnd.ms-msi", },
{ "Windows Installer", "vnd.ms-msi", },
{ NULL, NULL, },
}, name2mime[] = {
{ "Book", "vnd.ms-excel", },
{ "Workbook", "vnd.ms-excel", },
{ "WordDocument", "msword", },
{ "PowerPoint", "vnd.ms-powerpoint", },
{ "DigitalSignature", "vnd.ms-msi", },
{ NULL, NULL, },
}, name2desc[] = {
{ "Book", "Microsoft Excel", },
{ "Workbook", "Microsoft Excel", },
{ "WordDocument", "Microsoft Word", },
{ "PowerPoint", "Microsoft PowerPoint", },
{ "DigitalSignature", "Microsoft Installer", },
{ NULL, NULL, },
};
static const struct cv {
uint64_t clsid[2];
const char *mime;
} clsid2mime[] = {
{
{ 0x00000000000c1084ULL, 0x46000000000000c0ULL },
"x-msi",
},
{ { 0, 0 },
NULL,
},
}, clsid2desc[] = {
{
{ 0x00000000000c1084ULL, 0x46000000000000c0ULL },
"MSI Installer",
},
{ { 0, 0 },
NULL,
},
};
private const char *
cdf_clsid_to_mime(const uint64_t clsid[2], const struct cv *cv)
{
size_t i;
for (i = 0; cv[i].mime != NULL; i++) {
if (clsid[0] == cv[i].clsid[0] && clsid[1] == cv[i].clsid[1])
return cv[i].mime;
}
return NULL;
}
private const char *
cdf_app_to_mime(const char *vbuf, const struct nv *nv)
{
size_t i;
const char *rv = NULL;
char *vbuf_lower;
vbuf_lower = zend_str_tolower_dup(vbuf, strlen(vbuf));
for (i = 0; nv[i].pattern != NULL; i++) {
char *pattern_lower;
int found;
pattern_lower = zend_str_tolower_dup(nv[i].pattern, strlen(nv[i].pattern));
found = (strstr(vbuf_lower, pattern_lower) != NULL);
efree(pattern_lower);
if (found) {
rv = nv[i].mime;
break;
}
}
efree(vbuf_lower);
return rv;
}
private int
cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info,
size_t count, const cdf_directory_t *root_storage)
{
size_t i;
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
const char *str = NULL;
const char *s, *e;
int len;
memset(&ts, 0, sizeof(ts));
if (!NOTMIME(ms) && root_storage)
str = cdf_clsid_to_mime(root_storage->d_storage_uuid,
clsid2mime);
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf,
info[i].pi_s16) == -1)
return -1;
break;
case CDF_SIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf,
info[i].pi_s32) == -1)
return -1;
break;
case CDF_UNSIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf,
info[i].pi_u32) == -1)
return -1;
break;
case CDF_FLOAT:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_f) == -1)
return -1;
break;
case CDF_DOUBLE:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_d) == -1)
return -1;
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
len = info[i].pi_str.s_len;
if (len > 1) {
char vbuf[1024];
size_t j, k = 1;
if (info[i].pi_type == CDF_LENGTH32_WSTRING)
k++;
s = info[i].pi_str.s_buf;
e = info[i].pi_str.s_buf + len;
for (j = 0; s < e && j < sizeof(vbuf)
&& len--; s += k) {
if (*s == '\0')
break;
if (isprint(CAST(unsigned char, *s)))
vbuf[j++] = *s;
}
if (j == sizeof(vbuf))
--j;
vbuf[j] = '\0';
if (NOTMIME(ms)) {
if (vbuf[0]) {
if (file_printf(ms, ", %s: %s",
buf, vbuf) == -1)
return -1;
}
} else if (str == NULL && info[i].pi_id ==
CDF_PROPERTY_NAME_OF_APPLICATION) {
str = cdf_app_to_mime(vbuf, app2mime);
}
}
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp != 0) {
char tbuf[64];
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(tbuf,
sizeof(tbuf), tp);
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, tbuf) == -1)
return -1;
} else {
char *c, *ec;
cdf_timestamp_to_timespec(&ts, tp);
c = cdf_ctime(&ts.tv_sec, tbuf);
if (c != NULL &&
(ec = strchr(c, '\n')) != NULL)
*ec = '\0';
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, c) == -1)
return -1;
}
}
break;
case CDF_CLIPBOARD:
break;
default:
return -1;
}
}
if (ms->flags & MAGIC_MIME_TYPE) {
if (str == NULL)
return 0;
if (file_printf(ms, "application/%s", str) == -1)
return -1;
}
return 1;
}
private int
cdf_file_catalog(struct magic_set *ms, const cdf_header_t *h,
const cdf_stream_t *sst)
{
cdf_catalog_t *cat;
size_t i;
char buf[256];
cdf_catalog_entry_t *ce;
if (NOTMIME(ms)) {
if (file_printf(ms, "Microsoft Thumbs.db [") == -1)
return -1;
if (cdf_unpack_catalog(h, sst, &cat) == -1)
return -1;
ce = cat->cat_e;
/* skip first entry since it has a , or paren */
for (i = 1; i < cat->cat_num; i++)
if (file_printf(ms, "%s%s",
cdf_u16tos8(buf, ce[i].ce_namlen, ce[i].ce_name),
i == cat->cat_num - 1 ? "]" : ", ") == -1) {
efree(cat);
return -1;
}
efree(cat);
} else if (ms->flags & MAGIC_MIME_TYPE) {
if (file_printf(ms, "application/CDFV2") == -1)
return -1;
}
return 1;
}
private int
cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h,
const cdf_stream_t *sst, const cdf_directory_t *root_storage)
{
cdf_summary_info_header_t si;
cdf_property_info_t *info;
size_t count;
int m;
if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1)
return -1;
if (NOTMIME(ms)) {
const char *str;
if (file_printf(ms, "Composite Document File V2 Document")
== -1)
return -1;
if (file_printf(ms, ", %s Endian",
si.si_byte_order == 0xfffe ? "Little" : "Big") == -1)
return -2;
switch (si.si_os) {
case 2:
if (file_printf(ms, ", Os: Windows, Version %d.%d",
si.si_os_version & 0xff,
CAST(uint32_t, si.si_os_version) >> 8) == -1)
return -2;
break;
case 1:
if (file_printf(ms, ", Os: MacOS, Version %d.%d",
CAST(uint32_t, si.si_os_version) >> 8,
si.si_os_version & 0xff) == -1)
return -2;
break;
default:
if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os,
si.si_os_version & 0xff,
CAST(uint32_t, si.si_os_version) >> 8) == -1)
return -2;
break;
}
if (root_storage) {
str = cdf_clsid_to_mime(root_storage->d_storage_uuid,
clsid2desc);
if (str) {
if (file_printf(ms, ", %s", str) == -1)
return -2;
}
}
}
m = cdf_file_property_info(ms, info, count, root_storage);
efree(info);
return m == -1 ? -2 : m;
}
#ifdef notdef
private char *
format_clsid(char *buf, size_t len, const uint64_t uuid[2]) {
snprintf(buf, len, "%.8" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.4"
PRIx64 "-%.12" PRIx64,
(uuid[0] >> 32) & (uint64_t)0x000000000ffffffffULL,
(uuid[0] >> 16) & (uint64_t)0x0000000000000ffffULL,
(uuid[0] >> 0) & (uint64_t)0x0000000000000ffffULL,
(uuid[1] >> 48) & (uint64_t)0x0000000000000ffffULL,
(uuid[1] >> 0) & (uint64_t)0x0000fffffffffffffULL);
return buf;
}
#endif
private int
cdf_file_catalog_info(struct magic_set *ms, const cdf_info_t *info,
const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat,
const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn)
{
int i;
if ((i = cdf_read_user_stream(info, h, sat, ssat, sst,
dir, "Catalog", scn)) == -1)
return i;
#ifdef CDF_DEBUG
cdf_dump_catalog(h, scn);
#endif
if ((i = cdf_file_catalog(ms, h, scn)) == -1)
return -1;
return i;
}
private int
cdf_check_summary_info(struct magic_set *ms, const cdf_info_t *info,
const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat,
const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t *root_storage, const char **expn)
{
int i;
const char *str = NULL;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
size_t j, k;
#ifdef CDF_DEBUG
cdf_dump_summary_info(h, scn);
#endif
if ((i = cdf_file_summary_info(ms, h, scn, root_storage)) < 0) {
*expn = "Can't expand summary_info";
return i;
}
if (i == 1)
return i;
for (j = 0; str == NULL && j < dir->dir_len; j++) {
d = &dir->dir_tab[j];
for (k = 0; k < sizeof(name); k++)
name[k] = CAST(char, cdf_tole2(d->d_name[k]));
str = cdf_app_to_mime(name,
NOTMIME(ms) ? name2desc : name2mime);
}
if (NOTMIME(ms)) {
if (str != NULL) {
if (file_printf(ms, "%s", str) == -1)
return -1;
i = 1;
}
} else if (ms->flags & MAGIC_MIME_TYPE) {
if (str == NULL)
str = "vnd.ms-office";
if (file_printf(ms, "application/%s", str) == -1)
return -1;
i = 1;
}
if (i <= 0) {
i = cdf_file_catalog_info(ms, info, h, sat, ssat, sst,
dir, scn);
}
return i;
}
private struct sinfo {
const char *name;
const char *mime;
const char *sections[5];
const int types[5];
} sectioninfo[] = {
{ "Encrypted", "encrypted",
{
"EncryptedPackage", "EncryptedSummary",
NULL, NULL, NULL,
},
{
CDF_DIR_TYPE_USER_STREAM,
CDF_DIR_TYPE_USER_STREAM,
0, 0, 0,
},
},
{ "QuickBooks", "quickbooks",
{
#if 0
"TaxForms", "PDFTaxForms", "modulesInBackup",
#endif
"mfbu_header", NULL, NULL, NULL, NULL,
},
{
#if 0
CDF_DIR_TYPE_USER_STORAGE,
CDF_DIR_TYPE_USER_STORAGE,
CDF_DIR_TYPE_USER_STREAM,
#endif
CDF_DIR_TYPE_USER_STREAM,
0, 0, 0, 0
},
},
{ "Microsoft Excel", "vnd.ms-excel",
{
"Book", "Workbook", NULL, NULL, NULL,
},
{
CDF_DIR_TYPE_USER_STREAM,
CDF_DIR_TYPE_USER_STREAM,
0, 0, 0,
},
},
{ "Microsoft Word", "msword",
{
"WordDocument", NULL, NULL, NULL, NULL,
},
{
CDF_DIR_TYPE_USER_STREAM,
0, 0, 0, 0,
},
},
{ "Microsoft PowerPoint", "vnd.ms-powerpoint",
{
"PowerPoint", NULL, NULL, NULL, NULL,
},
{
CDF_DIR_TYPE_USER_STREAM,
0, 0, 0, 0,
},
},
{ "Microsoft Outlook Message", "vnd.ms-outlook",
{
"__properties_version1.0",
"__recip_version1.0_#00000000",
NULL, NULL, NULL,
},
{
CDF_DIR_TYPE_USER_STREAM,
CDF_DIR_TYPE_USER_STORAGE,
0, 0, 0,
},
},
};
private int
cdf_file_dir_info(struct magic_set *ms, const cdf_dir_t *dir)
{
size_t sd, j;
for (sd = 0; sd < __arraycount(sectioninfo); sd++) {
const struct sinfo *si = §ioninfo[sd];
for (j = 0; si->sections[j]; j++) {
if (cdf_find_stream(dir, si->sections[j], si->types[j])
> 0)
break;
#ifdef CDF_DEBUG
fprintf(stderr, "Can't read %s\n", si->sections[j]);
#endif
}
if (si->sections[j] == NULL)
continue;
if (NOTMIME(ms)) {
if (file_printf(ms, "CDFV2 %s", si->name) == -1)
return -1;
} else if (ms->flags & MAGIC_MIME_TYPE) {
if (file_printf(ms, "application/%s", si->mime) == -1)
return -1;
}
return 1;
}
return -1;
}
protected int
file_trycdf(struct magic_set *ms, const struct buffer *b)
{
int fd = b->fd;
const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
size_t nbytes = b->flen;
cdf_info_t info;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
int i;
const char *expn = "";
const cdf_directory_t *root_storage;
scn.sst_tab = NULL;
info.i_fd = fd;
info.i_buf = buf;
info.i_len = nbytes;
if (ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION))
return 0;
if (cdf_read_header(&info, &h) == -1)
return 0;
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if ((i = cdf_read_sat(&info, &h, &sat)) == -1) {
expn = "Can't read SAT";
goto out0;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if ((i = cdf_read_ssat(&info, &h, &sat, &ssat)) == -1) {
expn = "Can't read SSAT";
goto out1;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if ((i = cdf_read_dir(&info, &h, &sat, &dir)) == -1) {
expn = "Can't read directory";
goto out2;
}
if ((i = cdf_read_short_stream(&info, &h, &sat, &dir, &sst,
&root_storage)) == -1) {
expn = "Cannot read short stream";
goto out3;
}
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
#ifdef notdef
if (root_storage) {
if (NOTMIME(ms)) {
char clsbuf[128];
if (file_printf(ms, "CLSID %s, ",
format_clsid(clsbuf, sizeof(clsbuf),
root_storage->d_storage_uuid)) == -1)
return -1;
}
}
#endif
if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir,
"FileHeader", &scn) != -1) {
#define HWP5_SIGNATURE "HWP Document File"
if (scn.sst_len * scn.sst_ss >= sizeof(HWP5_SIGNATURE) - 1
&& memcmp(scn.sst_tab, HWP5_SIGNATURE,
sizeof(HWP5_SIGNATURE) - 1) == 0) {
if (NOTMIME(ms)) {
if (file_printf(ms,
"Hangul (Korean) Word Processor File 5.x") == -1)
return -1;
} else if (ms->flags & MAGIC_MIME_TYPE) {
if (file_printf(ms, "application/x-hwp") == -1)
return -1;
}
i = 1;
goto out5;
} else {
cdf_zero_stream(&scn);
}
}
if ((i = cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn)) == -1) {
if (errno != ESRCH) {
expn = "Cannot read summary info";
}
} else {
i = cdf_check_summary_info(ms, &info, &h,
&sat, &ssat, &sst, &dir, &scn, root_storage, &expn);
cdf_zero_stream(&scn);
}
if (i <= 0) {
if ((i = cdf_read_doc_summary_info(&info, &h, &sat, &ssat,
&sst, &dir, &scn)) == -1) {
if (errno != ESRCH) {
expn = "Cannot read summary info";
}
} else {
i = cdf_check_summary_info(ms, &info, &h, &sat, &ssat,
&sst, &dir, &scn, root_storage, &expn);
}
}
if (i <= 0) {
i = cdf_file_dir_info(ms, &dir);
if (i < 0)
expn = "Cannot read section info";
}
out5:
cdf_zero_stream(&scn);
cdf_zero_stream(&sst);
out3:
efree(dir.dir_tab);
out2:
efree(ssat.sat_tab);
out1:
efree(sat.sat_tab);
out0:
/* If we handled it already, return */
if (i != -1)
return i;
/* Provide a default handler */
if (NOTMIME(ms)) {
if (file_printf(ms,
"Composite Document File V2 Document") == -1)
return -1;
if (*expn)
if (file_printf(ms, ", %s", expn) == -1)
return -1;
} else if (ms->flags & MAGIC_MIME_TYPE) {
/* https://reposcope.com/mimetype/application/x-ole-storage */
if (file_printf(ms, "application/x-ole-storage") == -1)
return -1;
}
return 1;
}
| 16,302 | 23.260417 | 78 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/strcasestr.c
|
/* $NetBSD: strcasestr.c,v 1.3 2005/11/29 03:12:00 christos Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: strcasestr.c,v 1.3 2005/11/29 03:12:00 christos Exp $");
__RCSID("$NetBSD: strncasecmp.c,v 1.2 2007/06/04 18:19:27 christos Exp $");
#endif /* LIBC_SCCS and not lint */
#include "file.h"
#include <assert.h>
#include <ctype.h>
#include <string.h>
static int
_strncasecmp(const char *s1, const char *s2, size_t n)
{
if (n != 0) {
const unsigned char *us1 = (const unsigned char *)s1,
*us2 = (const unsigned char *)s2;
do {
if (tolower(*us1) != tolower(*us2++))
return tolower(*us1) - tolower(*--us2);
if (*us1++ == '\0')
break;
} while (--n != 0);
}
return 0;
}
/*
* Find the first occurrence of find in s, ignore case.
*/
char *
strcasestr(const char *s, const char *find)
{
char c, sc;
size_t len;
if ((c = *find++) != 0) {
c = tolower((unsigned char)c);
len = strlen(find);
do {
do {
if ((sc = *s++) == 0)
return (NULL);
} while ((char)tolower((unsigned char)sc) != c);
} while (_strncasecmp(s, find, len) != 0);
s--;
}
return (char *)(intptr_t)(s);
}
| 2,827 | 32.270588 | 77 |
c
|
php-src
|
php-src-master/ext/fileinfo/libmagic/tar.h
|
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Header file for public domain tar (tape archive) program.
*
* @(#)tar.h 1.20 86/10/29 Public Domain.
*
* Created 25 August 1985 by John Gilmore, ihnp4!hoptoad!gnu.
*
* $File: tar.h,v 1.13 2010/11/30 14:58:53 rrt Exp $ # checkin only
*/
/*
* Header block on tape.
*
* I'm going to use traditional DP naming conventions here.
* A "block" is a big chunk of stuff that we do I/O on.
* A "record" is a piece of info that we care about.
* Typically many "record"s fit into a "block".
*/
#define RECORDSIZE 512
#define NAMSIZ 100
#define TUNMLEN 32
#define TGNMLEN 32
union record {
unsigned char charptr[RECORDSIZE];
struct header {
char name[NAMSIZ];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char chksum[8];
char linkflag;
char linkname[NAMSIZ];
char magic[8];
char uname[TUNMLEN];
char gname[TGNMLEN];
char devmajor[8];
char devminor[8];
} header;
};
/* The magic field is filled with this if uname and gname are valid. */
#define TMAGIC "ustar" /* 5 chars and a null */
#define GNUTMAGIC "ustar " /* 7 chars and a null */
| 2,618 | 34.391892 | 77 |
h
|
php-src
|
php-src-master/ext/filter/callback_filter.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Derick Rethans <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_filter.h"
void php_filter_callback(PHP_INPUT_FILTER_PARAM_DECL)
{
zval retval;
zval args[1];
int status;
if (!option_array || !zend_is_callable(option_array, IS_CALLABLE_SUPPRESS_DEPRECATIONS, NULL)) {
zend_type_error("%s(): Option must be a valid callback", get_active_function_name());
zval_ptr_dtor(value);
ZVAL_NULL(value);
return;
}
ZVAL_COPY(&args[0], value);
status = call_user_function(NULL, NULL, option_array, &retval, 1, args);
if (status == SUCCESS && !Z_ISUNDEF(retval)) {
zval_ptr_dtor(value);
ZVAL_COPY_VALUE(value, &retval);
} else {
zval_ptr_dtor(value);
ZVAL_NULL(value);
}
zval_ptr_dtor(&args[0]);
}
| 1,647 | 35.622222 | 97 |
c
|
php-src
|
php-src-master/ext/filter/filter_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: c3f3240137eaa89316276920acf35f975b2dd8f9 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_filter_has_var, 0, 2, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, input_type, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, var_name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_filter_input, 0, 2, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, type, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, var_name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, filter, IS_LONG, 0, "FILTER_DEFAULT")
ZEND_ARG_TYPE_MASK(0, options, MAY_BE_ARRAY|MAY_BE_LONG, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_filter_var, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, filter, IS_LONG, 0, "FILTER_DEFAULT")
ZEND_ARG_TYPE_MASK(0, options, MAY_BE_ARRAY|MAY_BE_LONG, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_filter_input_array, 0, 1, MAY_BE_ARRAY|MAY_BE_FALSE|MAY_BE_NULL)
ZEND_ARG_TYPE_INFO(0, type, IS_LONG, 0)
ZEND_ARG_TYPE_MASK(0, options, MAY_BE_ARRAY|MAY_BE_LONG, "FILTER_DEFAULT")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, add_empty, _IS_BOOL, 0, "true")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_filter_var_array, 0, 1, MAY_BE_ARRAY|MAY_BE_FALSE|MAY_BE_NULL)
ZEND_ARG_TYPE_INFO(0, array, IS_ARRAY, 0)
ZEND_ARG_TYPE_MASK(0, options, MAY_BE_ARRAY|MAY_BE_LONG, "FILTER_DEFAULT")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, add_empty, _IS_BOOL, 0, "true")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_filter_list, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_filter_id, 0, 1, MAY_BE_LONG|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(filter_has_var);
ZEND_FUNCTION(filter_input);
ZEND_FUNCTION(filter_var);
ZEND_FUNCTION(filter_input_array);
ZEND_FUNCTION(filter_var_array);
ZEND_FUNCTION(filter_list);
ZEND_FUNCTION(filter_id);
static const zend_function_entry ext_functions[] = {
ZEND_FE(filter_has_var, arginfo_filter_has_var)
ZEND_FE(filter_input, arginfo_filter_input)
ZEND_FE(filter_var, arginfo_filter_var)
ZEND_FE(filter_input_array, arginfo_filter_input_array)
ZEND_FE(filter_var_array, arginfo_filter_var_array)
ZEND_FE(filter_list, arginfo_filter_list)
ZEND_FE(filter_id, arginfo_filter_id)
ZEND_FE_END
};
static void register_filter_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("INPUT_POST", PARSE_POST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("INPUT_GET", PARSE_GET, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("INPUT_COOKIE", PARSE_COOKIE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("INPUT_ENV", PARSE_ENV, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("INPUT_SERVER", PARSE_SERVER, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_NONE", FILTER_FLAG_NONE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_REQUIRE_SCALAR", FILTER_REQUIRE_SCALAR, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_REQUIRE_ARRAY", FILTER_REQUIRE_ARRAY, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FORCE_ARRAY", FILTER_FORCE_ARRAY, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_NULL_ON_FAILURE", FILTER_NULL_ON_FAILURE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_INT", FILTER_VALIDATE_INT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOLEAN", FILTER_VALIDATE_BOOL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOL", FILTER_VALIDATE_BOOL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_FLOAT", FILTER_VALIDATE_FLOAT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_REGEXP", FILTER_VALIDATE_REGEXP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_DOMAIN", FILTER_VALIDATE_DOMAIN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_URL", FILTER_VALIDATE_URL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_EMAIL", FILTER_VALIDATE_EMAIL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_IP", FILTER_VALIDATE_IP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_VALIDATE_MAC", FILTER_VALIDATE_MAC, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_DEFAULT", FILTER_DEFAULT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_UNSAFE_RAW", FILTER_UNSAFE_RAW, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRING", FILTER_SANITIZE_STRING, CONST_PERSISTENT | CONST_DEPRECATED);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRIPPED", FILTER_SANITIZE_STRING, CONST_PERSISTENT | CONST_DEPRECATED);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ENCODED", FILTER_SANITIZE_ENCODED, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_FULL_SPECIAL_CHARS", FILTER_SANITIZE_FULL_SPECIAL_CHARS, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_EMAIL", FILTER_SANITIZE_EMAIL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_URL", FILTER_SANITIZE_URL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_INT", FILTER_SANITIZE_NUMBER_INT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_FLOAT", FILTER_SANITIZE_NUMBER_FLOAT, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ADD_SLASHES", FILTER_SANITIZE_ADD_SLASHES, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_CALLBACK", FILTER_CALLBACK, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_OCTAL", FILTER_FLAG_ALLOW_OCTAL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_HEX", FILTER_FLAG_ALLOW_HEX, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_LOW", FILTER_FLAG_STRIP_LOW, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_HIGH", FILTER_FLAG_STRIP_HIGH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_BACKTICK", FILTER_FLAG_STRIP_BACKTICK, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_LOW", FILTER_FLAG_ENCODE_LOW, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_HIGH", FILTER_FLAG_ENCODE_HIGH, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_AMP", FILTER_FLAG_ENCODE_AMP, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_ENCODE_QUOTES", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_EMPTY_STRING_NULL", FILTER_FLAG_EMPTY_STRING_NULL, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_FRACTION", FILTER_FLAG_ALLOW_FRACTION, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_THOUSAND", FILTER_FLAG_ALLOW_THOUSAND, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_SCIENTIFIC", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_PATH_REQUIRED", FILTER_FLAG_PATH_REQUIRED, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_QUERY_REQUIRED", FILTER_FLAG_QUERY_REQUIRED, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV4", FILTER_FLAG_IPV4, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV6", FILTER_FLAG_IPV6, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_RES_RANGE", FILTER_FLAG_NO_RES_RANGE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_PRIV_RANGE", FILTER_FLAG_NO_PRIV_RANGE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_GLOBAL_RANGE", FILTER_FLAG_GLOBAL_RANGE, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_HOSTNAME", FILTER_FLAG_HOSTNAME, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("FILTER_FLAG_EMAIL_UNICODE", FILTER_FLAG_EMAIL_UNICODE, CONST_PERSISTENT);
}
| 7,580 | 62.175 | 116 |
h
|
php-src
|
php-src-master/ext/filter/filter_private.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Derick Rethans <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef FILTER_PRIVATE_H
#define FILTER_PRIVATE_H
#define FILTER_FLAG_NONE 0x0000
#define FILTER_REQUIRE_ARRAY 0x1000000
#define FILTER_REQUIRE_SCALAR 0x2000000
#define FILTER_FORCE_ARRAY 0x4000000
#define FILTER_NULL_ON_FAILURE 0x8000000
#define FILTER_FLAG_ALLOW_OCTAL 0x0001
#define FILTER_FLAG_ALLOW_HEX 0x0002
#define FILTER_FLAG_STRIP_LOW 0x0004
#define FILTER_FLAG_STRIP_HIGH 0x0008
#define FILTER_FLAG_ENCODE_LOW 0x0010
#define FILTER_FLAG_ENCODE_HIGH 0x0020
#define FILTER_FLAG_ENCODE_AMP 0x0040
#define FILTER_FLAG_NO_ENCODE_QUOTES 0x0080
#define FILTER_FLAG_EMPTY_STRING_NULL 0x0100
#define FILTER_FLAG_STRIP_BACKTICK 0x0200
#define FILTER_FLAG_ALLOW_FRACTION 0x1000
#define FILTER_FLAG_ALLOW_THOUSAND 0x2000
#define FILTER_FLAG_ALLOW_SCIENTIFIC 0x4000
#define FILTER_FLAG_SCHEME_REQUIRED 0x010000
#define FILTER_FLAG_HOST_REQUIRED 0x020000
#define FILTER_FLAG_PATH_REQUIRED 0x040000
#define FILTER_FLAG_QUERY_REQUIRED 0x080000
#define FILTER_FLAG_IPV4 0x00100000
#define FILTER_FLAG_IPV6 0x00200000
#define FILTER_FLAG_NO_RES_RANGE 0x00400000
#define FILTER_FLAG_NO_PRIV_RANGE 0x00800000
#define FILTER_FLAG_GLOBAL_RANGE 0x10000000
#define FILTER_FLAG_HOSTNAME 0x100000
#define FILTER_FLAG_EMAIL_UNICODE 0x100000
#define FILTER_VALIDATE_INT 0x0101
#define FILTER_VALIDATE_BOOL 0x0102
#define FILTER_VALIDATE_FLOAT 0x0103
#define FILTER_VALIDATE_REGEXP 0x0110
#define FILTER_VALIDATE_URL 0x0111
#define FILTER_VALIDATE_EMAIL 0x0112
#define FILTER_VALIDATE_IP 0x0113
#define FILTER_VALIDATE_MAC 0x0114
#define FILTER_VALIDATE_DOMAIN 0x0115
#define FILTER_VALIDATE_LAST 0x0115
#define FILTER_VALIDATE_ALL 0x0100
#define FILTER_DEFAULT 0x0204
#define FILTER_UNSAFE_RAW 0x0204
#define FILTER_SANITIZE_STRING 0x0201
#define FILTER_SANITIZE_ENCODED 0x0202
#define FILTER_SANITIZE_SPECIAL_CHARS 0x0203
#define FILTER_SANITIZE_EMAIL 0x0205
#define FILTER_SANITIZE_URL 0x0206
#define FILTER_SANITIZE_NUMBER_INT 0x0207
#define FILTER_SANITIZE_NUMBER_FLOAT 0x0208
#define FILTER_SANITIZE_FULL_SPECIAL_CHARS 0x020a
#define FILTER_SANITIZE_ADD_SLASHES 0x020b
#define FILTER_SANITIZE_LAST 0x020b
#define FILTER_SANITIZE_ALL 0x0200
#define FILTER_CALLBACK 0x0400
#define PHP_FILTER_ID_EXISTS(id) \
((id >= FILTER_SANITIZE_ALL && id <= FILTER_SANITIZE_LAST) \
|| (id >= FILTER_VALIDATE_ALL && id <= FILTER_VALIDATE_LAST) \
|| id == FILTER_CALLBACK)
#define RETURN_VALIDATION_FAILED \
if (EG(exception)) { \
return; \
} else if (flags & FILTER_NULL_ON_FAILURE) { \
zval_ptr_dtor(value); \
ZVAL_NULL(value); \
} else { \
zval_ptr_dtor(value); \
ZVAL_FALSE(value); \
} \
return; \
#define PHP_FILTER_TRIM_DEFAULT(p, len) PHP_FILTER_TRIM_DEFAULT_EX(p, len, 1);
#define PHP_FILTER_TRIM_DEFAULT_EX(p, len, return_if_empty) { \
while ((len > 0) && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\v' || *p == '\n')) { \
p++; \
len--; \
} \
if (len < 1 && return_if_empty) { \
RETURN_VALIDATION_FAILED \
} \
if (len > 0) { \
while (p[len-1] == ' ' || p[len-1] == '\t' || p[len-1] == '\r' || p[len-1] == '\v' || p[len-1] == '\n') { \
len--; \
} \
} \
}
#endif /* FILTER_PRIVATE_H */
| 4,600 | 35.515873 | 109 |
h
|
php-src
|
php-src-master/ext/filter/php_filter.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <[email protected]> |
| Derick Rethans <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_FILTER_H
#define PHP_FILTER_H
#include "SAPI.h"
#include "zend_API.h"
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/php_string.h"
#include "ext/standard/html.h"
#include "php_variables.h"
extern zend_module_entry filter_module_entry;
#define phpext_filter_ptr &filter_module_entry
#ifdef ZTS
#include "TSRM.h"
#endif
#define PHP_FILTER_VERSION PHP_VERSION
PHP_MINIT_FUNCTION(filter);
PHP_MSHUTDOWN_FUNCTION(filter);
PHP_RINIT_FUNCTION(filter);
PHP_RSHUTDOWN_FUNCTION(filter);
PHP_MINFO_FUNCTION(filter);
ZEND_BEGIN_MODULE_GLOBALS(filter)
zval post_array;
zval get_array;
zval cookie_array;
zval env_array;
zval server_array;
#if 0
zval session_array;
#endif
zend_long default_filter;
zend_long default_filter_flags;
ZEND_END_MODULE_GLOBALS(filter)
#if defined(COMPILE_DL_FILTER) && defined(ZTS)
ZEND_TSRMLS_CACHE_EXTERN()
#endif
#define IF_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(filter, v)
#define PHP_INPUT_FILTER_PARAM_DECL zval *value, zend_long flags, zval *option_array, char *charset
void php_filter_int(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_boolean(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_float(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_validate_regexp(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_validate_domain(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_validate_email(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_validate_ip(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_validate_mac(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_string(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_encoded(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_special_chars(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_full_special_chars(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_unsafe_raw(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_email(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_url(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_number_int(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_number_float(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_add_slashes(PHP_INPUT_FILTER_PARAM_DECL);
void php_filter_callback(PHP_INPUT_FILTER_PARAM_DECL);
#endif /* FILTER_H */
| 3,279 | 35.853933 | 99 |
h
|
php-src
|
php-src-master/ext/ftp/ftp.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andrew Skalski <[email protected]> |
| Stefan Esser <[email protected]> (resume functions) |
+----------------------------------------------------------------------+
*/
#ifndef FTP_H
#define FTP_H
#include "php_network.h"
#include <stdio.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#define FTP_DEFAULT_TIMEOUT 90
#define FTP_DEFAULT_AUTOSEEK 1
#define FTP_DEFAULT_USEPASVADDRESS 1
#define PHP_FTP_FAILED 0
#define PHP_FTP_FINISHED 1
#define PHP_FTP_MOREDATA 2
/* XXX this should be configurable at runtime XXX */
#define FTP_BUFSIZE 4096
typedef enum ftptype {
FTPTYPE_ASCII=1,
FTPTYPE_IMAGE
} ftptype_t;
typedef struct databuf
{
int listener; /* listener socket */
php_socket_t fd; /* data connection */
ftptype_t type; /* transfer type */
char buf[FTP_BUFSIZE]; /* data buffer */
#ifdef HAVE_FTP_SSL
SSL *ssl_handle; /* ssl handle */
int ssl_active; /* flag if ssl is active or not */
#endif
} databuf_t;
typedef struct ftpbuf
{
php_socket_t fd; /* control connection */
php_sockaddr_storage localaddr; /* local address */
int resp; /* last response code */
char inbuf[FTP_BUFSIZE]; /* last response text */
char *extra; /* extra characters */
int extralen; /* number of extra chars */
char outbuf[FTP_BUFSIZE]; /* command output buffer */
char *pwd; /* cached pwd */
char *syst; /* cached system type */
ftptype_t type; /* current transfer type */
int pasv; /* 0=off; 1=pasv; 2=ready */
php_sockaddr_storage pasvaddr; /* passive mode address */
zend_long timeout_sec; /* User configurable timeout (seconds) */
int autoseek; /* User configurable autoseek flag */
int usepasvaddress; /* Use the address returned by the pasv command */
int nb; /* "nonblocking" transfer in progress */
databuf_t *data; /* Data connection for "nonblocking" transfers */
php_stream *stream; /* output stream for "nonblocking" transfers */
int lastch; /* last char of previous call */
int direction; /* recv = 0 / send = 1 */
int closestream;/* close or not close stream */
#ifdef HAVE_FTP_SSL
int use_ssl; /* enable(1) or disable(0) ssl */
int use_ssl_for_data; /* en/disable ssl for the dataconnection */
int old_ssl; /* old mode = forced data encryption */
SSL *ssl_handle; /* handle for control connection */
int ssl_active; /* ssl active on control conn */
#endif
} ftpbuf_t;
/* open a FTP connection, returns ftpbuf (NULL on error)
* port is the ftp port in network byte order, or 0 for the default
*/
ftpbuf_t* ftp_open(const char *host, short port, zend_long timeout_sec);
/* quits from the ftp session (it still needs to be closed)
* return true on success, false on error
*/
int ftp_quit(ftpbuf_t *ftp);
/* frees up any cached data held in the ftp buffer */
void ftp_gc(ftpbuf_t *ftp);
/* close the FTP connection and return NULL */
ftpbuf_t* ftp_close(ftpbuf_t *ftp);
/* logs into the FTP server, returns true on success, false on error */
int ftp_login(ftpbuf_t *ftp, const char *user, const size_t user_len, const char *pass, const size_t pass_len);
/* reinitializes the connection, returns true on success, false on error */
int ftp_reinit(ftpbuf_t *ftp);
/* returns the remote system type (NULL on error) */
const char* ftp_syst(ftpbuf_t *ftp);
/* returns the present working directory (NULL on error) */
const char* ftp_pwd(ftpbuf_t *ftp);
/* exec a command [special features], return true on success, false on error */
int ftp_exec(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len);
/* send a raw ftp command, return response as a hashtable, NULL on error */
void ftp_raw(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len, zval *return_value);
/* changes directories, return true on success, false on error */
int ftp_chdir(ftpbuf_t *ftp, const char *dir, const size_t dir_len);
/* changes to parent directory, return true on success, false on error */
int ftp_cdup(ftpbuf_t *ftp);
/* creates a directory, return the directory name on success, NULL on error.
* the return value must be freed
*/
zend_string* ftp_mkdir(ftpbuf_t *ftp, const char *dir, const size_t dir_len);
/* removes a directory, return true on success, false on error */
int ftp_rmdir(ftpbuf_t *ftp, const char *dir, const size_t dir_len);
/* Set permissions on a file */
int ftp_chmod(ftpbuf_t *ftp, const int mode, const char *filename, const int filename_len);
/* Allocate space on remote server with ALLO command
* Many servers will respond with 202 Allocation not necessary,
* however some servers will not accept STOR or APPE until ALLO is confirmed.
* If response is passed, it is estrdup()ed from ftp->inbuf and must be freed
* or assigned to a zval returned to the user */
int ftp_alloc(ftpbuf_t *ftp, const zend_long size, zend_string **response);
/* returns a NULL-terminated array of filenames in the given path
* or NULL on error. the return array must be freed (but don't
* free the array elements)
*/
char** ftp_nlist(ftpbuf_t *ftp, const char *path, const size_t path_len);
/* returns a NULL-terminated array of lines returned by the ftp
* LIST command for the given path or NULL on error. the return
* array must be freed (but don't
* free the array elements)
*/
char** ftp_list(ftpbuf_t *ftp, const char *path, const size_t path_len, int recursive);
/* populates a hashtable with the facts contained in one line of
* an MLSD response.
*/
int ftp_mlsd_parse_line(HashTable *ht, const char *input);
/* returns a NULL-terminated array of lines returned by the ftp
* MLSD command for the given path or NULL on error. the return
* array must be freed (but don't
* free the array elements)
*/
char** ftp_mlsd(ftpbuf_t *ftp, const char *path, const size_t path_len);
/* switches passive mode on or off
* returns true on success, false on error
*/
int ftp_pasv(ftpbuf_t *ftp, int pasv);
/* retrieves a file and saves its contents to outfp
* returns true on success, false on error
*/
int ftp_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, const size_t path_len, ftptype_t type, zend_long resumepos);
/* stores the data from a file, socket, or process as a file on the remote server
* returns true on success, false on error
*/
int ftp_put(ftpbuf_t *ftp, const char *path, const size_t path_len, php_stream *instream, ftptype_t type, zend_long startpos);
/* append the data from a file, socket, or process as a file on the remote server
* returns true on success, false on error
*/
int ftp_append(ftpbuf_t *ftp, const char *path, const size_t path_len, php_stream *instream, ftptype_t type);
/* returns the size of the given file, or -1 on error */
zend_long ftp_size(ftpbuf_t *ftp, const char *path, const size_t path_len);
/* returns the last modified time of the given file, or -1 on error */
time_t ftp_mdtm(ftpbuf_t *ftp, const char *path, const size_t path_len);
/* renames a file on the server */
int ftp_rename(ftpbuf_t *ftp, const char *src, const size_t src_len, const char *dest, const size_t dest_len);
/* deletes the file from the server */
int ftp_delete(ftpbuf_t *ftp, const char *path, const size_t path_len);
/* sends a SITE command to the server */
int ftp_site(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len);
/* retrieves part of a file and saves its contents to outfp
* returns true on success, false on error
*/
int ftp_nb_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, const size_t path_len, ftptype_t type, zend_long resumepos);
/* stores the data from a file, socket, or process as a file on the remote server
* returns true on success, false on error
*/
int ftp_nb_put(ftpbuf_t *ftp, const char *path, const size_t path_len, php_stream *instream, ftptype_t type, zend_long startpos);
/* continues a previous nb_(f)get command
*/
int ftp_nb_continue_read(ftpbuf_t *ftp);
/* continues a previous nb_(f)put command
*/
int ftp_nb_continue_write(ftpbuf_t *ftp);
#endif
| 8,851 | 37.655022 | 132 |
h
|
php-src
|
php-src-master/ext/ftp/php_ftp.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andrew Skalski <[email protected]> |
| Stefan Esser <[email protected]> (resume functions) |
+----------------------------------------------------------------------+
*/
#ifndef _INCLUDED_FTP_H
#define _INCLUDED_FTP_H
extern zend_module_entry php_ftp_module_entry;
#define phpext_ftp_ptr &php_ftp_module_entry
#include "php_version.h"
#define PHP_FTP_VERSION PHP_VERSION
#define PHP_FTP_OPT_TIMEOUT_SEC 0
#define PHP_FTP_OPT_AUTOSEEK 1
#define PHP_FTP_OPT_USEPASVADDRESS 2
#define PHP_FTP_AUTORESUME -1
PHP_MINIT_FUNCTION(ftp);
PHP_MINFO_FUNCTION(ftp);
#endif
| 1,468 | 39.805556 | 75 |
h
|
php-src
|
php-src-master/ext/gd/php_gd.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <[email protected]> |
| Stig Bakken <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_GD_H
#define PHP_GD_H
#include "zend_string.h"
#include "php_streams.h"
#if defined(HAVE_LIBGD) || defined(HAVE_GD_BUNDLED)
/* open_basedir and safe_mode checks */
#define PHP_GD_CHECK_OPEN_BASEDIR(filename, errormsg) \
if (!filename || php_check_open_basedir(filename)) { \
php_error_docref(NULL, E_WARNING, errormsg); \
RETURN_FALSE; \
}
#define PHP_GDIMG_TYPE_GIF 1
#define PHP_GDIMG_TYPE_PNG 2
#define PHP_GDIMG_TYPE_JPG 3
#define PHP_GDIMG_TYPE_WBM 4
#define PHP_GDIMG_TYPE_XBM 5
#define PHP_GDIMG_TYPE_XPM 6
#define PHP_GDIMG_TYPE_GD 8
#define PHP_GDIMG_TYPE_GD2 9
#define PHP_GDIMG_TYPE_GD2PART 10
#define PHP_GDIMG_TYPE_WEBP 11
#define PHP_GDIMG_TYPE_BMP 12
#define PHP_GDIMG_TYPE_TGA 13
#define PHP_GDIMG_TYPE_AVIF 14
#define PHP_IMG_GIF 1
#define PHP_IMG_JPG 2
#define PHP_IMG_JPEG 2
#define PHP_IMG_PNG 4
#define PHP_IMG_WBMP 8
#define PHP_IMG_XPM 16
#define PHP_IMG_WEBP 32
#define PHP_IMG_BMP 64
#define PHP_IMG_TGA 128
#define PHP_IMG_AVIF 256
/* Section Filters Declarations */
/* IMPORTANT NOTE FOR NEW FILTER
* Do not forget to update:
* IMAGE_FILTER_MAX: define the last filter index
* IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments
* image_filter array in PHP_FUNCTION(imagefilter)
* */
#define IMAGE_FILTER_NEGATE 0
#define IMAGE_FILTER_GRAYSCALE 1
#define IMAGE_FILTER_BRIGHTNESS 2
#define IMAGE_FILTER_CONTRAST 3
#define IMAGE_FILTER_COLORIZE 4
#define IMAGE_FILTER_EDGEDETECT 5
#define IMAGE_FILTER_EMBOSS 6
#define IMAGE_FILTER_GAUSSIAN_BLUR 7
#define IMAGE_FILTER_SELECTIVE_BLUR 8
#define IMAGE_FILTER_MEAN_REMOVAL 9
#define IMAGE_FILTER_SMOOTH 10
#define IMAGE_FILTER_PIXELATE 11
#define IMAGE_FILTER_SCATTER 12
#define IMAGE_FILTER_MAX 12
#define IMAGE_FILTER_MAX_ARGS 6
#ifdef HAVE_GD_BUNDLED
#define GD_BUNDLED 1
#else
#define GD_BUNDLED 0
#endif
#ifdef PHP_WIN32
# ifdef PHP_GD_EXPORTS
# define PHP_GD_API __declspec(dllexport)
# else
# define PHP_GD_API __declspec(dllimport)
# endif
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_GD_API __attribute__ ((visibility("default")))
#else
# define PHP_GD_API
#endif
PHPAPI extern const char php_sig_gif[3];
PHPAPI extern const char php_sig_jpg[3];
PHPAPI extern const char php_sig_png[8];
PHPAPI extern const char php_sig_bmp[2];
PHPAPI extern const char php_sig_riff[4];
PHPAPI extern const char php_sig_webp[4];
PHPAPI extern const char php_sig_avif[4];
extern zend_module_entry gd_module_entry;
#define phpext_gd_ptr &gd_module_entry
#include "php_version.h"
#define PHP_GD_VERSION PHP_VERSION
/* gd.c functions */
PHP_MINFO_FUNCTION(gd);
PHP_MINIT_FUNCTION(gd);
PHP_MSHUTDOWN_FUNCTION(gd);
PHP_RSHUTDOWN_FUNCTION(gd);
PHP_GD_API struct gdImageStruct *php_gd_libgdimageptr_from_zval_p(zval* zp);
#else
#define phpext_gd_ptr NULL
#endif
#endif /* PHP_GD_H */
| 4,105 | 31.078125 | 77 |
h
|
php-src
|
php-src-master/ext/gd/libgd/bmp.h
|
/* $Id$ */
#ifdef __cplusplus
extern "C" {
#endif
/*
gd_bmp.c
Bitmap format support for libgd
* Written 2007, Scott MacVicar
---------------------------------------------------------------------------
Todo:
RLE4, RLE8 and Bitfield encoding
Add full support for Windows v4 and Windows v5 header formats
----------------------------------------------------------------------------
*/
#ifndef BMP_H
#define BMP_H 1
#define BMP_PALETTE_3 1
#define BMP_PALETTE_4 2
#define BMP_WINDOWS_V3 40
#define BMP_OS2_V1 12
#define BMP_OS2_V2 64
#define BMP_WINDOWS_V4 108
#define BMP_WINDOWS_V5 124
#define BMP_BI_RGB 0
#define BMP_BI_RLE8 1
#define BMP_BI_RLE4 2
#define BMP_BI_BITFIELDS 3
#define BMP_BI_JPEG 4
#define BMP_BI_PNG 5
#define BMP_RLE_COMMAND 0
#define BMP_RLE_ENDOFLINE 0
#define BMP_RLE_ENDOFBITMAP 1
#define BMP_RLE_DELTA 2
#define BMP_RLE_TYPE_RAW 0
#define BMP_RLE_TYPE_RLE 1
/* BMP header. */
typedef struct {
/* 16 bit - header identifying the type */
signed short int magic;
/* 32bit - size of the file */
int size;
/* 16bit - these two are in the spec but "reserved" */
signed short int reserved1;
signed short int reserved2;
/* 32 bit - offset of the bitmap header from data in bytes */
signed int off;
} bmp_hdr_t;
/* BMP info. */
typedef struct {
/* 16bit - Type, ie Windows or OS/2 for the palette info */
signed short int type;
/* 32bit - The length of the bitmap information header in bytes. */
signed int len;
/* 32bit - The width of the bitmap in pixels. */
signed int width;
/* 32bit - The height of the bitmap in pixels. */
signed int height;
/* 8 bit - The bitmap data is specified in top-down order. */
signed char topdown;
/* 16 bit - The number of planes. This must be set to a value of one. */
signed short int numplanes;
/* 16 bit - The number of bits per pixel. */
signed short int depth;
/* 32bit - The type of compression used. */
signed int enctype;
/* 32bit - The size of the image in bytes. */
signed int size;
/* 32bit - The horizontal resolution in pixels/metre. */
signed int hres;
/* 32bit - The vertical resolution in pixels/metre. */
signed int vres;
/* 32bit - The number of color indices used by the bitmap. */
signed int numcolors;
/* 32bit - The number of color indices important for displaying the bitmap. */
signed int mincolors;
} bmp_info_t;
#endif
#ifdef __cplusplus
}
#endif
| 2,450 | 20.690265 | 80 |
h
|
php-src
|
php-src-master/ext/gd/libgd/gd2topng.c
|
#include <stdio.h>
#include "gd.h"
/* A short program which converts a .png file into a .gd file, for
your convenience in creating images on the fly from a
basis image that must be loaded quickly. The .gd format
is not intended to be a general-purpose format. */
int
main (int argc, char **argv)
{
gdImagePtr im;
FILE *in, *out;
if (argc != 3)
{
fprintf (stderr, "Usage: gd2topng filename.gd2 filename.png\n");
exit (1);
}
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Input file does not exist!\n");
exit (1);
}
im = gdImageCreateFromGd2 (in);
fclose (in);
if (!im)
{
fprintf (stderr, "Input is not in GD2 format!\n");
exit (1);
}
out = fopen (argv[2], "wb");
if (!out)
{
fprintf (stderr, "Output file cannot be written to!\n");
gdImageDestroy (im);
exit (1);
}
#ifdef HAVE_LIBPNG
gdImagePng (im, out);
#else
fprintf(stderr, "No PNG library support available.\n");
#endif
fclose (out);
gdImageDestroy (im);
return 0;
}
| 1,060 | 20.22 | 70 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_avif.c
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#include "gd.h"
#include "gd_errors.h"
#include "gdhelpers.h"
#include "gd_intern.h"
#ifdef HAVE_LIBAVIF
#include <avif/avif.h>
/*
Define defaults for encoding images:
CHROMA_SUBSAMPLING_DEFAULT: 4:2:0 is commonly used for Chroma subsampling.
CHROMA_SUBAMPLING_HIGH_QUALITY: Use 4:4:4, or no subsampling, when a sufficient high quality is requested.
SUBAMPLING_HIGH_QUALITY_THRESHOLD: At or above this value, use CHROMA_SUBAMPLING_HIGH_QUALITY
QUANTIZER_DEFAULT:
We need more testing to really know what quantizer settings are optimal,
but teams at Google have been using maximum=30 as a starting point.
QUALITY_DEFAULT: following gd conventions, -1 indicates the default.
SPEED_DEFAULT:
AVIF_SPEED_DEFAULT is simply the default encoding speed of the AV1 codec.
This could be as slow as 0. So we use 6, which is currently considered to be a fine default.
*/
#define CHROMA_SUBSAMPLING_DEFAULT AVIF_PIXEL_FORMAT_YUV420
#define CHROMA_SUBAMPLING_HIGH_QUALITY AVIF_PIXEL_FORMAT_YUV444
#define HIGH_QUALITY_SUBSAMPLING_THRESHOLD 90
#define QUANTIZER_DEFAULT 30
#define QUALITY_DEFAULT -1
#define SPEED_DEFAULT 6
// This initial size for the gdIOCtx is standard among GD image conversion functions.
#define NEW_DYNAMIC_CTX_SIZE 2048
// Our quality param ranges from 0 to 100.
// To calculate quality, we convert from AVIF's quantizer scale, which runs from 63 to 0.
#define MAX_QUALITY 100
// These constants are for computing the number of tiles and threads to use during encoding.
// Maximum threads are from libavif/contrib/gkd-pixbuf/loader.c.
#define MIN_TILE_AREA (512 * 512)
#define MAX_TILES 8
#define MAX_THREADS 64
/*** Macros ***/
/*
From gd_png.c:
convert the 7-bit alpha channel to an 8-bit alpha channel.
We do a little bit-flipping magic, repeating the MSB
as the LSB, to ensure that 0 maps to 0 and
127 maps to 255. We also have to invert to match
PNG's convention in which 255 is opaque.
*/
#define alpha7BitTo8Bit(alpha7Bit) \
(alpha7Bit == 127 ? \
0 : \
255 - ((alpha7Bit << 1) + (alpha7Bit >> 6)))
#define alpha8BitTo7Bit(alpha8Bit) (gdAlphaMax - (alpha8Bit >> 1))
/*** Helper functions ***/
/* Convert the quality param we expose to the quantity params used by libavif.
The *Quantizer* params values can range from 0 to 63, with 0 = highest quality and 63 = worst.
We make the scale 0-100, and we reverse this, so that 0 = worst quality and 100 = highest.
Values below 0 are set to 0, and values below MAX_QUALITY are set to MAX_QUALITY.
*/
static int quality2Quantizer(int quality) {
int clampedQuality = CLAMP(quality, 0, MAX_QUALITY);
float scaleFactor = (float) AVIF_QUANTIZER_WORST_QUALITY / (float) MAX_QUALITY;
return round(scaleFactor * (MAX_QUALITY - clampedQuality));
}
/*
As of February 2021, this algorithm reflects the latest research on how many tiles
and threads to include for a given image size.
This is subject to change as research continues.
Returns false if there was an error, true if all was well.
*/
static avifBool setEncoderTilesAndThreads(avifEncoder *encoder, avifRGBImage *rgb) {
int imageArea, tiles, tilesLog2, encoderTiles;
// _gdImageAvifCtx(), the calling function, checks this operation for overflow
imageArea = rgb->width * rgb->height;
tiles = (int) ceil((double) imageArea / MIN_TILE_AREA);
tiles = MIN(tiles, MAX_TILES);
tiles = MIN(tiles, MAX_THREADS);
// The number of tiles in any dimension will always be a power of 2. We can only specify log(2)tiles.
tilesLog2 = floor(log2(tiles));
// If the image's width is greater than the height, use more tile columns
// than tile rows to make the tile size close to a square.
if (rgb->width >= rgb->height) {
encoder->tileRowsLog2 = tilesLog2 / 2;
encoder->tileColsLog2 = tilesLog2 - encoder->tileRowsLog2;
} else {
encoder->tileColsLog2 = tilesLog2 / 2;
encoder->tileRowsLog2 = tilesLog2 - encoder->tileColsLog2;
}
// It's good to have one thread per tile.
encoderTiles = (1 << encoder->tileRowsLog2) * (1 << encoder->tileColsLog2);
encoder->maxThreads = encoderTiles;
return AVIF_TRUE;
}
/*
We can handle AVIF images whose color profile is sRGB, or whose color profile isn't set.
*/
static avifBool isAvifSrgbImage(avifImage *avifIm) {
return
(avifIm->colorPrimaries == AVIF_COLOR_PRIMARIES_BT709 ||
avifIm->colorPrimaries == AVIF_COLOR_PRIMARIES_UNSPECIFIED) &&
(avifIm->transferCharacteristics == AVIF_TRANSFER_CHARACTERISTICS_SRGB ||
avifIm->transferCharacteristics == AVIF_TRANSFER_CHARACTERISTICS_UNSPECIFIED)
;
}
/*
Check the result from an Avif function to see if it's an error.
If so, decode the error and output it, and return true.
Otherwise, return false.
*/
static avifBool isAvifError(avifResult result, const char *msg) {
if (result != AVIF_RESULT_OK) {
gd_error("avif error - %s: %s\n", msg, avifResultToString(result));
return AVIF_TRUE;
}
return AVIF_FALSE;
}
typedef struct avifIOCtxReader {
avifIO io; // this must be the first member for easy casting to avifIO*
avifROData rodata;
} avifIOCtxReader;
/*
<readfromCtx> implements the avifIOReadFunc interface by calling the relevant functions
in the gdIOCtx. Our logic is inspired by avifIOMemoryReaderRead() and avifIOFileReaderRead().
We don't know whether we're reading from a file or from memory. We don't have to know,
since we rely on the helper functions in the gdIOCtx.
We assume we've stashed the gdIOCtx in io->data, as we do in createAvifIOFromCtx().
We ignore readFlags, just as the avifIO*ReaderRead() functions do.
If there's a problem, this returns an avifResult error.
If things go well, return AVIF_RESULT_OK.
Of course these AVIF codes shouldn't be returned by any top-level GD function.
*/
static avifResult readFromCtx(avifIO *io, uint32_t readFlags, uint64_t offset, size_t size, avifROData *out)
{
gdIOCtx *ctx = (gdIOCtx *) io->data;
avifIOCtxReader *reader = (avifIOCtxReader *) io;
// readFlags is unsupported
if (readFlags != 0) {
return AVIF_RESULT_IO_ERROR;
}
// TODO: if we set sizeHint, this will be more efficient.
if (offset > INT_MAX || size > INT_MAX)
return AVIF_RESULT_IO_ERROR;
// Try to seek offset bytes forward. If we pass the end of the buffer, throw an error.
if (!ctx->seek(ctx, (int) offset))
return AVIF_RESULT_IO_ERROR;
if (size > reader->rodata.size) {
reader->rodata.data = gdRealloc((void *) reader->rodata.data, size);
reader->rodata.size = size;
}
if (!reader->rodata.data) {
gd_error("avif error - couldn't allocate memory");
return AVIF_RESULT_UNKNOWN_ERROR;
}
// Read the number of bytes requested.
// If getBuf() returns a negative value, that means there was an error.
int charsRead = ctx->getBuf(ctx, (void *) reader->rodata.data, (int) size);
if (charsRead < 0) {
return AVIF_RESULT_IO_ERROR;
}
out->data = reader->rodata.data;
out->size = charsRead;
return AVIF_RESULT_OK;
}
// avif.h says this is optional, but it seemed easy to implement.
static void destroyAvifIO(struct avifIO *io) {
avifIOCtxReader *reader = (avifIOCtxReader *) io;
if (reader->rodata.data != NULL) {
gdFree((void *) reader->rodata.data);
}
gdFree(reader);
}
/* Set up an avifIO object.
The functions in the gdIOCtx struct may point either to a file or a memory buffer.
To us, that's immaterial.
Our task is simply to assign avifIO functions to the proper functions from gdIOCtx.
The destroy function needs to destroy the avifIO object and anything else it uses.
Returns NULL if memory for the object can't be allocated.
*/
// TODO: can we get sizeHint somehow?
static avifIO *createAvifIOFromCtx(gdIOCtx *ctx) {
struct avifIOCtxReader *reader;
reader = gdMalloc(sizeof(*reader));
if (reader == NULL)
return NULL;
// TODO: setting persistent=FALSE is safe, but it's less efficient. Is it necessary?
reader->io.persistent = AVIF_FALSE;
reader->io.read = readFromCtx;
reader->io.write = NULL; // this function is currently unused; see avif.h
reader->io.destroy = destroyAvifIO;
reader->io.sizeHint = 0; // sadly, we don't get this information from the gdIOCtx.
reader->io.data = ctx;
reader->rodata.data = NULL;
reader->rodata.size = 0;
return (avifIO *) reader;
}
/*** Decoding functions ***/
/*
Function: gdImageCreateFromAvif
<gdImageCreateFromAvif> is called to load truecolor images from
AVIF format files. Invoke <gdImageCreateFromAvif> with an
already opened pointer to a file containing the desired
image. <gdImageCreateFromAvif> returns a <gdImagePtr> to the new
truecolor image, or NULL if unable to load the image (most often
because the file is corrupt or does not contain a AVIF
image). <gdImageCreateFromAvif> does not close the file.
This function creates a gdIOCtx struct from the file pointer it's passed.
And then it relies on <gdImageCreateFromAvifCtx> to do the real decoding work.
If the file contains an image sequence, we simply read the first one, discarding the rest.
Variants:
<gdImageCreateFromAvifPtr> creates an image from AVIF data
already in memory.
<gdImageCreateFromAvifCtx> reads data from the function
pointers in a <gdIOCtx> structure.
Parameters:
infile - pointer to the input file
Returns:
A pointer to the new truecolor image. This will need to be
destroyed with <gdImageDestroy> once it is no longer needed.
On error, returns 0.
*/
gdImagePtr gdImageCreateFromAvif(FILE *infile)
{
gdImagePtr im;
gdIOCtx *ctx = gdNewFileCtx(infile);
if (!ctx)
return NULL;
im = gdImageCreateFromAvifCtx(ctx);
ctx->gd_free(ctx);
return im;
}
/*
Function: gdImageCreateFromAvifPtr
See <gdImageCreateFromAvif>.
Parameters:
size - size of Avif data in bytes.
data - pointer to Avif data.
*/
gdImagePtr gdImageCreateFromAvifPtr(int size, void *data)
{
gdImagePtr im;
gdIOCtx *ctx = gdNewDynamicCtxEx(size, data, 0);
if (!ctx)
return 0;
im = gdImageCreateFromAvifCtx(ctx);
ctx->gd_free(ctx);
return im;
}
/*
Function: gdImageCreateFromAvifCtx
See <gdImageCreateFromAvif>.
Additional details: the AVIF library comes with functions to create an IO object from
a file and from a memory pointer. Of course, it doesn't have a way to create an IO object
from a gdIOCtx. So, here, we use our own helper function, <createAvifIOfromCtx>.
Otherwise, we create the image by calling AVIF library functions in order:
* avifDecoderCreate(), to create the decoder
* avifDecoderSetIO(), to tell libavif how to read from our data structure
* avifDecoderParse(), to parse the image
* avifDecoderNextImage(), to read the first image from the decoder
* avifRGBImageSetDefaults(), to create the avifRGBImage
* avifRGBImageAllocatePixels(), to allocate memory for the pixels
* avifImageYUVToRGB(), to convert YUV to RGB
Finally, we create a new gd image and copy over the pixel data.
Parameters:
ctx - a gdIOCtx struct
*/
gdImagePtr gdImageCreateFromAvifCtx (gdIOCtx *ctx)
{
uint32_t x, y;
gdImage *im = NULL;
avifResult result;
avifIO *io;
avifDecoder *decoder;
avifRGBImage rgb;
// this lets us know that memory hasn't been allocated yet for the pixels
rgb.pixels = NULL;
decoder = avifDecoderCreate();
// Check if libavif version is >= 0.9.1
// If so, allow the PixelInformationProperty ('pixi') to be missing in AV1 image
// items. libheif v1.11.0 or older does not add the 'pixi' item property to
// AV1 image items. (This issue has been corrected in libheif v1.12.0.)
#if AVIF_VERSION >= 90100
decoder->strictFlags &= ~AVIF_STRICT_PIXI_REQUIRED;
#endif
io = createAvifIOFromCtx(ctx);
if (!io) {
gd_error("avif error - Could not allocate memory");
goto cleanup;
}
avifDecoderSetIO(decoder, io);
result = avifDecoderParse(decoder);
if (isAvifError(result, "Could not parse image"))
goto cleanup;
// Note again that, for an image sequence, we read only the first image, ignoring the rest.
result = avifDecoderNextImage(decoder);
if (isAvifError(result, "Could not decode image"))
goto cleanup;
if (!isAvifSrgbImage(decoder->image))
gd_error_ex(GD_NOTICE, "Image's color profile is not sRGB");
// Set up the avifRGBImage, and convert it from YUV to an 8-bit RGB image.
// (While AVIF image pixel depth can be 8, 10, or 12 bits, GD truecolor images are 8-bit.)
avifRGBImageSetDefaults(&rgb, decoder->image);
rgb.depth = 8;
avifRGBImageAllocatePixels(&rgb);
result = avifImageYUVToRGB(decoder->image, &rgb);
if (isAvifError(result, "Conversion from YUV to RGB failed"))
goto cleanup;
im = gdImageCreateTrueColor(decoder->image->width, decoder->image->height);
if (!im) {
gd_error("avif error - Could not create GD truecolor image");
goto cleanup;
}
im->saveAlphaFlag = 1;
// Read the pixels from the AVIF image and copy them into the GD image.
uint8_t *p = rgb.pixels;
for (y = 0; y < decoder->image->height; y++) {
for (x = 0; x < decoder->image->width; x++) {
uint8_t r = *(p++);
uint8_t g = *(p++);
uint8_t b = *(p++);
uint8_t a = alpha8BitTo7Bit(*(p++));
im->tpixels[y][x] = gdTrueColorAlpha(r, g, b, a);
}
}
cleanup:
// if io has been allocated, this frees it
avifDecoderDestroy(decoder);
if (rgb.pixels)
avifRGBImageFreePixels(&rgb);
return im;
}
/*** Encoding functions ***/
/*
Function: gdImageAvifEx
<gdImageAvifEx> outputs the specified image to the specified file in
AVIF format. The file must be open for writing. Under MSDOS and
all versions of Windows, it is important to use "wb" as opposed to
simply "w" as the mode when opening the file, and under Unix there
is no penalty for doing so. <gdImageAvifEx> does not close the file;
your code must do so.
Variants:
<gdImageAvifEx> writes the image to a file, encoding with the default quality and speed.
<gdImageAvifPtrEx> stores the image in RAM.
<gdImageAvifPtr> stores the image in RAM, encoding with the default quality and speed.
<gdImageAvifCtx> stores the image using a <gdIOCtx> struct.
Parameters:
im - The image to save.
outFile - The FILE pointer to write to.
quality - Compression quality (0-100). 0 is lowest-quality, 100 is highest.
speed - The speed of compression (0-10). 0 is slowest, 10 is fastest.
Notes on parameters:
quality - If quality = -1, we use a default quality as defined in QUALITY_DEFAULT.
For information on how we convert this quality to libavif's quantity param, see <quality2Quantizer>.
speed - At slower speeds, encoding may be quite slow. Use judiciously.
Qualities or speeds that are lower than the minimum value get clamped to the minimum value,
and qualities or speeds that are lower than the maximum value get clamped to the maxmum value.
Note that AVIF_SPEED_DEFAULT is -1. If we ever set SPEED_DEFAULT = AVIF_SPEED_DEFAULT,
we'd want to add a conditional to ensure that value doesn't get clamped.
Returns:
* for <gdImageAvifEx>, <gdImageAvif>, and <gdImageAvifCtx>, nothing.
* for <gdImageAvifPtrEx> and <gdImageAvifPtr>, a pointer to the image in memory.
*/
/*
If we're passed the QUALITY_DEFAULT of -1, set the quantizer params to QUANTIZER_DEFAULT.
*/
void gdImageAvifCtx(gdImagePtr im, gdIOCtx *outfile, int quality, int speed)
{
avifResult result;
avifRGBImage rgb;
avifRWData avifOutput = AVIF_DATA_EMPTY;
avifBool lossless = quality == 100;
avifEncoder *encoder = NULL;
uint32_t val;
uint8_t *p;
uint32_t x, y;
if (im == NULL)
return;
if (!gdImageTrueColor(im)) {
gd_error("avif error - avif doesn't support palette images");
return;
}
if (!gdImageSX(im) || !gdImageSY(im)) {
gd_error("avif error - image dimensions must not be zero");
return;
}
if (overflow2(gdImageSX(im), gdImageSY(im))) {
gd_error("avif error - image dimensions are too large");
return;
}
speed = CLAMP(speed, AVIF_SPEED_SLOWEST, AVIF_SPEED_FASTEST);
avifPixelFormat subsampling = quality >= HIGH_QUALITY_SUBSAMPLING_THRESHOLD ?
CHROMA_SUBAMPLING_HIGH_QUALITY : CHROMA_SUBSAMPLING_DEFAULT;
// Create the AVIF image.
// Set the ICC to sRGB, as that's what gd supports right now.
// Note that MATRIX_COEFFICIENTS_IDENTITY enables lossless conversion from RGB to YUV.
avifImage *avifIm = avifImageCreate(gdImageSX(im), gdImageSY(im), 8, subsampling);
avifIm->colorPrimaries = AVIF_COLOR_PRIMARIES_BT709;
avifIm->transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_SRGB;
avifIm->matrixCoefficients = lossless ? AVIF_MATRIX_COEFFICIENTS_IDENTITY : AVIF_MATRIX_COEFFICIENTS_BT709;
avifRGBImageSetDefaults(&rgb, avifIm);
// this allocates memory, and sets rgb.rowBytes and rgb.pixels.
avifRGBImageAllocatePixels(&rgb);
// Parse RGB data from the GD image, and copy it into the AVIF RGB image.
// Convert 7-bit GD alpha channel values to 8-bit AVIF values.
p = rgb.pixels;
for (y = 0; y < rgb.height; y++) {
for (x = 0; x < rgb.width; x++) {
val = im->tpixels[y][x];
*(p++) = gdTrueColorGetRed(val);
*(p++) = gdTrueColorGetGreen(val);
*(p++) = gdTrueColorGetBlue(val);
*(p++) = alpha7BitTo8Bit(gdTrueColorGetAlpha(val));
}
}
// Convert the RGB image to YUV.
result = avifImageRGBToYUV(avifIm, &rgb);
if (isAvifError(result, "Could not convert image to YUV"))
goto cleanup;
// Encode the image in AVIF format.
encoder = avifEncoderCreate();
int quantizerQuality = quality == QUALITY_DEFAULT ?
QUANTIZER_DEFAULT : quality2Quantizer(quality);
encoder->minQuantizer = quantizerQuality;
encoder->maxQuantizer = quantizerQuality;
encoder->minQuantizerAlpha = quantizerQuality;
encoder->maxQuantizerAlpha = quantizerQuality;
encoder->speed = speed;
if (!setEncoderTilesAndThreads(encoder, &rgb))
goto cleanup;
//TODO: is there a reason to use timeSscales != 1?
result = avifEncoderAddImage(encoder, avifIm, 1, AVIF_ADD_IMAGE_FLAG_SINGLE);
if (isAvifError(result, "Could not encode image"))
goto cleanup;
result = avifEncoderFinish(encoder, &avifOutput);
if (isAvifError(result, "Could not finish encoding"))
goto cleanup;
// Write the AVIF image bytes to the GD ctx.
gdPutBuf(avifOutput.data, avifOutput.size, outfile);
cleanup:
if (rgb.pixels)
avifRGBImageFreePixels(&rgb);
if (encoder)
avifEncoderDestroy(encoder);
if (avifOutput.data)
avifRWDataFree(&avifOutput);
if (avifIm)
avifImageDestroy(avifIm);
}
void gdImageAvifEx(gdImagePtr im, FILE *outFile, int quality, int speed)
{
gdIOCtx *out = gdNewFileCtx(outFile);
if (out != NULL) {
gdImageAvifCtx(im, out, quality, speed);
out->gd_free(out);
}
}
void gdImageAvif(gdImagePtr im, FILE *outFile)
{
gdImageAvifEx(im, outFile, QUALITY_DEFAULT, SPEED_DEFAULT);
}
void * gdImageAvifPtrEx(gdImagePtr im, int *size, int quality, int speed)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(NEW_DYNAMIC_CTX_SIZE, NULL);
if (out == NULL) {
return NULL;
}
gdImageAvifCtx(im, out, quality, speed);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
void * gdImageAvifPtr(gdImagePtr im, int *size)
{
return gdImageAvifPtrEx(im, size, QUALITY_DEFAULT, AVIF_SPEED_DEFAULT);
}
#endif /* HAVE_LIBAVIF */
| 19,183 | 29.258675 | 108 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_color_match.c
|
#include "gd.h"
#include "gdhelpers.h"
#include "gd_intern.h"
#include "php.h"
/* bring the palette colors in im2 to be closer to im1
*
*/
int gdImageColorMatch (gdImagePtr im1, gdImagePtr im2)
{
unsigned long *buf; /* stores our calculations */
unsigned long *bp; /* buf ptr */
int color, rgb;
int x,y;
int count;
if( !im1->trueColor ) {
return -1; /* im1 must be True Color */
}
if( im2->trueColor ) {
return -2; /* im2 must be indexed */
}
if( (im1->sx != im2->sx) || (im1->sy != im2->sy) ) {
return -3; /* the images are meant to be the same dimensions */
}
if (im2->colorsTotal<1) {
return -4; /* At least 1 color must be allocated */
}
buf = (unsigned long *)safe_emalloc(sizeof(unsigned long), 5 * gdMaxColors, 0);
memset( buf, 0, sizeof(unsigned long) * 5 * gdMaxColors );
for (x=0; x<im1->sx; x++) {
for( y=0; y<im1->sy; y++ ) {
color = im2->pixels[y][x];
rgb = im1->tpixels[y][x];
bp = buf + (color * 5);
(*(bp++))++;
*(bp++) += gdTrueColorGetRed(rgb);
*(bp++) += gdTrueColorGetGreen(rgb);
*(bp++) += gdTrueColorGetBlue(rgb);
*(bp++) += gdTrueColorGetAlpha(rgb);
}
}
bp = buf;
for (color=0; color<im2->colorsTotal; color++) {
count = *(bp++);
if( count > 0 ) {
im2->red[color] = *(bp++) / count;
im2->green[color] = *(bp++) / count;
im2->blue[color] = *(bp++) / count;
im2->alpha[color] = *(bp++) / count;
} else {
bp += 4;
}
}
gdFree(buf);
return 0;
}
| 1,454 | 22.095238 | 80 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_crop.c
|
/**
* Title: Crop
*
* A couple of functions to crop images, automatically (auto detection of
* the borders color), using a given color (with or without tolerance)
* or using a selection.
*
* The threshold method works relatively well but it can be improved.
* Maybe L*a*b* and Delta-E will give better results (and a better
* granularity).
*
* Example:
* (start code)
* im2 = gdImageAutoCrop(im, GD_CROP_SIDES);
* if (im2) {
* }
* gdImageDestroy(im2);
* (end code)
**/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "gd.h"
static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color);
static int gdColorMatch(gdImagePtr im, int col1, int col2, float threshold);
/**
* Function: gdImageCrop
* Crops the src image using the area defined by the <crop> rectangle.
* The result is returned as a new image.
*
*
* Parameters:
* src - Source image
* crop - Rectangular region to crop
*
* Returns:
* <gdImagePtr> on success or NULL
*/
gdImagePtr gdImageCrop(gdImagePtr src, const gdRectPtr crop)
{
gdImagePtr dst;
int alphaBlendingFlag;
if (gdImageTrueColor(src)) {
dst = gdImageCreateTrueColor(crop->width, crop->height);
} else {
dst = gdImageCreate(crop->width, crop->height);
}
if (!dst) return NULL;
alphaBlendingFlag = dst->alphaBlendingFlag;
gdImageAlphaBlending(dst, gdEffectReplace);
gdImageCopy(dst, src, 0, 0, crop->x, crop->y, crop->width, crop->height);
gdImageAlphaBlending(dst, alphaBlendingFlag);
return dst;
}
/**
* Function: gdImageAutoCrop
* Automatic croping of the src image using the given mode
* (see <gdCropMode>)
*
*
* Parameters:
* im - Source image
* mode - crop mode
*
* Returns:
* <gdImagePtr> on success or NULL
*
* See also:
* <gdCropMode>
*/
gdImagePtr gdImageCropAuto(gdImagePtr im, const unsigned int mode)
{
const int width = gdImageSX(im);
const int height = gdImageSY(im);
int x,y;
int color, match;
gdRect crop;
crop.x = 0;
crop.y = 0;
crop.width = 0;
crop.height = 0;
switch (mode) {
case GD_CROP_TRANSPARENT:
color = gdImageGetTransparent(im);
break;
case GD_CROP_BLACK:
color = gdImageColorClosestAlpha(im, 0, 0, 0, 0);
break;
case GD_CROP_WHITE:
color = gdImageColorClosestAlpha(im, 255, 255, 255, 0);
break;
case GD_CROP_SIDES:
gdGuessBackgroundColorFromCorners(im, &color);
break;
case GD_CROP_DEFAULT:
default:
color = gdImageGetTransparent(im);
break;
}
/* TODO: Add gdImageGetRowPtr and works with ptr at the row level
* for the true color and palette images
* new formats will simply work with ptr
*/
match = 1;
for (y = 0; match && y < height; y++) {
for (x = 0; match && x < width; x++) {
int c2 = gdImageGetPixel(im, x, y);
match = (color == c2);
}
}
/* Whole image would be cropped > bye */
if (match) {
return NULL;
}
crop.y = y - 1;
match = 1;
for (y = height - 1; match && y >= 0; y--) {
for (x = 0; match && x < width; x++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
crop.height = y - crop.y + 2;
match = 1;
for (x = 0; match && x < width; x++) {
for (y = 0; match && y < crop.y + crop.height; y++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
crop.x = x - 1;
match = 1;
for (x = width - 1; match && x >= 0; x--) {
for (y = 0; match && y < crop.y + crop.height; y++) {
match = (color == gdImageGetPixel(im, x,y));
}
}
crop.width = x - crop.x + 2;
return gdImageCrop(im, &crop);
}
/*TODOs: Implement DeltaE instead, way better perceptual differences */
/**
* Function: gdImageThresholdCrop
* Crop an image using a given color. The threshold argument defines
* the tolerance to be used while comparing the image color and the
* color to crop. The method used to calculate the color difference
* is based on the color distance in the RGB(a) cube.
*
*
* Parameters:
* im - Source image
* color - color to crop
* threshold - tolerance (0..100)
*
* Returns:
* <gdImagePtr> on success or NULL
*
* See also:
* <gdCropMode>, <gdImageAutoCrop> or <gdImageCrop>
*/
gdImagePtr gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold)
{
const int width = gdImageSX(im);
const int height = gdImageSY(im);
int x,y;
int match;
gdRect crop;
crop.x = 0;
crop.y = 0;
crop.width = 0;
crop.height = 0;
/* Pierre: crop everything sounds bad */
if (threshold > 100.0) {
return NULL;
}
if (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im)) {
return NULL;
}
/* TODO: Add gdImageGetRowPtr and works with ptr at the row level
* for the true color and palette images
* new formats will simply work with ptr
*/
match = 1;
for (y = 0; match && y < height; y++) {
for (x = 0; match && x < width; x++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
/* Whole image would be cropped > bye */
if (match) {
return NULL;
}
crop.y = y - 1;
match = 1;
for (y = height - 1; match && y >= 0; y--) {
for (x = 0; match && x < width; x++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0;
}
}
crop.height = y - crop.y + 2;
match = 1;
for (x = 0; match && x < width; x++) {
for (y = 0; match && y < crop.y + crop.height; y++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
crop.x = x - 1;
match = 1;
for (x = width - 1; match && x >= 0; x--) {
for (y = 0; match && y < crop.y + crop.height; y++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
crop.width = x - crop.x + 2;
return gdImageCrop(im, &crop);
}
/* This algorithm comes from pnmcrop (http://netpbm.sourceforge.net/)
* Three steps:
* - if 3 corners are equal.
* - if two are equal.
* - Last solution: average the colors
*/
static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color)
{
const int tl = gdImageGetPixel(im, 0, 0);
const int tr = gdImageGetPixel(im, gdImageSX(im) - 1, 0);
const int bl = gdImageGetPixel(im, 0, gdImageSY(im) -1);
const int br = gdImageGetPixel(im, gdImageSX(im) - 1, gdImageSY(im) -1);
if (tr == bl && tr == br) {
*color = tr;
return 3;
} else if (tl == bl && tl == br) {
*color = tl;
return 3;
} else if (tl == tr && tl == br) {
*color = tl;
return 3;
} else if (tl == tr && tl == bl) {
*color = tl;
return 3;
} else if (tl == tr || tl == bl || tl == br) {
*color = tl;
return 2;
} else if (tr == bl || tr == br) {
*color = tr;
return 2;
} else if (br == bl) {
*color = bl;
return 2;
} else {
register int r,b,g,a;
r = (int)(0.5f + (gdImageRed(im, tl) + gdImageRed(im, tr) + gdImageRed(im, bl) + gdImageRed(im, br)) / 4);
g = (int)(0.5f + (gdImageGreen(im, tl) + gdImageGreen(im, tr) + gdImageGreen(im, bl) + gdImageGreen(im, br)) / 4);
b = (int)(0.5f + (gdImageBlue(im, tl) + gdImageBlue(im, tr) + gdImageBlue(im, bl) + gdImageBlue(im, br)) / 4);
a = (int)(0.5f + (gdImageAlpha(im, tl) + gdImageAlpha(im, tr) + gdImageAlpha(im, bl) + gdImageAlpha(im, br)) / 4);
*color = gdImageColorClosestAlpha(im, r, g, b, a);
return 0;
}
}
static int gdColorMatch(gdImagePtr im, int col1, int col2, float threshold)
{
const int dr = gdImageRed(im, col1) - gdImageRed(im, col2);
const int dg = gdImageGreen(im, col1) - gdImageGreen(im, col2);
const int db = gdImageBlue(im, col1) - gdImageBlue(im, col2);
const int da = gdImageAlpha(im, col1) - gdImageAlpha(im, col2);
const int dist = dr * dr + dg * dg + db * db + da * da;
return (100.0 * dist / 195075) < threshold;
}
/*
* To be implemented when we have more image formats.
* Buffer like gray8 gray16 or rgb8 will require some tweak
* and can be done in this function (called from the autocrop
* function. (Pierre)
*/
#if 0
static int colors_equal (const int col1, const in col2)
{
}
#endif
| 7,862 | 23.726415 | 116 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_errors.h
|
#ifndef GD_ERRORS_H
#define GD_ERRORS_H
#ifndef _WIN32
# include <syslog.h>
#else
# include "win32/syslog.h"
#endif
/*
LOG_EMERG system is unusable
LOG_ALERT action must be taken immediately
LOG_CRIT critical conditions
LOG_ERR error conditions
LOG_WARNING warning conditions
LOG_NOTICE normal, but significant, condition
LOG_INFO informational message
LOG_DEBUG debug-level message
*/
#define GD_ERROR LOG_ERR
#define GD_WARNING LOG_WARNING
#define GD_NOTICE LOG_NOTICE
#define GD_INFO LOG_INFO
#define GD_DEBUG LOG_DEBUG
void gd_error(const char *format, ...);
void gd_error_ex(int priority, const char *format, ...);
#endif
| 673 | 20.741935 | 56 |
h
|
php-src
|
php-src-master/ext/gd/libgd/gd_filter.c
|
#include "gd.h"
#include "gd_intern.h"
#ifdef _WIN32
# include <windows.h>
#else
# include <unistd.h>
#endif
#include <stdlib.h>
#include <time.h>
/* Filters function added on 2003/12
* by Pierre-Alain Joye ([email protected])
*
* Scatter filter added in libgd 2.1.0
* by Kalle Sommer Nielsen ([email protected])
**/
/* Begin filters function */
#define GET_PIXEL_FUNCTION(src)(src->trueColor?gdImageGetTrueColorPixel:gdImageGetPixel)
#ifdef _WIN32
# define GD_SCATTER_SEED() (unsigned int)(time(0) * GetCurrentProcessId())
#else
# define GD_SCATTER_SEED() (unsigned int)(time(0) * getpid())
#endif
int gdImageScatter(gdImagePtr im, int sub, int plus)
{
gdScatter s;
s.sub = sub;
s.plus = plus;
s.num_colors = 0;
s.seed = GD_SCATTER_SEED();
return gdImageScatterEx(im, &s);
}
int gdImageScatterColor(gdImagePtr im, int sub, int plus, int colors[], unsigned int num_colors)
{
gdScatter s;
s.sub = sub;
s.plus = plus;
s.colors = colors;
s.num_colors = num_colors;
s.seed = GD_SCATTER_SEED();
return gdImageScatterEx(im, &s);
}
int gdImageScatterEx(gdImagePtr im, gdScatterPtr scatter)
{
register int x, y;
int dest_x, dest_y;
int pxl, new_pxl;
unsigned int n;
int sub = scatter->sub, plus = scatter->plus;
if (plus == 0 && sub == 0) {
return 1;
}
else if (sub >= plus) {
return 0;
}
(void)srand(scatter->seed);
if (scatter->num_colors) {
for (y = 0; y < im->sy; y++) {
for (x = 0; x < im->sx; x++) {
dest_x = (int)(x + ((rand() % (plus - sub)) + sub));
dest_y = (int)(y + ((rand() % (plus - sub)) + sub));
if (!gdImageBoundsSafe(im, dest_x, dest_y)) {
continue;
}
pxl = gdImageGetPixel(im, x, y);
new_pxl = gdImageGetPixel(im, dest_x, dest_y);
for (n = 0; n < scatter->num_colors; n++) {
if (pxl == scatter->colors[n]) {
gdImageSetPixel(im, dest_x, dest_y, pxl);
gdImageSetPixel(im, x, y, new_pxl);
}
}
}
}
}
else {
for (y = 0; y < im->sy; y++) {
for (x = 0; x < im->sx; x++) {
dest_x = (int)(x + ((rand() % (plus - sub)) + sub));
dest_y = (int)(y + ((rand() % (plus - sub)) + sub));
if (!gdImageBoundsSafe(im, dest_x, dest_y)) {
continue;
}
pxl = gdImageGetPixel(im, x, y);
new_pxl = gdImageGetPixel(im, dest_x, dest_y);
gdImageSetPixel(im, dest_x, dest_y, pxl);
gdImageSetPixel(im, x, y, new_pxl);
}
}
}
return 1;
}
/* invert src image */
int gdImageNegate(gdImagePtr src)
{
int x, y;
int r,g,b,a;
int new_pxl, pxl;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src==NULL) {
return 0;
}
f = GET_PIXEL_FUNCTION(src);
for (y=0; y<src->sy; ++y) {
for (x=0; x<src->sx; ++x) {
pxl = f (src, x, y);
r = gdImageRed(src, pxl);
g = gdImageGreen(src, pxl);
b = gdImageBlue(src, pxl);
a = gdImageAlpha(src, pxl);
new_pxl = gdImageColorAllocateAlpha(src, 255-r, 255-g, 255-b, a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, 255-r, 255-g, 255-b, a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
return 1;
}
/* Convert the image src to a grayscale image */
int gdImageGrayScale(gdImagePtr src)
{
int x, y;
int r,g,b,a;
int new_pxl, pxl;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
int alpha_blending;
f = GET_PIXEL_FUNCTION(src);
if (src==NULL) {
return 0;
}
alpha_blending = src->alphaBlendingFlag;
gdImageAlphaBlending(src, gdEffectReplace);
for (y=0; y<src->sy; ++y) {
for (x=0; x<src->sx; ++x) {
pxl = f (src, x, y);
r = gdImageRed(src, pxl);
g = gdImageGreen(src, pxl);
b = gdImageBlue(src, pxl);
a = gdImageAlpha(src, pxl);
r = g = b = (int) (.299 * r + .587 * g + .114 * b);
new_pxl = gdImageColorAllocateAlpha(src, r, g, b, a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, r, g, b, a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
gdImageAlphaBlending(src, alpha_blending);
return 1;
}
/* Set the brightness level <level> for the image src */
int gdImageBrightness(gdImagePtr src, int brightness)
{
int x, y;
int r,g,b,a;
int new_pxl, pxl;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
f = GET_PIXEL_FUNCTION(src);
if (src==NULL || (brightness < -255 || brightness>255)) {
return 0;
}
if (brightness==0) {
return 1;
}
for (y=0; y<src->sy; ++y) {
for (x=0; x<src->sx; ++x) {
pxl = f (src, x, y);
r = gdImageRed(src, pxl);
g = gdImageGreen(src, pxl);
b = gdImageBlue(src, pxl);
a = gdImageAlpha(src, pxl);
r = r + brightness;
g = g + brightness;
b = b + brightness;
r = (r > 255)? 255 : ((r < 0)? 0:r);
g = (g > 255)? 255 : ((g < 0)? 0:g);
b = (b > 255)? 255 : ((b < 0)? 0:b);
new_pxl = gdImageColorAllocateAlpha(src, (int)r, (int)g, (int)b, a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, (int)r, (int)g, (int)b, a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
return 1;
}
int gdImageContrast(gdImagePtr src, double contrast)
{
int x, y;
int r,g,b,a;
double rf,gf,bf;
int new_pxl, pxl;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
f = GET_PIXEL_FUNCTION(src);
if (src==NULL) {
return 0;
}
contrast = (double)(100.0-contrast)/100.0;
contrast = contrast*contrast;
for (y=0; y<src->sy; ++y) {
for (x=0; x<src->sx; ++x) {
pxl = f(src, x, y);
r = gdImageRed(src, pxl);
g = gdImageGreen(src, pxl);
b = gdImageBlue(src, pxl);
a = gdImageAlpha(src, pxl);
rf = (double)r/255.0;
rf = rf-0.5;
rf = rf*contrast;
rf = rf+0.5;
rf = rf*255.0;
bf = (double)b/255.0;
bf = bf-0.5;
bf = bf*contrast;
bf = bf+0.5;
bf = bf*255.0;
gf = (double)g/255.0;
gf = gf-0.5;
gf = gf*contrast;
gf = gf+0.5;
gf = gf*255.0;
rf = (rf > 255.0)? 255.0 : ((rf < 0.0)? 0.0:rf);
gf = (gf > 255.0)? 255.0 : ((gf < 0.0)? 0.0:gf);
bf = (bf > 255.0)? 255.0 : ((bf < 0.0)? 0.0:bf);
new_pxl = gdImageColorAllocateAlpha(src, (int)rf, (int)gf, (int)bf, a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, (int)rf, (int)gf, (int)bf, a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
return 1;
}
int gdImageColor(gdImagePtr src, const int red, const int green, const int blue, const int alpha)
{
int x, y;
int new_pxl, pxl;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src == NULL) {
return 0;
}
f = GET_PIXEL_FUNCTION(src);
for (y=0; y<src->sy; ++y) {
for (x=0; x<src->sx; ++x) {
int r,g,b,a;
pxl = f(src, x, y);
r = gdImageRed(src, pxl);
g = gdImageGreen(src, pxl);
b = gdImageBlue(src, pxl);
a = gdImageAlpha(src, pxl);
r = r + red;
g = g + green;
b = b + blue;
a = a + alpha;
r = (r > 255)? 255 : ((r < 0)? 0 : r);
g = (g > 255)? 255 : ((g < 0)? 0 : g);
b = (b > 255)? 255 : ((b < 0)? 0 : b);
a = (a > 127)? 127 : ((a < 0)? 0 : a);
new_pxl = gdImageColorAllocateAlpha(src, r, g, b, a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, r, g, b, a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
return 1;
}
int gdImageConvolution(gdImagePtr src, float filter[3][3], float filter_div, float offset)
{
int x, y, i, j, new_a;
float new_r, new_g, new_b;
int new_pxl, pxl=0;
gdImagePtr srcback;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src==NULL) {
return 0;
}
/* We need the orinal image with each safe neoghb. pixel */
srcback = gdImageCreateTrueColor (src->sx, src->sy);
if (srcback==NULL) {
return 0;
}
gdImageSaveAlpha(srcback, 1);
new_pxl = gdImageColorAllocateAlpha(srcback, 0, 0, 0, 127);
gdImageFill(srcback, 0, 0, new_pxl);
gdImageCopy(srcback, src,0,0,0,0,src->sx,src->sy);
f = GET_PIXEL_FUNCTION(src);
for ( y=0; y<src->sy; y++) {
for(x=0; x<src->sx; x++) {
new_r = new_g = new_b = 0;
pxl = f(srcback, x, y);
new_a = gdImageAlpha(srcback, pxl);
for (j=0; j<3; j++) {
int yv = MIN(MAX(y - 1 + j, 0), src->sy - 1);
for (i=0; i<3; i++) {
pxl = f(srcback, MIN(MAX(x - 1 + i, 0), src->sx - 1), yv);
new_r += (float)gdImageRed(srcback, pxl) * filter[j][i];
new_g += (float)gdImageGreen(srcback, pxl) * filter[j][i];
new_b += (float)gdImageBlue(srcback, pxl) * filter[j][i];
}
}
new_r = (new_r/filter_div)+offset;
new_g = (new_g/filter_div)+offset;
new_b = (new_b/filter_div)+offset;
new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r);
new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g);
new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b);
new_pxl = gdImageColorAllocateAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
gdImageDestroy(srcback);
return 1;
}
int gdImageSelectiveBlur( gdImagePtr src)
{
int x, y, i, j;
float new_r, new_g, new_b;
int new_pxl, cpxl, pxl, new_a=0;
float flt_r [3][3];
float flt_g [3][3];
float flt_b [3][3];
float flt_r_sum, flt_g_sum, flt_b_sum;
gdImagePtr srcback;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src==NULL) {
return 0;
}
/* We need the orinal image with each safe neoghb. pixel */
srcback = gdImageCreateTrueColor (src->sx, src->sy);
if (srcback==NULL) {
return 0;
}
gdImageCopy(srcback, src,0,0,0,0,src->sx,src->sy);
f = GET_PIXEL_FUNCTION(src);
for(y = 0; y<src->sy; y++) {
for (x=0; x<src->sx; x++) {
flt_r_sum = flt_g_sum = flt_b_sum = 0.0;
cpxl = f(src, x, y);
for (j=0; j<3; j++) {
for (i=0; i<3; i++) {
if ((j == 1) && (i == 1)) {
flt_r[1][1] = flt_g[1][1] = flt_b[1][1] = 0.5;
} else {
pxl = f(src, x-(3>>1)+i, y-(3>>1)+j);
new_a = gdImageAlpha(srcback, pxl);
new_r = ((float)gdImageRed(srcback, cpxl)) - ((float)gdImageRed (srcback, pxl));
if (new_r < 0.0f) {
new_r = -new_r;
}
if (new_r != 0) {
flt_r[j][i] = 1.0f/new_r;
} else {
flt_r[j][i] = 1.0f;
}
new_g = ((float)gdImageGreen(srcback, cpxl)) - ((float)gdImageGreen(srcback, pxl));
if (new_g < 0.0f) {
new_g = -new_g;
}
if (new_g != 0) {
flt_g[j][i] = 1.0f/new_g;
} else {
flt_g[j][i] = 1.0f;
}
new_b = ((float)gdImageBlue(srcback, cpxl)) - ((float)gdImageBlue(srcback, pxl));
if (new_b < 0.0f) {
new_b = -new_b;
}
if (new_b != 0) {
flt_b[j][i] = 1.0f/new_b;
} else {
flt_b[j][i] = 1.0f;
}
}
flt_r_sum += flt_r[j][i];
flt_g_sum += flt_g[j][i];
flt_b_sum += flt_b [j][i];
}
}
for (j=0; j<3; j++) {
for (i=0; i<3; i++) {
if (flt_r_sum != 0.0) {
flt_r[j][i] /= flt_r_sum;
}
if (flt_g_sum != 0.0) {
flt_g[j][i] /= flt_g_sum;
}
if (flt_b_sum != 0.0) {
flt_b [j][i] /= flt_b_sum;
}
}
}
new_r = new_g = new_b = 0.0;
for (j=0; j<3; j++) {
for (i=0; i<3; i++) {
pxl = f(src, x-(3>>1)+i, y-(3>>1)+j);
new_r += (float)gdImageRed(srcback, pxl) * flt_r[j][i];
new_g += (float)gdImageGreen(srcback, pxl) * flt_g[j][i];
new_b += (float)gdImageBlue(srcback, pxl) * flt_b[j][i];
}
}
new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r);
new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g);
new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b);
new_pxl = gdImageColorAllocateAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a);
if (new_pxl == -1) {
new_pxl = gdImageColorClosestAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a);
}
gdImageSetPixel (src, x, y, new_pxl);
}
}
gdImageDestroy(srcback);
return 1;
}
int gdImageEdgeDetectQuick(gdImagePtr src)
{
float filter[3][3] = {{-1.0,0.0,-1.0},
{0.0,4.0,0.0},
{-1.0,0.0,-1.0}};
return gdImageConvolution(src, filter, 1, 127);
}
int gdImageGaussianBlur(gdImagePtr im)
{
float filter[3][3] = {{1.0,2.0,1.0},
{2.0,4.0,2.0},
{1.0,2.0,1.0}};
return gdImageConvolution(im, filter, 16, 0);
}
int gdImageEmboss(gdImagePtr im)
{
/*
float filter[3][3] = {{1.0,1.0,1.0},
{0.0,0.0,0.0},
{-1.0,-1.0,-1.0}};
*/
float filter[3][3] = {{ 1.5, 0.0, 0.0},
{ 0.0, 0.0, 0.0},
{ 0.0, 0.0,-1.5}};
return gdImageConvolution(im, filter, 1, 127);
}
int gdImageMeanRemoval(gdImagePtr im)
{
float filter[3][3] = {{-1.0,-1.0,-1.0},
{-1.0,9.0,-1.0},
{-1.0,-1.0,-1.0}};
return gdImageConvolution(im, filter, 1, 0);
}
int gdImageSmooth(gdImagePtr im, float weight)
{
float filter[3][3] = {{1.0,1.0,1.0},
{1.0,0.0,1.0},
{1.0,1.0,1.0}};
filter[1][1] = weight;
return gdImageConvolution(im, filter, weight+8, 0);
}
/* End filters function */
| 12,819 | 21.570423 | 97 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_io.h
|
#ifndef GD_IO_H
#define GD_IO_H 1
#include <stdio.h>
#ifdef VMS
#define Putchar gdPutchar
#endif
typedef struct gdIOCtx {
int (*getC)(struct gdIOCtx*);
int (*getBuf)(struct gdIOCtx*, void*, int);
void (*putC)(struct gdIOCtx*, int);
int (*putBuf)(struct gdIOCtx*, const void*, int);
int (*seek)(struct gdIOCtx*, const int);
long (*tell)(struct gdIOCtx*);
void (*gd_free)(struct gdIOCtx*);
void *data;
} gdIOCtx;
typedef struct gdIOCtx *gdIOCtxPtr;
void Putword(int w, gdIOCtx *ctx);
void Putchar(int c, gdIOCtx *ctx);
void gdPutC(const unsigned char c, gdIOCtx *ctx);
int gdPutBuf(const void *, int, gdIOCtx*);
void gdPutWord(int w, gdIOCtx *ctx);
void gdPutInt(int w, gdIOCtx *ctx);
int gdGetC(gdIOCtx *ctx);
int gdGetBuf(void *, int, gdIOCtx*);
int gdGetByte(int *result, gdIOCtx *ctx);
int gdGetWord(int *result, gdIOCtx *ctx);
int gdGetWordLSB(signed short int *result, gdIOCtx *ctx);
int gdGetInt(int *result, gdIOCtx *ctx);
int gdGetIntLSB(signed int *result, gdIOCtx *ctx);
int gdSeek(gdIOCtx *ctx, const int);
long gdTell(gdIOCtx *ctx);
#endif
| 1,072 | 21.829787 | 57 |
h
|
php-src
|
php-src-master/ext/gd/libgd/gd_matrix.c
|
#include "gd.h"
#include <math.h>
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
/**
* Title: Matrix
* Group: Affine Matrix
*/
/**
* Function: gdAffineApplyToPointF
* Applies an affine transformation to a point (floating point
* gdPointF)
*
*
* Parameters:
* dst - Where to store the resulting point
* affine - Source Point
* flip_horz - affine matrix
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdAffineApplyToPointF (gdPointFPtr dst, const gdPointFPtr src,
const double affine[6])
{
double x = src->x;
double y = src->y;
dst->x = x * affine[0] + y * affine[2] + affine[4];
dst->y = x * affine[1] + y * affine[3] + affine[5];
return GD_TRUE;
}
/**
* Function: gdAffineInvert
* Find the inverse of an affine transformation.
*
* All non-degenerate affine transforms are invertible. Applying the
* inverted matrix will restore the original values. Multiplying <src>
* by <dst> (commutative) will return the identity affine (rounding
* error possible).
*
* Parameters:
* dst - Where to store the resulting affine transform
* src_affine - Original affine matrix
* flip_horz - Whether or not to flip horizontally
* flip_vert - Whether or not to flip vertically
*
* See also:
* <gdAffineIdentity>
*
* Returns:
* GD_TRUE on success or GD_FALSE on failure
*/
int gdAffineInvert (double dst[6], const double src[6])
{
double r_det = (src[0] * src[3] - src[1] * src[2]);
if (r_det <= 0.0) {
return GD_FALSE;
}
r_det = 1.0 / r_det;
dst[0] = src[3] * r_det;
dst[1] = -src[1] * r_det;
dst[2] = -src[2] * r_det;
dst[3] = src[0] * r_det;
dst[4] = -src[4] * dst[0] - src[5] * dst[2];
dst[5] = -src[4] * dst[1] - src[5] * dst[3];
return GD_TRUE;
}
/**
* Function: gdAffineFlip
* Flip an affine transformation horizontally or vertically.
*
* Flips the affine transform, giving GD_FALSE for <flip_horz> and
* <flip_vert> will clone the affine matrix. GD_TRUE for both will
* copy a 180° rotation.
*
* Parameters:
* dst - Where to store the resulting affine transform
* src_affine - Original affine matrix
* flip_h - Whether or not to flip horizontally
* flip_v - Whether or not to flip vertically
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineFlip (double dst[6], const double src[6], const int flip_h, const int flip_v)
{
dst[0] = flip_h ? - src[0] : src[0];
dst[1] = flip_h ? - src[1] : src[1];
dst[2] = flip_v ? - src[2] : src[2];
dst[3] = flip_v ? - src[3] : src[3];
dst[4] = flip_h ? - src[4] : src[4];
dst[5] = flip_v ? - src[5] : src[5];
return GD_TRUE;
}
/**
* Function: gdAffineConcat
* Concat (Multiply) two affine transformation matrices.
*
* Concats two affine transforms together, i.e. the result
* will be the equivalent of doing first the transformation m1 and then
* m2. All parameters can be the same matrix (safe to call using
* the same array for all three arguments).
*
* Parameters:
* dst - Where to store the resulting affine transform
* m1 - First affine matrix
* m2 - Second affine matrix
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineConcat (double dst[6], const double m1[6], const double m2[6])
{
double dst0, dst1, dst2, dst3, dst4, dst5;
dst0 = m1[0] * m2[0] + m1[1] * m2[2];
dst1 = m1[0] * m2[1] + m1[1] * m2[3];
dst2 = m1[2] * m2[0] + m1[3] * m2[2];
dst3 = m1[2] * m2[1] + m1[3] * m2[3];
dst4 = m1[4] * m2[0] + m1[5] * m2[2] + m2[4];
dst5 = m1[4] * m2[1] + m1[5] * m2[3] + m2[5];
dst[0] = dst0;
dst[1] = dst1;
dst[2] = dst2;
dst[3] = dst3;
dst[4] = dst4;
dst[5] = dst5;
return GD_TRUE;
}
/**
* Function: gdAffineIdentity
* Set up the identity matrix.
*
* Parameters:
* dst - Where to store the resulting affine transform
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineIdentity (double dst[6])
{
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 1;
dst[4] = 0;
dst[5] = 0;
return GD_TRUE;
}
/**
* Function: gdAffineScale
* Set up a scaling matrix.
*
* Parameters:
* scale_x - X scale factor
* scale_y - Y scale factor
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineScale (double dst[6], const double scale_x, const double scale_y)
{
dst[0] = scale_x;
dst[1] = 0;
dst[2] = 0;
dst[3] = scale_y;
dst[4] = 0;
dst[5] = 0;
return GD_TRUE;
}
/**
* Function: gdAffineRotate
* Set up a rotation affine transform.
*
* Like the other angle in libGD, in which increasing y moves
* downward, this is a counterclockwise rotation.
*
* Parameters:
* dst - Where to store the resulting affine transform
* angle - Rotation angle in degrees
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineRotate (double dst[6], const double angle)
{
const double sin_t = sin (angle * M_PI / 180.0);
const double cos_t = cos (angle * M_PI / 180.0);
dst[0] = cos_t;
dst[1] = sin_t;
dst[2] = -sin_t;
dst[3] = cos_t;
dst[4] = 0;
dst[5] = 0;
return GD_TRUE;
}
/**
* Function: gdAffineShearHorizontal
* Set up a horizontal shearing matrix || becomes \\.
*
* Parameters:
* dst - Where to store the resulting affine transform
* angle - Shear angle in degrees
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineShearHorizontal(double dst[6], const double angle)
{
dst[0] = 1;
dst[1] = 0;
dst[2] = tan(angle * M_PI / 180.0);
dst[3] = 1;
dst[4] = 0;
dst[5] = 0;
return GD_TRUE;
}
/**
* Function: gdAffineShearVertical
* Set up a vertical shearing matrix, columns are untouched.
*
* Parameters:
* dst - Where to store the resulting affine transform
* angle - Shear angle in degrees
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineShearVertical(double dst[6], const double angle)
{
dst[0] = 1;
dst[1] = tan(angle * M_PI / 180.0);
dst[2] = 0;
dst[3] = 1;
dst[4] = 0;
dst[5] = 0;
return GD_TRUE;
}
/**
* Function: gdAffineTranslate
* Set up a translation matrix.
*
* Parameters:
* dst - Where to store the resulting affine transform
* offset_x - Horizontal translation amount
* offset_y - Vertical translation amount
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineTranslate (double dst[6], const double offset_x, const double offset_y)
{
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 1;
dst[4] = offset_x;
dst[5] = offset_y;
return GD_TRUE;
}
/**
* gdAffineexpansion: Find the affine's expansion factor.
* @src: The affine transformation.
*
* Finds the expansion factor, i.e. the square root of the factor
* by which the affine transform affects area. In an affine transform
* composed of scaling, rotation, shearing, and translation, returns
* the amount of scaling.
*
* GD_SUCCESS on success or GD_FAILURE
**/
double gdAffineExpansion (const double src[6])
{
return sqrt (fabs (src[0] * src[3] - src[1] * src[2]));
}
/**
* Function: gdAffineRectilinear
* Determines whether the affine transformation is axis aligned. A
* tolerance has been implemented using GD_EPSILON.
*
* Parameters:
* m - The affine transformation
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
int gdAffineRectilinear (const double m[6])
{
return ((fabs (m[1]) < GD_EPSILON && fabs (m[2]) < GD_EPSILON) ||
(fabs (m[0]) < GD_EPSILON && fabs (m[3]) < GD_EPSILON));
}
/**
* Function: gdAffineEqual
* Determines whether two affine transformations are equal. A tolerance
* has been implemented using GD_EPSILON.
*
* Parameters:
* m1 - The first affine transformation
* m2 - The first affine transformation
*
* Returns:
* GD_SUCCESS on success or GD_FAILURE
*/
int gdAffineEqual (const double m1[6], const double m2[6])
{
return (fabs (m1[0] - m2[0]) < GD_EPSILON &&
fabs (m1[1] - m2[1]) < GD_EPSILON &&
fabs (m1[2] - m2[2]) < GD_EPSILON &&
fabs (m1[3] - m2[3]) < GD_EPSILON &&
fabs (m1[4] - m2[4]) < GD_EPSILON &&
fabs (m1[5] - m2[5]) < GD_EPSILON);
}
| 7,926 | 22.876506 | 89 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_pixelate.c
|
#include "gd.h"
int gdImagePixelate(gdImagePtr im, int block_size, const unsigned int mode)
{
int x, y;
if (block_size <= 0) {
return 0;
} else if (block_size == 1) {
return 1;
}
switch (mode) {
case GD_PIXELATE_UPPERLEFT:
for (y = 0; y < im->sy; y += block_size) {
for (x = 0; x < im->sx; x += block_size) {
if (gdImageBoundsSafe(im, x, y)) {
int c = gdImageGetPixel(im, x, y);
gdImageFilledRectangle(im, x, y, x + block_size - 1, y + block_size - 1, c);
}
}
}
break;
case GD_PIXELATE_AVERAGE:
for (y = 0; y < im->sy; y += block_size) {
for (x = 0; x < im->sx; x += block_size) {
int a, r, g, b, c;
int total;
int cx, cy;
a = r = g = b = c = total = 0;
/* sampling */
for (cy = 0; cy < block_size; cy++) {
for (cx = 0; cx < block_size; cx++) {
if (!gdImageBoundsSafe(im, x + cx, y + cy)) {
continue;
}
c = gdImageGetPixel(im, x + cx, y + cy);
a += gdImageAlpha(im, c);
r += gdImageRed(im, c);
g += gdImageGreen(im, c);
b += gdImageBlue(im, c);
total++;
}
}
/* drawing */
if (total > 0) {
c = gdImageColorResolveAlpha(im, r / total, g / total, b / total, a / total);
gdImageFilledRectangle(im, x, y, x + block_size - 1, y + block_size - 1, c);
}
}
}
break;
default:
return 0;
}
return 1;
}
| 1,366 | 22.568966 | 82 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_png.c
|
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#include "gd_errors.h"
/* JCE: Arrange HAVE_LIBPNG so that it can be set in gd.h */
#ifdef HAVE_LIBPNG
#include "png.h" /* includes zlib.h and setjmp.h */
#include "gdhelpers.h"
#define TRUE 1
#define FALSE 0
/*---------------------------------------------------------------------------
gd_png.c Copyright 1999 Greg Roelofs and Thomas Boutell
The routines in this file, gdImagePng*() and gdImageCreateFromPng*(),
are drop-in replacements for gdImageGif*() and gdImageCreateFromGif*(),
except that these functions are noisier in the case of errors (comment
out all fprintf() statements to disable that).
GD 2.0 supports RGBA truecolor and will read and write truecolor PNGs.
GD 2.0 supports 8 bits of color resolution per channel and
7 bits of alpha channel resolution. Images with more than 8 bits
per channel are reduced to 8 bits. Images with an alpha channel are
only able to resolve down to '1/128th opaque' instead of '1/256th',
and this conversion is also automatic. I very much doubt you can see it.
Both tRNS and true alpha are supported.
Gamma is ignored, and there is no support for text annotations.
Last updated: 9 February 2001
---------------------------------------------------------------------------*/
const char * gdPngGetVersionString()
{
return PNG_LIBPNG_VER_STRING;
}
#ifdef PNG_SETJMP_SUPPORTED
typedef struct _jmpbuf_wrapper
{
jmp_buf jmpbuf;
} jmpbuf_wrapper;
static void gdPngErrorHandler (png_structp png_ptr, png_const_charp msg)
{
jmpbuf_wrapper *jmpbuf_ptr;
/* This function, aside from the extra step of retrieving the "error
* pointer" (below) and the fact that it exists within the application
* rather than within libpng, is essentially identical to libpng's
* default error handler. The second point is critical: since both
* setjmp() and longjmp() are called from the same code, they are
* guaranteed to have compatible notions of how big a jmp_buf is,
* regardless of whether _BSD_SOURCE or anything else has (or has not)
* been defined.
*/
gd_error_ex(GD_WARNING, "gd-png: fatal libpng error: %s", msg);
jmpbuf_ptr = png_get_error_ptr (png_ptr);
if (jmpbuf_ptr == NULL) { /* we are completely hosed now */
gd_error_ex(GD_ERROR, "gd-png: EXTREMELY fatal error: jmpbuf unrecoverable; terminating.");
}
longjmp (jmpbuf_ptr->jmpbuf, 1);
}
static void gdPngWarningHandler (png_structp png_ptr, png_const_charp msg)
{
gd_error_ex(GD_WARNING, "gd-png: libpng warning: %s", msg);
}
#endif
static void gdPngReadData (png_structp png_ptr, png_bytep data, png_size_t length)
{
int check;
check = gdGetBuf(data, length, (gdIOCtx *) png_get_io_ptr(png_ptr));
if (check != length) {
png_error(png_ptr, "Read Error: truncated data");
}
}
static void gdPngWriteData (png_structp png_ptr, png_bytep data, png_size_t length)
{
gdPutBuf (data, length, (gdIOCtx *) png_get_io_ptr(png_ptr));
}
static void gdPngFlushData (png_structp png_ptr)
{
}
gdImagePtr gdImageCreateFromPng (FILE * inFile)
{
gdImagePtr im;
gdIOCtx *in = gdNewFileCtx(inFile);
im = gdImageCreateFromPngCtx(in);
in->gd_free(in);
return im;
}
gdImagePtr gdImageCreateFromPngPtr (int size, void *data)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
im = gdImageCreateFromPngCtx(in);
in->gd_free(in);
return im;
}
/* This routine is based in part on the Chapter 13 demo code in "PNG: The
* Definitive Guide" (http://www.cdrom.com/pub/png/pngbook.html).
*/
gdImagePtr gdImageCreateFromPngCtx (gdIOCtx * infile)
{
png_byte sig[8];
#ifdef PNG_SETJMP_SUPPORTED
jmpbuf_wrapper jbw;
#endif
png_structp png_ptr;
png_infop info_ptr;
png_uint_32 width, height, rowbytes, w, h, res_x, res_y;
int bit_depth, color_type, interlace_type, unit_type;
int num_palette, num_trans;
png_colorp palette;
png_color_16p trans_gray_rgb;
png_color_16p trans_color_rgb;
png_bytep trans;
volatile png_bytep image_data = NULL;
volatile png_bytepp row_pointers = NULL;
gdImagePtr im = NULL;
int i, j, *open = NULL;
volatile int transparent = -1;
volatile int palette_allocated = FALSE;
/* Make sure the signature can't match by dumb luck -- TBB */
/* GRR: isn't sizeof(infile) equal to the size of the pointer? */
memset (sig, 0, sizeof(sig));
/* first do a quick check that the file really is a PNG image; could
* have used slightly more general png_sig_cmp() function instead
*/
if (gdGetBuf(sig, 8, infile) < 8) {
return NULL;
}
if (png_sig_cmp(sig, 0, 8) != 0) { /* bad signature */
return NULL;
}
#ifdef PNG_SETJMP_SUPPORTED
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, &jbw, gdPngErrorHandler, gdPngWarningHandler);
#else
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
#endif
if (png_ptr == NULL) {
gd_error("gd-png error: cannot allocate libpng main struct");
return NULL;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
gd_error("gd-png error: cannot allocate libpng info struct");
png_destroy_read_struct (&png_ptr, NULL, NULL);
return NULL;
}
/* we could create a second info struct here (end_info), but it's only
* useful if we want to keep pre- and post-IDAT chunk info separated
* (mainly for PNG-aware image editors and converters)
*/
/* setjmp() must be called in every non-callback function that calls a
* PNG-reading libpng function
*/
#ifdef PNG_SETJMP_SUPPORTED
if (setjmp(jbw.jmpbuf)) {
gd_error("gd-png error: setjmp returns error condition");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return NULL;
}
#endif
png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */
png_set_read_fn(png_ptr, (void *) infile, gdPngReadData);
png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
if ((color_type == PNG_COLOR_TYPE_RGB) || (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
|| color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
im = gdImageCreateTrueColor((int) width, (int) height);
} else {
im = gdImageCreate((int) width, (int) height);
}
if (im == NULL) {
gd_error("gd-png error: cannot allocate gdImage struct");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return NULL;
}
if (bit_depth == 16) {
png_set_strip_16(png_ptr);
} else if (bit_depth < 8) {
png_set_packing (png_ptr); /* expand to 1 byte per pixel */
}
/* setjmp() must be called in every non-callback function that calls a
* PNG-reading libpng function
*/
#ifdef PNG_SETJMP_SUPPORTED
if (setjmp(jbw.jmpbuf)) {
gd_error("gd-png error: setjmp returns error condition");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
gdFree(image_data);
gdFree(row_pointers);
if (im) {
gdImageDestroy(im);
}
return NULL;
}
#endif
#ifdef PNG_pHYs_SUPPORTED
/* check if the resolution is specified */
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_pHYs)) {
if (png_get_pHYs(png_ptr, info_ptr, &res_x, &res_y, &unit_type)) {
switch (unit_type) {
case PNG_RESOLUTION_METER:
im->res_x = DPM2DPI(res_x);
im->res_y = DPM2DPI(res_y);
break;
}
}
}
#endif
switch (color_type) {
case PNG_COLOR_TYPE_PALETTE:
png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
#ifdef DEBUG
gd_error("gd-png color_type is palette, colors: %d", num_palette);
#endif /* DEBUG */
if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS)) {
/* gd 2.0: we support this rather thoroughly now. Grab the
* first fully transparent entry, if any, as the value of
* the simple-transparency index, mostly for backwards
* binary compatibility. The alpha channel is where it's
* really at these days.
*/
int firstZero = 1;
png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
for (i = 0; i < num_trans; ++i) {
im->alpha[i] = gdAlphaMax - (trans[i] >> 1);
if ((trans[i] == 0) && (firstZero)) {
transparent = i;
firstZero = 0;
}
}
}
break;
case PNG_COLOR_TYPE_GRAY:
/* create a fake palette and check for single-shade transparency */
if ((palette = (png_colorp) gdMalloc (256 * sizeof (png_color))) == NULL) {
gd_error("gd-png error: cannot allocate gray palette");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return NULL;
}
palette_allocated = TRUE;
if (bit_depth < 8) {
num_palette = 1 << bit_depth;
for (i = 0; i < 256; ++i) {
j = (255 * i) / (num_palette - 1);
palette[i].red = palette[i].green = palette[i].blue = j;
}
} else {
num_palette = 256;
for (i = 0; i < 256; ++i) {
palette[i].red = palette[i].green = palette[i].blue = i;
}
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_gray_rgb);
if (bit_depth == 16) { /* png_set_strip_16() not yet in effect */
transparent = trans_gray_rgb->gray >> 8;
} else {
transparent = trans_gray_rgb->gray;
}
/* Note slight error in 16-bit case: up to 256 16-bit shades
* may get mapped to a single 8-bit shade, and only one of them
* is supposed to be transparent. IOW, both opaque pixels and
* transparent pixels will be mapped into the transparent entry.
* There is no particularly good way around this in the case
* that all 256 8-bit shades are used, but one could write some
* custom 16-bit code to handle the case where there are gdFree
* palette entries. This error will be extremely rare in
* general, though. (Quite possibly there is only one such
* image in existence.)
*/
}
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
png_set_gray_to_rgb(png_ptr);
ZEND_FALLTHROUGH;
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_RGB_ALPHA:
/* gd 2.0: we now support truecolor. See the comment above
* for a rare situation in which the transparent pixel may not
* work properly with 16-bit channels.
*/
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_color_rgb);
if (bit_depth == 16) { /* png_set_strip_16() not yet in effect */
transparent = gdTrueColor(trans_color_rgb->red >> 8,
trans_color_rgb->green >> 8,
trans_color_rgb->blue >> 8);
} else {
transparent = gdTrueColor(trans_color_rgb->red,
trans_color_rgb->green,
trans_color_rgb->blue);
}
}
break;
}
/* enable the interlace transform if supported */
#ifdef PNG_READ_INTERLACING_SUPPORTED
(void)png_set_interlace_handling(png_ptr);
#endif
png_read_update_info(png_ptr, info_ptr);
/* allocate space for the PNG image data */
rowbytes = png_get_rowbytes(png_ptr, info_ptr);
image_data = (png_bytep) safe_emalloc(rowbytes, height, 0);
row_pointers = (png_bytepp) safe_emalloc(height, sizeof(png_bytep), 0);
/* set the individual row_pointers to point at the correct offsets */
for (h = 0; h < height; ++h) {
row_pointers[h] = image_data + h * rowbytes;
}
png_read_image(png_ptr, row_pointers); /* read whole image... */
png_read_end(png_ptr, NULL); /* ...done! */
if (!im->trueColor) {
im->colorsTotal = num_palette;
/* load the palette and mark all entries "open" (unused) for now */
open = im->open;
for (i = 0; i < num_palette; ++i) {
im->red[i] = palette[i].red;
im->green[i] = palette[i].green;
im->blue[i] = palette[i].blue;
open[i] = 1;
}
for (i = num_palette; i < gdMaxColors; ++i) {
open[i] = 1;
}
}
/* 2.0.12: Slaven Rezic: palette images are not the only images
* with a simple transparent color setting.
*/
im->transparent = transparent;
im->interlace = (interlace_type == PNG_INTERLACE_ADAM7);
/* can't nuke structs until done with palette */
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
for (h = 0; h < height; h++) {
int boffset = 0;
for (w = 0; w < width; w++) {
register png_byte r = row_pointers[h][boffset++];
register png_byte g = row_pointers[h][boffset++];
register png_byte b = row_pointers[h][boffset++];
im->tpixels[h][w] = gdTrueColor (r, g, b);
}
}
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
case PNG_COLOR_TYPE_RGB_ALPHA:
for (h = 0; h < height; h++) {
int boffset = 0;
for (w = 0; w < width; w++) {
register png_byte r = row_pointers[h][boffset++];
register png_byte g = row_pointers[h][boffset++];
register png_byte b = row_pointers[h][boffset++];
/* gd has only 7 bits of alpha channel resolution, and
* 127 is transparent, 0 opaque. A moment of convenience,
* a lifetime of compatibility.
*/
register png_byte a = gdAlphaMax - (row_pointers[h][boffset++] >> 1);
im->tpixels[h][w] = gdTrueColorAlpha(r, g, b, a);
}
}
break;
default:
/* Palette image, or something coerced to be one */
for (h = 0; h < height; ++h) {
for (w = 0; w < width; ++w) {
register png_byte idx = row_pointers[h][w];
im->pixels[h][w] = idx;
open[idx] = 0;
}
}
}
#ifdef DEBUG
if (!im->trueColor) {
for (i = num_palette; i < gdMaxColors; ++i) {
if (!open[i]) {
gd_error("gd-png warning: image data references out-of-range color index (%d)", i);
}
}
}
#endif
if (palette_allocated) {
gdFree(palette);
}
gdFree(image_data);
gdFree(row_pointers);
return im;
}
void gdImagePngEx (gdImagePtr im, FILE * outFile, int level, int basefilter)
{
gdIOCtx *out = gdNewFileCtx(outFile);
gdImagePngCtxEx(im, out, level, basefilter);
out->gd_free(out);
}
void gdImagePng (gdImagePtr im, FILE * outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
gdImagePngCtxEx(im, out, -1, -1);
out->gd_free(out);
}
void * gdImagePngPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
gdImagePngCtxEx(im, out, -1, -1);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
void * gdImagePngPtrEx (gdImagePtr im, int *size, int level, int basefilter)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
gdImagePngCtxEx(im, out, level, basefilter);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
void gdImagePngCtx (gdImagePtr im, gdIOCtx * outfile)
{
gdImagePngCtxEx(im, outfile, -1, -1);
}
/* This routine is based in part on code from Dale Lutz (Safe Software Inc.)
* and in part on demo code from Chapter 15 of "PNG: The Definitive Guide"
* (http://www.cdrom.com/pub/png/pngbook.html).
*/
void gdImagePngCtxEx (gdImagePtr im, gdIOCtx * outfile, int level, int basefilter)
{
int i, j, bit_depth = 0, interlace_type;
int width = im->sx;
int height = im->sy;
int colors = im->colorsTotal;
int *open = im->open;
int mapping[gdMaxColors]; /* mapping[gd_index] == png_index */
png_byte trans_values[256];
png_color_16 trans_rgb_value;
png_color palette[gdMaxColors];
png_structp png_ptr;
png_infop info_ptr;
volatile int transparent = im->transparent;
volatile int remap = FALSE;
#ifdef PNG_SETJMP_SUPPORTED
jmpbuf_wrapper jbw;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, &jbw, gdPngErrorHandler, gdPngWarningHandler);
#else
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
#endif
if (png_ptr == NULL) {
gd_error("gd-png error: cannot allocate libpng main struct");
return;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
gd_error("gd-png error: cannot allocate libpng info struct");
png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
return;
}
#ifdef PNG_SETJMP_SUPPORTED
if (setjmp(jbw.jmpbuf)) {
gd_error("gd-png error: setjmp returns error condition");
png_destroy_write_struct (&png_ptr, &info_ptr);
return;
}
#endif
png_set_write_fn(png_ptr, (void *) outfile, gdPngWriteData, gdPngFlushData);
/* This is best for palette images, and libpng defaults to it for
* palette images anyway, so we don't need to do it explicitly.
* What to ideally do for truecolor images depends, alas, on the image.
* gd is intentionally imperfect and doesn't spend a lot of time
* fussing with such things.
*/
/* png_set_filter(png_ptr, 0, PNG_FILTER_NONE); */
/* 2.0.12: this is finally a parameter */
if (level != -1 && (level < 0 || level > 9)) {
gd_error("gd-png error: compression level must be 0 through 9");
return;
}
png_set_compression_level(png_ptr, level);
if (basefilter >= 0) {
png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, basefilter);
}
#ifdef PNG_pHYs_SUPPORTED
/* 2.1.0: specify the resolution */
png_set_pHYs(png_ptr, info_ptr, DPI2DPM(im->res_x), DPI2DPM(im->res_y),
PNG_RESOLUTION_METER);
#endif
/* can set this to a smaller value without compromising compression if all
* image data is 16K or less; will save some decoder memory [min == 8]
*/
/* png_set_compression_window_bits(png_ptr, 15); */
if (!im->trueColor) {
if (transparent >= im->colorsTotal || (transparent >= 0 && open[transparent])) {
transparent = -1;
}
for (i = 0; i < gdMaxColors; ++i) {
mapping[i] = -1;
}
/* count actual number of colors used (colorsTotal == high-water mark) */
colors = 0;
for (i = 0; i < im->colorsTotal; ++i) {
if (!open[i]) {
mapping[i] = colors;
++colors;
}
}
if (colors == 0) {
gd_error("gd-png error: no colors in palette");
goto bail;
}
if (colors < im->colorsTotal) {
remap = TRUE;
}
if (colors <= 2) {
bit_depth = 1;
} else if (colors <= 4) {
bit_depth = 2;
} else if (colors <= 16) {
bit_depth = 4;
} else {
bit_depth = 8;
}
}
interlace_type = im->interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE;
if (im->trueColor) {
if (im->saveAlphaFlag) {
png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
} else {
png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
}
} else {
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, PNG_COLOR_TYPE_PALETTE, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
}
if (im->trueColor && !im->saveAlphaFlag && (transparent >= 0)) {
/* 2.0.9: fixed by Thomas Winzig */
trans_rgb_value.red = gdTrueColorGetRed (im->transparent);
trans_rgb_value.green = gdTrueColorGetGreen (im->transparent);
trans_rgb_value.blue = gdTrueColorGetBlue (im->transparent);
png_set_tRNS(png_ptr, info_ptr, 0, 0, &trans_rgb_value);
}
if (!im->trueColor) {
/* Oy veh. Remap the PNG palette to put the entries with interesting alpha channel
* values first. This minimizes the size of the tRNS chunk and thus the size
* of the PNG file as a whole.
*/
int tc = 0;
int i;
int j;
int k;
for (i = 0; (i < im->colorsTotal); i++) {
if ((!im->open[i]) && (im->alpha[i] != gdAlphaOpaque)) {
tc++;
}
}
if (tc) {
#if 0
for (i = 0; (i < im->colorsTotal); i++) {
trans_values[i] = 255 - ((im->alpha[i] << 1) + (im->alpha[i] >> 6));
}
png_set_tRNS (png_ptr, info_ptr, trans_values, 256, NULL);
#endif
if (!remap) {
remap = TRUE;
}
/* (Semi-)transparent indexes come up from the bottom of the list of real colors; opaque
* indexes come down from the top
*/
j = 0;
k = colors - 1;
for (i = 0; i < im->colorsTotal; i++) {
if (!im->open[i]) {
if (im->alpha[i] != gdAlphaOpaque) {
/* Andrew Hull: >> 6, not >> 7! (gd 2.0.5) */
trans_values[j] = 255 - ((im->alpha[i] << 1) + (im->alpha[i] >> 6));
mapping[i] = j++;
} else {
mapping[i] = k--;
}
}
}
png_set_tRNS(png_ptr, info_ptr, trans_values, tc, NULL);
}
}
/* convert palette to libpng layout */
if (!im->trueColor) {
if (remap) {
for (i = 0; i < im->colorsTotal; ++i) {
if (mapping[i] < 0) {
continue;
}
palette[mapping[i]].red = im->red[i];
palette[mapping[i]].green = im->green[i];
palette[mapping[i]].blue = im->blue[i];
}
} else {
for (i = 0; i < colors; ++i) {
palette[i].red = im->red[i];
palette[i].green = im->green[i];
palette[i].blue = im->blue[i];
}
}
png_set_PLTE(png_ptr, info_ptr, palette, colors);
}
/* write out the PNG header info (everything up to first IDAT) */
png_write_info(png_ptr, info_ptr);
/* make sure < 8-bit images are packed into pixels as tightly as possible */
png_set_packing(png_ptr);
/* This code allocates a set of row buffers and copies the gd image data
* into them only in the case that remapping is necessary; in gd 1.3 and
* later, the im->pixels array is laid out identically to libpng's row
* pointers and can be passed to png_write_image() function directly.
* The remapping case could be accomplished with less memory for non-
* interlaced images, but interlacing causes some serious complications.
*/
if (im->trueColor) {
/* performance optimizations by Phong Tran */
int channels = im->saveAlphaFlag ? 4 : 3;
/* Our little 7-bit alpha channel trick costs us a bit here. */
png_bytep *row_pointers;
unsigned char* pOutputRow;
int **ptpixels = im->tpixels;
int *pThisRow;
unsigned char a;
int thisPixel;
png_bytep *prow_pointers;
int saveAlphaFlag = im->saveAlphaFlag;
row_pointers = safe_emalloc(sizeof(png_bytep), height, 0);
prow_pointers = row_pointers;
for (j = 0; j < height; ++j) {
*prow_pointers = (png_bytep) safe_emalloc(width, channels, 0);
pOutputRow = *prow_pointers++;
pThisRow = *ptpixels++;
for (i = 0; i < width; ++i) {
thisPixel = *pThisRow++;
*pOutputRow++ = gdTrueColorGetRed(thisPixel);
*pOutputRow++ = gdTrueColorGetGreen(thisPixel);
*pOutputRow++ = gdTrueColorGetBlue(thisPixel);
if (saveAlphaFlag) {
/* convert the 7-bit alpha channel to an 8-bit alpha channel.
* We do a little bit-flipping magic, repeating the MSB
* as the LSB, to ensure that 0 maps to 0 and
* 127 maps to 255. We also have to invert to match
* PNG's convention in which 255 is opaque.
*/
a = gdTrueColorGetAlpha(thisPixel);
/* Andrew Hull: >> 6, not >> 7! (gd 2.0.5) */
*pOutputRow++ = 255 - ((a << 1) + (a >> 6));
}
}
}
png_write_image(png_ptr, row_pointers);
png_write_end(png_ptr, info_ptr);
for (j = 0; j < height; ++j) {
gdFree(row_pointers[j]);
}
gdFree(row_pointers);
} else {
if (remap) {
png_bytep *row_pointers;
row_pointers = safe_emalloc(height, sizeof(png_bytep), 0);
for (j = 0; j < height; ++j) {
row_pointers[j] = (png_bytep) gdMalloc(width);
for (i = 0; i < width; ++i) {
row_pointers[j][i] = mapping[im->pixels[j][i]];
}
}
png_write_image(png_ptr, row_pointers);
png_write_end(png_ptr, info_ptr);
for (j = 0; j < height; ++j) {
gdFree(row_pointers[j]);
}
gdFree(row_pointers);
} else {
png_write_image(png_ptr, im->pixels);
png_write_end(png_ptr, info_ptr);
}
}
/* 1.6.3: maybe we should give that memory BACK! TBB */
bail:
png_destroy_write_struct(&png_ptr, &info_ptr);
}
#endif /* HAVE_LIBPNG */
| 23,292 | 28.710459 | 104 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_rotate.c
|
#include "gd.h"
#include "gd_intern.h"
#include <math.h>
/*
* Rotate function Added on 2003/12
* by Pierre-Alain Joye ([email protected])
**/
/* Begin rotate function */
#ifdef ROTATE_PI
#undef ROTATE_PI
#endif /* ROTATE_PI */
#define ROTATE_DEG2RAD 3.1415926535897932384626433832795/180
void gdImageSkewX (gdImagePtr dst, gdImagePtr src, int uRow, int iOffset, double dWeight, int clrBack, int ignoretransparent)
{
typedef int (*FuncPtr)(gdImagePtr, int, int);
int i, r, g, b, a, clrBackR, clrBackG, clrBackB, clrBackA;
FuncPtr f;
int pxlOldLeft, pxlLeft=0, pxlSrc;
/* Keep clrBack as color index if required */
if (src->trueColor) {
pxlOldLeft = clrBack;
f = gdImageGetTrueColorPixel;
} else {
pxlOldLeft = clrBack;
clrBackR = gdImageRed(src, clrBack);
clrBackG = gdImageGreen(src, clrBack);
clrBackB = gdImageBlue(src, clrBack);
clrBackA = gdImageAlpha(src, clrBack);
clrBack = gdTrueColorAlpha(clrBackR, clrBackG, clrBackB, clrBackA);
f = gdImageGetPixel;
}
for (i = 0; i < iOffset; i++) {
gdImageSetPixel (dst, i, uRow, clrBack);
}
if (i < dst->sx) {
gdImageSetPixel (dst, i, uRow, clrBack);
}
for (i = 0; i < src->sx; i++) {
pxlSrc = f (src,i,uRow);
r = (int)(gdImageRed(src,pxlSrc) * dWeight);
g = (int)(gdImageGreen(src,pxlSrc) * dWeight);
b = (int)(gdImageBlue(src,pxlSrc) * dWeight);
a = (int)(gdImageAlpha(src,pxlSrc) * dWeight);
pxlLeft = gdImageColorAllocateAlpha(src, r, g, b, a);
if (pxlLeft == -1) {
pxlLeft = gdImageColorClosestAlpha(src, r, g, b, a);
}
r = gdImageRed(src,pxlSrc) - (gdImageRed(src,pxlLeft) - gdImageRed(src,pxlOldLeft));
g = gdImageGreen(src,pxlSrc) - (gdImageGreen(src,pxlLeft) - gdImageGreen(src,pxlOldLeft));
b = gdImageBlue(src,pxlSrc) - (gdImageBlue(src,pxlLeft) - gdImageBlue(src,pxlOldLeft));
a = gdImageAlpha(src,pxlSrc) - (gdImageAlpha(src,pxlLeft) - gdImageAlpha(src,pxlOldLeft));
if (r>255) {
r = 255;
}
if (g>255) {
g = 255;
}
if (b>255) {
b = 255;
}
if (a>127) {
a = 127;
}
if (ignoretransparent && pxlSrc == dst->transparent) {
pxlSrc = dst->transparent;
} else {
pxlSrc = gdImageColorAllocateAlpha(dst, r, g, b, a);
if (pxlSrc == -1) {
pxlSrc = gdImageColorClosestAlpha(dst, r, g, b, a);
}
}
if ((i + iOffset >= 0) && (i + iOffset < dst->sx)) {
gdImageSetPixel (dst, i+iOffset, uRow, pxlSrc);
}
pxlOldLeft = pxlLeft;
}
i += iOffset;
if (i < dst->sx) {
gdImageSetPixel (dst, i, uRow, pxlLeft);
}
gdImageSetPixel (dst, iOffset, uRow, clrBack);
i--;
while (++i < dst->sx) {
gdImageSetPixel (dst, i, uRow, clrBack);
}
}
void gdImageSkewY (gdImagePtr dst, gdImagePtr src, int uCol, int iOffset, double dWeight, int clrBack, int ignoretransparent)
{
typedef int (*FuncPtr)(gdImagePtr, int, int);
int i, iYPos=0, r, g, b, a;
FuncPtr f;
int pxlOldLeft, pxlLeft=0, pxlSrc;
if (src->trueColor) {
f = gdImageGetTrueColorPixel;
} else {
f = gdImageGetPixel;
}
for (i = 0; i<=iOffset; i++) {
gdImageSetPixel (dst, uCol, i, clrBack);
}
r = (int)((double)gdImageRed(src,clrBack) * dWeight);
g = (int)((double)gdImageGreen(src,clrBack) * dWeight);
b = (int)((double)gdImageBlue(src,clrBack) * dWeight);
a = (int)((double)gdImageAlpha(src,clrBack) * dWeight);
pxlOldLeft = gdImageColorAllocateAlpha(dst, r, g, b, a);
for (i = 0; i < src->sy; i++) {
pxlSrc = f (src, uCol, i);
iYPos = i + iOffset;
r = (int)((double)gdImageRed(src,pxlSrc) * dWeight);
g = (int)((double)gdImageGreen(src,pxlSrc) * dWeight);
b = (int)((double)gdImageBlue(src,pxlSrc) * dWeight);
a = (int)((double)gdImageAlpha(src,pxlSrc) * dWeight);
pxlLeft = gdImageColorAllocateAlpha(src, r, g, b, a);
if (pxlLeft == -1) {
pxlLeft = gdImageColorClosestAlpha(src, r, g, b, a);
}
r = gdImageRed(src,pxlSrc) - (gdImageRed(src,pxlLeft) - gdImageRed(src,pxlOldLeft));
g = gdImageGreen(src,pxlSrc) - (gdImageGreen(src,pxlLeft) - gdImageGreen(src,pxlOldLeft));
b = gdImageBlue(src,pxlSrc) - (gdImageBlue(src,pxlLeft) - gdImageBlue(src,pxlOldLeft));
a = gdImageAlpha(src,pxlSrc) - (gdImageAlpha(src,pxlLeft) - gdImageAlpha(src,pxlOldLeft));
if (r>255) {
r = 255;
}
if (g>255) {
g = 255;
}
if (b>255) {
b = 255;
}
if (a>127) {
a = 127;
}
if (ignoretransparent && pxlSrc == dst->transparent) {
pxlSrc = dst->transparent;
} else {
pxlSrc = gdImageColorAllocateAlpha(dst, r, g, b, a);
if (pxlSrc == -1) {
pxlSrc = gdImageColorClosestAlpha(dst, r, g, b, a);
}
}
if ((iYPos >= 0) && (iYPos < dst->sy)) {
gdImageSetPixel (dst, uCol, iYPos, pxlSrc);
}
pxlOldLeft = pxlLeft;
}
i = iYPos;
if (i < dst->sy) {
gdImageSetPixel (dst, uCol, i, pxlLeft);
}
i--;
while (++i < dst->sy) {
gdImageSetPixel (dst, uCol, i, clrBack);
}
}
/* Rotates an image by 90 degrees (counter clockwise) */
gdImagePtr gdImageRotate90 (gdImagePtr src, int ignoretransparent)
{
int uY, uX;
int c,r,g,b,a;
gdImagePtr dst;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src->trueColor) {
f = gdImageGetTrueColorPixel;
} else {
f = gdImageGetPixel;
}
dst = gdImageCreateTrueColor(src->sy, src->sx);
if (dst != NULL) {
int old_blendmode = dst->alphaBlendingFlag;
dst->alphaBlendingFlag = 0;
dst->transparent = src->transparent;
gdImagePaletteCopy (dst, src);
for (uY = 0; uY<src->sy; uY++) {
for (uX = 0; uX<src->sx; uX++) {
c = f (src, uX, uY);
if (!src->trueColor) {
r = gdImageRed(src,c);
g = gdImageGreen(src,c);
b = gdImageBlue(src,c);
a = gdImageAlpha(src,c);
c = gdTrueColorAlpha(r, g, b, a);
}
if (ignoretransparent && c == dst->transparent) {
gdImageSetPixel(dst, uY, (dst->sy - uX - 1), dst->transparent);
} else {
gdImageSetPixel(dst, uY, (dst->sy - uX - 1), c);
}
}
}
dst->alphaBlendingFlag = old_blendmode;
}
return dst;
}
/* Rotates an image by 180 degrees (counter clockwise) */
gdImagePtr gdImageRotate180 (gdImagePtr src, int ignoretransparent)
{
int uY, uX;
int c,r,g,b,a;
gdImagePtr dst;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src->trueColor) {
f = gdImageGetTrueColorPixel;
} else {
f = gdImageGetPixel;
}
dst = gdImageCreateTrueColor(src->sx, src->sy);
if (dst != NULL) {
int old_blendmode = dst->alphaBlendingFlag;
dst->alphaBlendingFlag = 0;
dst->transparent = src->transparent;
gdImagePaletteCopy (dst, src);
for (uY = 0; uY<src->sy; uY++) {
for (uX = 0; uX<src->sx; uX++) {
c = f (src, uX, uY);
if (!src->trueColor) {
r = gdImageRed(src,c);
g = gdImageGreen(src,c);
b = gdImageBlue(src,c);
a = gdImageAlpha(src,c);
c = gdTrueColorAlpha(r, g, b, a);
}
if (ignoretransparent && c == dst->transparent) {
gdImageSetPixel(dst, (dst->sx - uX - 1), (dst->sy - uY - 1), dst->transparent);
} else {
gdImageSetPixel(dst, (dst->sx - uX - 1), (dst->sy - uY - 1), c);
}
}
}
dst->alphaBlendingFlag = old_blendmode;
}
return dst;
}
/* Rotates an image by 270 degrees (counter clockwise) */
gdImagePtr gdImageRotate270 (gdImagePtr src, int ignoretransparent)
{
int uY, uX;
int c,r,g,b,a;
gdImagePtr dst;
typedef int (*FuncPtr)(gdImagePtr, int, int);
FuncPtr f;
if (src->trueColor) {
f = gdImageGetTrueColorPixel;
} else {
f = gdImageGetPixel;
}
dst = gdImageCreateTrueColor (src->sy, src->sx);
if (dst != NULL) {
int old_blendmode = dst->alphaBlendingFlag;
dst->alphaBlendingFlag = 0;
dst->transparent = src->transparent;
gdImagePaletteCopy (dst, src);
for (uY = 0; uY<src->sy; uY++) {
for (uX = 0; uX<src->sx; uX++) {
c = f (src, uX, uY);
if (!src->trueColor) {
r = gdImageRed(src,c);
g = gdImageGreen(src,c);
b = gdImageBlue(src,c);
a = gdImageAlpha(src,c);
c = gdTrueColorAlpha(r, g, b, a);
}
if (ignoretransparent && c == dst->transparent) {
gdImageSetPixel(dst, (dst->sx - uY - 1), uX, dst->transparent);
} else {
gdImageSetPixel(dst, (dst->sx - uY - 1), uX, c);
}
}
}
dst->alphaBlendingFlag = old_blendmode;
}
return dst;
}
| 8,162 | 22.868421 | 125 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_ss.c
|
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#define TRUE 1
#define FALSE 0
/* Exported functions: */
extern void gdImagePngToSink (gdImagePtr im, gdSinkPtr out);
extern gdImagePtr gdImageCreateFromPngSource (gdSourcePtr inSource);
/* Use this for commenting out debug-print statements. */
/* Just use the first '#define' to allow all the prints... */
/*#define GD_SS_DBG(s) (s) */
#define GD_SS_DBG(s)
#ifdef HAVE_LIBPNG
void gdImagePngToSink (gdImagePtr im, gdSinkPtr outSink)
{
gdIOCtx *out = gdNewSSCtx(NULL, outSink);
gdImagePngCtx(im, out);
out->gd_free(out);
}
gdImagePtr gdImageCreateFromPngSource (gdSourcePtr inSource)
{
gdIOCtx *in = gdNewSSCtx(inSource, NULL);
gdImagePtr im;
im = gdImageCreateFromPngCtx(in);
in->gd_free(in);
return im;
}
#else /* no HAVE_LIBPNG */
void gdImagePngToSink (gdImagePtr im, gdSinkPtr outSink)
{
gd_error("PNG support is not available");
}
gdImagePtr gdImageCreateFromPngSource (gdSourcePtr inSource)
{
gd_error("PNG support is not available");
return NULL;
}
#endif /* HAVE_LIBPNG */
| 1,095 | 20.92 | 68 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_tga.h
|
#ifndef __TGA_H
#define __TGA_H 1
#include "gd.h"
#include "gdhelpers.h"
#include "gd_intern.h"
typedef struct oTga_ {
uint8_t identsize; // size of ID field that follows 18 uint8_t header (0 usually)
uint8_t colormaptype; // type of colour map 0=none, 1=has palette [IGNORED] Adrian requested no support
uint8_t imagetype; // type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed
int colormapstart; // first colour map entry in palette [IGNORED] Adrian requested no support
int colormaplength; // number of colours in palette [IGNORED] Adrian requested no support
uint8_t colormapbits; // number of bits per palette entry 15,16,24,32 [IGNORED] Adrian requested no support
int xstart; // image x origin
int ystart; // image y origin
int width; // image width in pixels
int height; // image height in pixels
uint8_t bits; // image bits per pixel 8,16,24,32
uint8_t alphabits; // alpha bits (low 4bits of header 17)
uint8_t fliph; // horizontal or vertical
uint8_t flipv; // flip
char *ident; // identifcation tag string
int *bitmap; // bitmap data
} oTga;
#define TGA_TYPE_NO_IMAGE 0
#define TGA_TYPE_INDEXED 1
#define TGA_TYPE_RGB 2
#define TGA_TYPE_GREYSCALE 3
#define TGA_TYPE_INDEXED_RLE 9
#define TGA_TYPE_RGB_RLE 10
#define TGA_TYPE_GREYSCALE_RLE 11
#define TGA_TYPE_INDEXED_HUFFMAN_DELTA_RLE 32
#define TGA_TYPE_RGB_HUFFMAN_DELTA_QUADTREE_RLE 33
#define TGA_BPP_8 8
#define TGA_BPP_16 16
#define TGA_BPP_24 24
#define TGA_BPP_32 32
#define TGA_RLE_FLAG 128
int read_header_tga(gdIOCtx *ctx, oTga *tga);
int read_image_tga(gdIOCtx *ctx, oTga *tga);
void free_tga(oTga *tga);
#endif //__TGA_H
| 1,704 | 31.169811 | 112 |
h
|
php-src
|
php-src-master/ext/gd/libgd/gd_wbmp.c
|
/*
WBMP: Wireless Bitmap Type 0: B/W, Uncompressed Bitmap
Specification of the WBMP format can be found in the file:
SPEC-WAESpec-19990524.pdf
You can download the WAP specification on: http://www.wapforum.com/
gd_wbmp.c
Copyright (C) Johan Van den Brande ([email protected])
Fixed: gdImageWBMPPtr, gdImageWBMP
Recoded: gdImageWBMPCtx for use with my wbmp library
(wbmp library included, but you can find the latest distribution
at http://www.vandenbrande.com/wbmp)
Implemented: gdImageCreateFromWBMPCtx, gdImageCreateFromWBMP
---------------------------------------------------------------------------
Parts of this code are from Maurice Smurlo.
** Copyright (C) Maurice Szmurlo --- T-SIT --- January 2000
** ([email protected])
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
---------------------------------------------------------------------------
Parts od this code are inspired by 'pbmtowbmp.c' and 'wbmptopbm.c' by
Terje Sannum <[email protected]>.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
**
---------------------------------------------------------------------------
Todo:
gdCreateFromWBMP function for reading WBMP files
----------------------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "gd.h"
#include "gdfonts.h"
#include "gd_errors.h"
#include "wbmp.h"
/* gd_putout
** ---------
** Wrapper around gdPutC for use with writewbmp
**
*/
void gd_putout (int i, void *out)
{
gdPutC(i, (gdIOCtx *) out);
}
/* gd_getin
** --------
** Wrapper around gdGetC for use with readwbmp
**
*/
int gd_getin (void *in)
{
return (gdGetC((gdIOCtx *) in));
}
static int _gdImageWBMPCtx(gdImagePtr image, int fg, gdIOCtx *out);
/* gdImageWBMPCtx
** --------------
** Write the image as a wbmp file
** Parameters are:
** image: gd image structure;
** fg: the index of the foreground color. any other value will be
** considered as background and will not be written
** out: the stream where to write
*/
void gdImageWBMPCtx (gdImagePtr image, int fg, gdIOCtx * out)
{
_gdImageWBMPCtx(image, fg, out);
}
/* returns 0 on success, 1 on failure */
static int _gdImageWBMPCtx(gdImagePtr image, int fg, gdIOCtx *out)
{
int x, y, pos;
Wbmp *wbmp;
/* create the WBMP */
if ((wbmp = createwbmp (gdImageSX (image), gdImageSY (image), WBMP_WHITE)) == NULL) {
gd_error("Could not create WBMP");
return 1;
}
/* fill up the WBMP structure */
pos = 0;
for (y = 0; y < gdImageSY(image); y++) {
for (x = 0; x < gdImageSX(image); x++) {
if (gdImageGetPixel (image, x, y) == fg) {
wbmp->bitmap[pos] = WBMP_BLACK;
}
pos++;
}
}
/* write the WBMP to a gd file descriptor */
if (writewbmp (wbmp, &gd_putout, out)) {
freewbmp(wbmp);
gd_error("Could not save WBMP");
return 1;
}
/* des submitted this bugfix: gdFree the memory. */
freewbmp(wbmp);
return 0;
}
/* gdImageCreateFromWBMPCtx
** ------------------------
** Create a gdImage from a WBMP file input from an gdIOCtx
*/
gdImagePtr gdImageCreateFromWBMPCtx (gdIOCtx * infile)
{
/* FILE *wbmp_file; */
Wbmp *wbmp;
gdImagePtr im = NULL;
int black, white;
int col, row, pos;
if (readwbmp (&gd_getin, infile, &wbmp)) {
return NULL;
}
if (!(im = gdImageCreate (wbmp->width, wbmp->height))) {
freewbmp (wbmp);
return NULL;
}
/* create the background color */
white = gdImageColorAllocate(im, 255, 255, 255);
/* create foreground color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* fill in image (in a wbmp 1 = white/ 0 = black) */
pos = 0;
for (row = 0; row < wbmp->height; row++) {
for (col = 0; col < wbmp->width; col++) {
if (wbmp->bitmap[pos++] == WBMP_WHITE) {
gdImageSetPixel(im, col, row, white);
} else {
gdImageSetPixel(im, col, row, black);
}
}
}
freewbmp(wbmp);
return im;
}
/* gdImageCreateFromWBMP
** ---------------------
*/
gdImagePtr gdImageCreateFromWBMP (FILE * inFile)
{
gdImagePtr im;
gdIOCtx *in = gdNewFileCtx(inFile);
im = gdImageCreateFromWBMPCtx(in);
in->gd_free(in);
return im;
}
gdImagePtr gdImageCreateFromWBMPPtr (int size, void *data)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
im = gdImageCreateFromWBMPCtx(in);
in->gd_free(in);
return im;
}
/* gdImageWBMP
** -----------
*/
void gdImageWBMP (gdImagePtr im, int fg, FILE * outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
gdImageWBMPCtx(im, fg, out);
out->gd_free(out);
}
/* gdImageWBMPPtr
** --------------
*/
void * gdImageWBMPPtr (gdImagePtr im, int *size, int fg)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (!_gdImageWBMPCtx(im, fg, out)) {
rv = gdDPExtractData(out, size);
} else {
rv = NULL;
}
out->gd_free(out);
return rv;
}
| 5,611 | 23.614035 | 86 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gd_xbm.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Marcus Boerger <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#include "gdhelpers.h"
#include "gd_errors.h"
#include "php.h"
#define MAX_XBM_LINE_SIZE 255
/* {{{ gdImagePtr gdImageCreateFromXbm */
gdImagePtr gdImageCreateFromXbm(FILE * fd)
{
char fline[MAX_XBM_LINE_SIZE];
char iname[MAX_XBM_LINE_SIZE];
char *type;
int value;
unsigned int width = 0, height = 0;
int fail = 0;
int max_bit = 0;
gdImagePtr im;
int bytes = 0, i;
int bit, x = 0, y = 0;
int ch;
char h[8];
unsigned int b;
rewind(fd);
while (fgets(fline, MAX_XBM_LINE_SIZE, fd)) {
fline[MAX_XBM_LINE_SIZE-1] = '\0';
if (strlen(fline) == MAX_XBM_LINE_SIZE-1) {
return 0;
}
if (sscanf(fline, "#define %s %d", iname, &value) == 2) {
if (!(type = strrchr(iname, '_'))) {
type = iname;
} else {
type++;
}
if (!strcmp("width", type)) {
width = (unsigned int) value;
}
if (!strcmp("height", type)) {
height = (unsigned int) value;
}
} else {
if ( sscanf(fline, "static unsigned char %s = {", iname) == 1
|| sscanf(fline, "static char %s = {", iname) == 1)
{
max_bit = 128;
} else if (sscanf(fline, "static unsigned short %s = {", iname) == 1
|| sscanf(fline, "static short %s = {", iname) == 1)
{
max_bit = 32768;
}
if (max_bit) {
bytes = (width + 7) / 8 * height;
if (!bytes) {
return 0;
}
if (!(type = strrchr(iname, '_'))) {
type = iname;
} else {
type++;
}
if (!strcmp("bits[]", type)) {
break;
}
}
}
}
if (!bytes || !max_bit) {
return 0;
}
if(!(im = gdImageCreate(width, height))) {
return 0;
}
gdImageColorAllocate(im, 255, 255, 255);
gdImageColorAllocate(im, 0, 0, 0);
h[2] = '\0';
h[4] = '\0';
for (i = 0; i < bytes; i++) {
while (1) {
if ((ch=getc(fd)) == EOF) {
fail = 1;
break;
}
if (ch == 'x') {
break;
}
}
if (fail) {
break;
}
/* Get hex value */
if ((ch=getc(fd)) == EOF) {
break;
}
h[0] = ch;
if ((ch=getc(fd)) == EOF) {
break;
}
h[1] = ch;
if (max_bit == 32768) {
if ((ch=getc(fd)) == EOF) {
break;
}
h[2] = ch;
if ((ch=getc(fd)) == EOF) {
break;
}
h[3] = ch;
}
if (sscanf(h, "%x", &b) != 1) {
gd_error("Invalid XBM");
gdImageDestroy(im);
return 0;
}
for (bit = 1; bit <= max_bit; bit = bit << 1) {
gdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0);
if (x == im->sx) {
x = 0;
y++;
if (y == im->sy) {
return im;
}
break;
}
}
}
gd_error("EOF before image was complete");
gdImageDestroy(im);
return 0;
}
/* }}} */
/* {{{ gdCtxPrintf */
void gdCtxPrintf(gdIOCtx * out, const char *format, ...)
{
char *buf;
int len;
va_list args;
va_start(args, format);
len = vspprintf(&buf, 0, format, args);
va_end(args);
out->putBuf(out, buf, len);
efree(buf);
}
/* }}} */
/* {{{ gdImageXbmCtx */
void gdImageXbmCtx(gdImagePtr image, char* file_name, int fg, gdIOCtx * out)
{
int x, y, c, b, sx, sy, p;
char *name, *f;
size_t i, l;
name = file_name;
if ((f = strrchr(name, '/')) != NULL) name = f+1;
if ((f = strrchr(name, '\\')) != NULL) name = f+1;
name = estrdup(name);
if ((f = strrchr(name, '.')) != NULL && !strcasecmp(f, ".XBM")) *f = '\0';
if ((l = strlen(name)) == 0) {
efree(name);
name = estrdup("image");
} else {
for (i=0; i<l; i++) {
/* only in C-locale isalnum() would work */
if (!isupper(name[i]) && !islower(name[i]) && !isdigit(name[i])) {
name[i] = '_';
}
}
}
gdCtxPrintf(out, "#define %s_width %d\n", name, gdImageSX(image));
gdCtxPrintf(out, "#define %s_height %d\n", name, gdImageSY(image));
gdCtxPrintf(out, "static unsigned char %s_bits[] = {\n ", name);
efree(name);
b = 1;
p = 0;
c = 0;
sx = gdImageSX(image);
sy = gdImageSY(image);
for (y = 0; y < sy; y++) {
for (x = 0; x < sx; x++) {
if (gdImageGetPixel(image, x, y) == fg) {
c |= b;
}
if ((b == 128) || (x == sx - 1)) {
b = 1;
if (p) {
gdCtxPrintf(out, ", ");
if (!(p%12)) {
gdCtxPrintf(out, "\n ");
p = 12;
}
}
p++;
gdCtxPrintf(out, "0x%02X", c);
c = 0;
} else {
b <<= 1;
}
}
}
gdCtxPrintf(out, "};\n");
}
/* }}} */
| 5,248 | 21.241525 | 76 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdcache.c
|
#include "gd.h"
#include "gdhelpers.h"
#ifdef HAVE_LIBFREETYPE
#define NEED_CACHE 1
#endif
#ifdef NEED_CACHE
/*
* gdcache.c
*
* Caches of pointers to user structs in which the least-recently-used
* element is replaced in the event of a cache miss after the cache has
* reached a given size.
*
* John Ellson ([email protected]) Oct 31, 1997
*
* Test this with:
* gcc -o gdcache -g -Wall -DTEST gdcache.c
*
* The cache is implemented by a singly-linked list of elements
* each containing a pointer to a user struct that is being managed by
* the cache.
*
* The head structure has a pointer to the most-recently-used
* element, and elements are moved to this position in the list each
* time they are used. The head also contains pointers to three
* user defined functions:
* - a function to test if a cached userdata matches some keydata
* - a function to provide a new userdata struct to the cache
* if there has been a cache miss.
* - a function to release a userdata struct when it is
* no longer being managed by the cache
*
* In the event of a cache miss the cache is allowed to grow up to
* a specified maximum size. After the maximum size is reached then
* the least-recently-used element is discarded to make room for the
* new. The most-recently-returned value is always left at the
* beginning of the list after retrieval.
*
* In the current implementation the cache is traversed by a linear
* search from most-recent to least-recent. This linear search
* probably limits the usefulness of this implementation to cache
* sizes of a few tens of elements.
*/
#include "gdcache.h"
/*********************************************************/
/* implementation */
/*********************************************************/
/* create a new cache */
gdCache_head_t *
gdCacheCreate (
int size,
gdCacheTestFn_t gdCacheTest,
gdCacheFetchFn_t gdCacheFetch,
gdCacheReleaseFn_t gdCacheRelease)
{
gdCache_head_t *head;
head = (gdCache_head_t *) gdPMalloc(sizeof (gdCache_head_t));
head->mru = NULL;
head->size = size;
head->gdCacheTest = gdCacheTest;
head->gdCacheFetch = gdCacheFetch;
head->gdCacheRelease = gdCacheRelease;
return head;
}
void
gdCacheDelete (gdCache_head_t * head)
{
gdCache_element_t *elem, *prev;
elem = head->mru;
while (elem)
{
(*(head->gdCacheRelease)) (elem->userdata);
prev = elem;
elem = elem->next;
gdPFree ((char *) prev);
}
gdPFree ((char *) head);
}
void *
gdCacheGet (gdCache_head_t * head, void *keydata)
{
int i = 0;
gdCache_element_t *elem, *prev = NULL, *prevprev = NULL;
void *userdata;
elem = head->mru;
while (elem)
{
if ((*(head->gdCacheTest)) (elem->userdata, keydata))
{
if (i)
{ /* if not already most-recently-used */
/* relink to top of list */
prev->next = elem->next;
elem->next = head->mru;
head->mru = elem;
}
return elem->userdata;
}
prevprev = prev;
prev = elem;
elem = elem->next;
i++;
}
userdata = (*(head->gdCacheFetch)) (&(head->error), keydata);
if (!userdata)
{
/* if there was an error in the fetch then don't cache */
return NULL;
}
if (i < head->size)
{ /* cache still growing - add new elem */
elem = (gdCache_element_t *) gdPMalloc(sizeof (gdCache_element_t));
}
else
{ /* cache full - replace least-recently-used */
/* preveprev becomes new end of list */
prevprev->next = NULL;
elem = prev;
(*(head->gdCacheRelease)) (elem->userdata);
}
/* relink to top of list */
elem->next = head->mru;
head->mru = elem;
elem->userdata = userdata;
return userdata;
}
/*********************************************************/
/* test stub */
/*********************************************************/
#ifdef TEST
#include <stdio.h>
typedef struct
{
int key;
int value;
}
key_value_t;
static int
cacheTest (void *map, void *key)
{
return (((key_value_t *) map)->key == *(int *) key);
}
static void *
cacheFetch (char **error, void *key)
{
key_value_t *map;
map = (key_value_t *) gdMalloc (sizeof (key_value_t));
map->key = *(int *) key;
map->value = 3;
*error = NULL;
return (void *) map;
}
static void
cacheRelease (void *map)
{
gdFree ((char *) map);
}
int
main (char *argv[], int argc)
{
gdCache_head_t *cacheTable;
int elem, key;
cacheTable = gdCacheCreate (3, cacheTest, cacheFetch, cacheRelease);
key = 20;
elem = *(int *) gdCacheGet (cacheTable, &key);
key = 30;
elem = *(int *) gdCacheGet (cacheTable, &key);
key = 40;
elem = *(int *) gdCacheGet (cacheTable, &key);
key = 50;
elem = *(int *) gdCacheGet (cacheTable, &key);
key = 30;
elem = *(int *) gdCacheGet (cacheTable, &key);
key = 30;
elem = *(int *) gdCacheGet (cacheTable, &key);
gdCacheDelete (cacheTable);
return 0;
}
#endif /* TEST */
#endif /* NEED_CACHE */
| 5,104 | 23.194313 | 78 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdcache.h
|
/*
* gdcache.h
*
* Caches of pointers to user structs in which the least-recently-used
* element is replaced in the event of a cache miss after the cache has
* reached a given size.
*
* John Ellson ([email protected]) Oct 31, 1997
*
* Test this with:
* gcc -o gdcache -g -Wall -DTEST gdcache.c
*
* The cache is implemented by a singly-linked list of elements
* each containing a pointer to a user struct that is being managed by
* the cache.
*
* The head structure has a pointer to the most-recently-used
* element, and elements are moved to this position in the list each
* time they are used. The head also contains pointers to three
* user defined functions:
* - a function to test if a cached userdata matches some keydata
* - a function to provide a new userdata struct to the cache
* if there has been a cache miss.
* - a function to release a userdata struct when it is
* no longer being managed by the cache
*
* In the event of a cache miss the cache is allowed to grow up to
* a specified maximum size. After the maximum size is reached then
* the least-recently-used element is discarded to make room for the
* new. The most-recently-returned value is always left at the
* beginning of the list after retrieval.
*
* In the current implementation the cache is traversed by a linear
* search from most-recent to least-recent. This linear search
* probably limits the usefulness of this implementation to cache
* sizes of a few tens of elements.
*/
/*********************************************************/
/* header */
/*********************************************************/
#include <stdlib.h>
#if (!defined(__OpenBSD__)) && defined(HAVE_MALLOC_H)
#include <malloc.h>
#endif
#ifndef NULL
#define NULL (void *)0
#endif
/* user defined function templates */
typedef int (*gdCacheTestFn_t)(void *userdata, void *keydata);
typedef void *(*gdCacheFetchFn_t)(char **error, void *keydata);
typedef void (*gdCacheReleaseFn_t)(void *userdata);
/* element structure */
typedef struct gdCache_element_s gdCache_element_t;
struct gdCache_element_s {
gdCache_element_t *next;
void *userdata;
};
/* head structure */
typedef struct gdCache_head_s gdCache_head_t;
struct gdCache_head_s {
gdCache_element_t *mru;
int size;
char *error;
gdCacheTestFn_t gdCacheTest;
gdCacheFetchFn_t gdCacheFetch;
gdCacheReleaseFn_t gdCacheRelease;
};
/* function templates */
gdCache_head_t *
gdCacheCreate(
int size,
gdCacheTestFn_t gdCacheTest,
gdCacheFetchFn_t gdCacheFetch,
gdCacheReleaseFn_t gdCacheRelease );
void
gdCacheDelete( gdCache_head_t *head );
void *
gdCacheGet( gdCache_head_t *head, void *keydata );
| 2,749 | 30.609195 | 71 |
h
|
php-src
|
php-src-master/ext/gd/libgd/gddemo.c
|
#include <stdio.h>
#include "gd.h"
#include "gdfontg.h"
#include "gdfonts.h"
int
main (void)
{
/* Input and output files */
FILE *in;
FILE *out;
/* Input and output images */
gdImagePtr im_in = 0, im_out = 0;
/* Brush image */
gdImagePtr brush;
/* Color indexes */
int white;
int blue;
int red;
int green;
/* Points for polygon */
gdPoint points[3];
/* Create output image, 256 by 256 pixels, true color. */
im_out = gdImageCreateTrueColor (256, 256);
/* First color allocated is background. */
white = gdImageColorAllocate (im_out, 255, 255, 255);
/* Set transparent color. */
gdImageColorTransparent (im_out, white);
/* Try to load demoin.png and paste part of it into the
output image. */
in = fopen ("demoin.png", "rb");
if (!in)
{
fprintf (stderr, "Can't load source image; this demo\n");
fprintf (stderr, "is much more impressive if demoin.png\n");
fprintf (stderr, "is available.\n");
im_in = 0;
}
else
{
im_in = gdImageCreateFromPng (in);
fclose (in);
/* Now copy, and magnify as we do so */
gdImageCopyResized (im_out, im_in,
32, 32, 0, 0, 192, 192, 255, 255);
}
red = gdImageColorAllocate (im_out, 255, 0, 0);
green = gdImageColorAllocate (im_out, 0, 255, 0);
blue = gdImageColorAllocate (im_out, 0, 0, 255);
/* Rectangle */
gdImageLine (im_out, 16, 16, 240, 16, green);
gdImageLine (im_out, 240, 16, 240, 240, green);
gdImageLine (im_out, 240, 240, 16, 240, green);
gdImageLine (im_out, 16, 240, 16, 16, green);
/* Circle */
gdImageArc (im_out, 128, 128, 60, 20, 0, 720, blue);
/* Arc */
gdImageArc (im_out, 128, 128, 40, 40, 90, 270, blue);
/* Flood fill: doesn't do much on a continuously
variable tone jpeg original. */
gdImageFill (im_out, 8, 8, blue);
/* Polygon */
points[0].x = 64;
points[0].y = 0;
points[1].x = 0;
points[1].y = 128;
points[2].x = 128;
points[2].y = 128;
gdImageFilledPolygon (im_out, points, 3, green);
/* Brush. A fairly wild example also involving a line style! */
if (im_in)
{
int style[8];
brush = gdImageCreateTrueColor (16, 16);
gdImageCopyResized (brush, im_in,
0, 0, 0, 0,
gdImageSX (brush), gdImageSY (brush),
gdImageSX (im_in), gdImageSY (im_in));
gdImageSetBrush (im_out, brush);
/* With a style, so they won't overprint each other.
Normally, they would, yielding a fat-brush effect. */
style[0] = 0;
style[1] = 0;
style[2] = 0;
style[3] = 0;
style[4] = 0;
style[5] = 0;
style[6] = 0;
style[7] = 1;
gdImageSetStyle (im_out, style, 8);
/* Draw the styled, brushed line */
gdImageLine (im_out, 0, 255, 255, 0, gdStyledBrushed);
}
/* Text */
gdImageString (im_out, gdFontGiant, 32, 32,
(unsigned char *) "hi", red);
gdImageStringUp (im_out, gdFontSmall, 64, 64,
(unsigned char *) "hi", red);
/* Make output image interlaced (progressive, in the case of JPEG) */
gdImageInterlace (im_out, 1);
out = fopen ("demoout.png", "wb");
/* Write PNG */
gdImagePng (im_out, out);
fclose (out);
gdImageDestroy (im_out);
if (im_in)
{
gdImageDestroy (im_in);
}
return 0;
}
| 3,261 | 26.411765 | 71 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdhelpers.h
|
#ifndef GDHELPERS_H
#define GDHELPERS_H 1
#include <sys/types.h>
#include "php.h"
/* TBB: strtok_r is not universal; provide an implementation of it. */
extern char *gd_strtok_r(char *s, char *sep, char **state);
/* These functions wrap memory management. gdFree is
in gd.h, where callers can utilize it to correctly
free memory allocated by these functions with the
right version of free(). */
#define gdCalloc(nmemb, size) ecalloc(nmemb, size)
#define gdMalloc(size) emalloc(size)
#define gdRealloc(ptr, size) erealloc(ptr, size)
#define gdEstrdup(ptr) estrdup(ptr)
#define gdFree(ptr) efree(ptr)
#define gdPMalloc(ptr) pemalloc(ptr, 1)
#define gdPFree(ptr) pefree(ptr, 1)
#define gdPEstrdup(ptr) pestrdup(ptr, 1)
/* Returns nonzero if multiplying the two quantities will
result in integer overflow. Also returns nonzero if
either quantity is negative. By Phil Knirsch based on
netpbm fixes by Alan Cox. */
int overflow2(int a, int b);
#ifdef ZTS
#define gdMutexDeclare(x) MUTEX_T x
#define gdMutexSetup(x) x = tsrm_mutex_alloc()
#define gdMutexShutdown(x) tsrm_mutex_free(x)
#define gdMutexLock(x) tsrm_mutex_lock(x)
#define gdMutexUnlock(x) tsrm_mutex_unlock(x)
#else
#define gdMutexDeclare(x)
#define gdMutexSetup(x)
#define gdMutexShutdown(x)
#define gdMutexLock(x)
#define gdMutexUnlock(x)
#endif
#define DPCM2DPI(dpcm) (unsigned int)((dpcm)*2.54 + 0.5)
#define DPM2DPI(dpm) (unsigned int)((dpm)*0.0254 + 0.5)
#define DPI2DPCM(dpi) (unsigned int)((dpi)/2.54 + 0.5)
#define DPI2DPM(dpi) (unsigned int)((dpi)/0.0254 + 0.5)
#endif /* GDHELPERS_H */
| 1,580 | 29.403846 | 70 |
h
|
php-src
|
php-src-master/ext/gd/libgd/gdparttopng.c
|
#include <stdio.h>
#include <stdlib.h> /* For atoi */
#include "gd.h"
/* A short program which converts a .png file into a .gd file, for
your convenience in creating images on the fly from a
basis image that must be loaded quickly. The .gd format
is not intended to be a general-purpose format. */
int
main (int argc, char **argv)
{
gdImagePtr im;
FILE *in, *out;
int x, y, w, h;
if (argc != 7)
{
fprintf (stderr, "Usage: gdparttopng filename.gd filename.png x y w h\n");
exit (1);
}
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Input file does not exist!\n");
exit (1);
}
x = atoi (argv[3]);
y = atoi (argv[4]);
w = atoi (argv[5]);
h = atoi (argv[6]);
printf ("Extracting from (%d, %d), size is %dx%d\n", x, y, w, h);
im = gdImageCreateFromGd2Part (in, x, y, w, h);
fclose (in);
if (!im)
{
fprintf (stderr, "Input is not in GD2 format!\n");
exit (1);
}
out = fopen (argv[2], "wb");
if (!out)
{
fprintf (stderr, "Output file cannot be written to!\n");
gdImageDestroy (im);
exit (1);
}
#ifdef HAVE_LIBPNG
gdImagePng (im, out);
#else
fprintf(stderr, "No PNG library support.\n");
#endif
fclose (out);
gdImageDestroy (im);
return 0;
}
| 1,289 | 20.5 | 80 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdtest.c
|
#include <stdio.h>
#ifdef _WIN32
#include <process.h>
int
unlink (const char *filename)
{
return _unlink (filename);
}
#else
#include <unistd.h> /* for getpid(), unlink() */
#endif
#include "gd.h"
void CompareImages (char *msg, gdImagePtr im1, gdImagePtr im2);
static int freadWrapper (void *context, char *buf, int len);
static int fwriteWrapper (void *context, const char *buffer, int len);
int
main (int argc, char **argv)
{
gdImagePtr im, ref, im2, im3;
FILE *in, *out;
void *iptr;
int sz;
gdIOCtxPtr ctx;
char of[256];
int colRed, colBlu;
gdSource imgsrc;
gdSink imgsnk;
int foreground;
int i;
if (argc != 2)
{
fprintf (stderr, "Usage: gdtest filename.png\n");
exit (1);
}
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Input file does not exist!\n");
exit (1);
}
im = gdImageCreateFromPng (in);
rewind (in);
ref = gdImageCreateFromPng (in);
fclose (in);
printf ("Reference File has %d Palette entries\n", ref->colorsTotal);
CompareImages ("Initial Versions", ref, im);
/* */
/* Send to PNG File then Ptr */
/* */
snprintf (of, sizeof(of), "%s.png", argv[1]);
out = fopen (of, "wb");
gdImagePng (im, out);
fclose (out);
in = fopen (of, "rb");
if (!in)
{
fprintf (stderr, "PNG Output file does not exist!\n");
exit (1);
}
im2 = gdImageCreateFromPng (in);
fclose (in);
CompareImages ("GD->PNG File->GD", ref, im2);
unlink (of);
gdImageDestroy (im2);
iptr = gdImagePngPtr (im, &sz);
ctx = gdNewDynamicCtx (sz, iptr);
im2 = gdImageCreateFromPngCtx (ctx);
CompareImages ("GD->PNG ptr->GD", ref, im2);
gdImageDestroy (im2);
ctx->gd_free (ctx);
/* */
/* Send to GD2 File then Ptr */
/* */
snprintf (of, sizeof(of), "%s.gd2", argv[1]);
out = fopen (of, "wb");
gdImageGd2 (im, out, 128, 2);
fclose (out);
in = fopen (of, "rb");
if (!in)
{
fprintf (stderr, "GD2 Output file does not exist!\n");
exit (1);
}
im2 = gdImageCreateFromGd2 (in);
fclose (in);
CompareImages ("GD->GD2 File->GD", ref, im2);
unlink (of);
gdImageDestroy (im2);
iptr = gdImageGd2Ptr (im, 128, 2, &sz);
/*printf("Got ptr %d (size %d)\n",iptr, sz); */
ctx = gdNewDynamicCtx (sz, iptr);
/*printf("Got ctx %d\n",ctx); */
im2 = gdImageCreateFromGd2Ctx (ctx);
/*printf("Got img2 %d\n",im2); */
CompareImages ("GD->GD2 ptr->GD", ref, im2);
gdImageDestroy (im2);
ctx->gd_free (ctx);
/* */
/* Send to GD File then Ptr */
/* */
snprintf (of, sizeof(of), "%s.gd", argv[1]);
out = fopen (of, "wb");
gdImageGd (im, out);
fclose (out);
in = fopen (of, "rb");
if (!in)
{
fprintf (stderr, "GD Output file does not exist!\n");
exit (1);
}
im2 = gdImageCreateFromGd (in);
fclose (in);
CompareImages ("GD->GD File->GD", ref, im2);
unlink (of);
gdImageDestroy (im2);
iptr = gdImageGdPtr (im, &sz);
/*printf("Got ptr %d (size %d)\n",iptr, sz); */
ctx = gdNewDynamicCtx (sz, iptr);
/*printf("Got ctx %d\n",ctx); */
im2 = gdImageCreateFromGdCtx (ctx);
/*printf("Got img2 %d\n",im2); */
CompareImages ("GD->GD ptr->GD", ref, im2);
gdImageDestroy (im2);
ctx->gd_free (ctx);
/*
** Test gdImageCreateFromPngSource'
* */
in = fopen (argv[1], "rb");
imgsrc.source = freadWrapper;
imgsrc.context = in;
im2 = gdImageCreateFromPngSource (&imgsrc);
fclose (in);
if (im2 == NULL)
{
printf ("GD Source: ERROR Null returned by gdImageCreateFromPngSource\n");
}
else
{
CompareImages ("GD Source", ref, im2);
gdImageDestroy (im2);
};
/*
** Test gdImagePngToSink'
* */
snprintf (of, sizeof(of), "%s.snk", argv[1]);
out = fopen (of, "wb");
imgsnk.sink = fwriteWrapper;
imgsnk.context = out;
gdImagePngToSink (im, &imgsnk);
fclose (out);
in = fopen (of, "rb");
if (!in)
{
fprintf (stderr, "GD Sink: ERROR - GD Sink Output file does not exist!\n");
}
else
{
im2 = gdImageCreateFromPng (in);
fclose (in);
CompareImages ("GD Sink", ref, im2);
gdImageDestroy (im2);
};
unlink (of);
/* */
/* Test Extraction */
/* */
in = fopen ("test/gdtest_200_300_150_100.png", "rb");
if (!in)
{
fprintf (stderr, "gdtest_200_300_150_100.png does not exist!\n");
exit (1);
}
im2 = gdImageCreateFromPng (in);
fclose (in);
in = fopen ("test/gdtest.gd2", "rb");
if (!in)
{
fprintf (stderr, "gdtest.gd2 does not exist!\n");
exit (1);
}
im3 = gdImageCreateFromGd2Part (in, 200, 300, 150, 100);
fclose (in);
CompareImages ("GD2Part (gdtest_200_300_150_100.png, gdtest.gd2(part))", im2, im3);
gdImageDestroy (im2);
gdImageDestroy (im3);
/* */
/* Copy Blend */
/* */
in = fopen ("test/gdtest.png", "rb");
if (!in)
{
fprintf (stderr, "gdtest.png does not exist!\n");
exit (1);
}
im2 = gdImageCreateFromPng (in);
fclose (in);
im3 = gdImageCreate (100, 60);
colRed = gdImageColorAllocate (im3, 255, 0, 0);
colBlu = gdImageColorAllocate (im3, 0, 0, 255);
gdImageFilledRectangle (im3, 0, 0, 49, 30, colRed);
gdImageFilledRectangle (im3, 50, 30, 99, 59, colBlu);
gdImageCopyMerge (im2, im3, 150, 200, 10, 10, 90, 50, 50);
gdImageCopyMerge (im2, im3, 180, 70, 10, 10, 90, 50, 50);
gdImageCopyMergeGray (im2, im3, 250, 160, 10, 10, 90, 50, 50);
gdImageCopyMergeGray (im2, im3, 80, 70, 10, 10, 90, 50, 50);
gdImageDestroy (im3);
in = fopen ("test/gdtest_merge.png", "rb");
if (!in)
{
fprintf (stderr, "gdtest_merge.png does not exist!\n");
exit (1);
}
im3 = gdImageCreateFromPng (in);
fclose (in);
printf ("[Merged Image has %d colours]\n", im2->colorsTotal);
CompareImages ("Merged (gdtest.png, gdtest_merge.png)", im2, im3);
gdImageDestroy (im2);
gdImageDestroy (im3);
#ifdef HAVE_JPEG
out = fopen ("test/gdtest.jpg", "wb");
if (!out)
{
fprintf (stderr, "Can't create file test/gdtest.jpg.\n");
exit (1);
}
gdImageJpeg (im, out, -1);
fclose (out);
in = fopen ("test/gdtest.jpg", "rb");
if (!in)
{
fprintf (stderr, "Can't open file test/gdtest.jpg.\n");
exit (1);
}
im2 = gdImageCreateFromJpeg (in);
fclose (in);
if (!im2)
{
fprintf (stderr, "gdImageCreateFromJpeg failed.\n");
exit (1);
}
gdImageDestroy (im2);
printf ("Created test/gdtest.jpg successfully. Compare this image\n"
"to the input image manually. Some difference must be\n"
"expected as JPEG is a lossy file format.\n");
#endif /* HAVE_JPEG */
/* Assume the color closest to black is the foreground
color for the B&W wbmp image. */
fprintf (stderr, "NOTE: the WBMP output image will NOT match the original unless the original\n"
"is also black and white. This is OK!\n");
foreground = gdImageColorClosest (im, 0, 0, 0);
fprintf (stderr, "Foreground index is %d\n", foreground);
if (foreground == -1)
{
fprintf (stderr, "Source image has no colors, skipping wbmp test.\n");
}
else
{
out = fopen ("test/gdtest.wbmp", "wb");
if (!out)
{
fprintf (stderr, "Can't create file test/gdtest.wbmp.\n");
exit (1);
}
gdImageWBMP (im, foreground, out);
fclose (out);
in = fopen ("test/gdtest.wbmp", "rb");
if (!in)
{
fprintf (stderr, "Can't open file test/gdtest.wbmp.\n");
exit (1);
}
im2 = gdImageCreateFromWBMP (in);
fprintf (stderr, "WBMP has %d colors\n", gdImageColorsTotal (im2));
fprintf (stderr, "WBMP colors are:\n");
for (i = 0; (i < gdImageColorsTotal (im2)); i++)
{
fprintf (stderr, "%02X%02X%02X\n",
gdImageRed (im2, i),
gdImageGreen (im2, i),
gdImageBlue (im2, i));
}
fclose (in);
if (!im2)
{
fprintf (stderr, "gdImageCreateFromWBMP failed.\n");
exit (1);
}
CompareImages ("WBMP test (gdtest.png, gdtest.wbmp)", ref, im2);
out = fopen ("test/gdtest_wbmp_to_png.png", "wb");
if (!out)
{
fprintf (stderr, "Can't create file test/gdtest_wbmp_to_png.png.\n");
exit (1);
}
gdImagePng (im2, out);
fclose (out);
gdImageDestroy (im2);
}
gdImageDestroy (im);
gdImageDestroy (ref);
return 0;
}
void
CompareImages (char *msg, gdImagePtr im1, gdImagePtr im2)
{
int cmpRes;
cmpRes = gdImageCompare (im1, im2);
if (cmpRes & GD_CMP_IMAGE)
{
printf ("%%%s: ERROR images differ: BAD\n", msg);
}
else if (cmpRes != 0)
{
printf ("%%%s: WARNING images differ: WARNING - Probably OK\n", msg);
}
else
{
printf ("%%%s: OK\n", msg);
return;
}
if (cmpRes & (GD_CMP_SIZE_X + GD_CMP_SIZE_Y))
{
printf ("-%s: INFO image sizes differ\n", msg);
}
if (cmpRes & GD_CMP_NUM_COLORS)
{
printf ("-%s: INFO number of palette entries differ %d Vs. %d\n", msg,
im1->colorsTotal, im2->colorsTotal);
}
if (cmpRes & GD_CMP_COLOR)
{
printf ("-%s: INFO actual colours of pixels differ\n", msg);
}
}
static int
freadWrapper (void *context, char *buf, int len)
{
int got = fread (buf, 1, len, (FILE *) context);
return got;
}
static int
fwriteWrapper (void *context, const char *buffer, int len)
{
return fwrite (buffer, 1, len, (FILE *) context);
}
| 9,323 | 21.741463 | 98 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdtestft.c
|
#include "gd.h"
#include <string.h>
#define PI 3.141592
#define DEG2RAD(x) ((x)*PI/180.)
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX4(x,y,z,w) \
((MAX((x),(y))) > (MAX((z),(w))) ? (MAX((x),(y))) : (MAX((z),(w))))
#define MIN4(x,y,z,w) \
((MIN((x),(y))) < (MIN((z),(w))) ? (MIN((x),(y))) : (MIN((z),(w))))
#define MAXX(x) MAX4(x[0],x[2],x[4],x[6])
#define MINX(x) MIN4(x[0],x[2],x[4],x[6])
#define MAXY(x) MAX4(x[1],x[3],x[5],x[7])
#define MINY(x) MIN4(x[1],x[3],x[5],x[7])
int
main (int argc, char *argv[])
{
#ifndef HAVE_LIBFREETYPE
fprintf (stderr, "gd was not compiled with HAVE_LIBFREETYPE defined.\n");
fprintf (stderr, "Install the FreeType library, including the\n");
fprintf (stderr, "header files. Then edit the gd Makefile, type\n");
fprintf (stderr, "make clean, and type make again.\n");
return 1;
#else
gdImagePtr im;
int black;
int white;
int brect[8];
int x, y;
char *err;
FILE *out;
#ifdef JISX0208
char *s = "Hello. ɂ Qyjpqg,"; /* String to draw. */
#else
char *s = "Hello. Qyjpqg,"; /* String to draw. */
#endif
double sz = 40.;
#if 0
double angle = 0.;
#else
double angle = DEG2RAD (-90);
#endif
#ifdef JISX0208
char *f = "/usr/openwin/lib/locale/ja/X11/fonts/TT/HG-MinchoL.ttf"; /* UNICODE */
/* char *f = "/usr/local/lib/fonts/truetype/DynaFont/dfpop1.ttf"; *//* SJIS */
#else
char *f = "times"; /* TrueType font */
#endif
/* obtain brect so that we can size the image */
err = gdImageStringFT ((gdImagePtr) NULL, &brect[0], 0, f, sz, angle, 0, 0, s);
if (err)
{
fprintf (stderr, "%s", err);
return 1;
}
/* create an image just big enough for the string */
x = MAXX (brect) - MINX (brect) + 6;
y = MAXY (brect) - MINY (brect) + 6;
#if 0
im = gdImageCreate (500, 500);
#else
/* gd 2.0: true color images can use freetype too */
im = gdImageCreateTrueColor (x, y);
#endif
/* Background color. gd 2.0: fill the image with it; truecolor
images have a black background otherwise. */
white = gdImageColorResolve (im, 255, 255, 255);
gdImageFilledRectangle (im, 0, 0, x, y, white);
black = gdImageColorResolve (im, 0, 0, 0);
/* render the string, offset origin to center string */
x = 0 - MINX (brect) + 3;
y = 0 - MINY (brect) + 3;
err = gdImageStringFT (im, NULL, black, f, sz, angle, x, y, s);
if (err)
{
fprintf (stderr, "%s", err);
return 1;
}
/* TBB: Write img to test/fttest.png */
out = fopen ("test/fttest.png", "wb");
if (!out)
{
fprintf (stderr, "Can't create test/fttest.png\n");
exit (1);
}
gdImagePng (im, out);
fclose (out);
fprintf (stderr, "Test image written to test/fttest.png\n");
/* Destroy it */
gdImageDestroy (im);
return 0;
#endif /* HAVE_LIBFREETYPE */
}
| 2,822 | 24.899083 | 83 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdtopng.c
|
#include <stdio.h>
#include "gd.h"
/* A short program which converts a .png file into a .gd file, for
your convenience in creating images on the fly from a
basis image that must be loaded quickly. The .gd format
is not intended to be a general-purpose format. */
int
main (int argc, char **argv)
{
gdImagePtr im;
FILE *in, *out;
if (argc != 3)
{
fprintf (stderr, "Usage: gdtopng filename.gd filename.png\n");
exit (1);
}
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Input file does not exist!\n");
exit (1);
}
im = gdImageCreateFromGd (in);
fclose (in);
if (!im)
{
fprintf (stderr, "Input is not in GD format!\n");
exit (1);
}
out = fopen (argv[2], "wb");
if (!out)
{
fprintf (stderr, "Output file cannot be written to!\n");
gdImageDestroy (im);
exit (1);
}
gdImagePng (im, out);
fclose (out);
gdImageDestroy (im);
return 0;
}
| 965 | 20.466667 | 68 |
c
|
php-src
|
php-src-master/ext/gd/libgd/gdxpm.c
|
/*
add ability to load xpm files to gd, requires the xpm
library.
[email protected]
http://www.csn.ul.ie/~caolan
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gd.h"
#include "gdhelpers.h"
#ifdef HAVE_XPM
#include <X11/xpm.h>
gdImagePtr gdImageCreateFromXpm (char *filename)
{
XpmInfo info = {0};
XpmImage image;
int i, j, k, number;
char buf[5];
gdImagePtr im = 0;
int *pointer;
int red = 0, green = 0, blue = 0;
int *colors;
int ret;
ret = XpmReadFileToXpmImage(filename, &image, &info);
if (ret != XpmSuccess) {
return 0;
}
number = image.ncolors;
for(i = 0; i < number; i++) {
if (!image.colorTable[i].c_color) {
goto done;
}
}
if (!(im = gdImageCreate(image.width, image.height))) {
goto done;
}
colors = (int *) safe_emalloc(number, sizeof(int), 0);
for (i = 0; i < number; i++) {
switch (strlen (image.colorTable[i].c_color)) {
case 4:
buf[1] = '\0';
buf[0] = image.colorTable[i].c_color[1];
red = strtol(buf, NULL, 16);
buf[0] = image.colorTable[i].c_color[2];
green = strtol(buf, NULL, 16);
buf[0] = image.colorTable[i].c_color[3];
blue = strtol(buf, NULL, 16);
break;
case 7:
buf[2] = '\0';
buf[0] = image.colorTable[i].c_color[1];
buf[1] = image.colorTable[i].c_color[2];
red = strtol(buf, NULL, 16);
buf[0] = image.colorTable[i].c_color[3];
buf[1] = image.colorTable[i].c_color[4];
green = strtol(buf, NULL, 16);
buf[0] = image.colorTable[i].c_color[5];
buf[1] = image.colorTable[i].c_color[6];
blue = strtol(buf, NULL, 16);
break;
case 10:
buf[3] = '\0';
buf[0] = image.colorTable[i].c_color[1];
buf[1] = image.colorTable[i].c_color[2];
buf[2] = image.colorTable[i].c_color[3];
red = strtol(buf, NULL, 16);
red /= 64;
buf[0] = image.colorTable[i].c_color[4];
buf[1] = image.colorTable[i].c_color[5];
buf[2] = image.colorTable[i].c_color[6];
green = strtol(buf, NULL, 16);
green /= 64;
buf[0] = image.colorTable[i].c_color[7];
buf[1] = image.colorTable[i].c_color[8];
buf[2] = image.colorTable[i].c_color[9];
blue = strtol(buf, NULL, 16);
blue /= 64;
break;
case 13:
buf[4] = '\0';
buf[0] = image.colorTable[i].c_color[1];
buf[1] = image.colorTable[i].c_color[2];
buf[2] = image.colorTable[i].c_color[3];
buf[3] = image.colorTable[i].c_color[4];
red = strtol(buf, NULL, 16);
red /= 256;
buf[0] = image.colorTable[i].c_color[5];
buf[1] = image.colorTable[i].c_color[6];
buf[2] = image.colorTable[i].c_color[7];
buf[3] = image.colorTable[i].c_color[8];
green = strtol(buf, NULL, 16);
green /= 256;
buf[0] = image.colorTable[i].c_color[9];
buf[1] = image.colorTable[i].c_color[10];
buf[2] = image.colorTable[i].c_color[11];
buf[3] = image.colorTable[i].c_color[12];
blue = strtol(buf, NULL, 16);
blue /= 256;
break;
}
colors[i] = gdImageColorResolve(im, red, green, blue);
}
pointer = (int *) image.data;
for (i = 0; i < image.height; i++) {
for (j = 0; j < image.width; j++) {
k = *pointer++;
gdImageSetPixel(im, j, i, colors[k]);
}
}
gdFree(colors);
done:
XpmFreeXpmImage(&image);
XpmFreeXpmInfo(&info);
return im;
}
#endif
| 3,290 | 22.507143 | 56 |
c
|
php-src
|
php-src-master/ext/gd/libgd/pngtogd.c
|
#include <stdio.h>
#include "gd.h"
/* A short program which converts a .png file into a .gd file, for
your convenience in creating images on the fly from a
basis image that must be loaded quickly. The .gd format
is not intended to be a general-purpose format. */
int
main (int argc, char **argv)
{
gdImagePtr im;
FILE *in, *out;
if (argc != 3)
{
fprintf (stderr, "Usage: pngtogd filename.png filename.gd\n");
exit (1);
}
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Input file does not exist!\n");
exit (1);
}
im = gdImageCreateFromPng (in);
fclose (in);
if (!im)
{
fprintf (stderr, "Input is not in PNG format!\n");
exit (1);
}
out = fopen (argv[2], "wb");
if (!out)
{
fprintf (stderr, "Output file cannot be written to!\n");
gdImageDestroy (im);
exit (1);
}
gdImageGd (im, out);
fclose (out);
gdImageDestroy (im);
return 0;
}
| 967 | 20.043478 | 68 |
c
|
php-src
|
php-src-master/ext/gd/libgd/pngtogd2.c
|
#include <stdio.h>
#include <stdlib.h>
#include "gd.h"
/* A short program which converts a .png file into a .gd file, for
your convenience in creating images on the fly from a
basis image that must be loaded quickly. The .gd format
is not intended to be a general-purpose format. */
int
main (int argc, char **argv)
{
gdImagePtr im;
FILE *in, *out;
int cs, fmt;
if (argc != 5)
{
fprintf (stderr, "Usage: pngtogd2 filename.png filename.gd2 cs fmt\n");
fprintf (stderr, " where cs is the chunk size\n");
fprintf (stderr, " fmt is 1 for raw, 2 for compressed\n");
exit (1);
}
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Input file does not exist!\n");
exit (1);
}
im = gdImageCreateFromPng (in);
fclose (in);
if (!im)
{
fprintf (stderr, "Input is not in PNG format!\n");
exit (1);
}
out = fopen (argv[2], "wb");
if (!out)
{
fprintf (stderr, "Output file cannot be written to!\n");
gdImageDestroy (im);
exit (1);
}
cs = atoi (argv[3]);
fmt = atoi (argv[4]);
gdImageGd2 (im, out, cs, fmt);
fclose (out);
gdImageDestroy (im);
return 0;
}
| 1,203 | 21.716981 | 77 |
c
|
php-src
|
php-src-master/ext/gd/libgd/testac.c
|
#include <stdio.h>
#include "gd.h"
/* If palette is true, we convert from truecolor to palette at the end,
to test gdImageTrueColorToPalette and see file size/
quality tradeoffs. */
void testDrawing (
gdImagePtr im_in,
double scale,
int blending,
int palette,
char *filename);
int
main (int argc, char *argv[])
{
/* Input and output files */
FILE *in;
FILE *out;
/* Input image */
gdImagePtr im_in = 0;
/* Colors */
int lightBlue;
if (argc != 2)
{
fprintf (stderr, "Usage: testac filename.png\n");
exit (1);
}
/* Load original PNG, which should contain alpha channel
information. We will use it in two ways: preserving it
literally, for use with compatible browsers, and
compositing it ourselves against a background of our
choosing (alpha blending). We'll change its size
and try creating palette versions of it. */
in = fopen (argv[1], "rb");
if (!in)
{
fprintf (stderr, "Can't load %s.\n", argv[1]);
exit (1);
}
else
{
im_in = gdImageCreateFromPng (in);
fclose (in);
}
testDrawing (im_in, 1.0, 0, 0, "noblending-fullsize-truecolor.png");
testDrawing (im_in, 1.0, 1, 0, "blending-fullsize-truecolor.png");
testDrawing (im_in, 0.5, 0, 0, "noblending-halfsize-truecolor.png");
testDrawing (im_in, 0.5, 1, 0, "blending-halfsize-truecolor.png");
testDrawing (im_in, 2.0, 0, 0, "noblending-doublesize-truecolor.png");
testDrawing (im_in, 2.0, 1, 0, "blending-doublesize-truecolor.png");
testDrawing (im_in, 1.0, 0, 1, "noblending-fullsize-palette.png");
testDrawing (im_in, 1.0, 1, 1, "blending-fullsize-palette.png");
testDrawing (im_in, 0.5, 0, 1, "noblending-halfsize-palette.png");
testDrawing (im_in, 0.5, 1, 1, "blending-halfsize-palette.png");
testDrawing (im_in, 2.0, 0, 1, "noblending-doublesize-palette.png");
testDrawing (im_in, 2.0, 1, 1, "blending-doublesize-palette.png");
gdImageDestroy (im_in);
return 0;
}
/* If palette is true, we convert from truecolor to palette at the end,
to test gdImageTrueColorToPalette and see file size/
quality tradeoffs. */
void
testDrawing (
gdImagePtr im_in,
double scale,
int blending,
int palette,
char *filename)
{
gdImagePtr im_out;
FILE *out;
/* Create output image. */
im_out = gdImageCreateTrueColor ((int) (gdImageSX (im_in) * scale),
(int) (gdImageSY (im_in) * scale));
/*
Request alpha blending. This causes future
drawing operations to perform alpha channel blending
with the background, resulting in an opaque image.
Without this call, pixels in the foreground color are
copied literally, *including* the alpha channel value,
resulting in an output image which is potentially
not opaque. This flag can be set and cleared as often
as desired. */
gdImageAlphaBlending (im_out, blending);
/* Flood with light blue. */
gdImageFill (im_out, (int) (gdImageSX (im_in) * scale / 2),
(int) (gdImageSY (im_in) * scale / 2),
gdTrueColor (192, 192, 255));
/* Copy the source image. Alpha blending should result in
compositing against red. With blending turned off, the
browser or viewer will composite against its preferred
background, or, if it does not support an alpha channel,
we will see the original colors for the pixels that
ought to be transparent or semitransparent. */
gdImageCopyResampled (im_out, im_in,
0, 0,
0, 0,
(int) (gdImageSX (im_in) * scale), (int) (gdImageSY (im_in) * scale),
gdImageSX (im_in), gdImageSY (im_in));
/* Write PNG */
out = fopen (filename, "wb");
/* If this image is the result of alpha channel blending,
it will not contain an interesting alpha channel itself.
Save a little file size by not saving the alpha channel.
Otherwise the file would typically be slightly larger. */
gdImageSaveAlpha (im_out, !blending);
/* If requested, convert from truecolor to palette. */
if (palette)
{
/* Dithering, 256 colors. */
gdImageTrueColorToPalette (im_out, 1, 256);
}
gdImagePng (im_out, out);
fclose (out);
gdImageDestroy (im_out);
}
| 4,208 | 31.376923 | 76 |
c
|
php-src
|
php-src-master/ext/gd/libgd/wbmp.h
|
/* WBMP
** ----
** WBMP Level 0: B/W, Uncompressed
** This implements the WBMP format as specified in WAPSpec 1.1 and 1.2.
** It does not support ExtHeaders as defined in the spec. The spec states
** that a WAP client does not need to implement ExtHeaders.
**
** (c) 2000 Johan Van den Brande <[email protected]>
**
** Header file
*/
#ifndef __WBMP_H
#define __WBMP_H 1
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_compat.h"
/* WBMP struct
** -----------
** A Wireless bitmap structure
**
*/
typedef struct Wbmp_
{
int type; /* type of the wbmp */
int width; /* width of the image */
int height; /* height of the image */
int *bitmap; /* pointer to data: 0 = WHITE , 1 = BLACK */
} Wbmp;
#define WBMP_WHITE 1
#define WBMP_BLACK 0
/* Proto's
** -------
**
*/
void putmbi( int i, void (*putout)(int c, void *out), void *out);
int getmbi ( int (*getin)(void *in), void *in );
int skipheader( int (*getin)(void *in), void *in );
Wbmp *createwbmp( int width, int height, int color );
int readwbmp( int (*getin)(void *in), void *in, Wbmp **wbmp );
int writewbmp( Wbmp *wbmp, void (*putout)( int c, void *out), void *out);
void freewbmp( Wbmp *wbmp );
void printwbmp( Wbmp *wbmp );
#endif
| 1,283 | 23.226415 | 74 |
h
|
php-src
|
php-src-master/ext/gd/libgd/webpng.c
|
/* Bring in the gd library functions */
#include "gd.h"
/* Bring in standard I/O and string manipulation functions */
#include <stdio.h>
#include <stdlib.h> /* for atoi() */
#include <string.h>
#ifdef _WIN32
#include <process.h>
int
getpid ()
{
return _getpid ();
}
#else
#include <unistd.h> /* for getpid(), unlink() */
#endif
int
main (int argc, char **argv)
{
FILE *in;
FILE *out;
char outFn[20];
int useStdinStdout = 0;
/* Declare our image pointer */
gdImagePtr im = 0;
int i;
/* We'll clear 'no' once we know the user has made a
reasonable request. */
int no = 1;
/* We'll set 'write' once we know the user's request
requires that the image be written back to disk. */
int write = 0;
/* C programs always get at least one argument; we want at
least one more (the image), more in practice. */
if (argc < 2 || !strcmp (argv[1], "--help"))
{
no = 1;
goto usage;
}
/* The last argument should be the image. Open the file. */
if (strcmp ("-", argv[argc - 1]) == 0)
{ /* - is synonymous with STDIN */
useStdinStdout = 1;
in = stdin;
}
else
{
in = fopen (argv[argc - 1], "rb");
}
if (!in)
{
fprintf (stderr,
"Error: can't open file %s.\n", argv[argc - 1]);
exit (1);
}
/* Now load the image. */
im = gdImageCreateFromPng (in);
fclose (in);
/* If the load failed, it must not be a PNG file. */
if (!im)
{
fprintf (stderr,
"Error: %s is not a valid PNG file.\n", argv[argc - 1]);
exit (1);
}
/* Consider each argument in turn. */
for (i = 1; (i < (argc - 1)); i++)
{
/* -i turns on and off interlacing. */
if (!strcmp (argv[i], "--help"))
{
/* Every program should use this for help! :) */
no = 1;
goto usage;
}
else if (!strcmp (argv[i], "-i"))
{
if (i == (argc - 2))
{
fprintf (stderr,
"Error: -i specified without y or n.\n");
no = 1;
goto usage;
}
if (!strcmp (argv[i + 1], "y"))
{
/* Set interlace. */
gdImageInterlace (im, 1);
}
else if (!strcmp (argv[i + 1], "n"))
{
/* Clear interlace. */
gdImageInterlace (im, 0);
}
else
{
fprintf (stderr,
"Error: -i specified without y or n.\n");
no = 1;
goto usage;
}
i++;
no = 0;
write = 1;
}
else if (!strcmp (argv[i], "-t"))
{
/* Set transparent index (or none). */
int index;
if (i == (argc - 2))
{
fprintf (stderr,
"Error: -t specified without a color table index.\n");
no = 1;
goto usage;
}
if (!strcmp (argv[i + 1], "none"))
{
/* -1 means not transparent. */
gdImageColorTransparent (im, -1);
}
else
{
/* OK, get an integer and set the index. */
index = atoi (argv[i + 1]);
gdImageColorTransparent (im, index);
}
i++;
write = 1;
no = 0;
}
else if (!strcmp (argv[i], "-l"))
{
/* List the colors in the color table. */
int j;
if (!im->trueColor)
{
/* Tabs used below. */
printf ("Index Red Green Blue Alpha\n");
for (j = 0; (j < gdImageColorsTotal (im)); j++)
{
/* Use access macros to learn colors. */
printf ("%d %d %d %d %d\n",
j,
gdImageRed (im, j),
gdImageGreen (im, j),
gdImageBlue (im, j),
gdImageAlpha (im, j));
}
}
else
{
printf ("Truecolor image, no palette entries to list.\n");
}
no = 0;
}
else if (!strcmp (argv[i], "-d"))
{
/* Output dimensions, etc. */
int t;
printf ("Width: %d Height: %d Colors: %d\n",
gdImageSX (im), gdImageSY (im),
gdImageColorsTotal (im));
t = gdImageGetTransparent (im);
if (t != (-1))
{
printf ("First 100%% transparent index: %d\n", t);
}
else
{
/* -1 means the image is not transparent. */
printf ("First 100%% transparent index: none\n");
}
if (gdImageGetInterlaced (im))
{
printf ("Interlaced: yes\n");
}
else
{
printf ("Interlaced: no\n");
}
no = 0;
}
else if (!strcmp(argv[i], "-a"))
{
int maxx, maxy, x, y, alpha, pix, nalpha = 0;
maxx = gdImageSX(im);
maxy = gdImageSY(im);
printf("alpha channel information:\n");
if (im->trueColor) {
for (y = 0; y < maxy; y++) {
for (x = 0; x < maxx; x++) {
pix = gdImageGetPixel(im, x, y);
alpha = gdTrueColorGetAlpha(pix);
if (alpha > gdAlphaOpaque) {
/* Use access macros to learn colors. */
printf ("%d %d %d %d\n",
gdTrueColorGetRed(pix),
gdTrueColorGetGreen(pix),
gdTrueColorGetBlue(pix),
alpha);
nalpha++;
}
}
}
}
else
printf("NOT a true color image\n");
no = 0;
printf("%d alpha channels\n", nalpha);
}
else
{
fprintf (stderr, "Unknown argument: %s\n", argv[i]);
break;
}
}
usage:
if (no)
{
/* If the command failed, output an explanation. */
fprintf (stderr,
"Usage: webpng [-i y|n ] [-l] [-t index|none ] [-d] pngname.png\n"
" -i [y|n] Turns on/off interlace\n"
" -l Prints the table of color indexes\n"
" -t [index] Set the transparent color to the specified index (0-255 or \"none\")\n"
" -d Reports the dimensions and other characteristics of the image.\n"
" -a Prints all alpha channels that are not 100%% opaque.\n"
"\n"
"If you specify '-' as the input file, stdin/stdout will be used input/output.\n"
);
}
if (write)
{
if (useStdinStdout)
{
out = stdout;
}
else
{
/* Open a temporary file. */
/* "temp.tmp" is not good temporary filename. */
snprintf (outFn, sizeof(outFn), "webpng.tmp%d", getpid ());
out = fopen (outFn, "wb");
if (!out)
{
fprintf (stderr,
"Unable to write to %s -- exiting\n", outFn);
exit (1);
}
}
/* Write the new PNG. */
gdImagePng (im, out);
if (!useStdinStdout)
{
fclose (out);
/* Erase the old PNG. */
unlink (argv[argc - 1]);
/* Rename the new to the old. */
if (rename (outFn, argv[argc - 1]) != 0)
{
perror ("rename");
exit (1);
}
}
}
/* Delete the image from memory. */
if (im)
{
gdImageDestroy (im);
}
/* All's well that ends well. */
return 0;
}
| 6,471 | 21.317241 | 93 |
c
|
php-src
|
php-src-master/ext/gettext/gettext.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Alex Plotnick <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef HAVE_LIBINTL
#include <stdio.h>
#include "ext/standard/info.h"
#include "php_gettext.h"
#include "gettext_arginfo.h"
#include <libintl.h>
zend_module_entry php_gettext_module_entry = {
STANDARD_MODULE_HEADER,
"gettext",
ext_functions,
NULL,
NULL,
NULL,
NULL,
PHP_MINFO(php_gettext),
PHP_GETTEXT_VERSION,
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_GETTEXT
ZEND_GET_MODULE(php_gettext)
#endif
#define PHP_GETTEXT_MAX_DOMAIN_LENGTH 1024
#define PHP_GETTEXT_MAX_MSGID_LENGTH 4096
#define PHP_GETTEXT_DOMAIN_LENGTH_CHECK(_arg_num, domain_len) \
if (UNEXPECTED(domain_len > PHP_GETTEXT_MAX_DOMAIN_LENGTH)) { \
zend_argument_value_error(_arg_num, "is too long"); \
RETURN_THROWS(); \
}
#define PHP_GETTEXT_LENGTH_CHECK(_arg_num, check_len) \
if (UNEXPECTED(check_len > PHP_GETTEXT_MAX_MSGID_LENGTH)) { \
zend_argument_value_error(_arg_num, "is too long"); \
RETURN_THROWS(); \
}
PHP_MINFO_FUNCTION(php_gettext)
{
php_info_print_table_start();
php_info_print_table_row(2, "GetText Support", "enabled");
php_info_print_table_end();
}
/* {{{ Set the textdomain to "domain". Returns the current domain */
PHP_FUNCTION(textdomain)
{
char *domain_name = NULL, *retval;
zend_string *domain = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "S!", &domain) == FAILURE) {
RETURN_THROWS();
}
if (domain != NULL && ZSTR_LEN(domain) != 0 && !zend_string_equals_literal(domain, "0")) {
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, ZSTR_LEN(domain))
domain_name = ZSTR_VAL(domain);
}
retval = textdomain(domain_name);
RETURN_STRING(retval);
}
/* }}} */
/* {{{ Return the translation of msgid for the current domain, or msgid unaltered if a translation does not exist */
PHP_FUNCTION(gettext)
{
char *msgstr;
zend_string *msgid;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(msgid)
ZEND_PARSE_PARAMETERS_END();
PHP_GETTEXT_LENGTH_CHECK(1, ZSTR_LEN(msgid))
msgstr = gettext(ZSTR_VAL(msgid));
if (msgstr != ZSTR_VAL(msgid)) {
RETURN_STRING(msgstr);
} else {
RETURN_STR_COPY(msgid);
}
}
/* }}} */
/* {{{ Return the translation of msgid for domain_name, or msgid unaltered if a translation does not exist */
PHP_FUNCTION(dgettext)
{
char *msgstr;
zend_string *domain, *msgid;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "SS", &domain, &msgid) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, ZSTR_LEN(domain))
PHP_GETTEXT_LENGTH_CHECK(2, ZSTR_LEN(msgid))
msgstr = dgettext(ZSTR_VAL(domain), ZSTR_VAL(msgid));
if (msgstr != ZSTR_VAL(msgid)) {
RETURN_STRING(msgstr);
} else {
RETURN_STR_COPY(msgid);
}
}
/* }}} */
/* {{{ Return the translation of msgid for domain_name and category, or msgid unaltered if a translation does not exist */
PHP_FUNCTION(dcgettext)
{
char *msgstr;
zend_string *domain, *msgid;
zend_long category;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "SSl", &domain, &msgid, &category) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, ZSTR_LEN(domain))
PHP_GETTEXT_LENGTH_CHECK(2, ZSTR_LEN(msgid))
msgstr = dcgettext(ZSTR_VAL(domain), ZSTR_VAL(msgid), category);
if (msgstr != ZSTR_VAL(msgid)) {
RETURN_STRING(msgstr);
} else {
RETURN_STR_COPY(msgid);
}
}
/* }}} */
/* {{{ Bind to the text domain domain_name, looking for translations in dir. Returns the current domain */
PHP_FUNCTION(bindtextdomain)
{
char *domain;
size_t domain_len;
zend_string *dir = NULL;
char *retval, dir_name[MAXPATHLEN];
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sS!", &domain, &domain_len, &dir) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, domain_len)
if (domain[0] == '\0') {
zend_argument_value_error(1, "cannot be empty");
RETURN_THROWS();
}
if (dir == NULL) {
RETURN_STRING(bindtextdomain(domain, NULL));
}
if (ZSTR_LEN(dir) != 0 && !zend_string_equals_literal(dir, "0")) {
if (!VCWD_REALPATH(ZSTR_VAL(dir), dir_name)) {
RETURN_FALSE;
}
} else if (!VCWD_GETCWD(dir_name, MAXPATHLEN)) {
RETURN_FALSE;
}
retval = bindtextdomain(domain, dir_name);
RETURN_STRING(retval);
}
/* }}} */
#ifdef HAVE_NGETTEXT
/* {{{ Plural version of gettext() */
PHP_FUNCTION(ngettext)
{
char *msgid1, *msgid2, *msgstr;
size_t msgid1_len, msgid2_len;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssl", &msgid1, &msgid1_len, &msgid2, &msgid2_len, &count) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_LENGTH_CHECK(1, msgid1_len)
PHP_GETTEXT_LENGTH_CHECK(2, msgid2_len)
msgstr = ngettext(msgid1, msgid2, count);
ZEND_ASSERT(msgstr);
RETURN_STRING(msgstr);
}
/* }}} */
#endif
#ifdef HAVE_DNGETTEXT
/* {{{ Plural version of dgettext() */
PHP_FUNCTION(dngettext)
{
char *domain, *msgid1, *msgid2, *msgstr = NULL;
size_t domain_len, msgid1_len, msgid2_len;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sssl", &domain, &domain_len,
&msgid1, &msgid1_len, &msgid2, &msgid2_len, &count) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, domain_len)
PHP_GETTEXT_LENGTH_CHECK(2, msgid1_len)
PHP_GETTEXT_LENGTH_CHECK(3, msgid2_len)
msgstr = dngettext(domain, msgid1, msgid2, count);
ZEND_ASSERT(msgstr);
RETURN_STRING(msgstr);
}
/* }}} */
#endif
#ifdef HAVE_DCNGETTEXT
/* {{{ Plural version of dcgettext() */
PHP_FUNCTION(dcngettext)
{
char *domain, *msgid1, *msgid2, *msgstr = NULL;
size_t domain_len, msgid1_len, msgid2_len;
zend_long count, category;
RETVAL_FALSE;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sssll", &domain, &domain_len,
&msgid1, &msgid1_len, &msgid2, &msgid2_len, &count, &category) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, domain_len)
PHP_GETTEXT_LENGTH_CHECK(2, msgid1_len)
PHP_GETTEXT_LENGTH_CHECK(3, msgid2_len)
msgstr = dcngettext(domain, msgid1, msgid2, count, category);
ZEND_ASSERT(msgstr);
RETURN_STRING(msgstr);
}
/* }}} */
#endif
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
/* {{{ Specify the character encoding in which the messages from the DOMAIN message catalog will be returned. */
PHP_FUNCTION(bind_textdomain_codeset)
{
char *domain, *codeset = NULL, *retval = NULL;
size_t domain_len, codeset_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss!", &domain, &domain_len, &codeset, &codeset_len) == FAILURE) {
RETURN_THROWS();
}
PHP_GETTEXT_DOMAIN_LENGTH_CHECK(1, domain_len)
retval = bind_textdomain_codeset(domain, codeset);
if (!retval) {
RETURN_FALSE;
}
RETURN_STRING(retval);
}
/* }}} */
#endif
#endif /* HAVE_LIBINTL */
| 7,531 | 24.275168 | 122 |
c
|
php-src
|
php-src-master/ext/gettext/gettext_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: 864b3389d4f99b0d7302ae399544e6fb9fb80b7e */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_textdomain, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gettext, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo__ arginfo_gettext
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dgettext, 0, 2, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dcgettext, 0, 3, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, category, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_bindtextdomain, 0, 2, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, directory, IS_STRING, 1)
ZEND_END_ARG_INFO()
#if defined(HAVE_NGETTEXT)
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ngettext, 0, 3, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, singular, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, plural, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, count, IS_LONG, 0)
ZEND_END_ARG_INFO()
#endif
#if defined(HAVE_DNGETTEXT)
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dngettext, 0, 4, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, singular, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, plural, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, count, IS_LONG, 0)
ZEND_END_ARG_INFO()
#endif
#if defined(HAVE_DCNGETTEXT)
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_dcngettext, 0, 5, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, singular, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, plural, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, count, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, category, IS_LONG, 0)
ZEND_END_ARG_INFO()
#endif
#if defined(HAVE_BIND_TEXTDOMAIN_CODESET)
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_bind_textdomain_codeset, 0, 2, MAY_BE_STRING|MAY_BE_FALSE)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, codeset, IS_STRING, 1)
ZEND_END_ARG_INFO()
#endif
ZEND_FUNCTION(textdomain);
ZEND_FUNCTION(gettext);
ZEND_FUNCTION(dgettext);
ZEND_FUNCTION(dcgettext);
ZEND_FUNCTION(bindtextdomain);
#if defined(HAVE_NGETTEXT)
ZEND_FUNCTION(ngettext);
#endif
#if defined(HAVE_DNGETTEXT)
ZEND_FUNCTION(dngettext);
#endif
#if defined(HAVE_DCNGETTEXT)
ZEND_FUNCTION(dcngettext);
#endif
#if defined(HAVE_BIND_TEXTDOMAIN_CODESET)
ZEND_FUNCTION(bind_textdomain_codeset);
#endif
static const zend_function_entry ext_functions[] = {
ZEND_FE(textdomain, arginfo_textdomain)
ZEND_FE(gettext, arginfo_gettext)
ZEND_FALIAS(_, gettext, arginfo__)
ZEND_FE(dgettext, arginfo_dgettext)
ZEND_FE(dcgettext, arginfo_dcgettext)
ZEND_FE(bindtextdomain, arginfo_bindtextdomain)
#if defined(HAVE_NGETTEXT)
ZEND_FE(ngettext, arginfo_ngettext)
#endif
#if defined(HAVE_DNGETTEXT)
ZEND_FE(dngettext, arginfo_dngettext)
#endif
#if defined(HAVE_DCNGETTEXT)
ZEND_FE(dcngettext, arginfo_dcngettext)
#endif
#if defined(HAVE_BIND_TEXTDOMAIN_CODESET)
ZEND_FE(bind_textdomain_codeset, arginfo_bind_textdomain_codeset)
#endif
ZEND_FE_END
};
| 3,346 | 30.87619 | 106 |
h
|
php-src
|
php-src-master/ext/gettext/php_gettext.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Alex Plotnick <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_GETTEXT_H
#define PHP_GETTEXT_H
#ifdef HAVE_LIBINTL
extern zend_module_entry php_gettext_module_entry;
#define gettext_module_ptr &php_gettext_module_entry
#include "php_version.h"
#define PHP_GETTEXT_VERSION PHP_VERSION
PHP_MINFO_FUNCTION(php_gettext);
#else
#define gettext_module_ptr NULL
#endif /* HAVE_LIBINTL */
#define phpext_gettext_ptr gettext_module_ptr
#endif /* PHP_GETTEXT_H */
| 1,405 | 37 | 75 |
h
|
php-src
|
php-src-master/ext/gmp/gmp_arginfo.h
|
/* This is a generated file, edit the .stub.php file instead.
* Stub hash: d52f82c7084a8122fe07c91eb6d4ab6030daa27d */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_init, 0, 1, GMP, 0)
ZEND_ARG_TYPE_MASK(0, num, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, base, IS_LONG, 0, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_import, 0, 1, GMP, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, word_size, IS_LONG, 0, "1")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "GMP_MSW_FIRST | GMP_NATIVE_ENDIAN")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_export, 0, 1, IS_STRING, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, word_size, IS_LONG, 0, "1")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_LONG, 0, "GMP_MSW_FIRST | GMP_NATIVE_ENDIAN")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_intval, 0, 1, IS_LONG, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_strval, 0, 1, IS_STRING, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, base, IS_LONG, 0, "10")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_add, 0, 2, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, num2, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_gmp_sub arginfo_gmp_add
#define arginfo_gmp_mul arginfo_gmp_add
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_div_qr, 0, 2, IS_ARRAY, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, num2, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, rounding_mode, IS_LONG, 0, "GMP_ROUND_ZERO")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_div_q, 0, 2, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, num2, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, rounding_mode, IS_LONG, 0, "GMP_ROUND_ZERO")
ZEND_END_ARG_INFO()
#define arginfo_gmp_div_r arginfo_gmp_div_q
#define arginfo_gmp_div arginfo_gmp_div_q
#define arginfo_gmp_mod arginfo_gmp_add
#define arginfo_gmp_divexact arginfo_gmp_add
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_neg, 0, 1, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_gmp_abs arginfo_gmp_neg
#define arginfo_gmp_fact arginfo_gmp_neg
#define arginfo_gmp_sqrt arginfo_gmp_neg
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_sqrtrem, 0, 1, IS_ARRAY, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_root, 0, 2, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO(0, nth, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_rootrem, 0, 2, IS_ARRAY, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO(0, nth, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_pow, 0, 2, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO(0, exponent, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_powm, 0, 3, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, exponent, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, modulus, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_perfect_square, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_gmp_perfect_power arginfo_gmp_perfect_square
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_prob_prime, 0, 1, IS_LONG, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, repetitions, IS_LONG, 0, "10")
ZEND_END_ARG_INFO()
#define arginfo_gmp_gcd arginfo_gmp_add
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_gcdext, 0, 2, IS_ARRAY, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, num2, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_gmp_lcm arginfo_gmp_add
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_gmp_invert, 0, 2, GMP, MAY_BE_FALSE)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, num2, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_jacobi, 0, 2, IS_LONG, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, num2, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_gmp_legendre arginfo_gmp_jacobi
#define arginfo_gmp_kronecker arginfo_gmp_jacobi
#define arginfo_gmp_cmp arginfo_gmp_jacobi
#define arginfo_gmp_sign arginfo_gmp_intval
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_random_seed, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, seed, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_random_bits, 0, 1, GMP, 0)
ZEND_ARG_TYPE_INFO(0, bits, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_random_range, 0, 2, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, min, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, max, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_gmp_and arginfo_gmp_add
#define arginfo_gmp_or arginfo_gmp_add
#define arginfo_gmp_com arginfo_gmp_neg
#define arginfo_gmp_xor arginfo_gmp_add
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_setbit, 0, 2, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, num, GMP, 0)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, value, _IS_BOOL, 0, "true")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_clrbit, 0, 2, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, num, GMP, 0)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_testbit, 0, 2, _IS_BOOL, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_gmp_scan0, 0, 2, IS_LONG, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, num1, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO(0, start, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_gmp_scan1 arginfo_gmp_scan0
#define arginfo_gmp_popcount arginfo_gmp_intval
#define arginfo_gmp_hamdist arginfo_gmp_jacobi
#define arginfo_gmp_nextprime arginfo_gmp_neg
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_gmp_binomial, 0, 2, GMP, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, n, GMP, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_INFO(0, k, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_GMP___construct, 0, 0, 0)
ZEND_ARG_TYPE_MASK(0, num, MAY_BE_LONG|MAY_BE_STRING, "0")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, base, IS_LONG, 0, "0")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_GMP___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_GMP___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_FUNCTION(gmp_init);
ZEND_FUNCTION(gmp_import);
ZEND_FUNCTION(gmp_export);
ZEND_FUNCTION(gmp_intval);
ZEND_FUNCTION(gmp_strval);
ZEND_FUNCTION(gmp_add);
ZEND_FUNCTION(gmp_sub);
ZEND_FUNCTION(gmp_mul);
ZEND_FUNCTION(gmp_div_qr);
ZEND_FUNCTION(gmp_div_q);
ZEND_FUNCTION(gmp_div_r);
ZEND_FUNCTION(gmp_mod);
ZEND_FUNCTION(gmp_divexact);
ZEND_FUNCTION(gmp_neg);
ZEND_FUNCTION(gmp_abs);
ZEND_FUNCTION(gmp_fact);
ZEND_FUNCTION(gmp_sqrt);
ZEND_FUNCTION(gmp_sqrtrem);
ZEND_FUNCTION(gmp_root);
ZEND_FUNCTION(gmp_rootrem);
ZEND_FUNCTION(gmp_pow);
ZEND_FUNCTION(gmp_powm);
ZEND_FUNCTION(gmp_perfect_square);
ZEND_FUNCTION(gmp_perfect_power);
ZEND_FUNCTION(gmp_prob_prime);
ZEND_FUNCTION(gmp_gcd);
ZEND_FUNCTION(gmp_gcdext);
ZEND_FUNCTION(gmp_lcm);
ZEND_FUNCTION(gmp_invert);
ZEND_FUNCTION(gmp_jacobi);
ZEND_FUNCTION(gmp_legendre);
ZEND_FUNCTION(gmp_kronecker);
ZEND_FUNCTION(gmp_cmp);
ZEND_FUNCTION(gmp_sign);
ZEND_FUNCTION(gmp_random_seed);
ZEND_FUNCTION(gmp_random_bits);
ZEND_FUNCTION(gmp_random_range);
ZEND_FUNCTION(gmp_and);
ZEND_FUNCTION(gmp_or);
ZEND_FUNCTION(gmp_com);
ZEND_FUNCTION(gmp_xor);
ZEND_FUNCTION(gmp_setbit);
ZEND_FUNCTION(gmp_clrbit);
ZEND_FUNCTION(gmp_testbit);
ZEND_FUNCTION(gmp_scan0);
ZEND_FUNCTION(gmp_scan1);
ZEND_FUNCTION(gmp_popcount);
ZEND_FUNCTION(gmp_hamdist);
ZEND_FUNCTION(gmp_nextprime);
ZEND_FUNCTION(gmp_binomial);
ZEND_METHOD(GMP, __construct);
ZEND_METHOD(GMP, __serialize);
ZEND_METHOD(GMP, __unserialize);
static const zend_function_entry ext_functions[] = {
ZEND_FE(gmp_init, arginfo_gmp_init)
ZEND_FE(gmp_import, arginfo_gmp_import)
ZEND_FE(gmp_export, arginfo_gmp_export)
ZEND_FE(gmp_intval, arginfo_gmp_intval)
ZEND_FE(gmp_strval, arginfo_gmp_strval)
ZEND_FE(gmp_add, arginfo_gmp_add)
ZEND_FE(gmp_sub, arginfo_gmp_sub)
ZEND_FE(gmp_mul, arginfo_gmp_mul)
ZEND_FE(gmp_div_qr, arginfo_gmp_div_qr)
ZEND_FE(gmp_div_q, arginfo_gmp_div_q)
ZEND_FE(gmp_div_r, arginfo_gmp_div_r)
ZEND_FALIAS(gmp_div, gmp_div_q, arginfo_gmp_div)
ZEND_FE(gmp_mod, arginfo_gmp_mod)
ZEND_FE(gmp_divexact, arginfo_gmp_divexact)
ZEND_FE(gmp_neg, arginfo_gmp_neg)
ZEND_FE(gmp_abs, arginfo_gmp_abs)
ZEND_FE(gmp_fact, arginfo_gmp_fact)
ZEND_FE(gmp_sqrt, arginfo_gmp_sqrt)
ZEND_FE(gmp_sqrtrem, arginfo_gmp_sqrtrem)
ZEND_FE(gmp_root, arginfo_gmp_root)
ZEND_FE(gmp_rootrem, arginfo_gmp_rootrem)
ZEND_FE(gmp_pow, arginfo_gmp_pow)
ZEND_FE(gmp_powm, arginfo_gmp_powm)
ZEND_FE(gmp_perfect_square, arginfo_gmp_perfect_square)
ZEND_FE(gmp_perfect_power, arginfo_gmp_perfect_power)
ZEND_FE(gmp_prob_prime, arginfo_gmp_prob_prime)
ZEND_FE(gmp_gcd, arginfo_gmp_gcd)
ZEND_FE(gmp_gcdext, arginfo_gmp_gcdext)
ZEND_FE(gmp_lcm, arginfo_gmp_lcm)
ZEND_FE(gmp_invert, arginfo_gmp_invert)
ZEND_FE(gmp_jacobi, arginfo_gmp_jacobi)
ZEND_FE(gmp_legendre, arginfo_gmp_legendre)
ZEND_FE(gmp_kronecker, arginfo_gmp_kronecker)
ZEND_FE(gmp_cmp, arginfo_gmp_cmp)
ZEND_FE(gmp_sign, arginfo_gmp_sign)
ZEND_FE(gmp_random_seed, arginfo_gmp_random_seed)
ZEND_FE(gmp_random_bits, arginfo_gmp_random_bits)
ZEND_FE(gmp_random_range, arginfo_gmp_random_range)
ZEND_FE(gmp_and, arginfo_gmp_and)
ZEND_FE(gmp_or, arginfo_gmp_or)
ZEND_FE(gmp_com, arginfo_gmp_com)
ZEND_FE(gmp_xor, arginfo_gmp_xor)
ZEND_FE(gmp_setbit, arginfo_gmp_setbit)
ZEND_FE(gmp_clrbit, arginfo_gmp_clrbit)
ZEND_FE(gmp_testbit, arginfo_gmp_testbit)
ZEND_FE(gmp_scan0, arginfo_gmp_scan0)
ZEND_FE(gmp_scan1, arginfo_gmp_scan1)
ZEND_FE(gmp_popcount, arginfo_gmp_popcount)
ZEND_FE(gmp_hamdist, arginfo_gmp_hamdist)
ZEND_FE(gmp_nextprime, arginfo_gmp_nextprime)
ZEND_FE(gmp_binomial, arginfo_gmp_binomial)
ZEND_FE_END
};
static const zend_function_entry class_GMP_methods[] = {
ZEND_ME(GMP, __construct, arginfo_class_GMP___construct, ZEND_ACC_PUBLIC)
ZEND_ME(GMP, __serialize, arginfo_class_GMP___serialize, ZEND_ACC_PUBLIC)
ZEND_ME(GMP, __unserialize, arginfo_class_GMP___unserialize, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static void register_gmp_symbols(int module_number)
{
REGISTER_LONG_CONSTANT("GMP_ROUND_ZERO", GMP_ROUND_ZERO, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_ROUND_PLUSINF", GMP_ROUND_PLUSINF, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_ROUND_MINUSINF", GMP_ROUND_MINUSINF, CONST_PERSISTENT);
#if defined(mpir_version)
REGISTER_STRING_CONSTANT("GMP_MPIR_VERSION", GMP_MPIR_VERSION_STRING, CONST_PERSISTENT);
#endif
REGISTER_STRING_CONSTANT("GMP_VERSION", GMP_VERSION_STRING, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_MSW_FIRST", GMP_MSW_FIRST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_LSW_FIRST", GMP_LSW_FIRST, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_LITTLE_ENDIAN", GMP_LITTLE_ENDIAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_BIG_ENDIAN", GMP_BIG_ENDIAN, CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("GMP_NATIVE_ENDIAN", GMP_NATIVE_ENDIAN, CONST_PERSISTENT);
}
static zend_class_entry *register_class_GMP(void)
{
zend_class_entry ce, *class_entry;
INIT_CLASS_ENTRY(ce, "GMP", class_GMP_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
return class_entry;
}
| 12,860 | 36.495627 | 97 |
h
|
php-src
|
php-src-master/ext/gmp/php_gmp.h
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Stanislav Malyshev <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_GMP_H
#define PHP_GMP_H
#include <gmp.h>
extern zend_module_entry gmp_module_entry;
#define phpext_gmp_ptr &gmp_module_entry
#include "php_version.h"
#define PHP_GMP_VERSION PHP_VERSION
ZEND_MODULE_STARTUP_D(gmp);
ZEND_MODULE_DEACTIVATE_D(gmp);
ZEND_MODULE_INFO_D(gmp);
ZEND_BEGIN_MODULE_GLOBALS(gmp)
bool rand_initialized;
gmp_randstate_t rand_state;
ZEND_END_MODULE_GLOBALS(gmp)
#define GMPG(v) ZEND_MODULE_GLOBALS_ACCESSOR(gmp, v)
#if defined(ZTS) && defined(COMPILE_DL_GMP)
ZEND_TSRMLS_CACHE_EXTERN()
#endif
#endif /* PHP_GMP_H */
| 1,553 | 34.318182 | 75 |
h
|
php-src
|
php-src-master/ext/hash/hash_adler32.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Michael Wallner <[email protected]> |
| Sara Golemon <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_hash.h"
#include "php_hash_adler32.h"
PHP_HASH_API void PHP_ADLER32Init(PHP_ADLER32_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
context->state = 1;
}
PHP_HASH_API void PHP_ADLER32Update(PHP_ADLER32_CTX *context, const unsigned char *input, size_t len)
{
uint32_t i, s[2];
s[0] = context->state & 0xffff;
s[1] = (context->state >> 16) & 0xffff;
for (i = 0; i < len; ++i) {
s[0] += input[i];
s[1] += s[0];
if (s[1]>=0x7fffffff)
{
s[0] = s[0] % 65521;
s[1] = s[1] % 65521;
}
}
s[0] = s[0] % 65521;
s[1] = s[1] % 65521;
context->state = s[0] + (s[1] << 16);
}
PHP_HASH_API void PHP_ADLER32Final(unsigned char digest[4], PHP_ADLER32_CTX *context)
{
digest[0] = (unsigned char) ((context->state >> 24) & 0xff);
digest[1] = (unsigned char) ((context->state >> 16) & 0xff);
digest[2] = (unsigned char) ((context->state >> 8) & 0xff);
digest[3] = (unsigned char) (context->state & 0xff);
context->state = 0;
}
PHP_HASH_API int PHP_ADLER32Copy(const php_hash_ops *ops, PHP_ADLER32_CTX *orig_context, PHP_ADLER32_CTX *copy_context)
{
copy_context->state = orig_context->state;
return SUCCESS;
}
const php_hash_ops php_hash_adler32_ops = {
"adler32",
(php_hash_init_func_t) PHP_ADLER32Init,
(php_hash_update_func_t) PHP_ADLER32Update,
(php_hash_final_func_t) PHP_ADLER32Final,
(php_hash_copy_func_t) PHP_ADLER32Copy,
php_hash_serialize,
php_hash_unserialize,
PHP_ADLER32_SPEC,
4, /* what to say here? */
4,
sizeof(PHP_ADLER32_CTX),
0
};
| 2,557 | 33.106667 | 119 |
c
|
php-src
|
php-src-master/ext/hash/hash_crc32.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Michael Wallner <[email protected]> |
| Sara Golemon <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_hash.h"
#include "php_hash_crc32.h"
#include "php_hash_crc32_tables.h"
#include "ext/standard/crc32_x86.h"
PHP_HASH_API void PHP_CRC32Init(PHP_CRC32_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
context->state = ~0;
}
PHP_HASH_API void PHP_CRC32Update(PHP_CRC32_CTX *context, const unsigned char *input, size_t len)
{
size_t i = 0;
#if ZEND_INTRIN_SSE4_2_PCLMUL_NATIVE || ZEND_INTRIN_SSE4_2_PCLMUL_RESOLVER
i += crc32_x86_simd_update(X86_CRC32, &context->state, input, len);
#endif
for (; i < len; ++i) {
context->state = (context->state << 8) ^ crc32_table[(context->state >> 24) ^ (input[i] & 0xff)];
}
}
PHP_HASH_API void PHP_CRC32BUpdate(PHP_CRC32_CTX *context, const unsigned char *input, size_t len)
{
size_t i = 0;
#if ZEND_INTRIN_SSE4_2_PCLMUL_NATIVE || ZEND_INTRIN_SSE4_2_PCLMUL_RESOLVER
i += crc32_x86_simd_update(X86_CRC32B, &context->state, input, len);
#endif
for (; i < len; ++i) {
context->state = (context->state >> 8) ^ crc32b_table[(context->state ^ input[i]) & 0xff];
}
}
PHP_HASH_API void PHP_CRC32CUpdate(PHP_CRC32_CTX *context, const unsigned char *input, size_t len)
{
size_t i = 0;
#if ZEND_INTRIN_SSE4_2_PCLMUL_NATIVE || ZEND_INTRIN_SSE4_2_PCLMUL_RESOLVER
i += crc32_x86_simd_update(X86_CRC32C, &context->state, input, len);
#endif
for (; i < len; ++i) {
context->state = (context->state >> 8) ^ crc32c_table[(context->state ^ input[i]) & 0xff];
}
}
PHP_HASH_API void PHP_CRC32LEFinal(unsigned char digest[4], PHP_CRC32_CTX *context)
{
context->state=~context->state;
digest[3] = (unsigned char) ((context->state >> 24) & 0xff);
digest[2] = (unsigned char) ((context->state >> 16) & 0xff);
digest[1] = (unsigned char) ((context->state >> 8) & 0xff);
digest[0] = (unsigned char) (context->state & 0xff);
context->state = 0;
}
PHP_HASH_API void PHP_CRC32BEFinal(unsigned char digest[4], PHP_CRC32_CTX *context)
{
context->state=~context->state;
digest[0] = (unsigned char) ((context->state >> 24) & 0xff);
digest[1] = (unsigned char) ((context->state >> 16) & 0xff);
digest[2] = (unsigned char) ((context->state >> 8) & 0xff);
digest[3] = (unsigned char) (context->state & 0xff);
context->state = 0;
}
PHP_HASH_API int PHP_CRC32Copy(const php_hash_ops *ops, PHP_CRC32_CTX *orig_context, PHP_CRC32_CTX *copy_context)
{
copy_context->state = orig_context->state;
return SUCCESS;
}
const php_hash_ops php_hash_crc32_ops = {
"crc32",
(php_hash_init_func_t) PHP_CRC32Init,
(php_hash_update_func_t) PHP_CRC32Update,
(php_hash_final_func_t) PHP_CRC32LEFinal,
(php_hash_copy_func_t) PHP_CRC32Copy,
php_hash_serialize,
php_hash_unserialize,
PHP_CRC32_SPEC,
4, /* what to say here? */
4,
sizeof(PHP_CRC32_CTX),
0
};
const php_hash_ops php_hash_crc32b_ops = {
"crc32b",
(php_hash_init_func_t) PHP_CRC32Init,
(php_hash_update_func_t) PHP_CRC32BUpdate,
(php_hash_final_func_t) PHP_CRC32BEFinal,
(php_hash_copy_func_t) PHP_CRC32Copy,
php_hash_serialize,
php_hash_unserialize,
PHP_CRC32_SPEC,
4, /* what to say here? */
4,
sizeof(PHP_CRC32_CTX),
0
};
const php_hash_ops php_hash_crc32c_ops = {
"crc32c",
(php_hash_init_func_t) PHP_CRC32Init,
(php_hash_update_func_t) PHP_CRC32CUpdate,
(php_hash_final_func_t) PHP_CRC32BEFinal,
(php_hash_copy_func_t) PHP_CRC32Copy,
php_hash_serialize,
php_hash_unserialize,
PHP_CRC32_SPEC,
4, /* what to say here? */
4,
sizeof(PHP_CRC32_CTX),
0
};
| 4,454 | 31.518248 | 113 |
c
|
php-src
|
php-src-master/ext/hash/hash_fnv.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Michael Maclean <[email protected]> |
+----------------------------------------------------------------------+
*/
/* Based on the public domain algorithm found at
http://www.isthe.com/chongo/tech/comp/fnv/index.html */
#include "php_hash.h"
#include "php_hash_fnv.h"
const php_hash_ops php_hash_fnv132_ops = {
"fnv132",
(php_hash_init_func_t) PHP_FNV132Init,
(php_hash_update_func_t) PHP_FNV132Update,
(php_hash_final_func_t) PHP_FNV132Final,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_FNV132_SPEC,
4,
4,
sizeof(PHP_FNV132_CTX),
0
};
const php_hash_ops php_hash_fnv1a32_ops = {
"fnv1a32",
(php_hash_init_func_t) PHP_FNV132Init,
(php_hash_update_func_t) PHP_FNV1a32Update,
(php_hash_final_func_t) PHP_FNV132Final,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_FNV132_SPEC,
4,
4,
sizeof(PHP_FNV132_CTX),
0
};
const php_hash_ops php_hash_fnv164_ops = {
"fnv164",
(php_hash_init_func_t) PHP_FNV164Init,
(php_hash_update_func_t) PHP_FNV164Update,
(php_hash_final_func_t) PHP_FNV164Final,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_FNV164_SPEC,
8,
4,
sizeof(PHP_FNV164_CTX),
0
};
const php_hash_ops php_hash_fnv1a64_ops = {
"fnv1a64",
(php_hash_init_func_t) PHP_FNV164Init,
(php_hash_update_func_t) PHP_FNV1a64Update,
(php_hash_final_func_t) PHP_FNV164Final,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_FNV164_SPEC,
8,
4,
sizeof(PHP_FNV164_CTX),
0
};
/* {{{ PHP_FNV132Init
* 32-bit FNV-1 hash initialisation
*/
PHP_HASH_API void PHP_FNV132Init(PHP_FNV132_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
context->state = PHP_FNV1_32_INIT;
}
/* }}} */
PHP_HASH_API void PHP_FNV132Update(PHP_FNV132_CTX *context, const unsigned char *input,
size_t inputLen)
{
context->state = fnv_32_buf((void *)input, inputLen, context->state, 0);
}
PHP_HASH_API void PHP_FNV1a32Update(PHP_FNV132_CTX *context, const unsigned char *input,
size_t inputLen)
{
context->state = fnv_32_buf((void *)input, inputLen, context->state, 1);
}
PHP_HASH_API void PHP_FNV132Final(unsigned char digest[4], PHP_FNV132_CTX * context)
{
#ifdef WORDS_BIGENDIAN
memcpy(digest, &context->state, 4);
#else
int i = 0;
unsigned char *c = (unsigned char *) &context->state;
for (i = 0; i < 4; i++) {
digest[i] = c[3 - i];
}
#endif
}
/* {{{ PHP_FNV164Init
* 64-bit FNV-1 hash initialisation
*/
PHP_HASH_API void PHP_FNV164Init(PHP_FNV164_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
context->state = PHP_FNV1_64_INIT;
}
/* }}} */
PHP_HASH_API void PHP_FNV164Update(PHP_FNV164_CTX *context, const unsigned char *input,
size_t inputLen)
{
context->state = fnv_64_buf((void *)input, inputLen, context->state, 0);
}
PHP_HASH_API void PHP_FNV1a64Update(PHP_FNV164_CTX *context, const unsigned char *input,
size_t inputLen)
{
context->state = fnv_64_buf((void *)input, inputLen, context->state, 1);
}
PHP_HASH_API void PHP_FNV164Final(unsigned char digest[8], PHP_FNV164_CTX * context)
{
#ifdef WORDS_BIGENDIAN
memcpy(digest, &context->state, 8);
#else
int i = 0;
unsigned char *c = (unsigned char *) &context->state;
for (i = 0; i < 8; i++) {
digest[i] = c[7 - i];
}
#endif
}
/*
* fnv_32_buf - perform a 32 bit Fowler/Noll/Vo hash on a buffer
*
* input:
* buf - start of buffer to hash
* len - length of buffer in octets
* hval - previous hash value or 0 if first call
* alternate - if > 0 use the alternate version
*
* returns:
* 32-bit hash as a static hash type
*/
static uint32_t
fnv_32_buf(void *buf, size_t len, uint32_t hval, int alternate)
{
unsigned char *bp = (unsigned char *)buf; /* start of buffer */
unsigned char *be = bp + len; /* beyond end of buffer */
/*
* FNV-1 hash each octet in the buffer
*/
if (alternate == 0) {
while (bp < be) {
/* multiply by the 32 bit FNV magic prime mod 2^32 */
hval *= PHP_FNV_32_PRIME;
/* xor the bottom with the current octet */
hval ^= (uint32_t)*bp++;
}
} else {
while (bp < be) {
/* xor the bottom with the current octet */
hval ^= (uint32_t)*bp++;
/* multiply by the 32 bit FNV magic prime mod 2^32 */
hval *= PHP_FNV_32_PRIME;
}
}
/* return our new hash value */
return hval;
}
/*
* fnv_64_buf - perform a 64 bit Fowler/Noll/Vo hash on a buffer
*
* input:
* buf - start of buffer to hash
* len - length of buffer in octets
* hval - previous hash value or 0 if first call
* alternate - if > 0 use the alternate version
*
* returns:
* 64-bit hash as a static hash type
*/
static uint64_t
fnv_64_buf(void *buf, size_t len, uint64_t hval, int alternate)
{
unsigned char *bp = (unsigned char *)buf; /* start of buffer */
unsigned char *be = bp + len; /* beyond end of buffer */
/*
* FNV-1 hash each octet of the buffer
*/
if (alternate == 0) {
while (bp < be) {
/* multiply by the 64 bit FNV magic prime mod 2^64 */
hval *= PHP_FNV_64_PRIME;
/* xor the bottom with the current octet */
hval ^= (uint64_t)*bp++;
}
} else {
while (bp < be) {
/* xor the bottom with the current octet */
hval ^= (uint64_t)*bp++;
/* multiply by the 64 bit FNV magic prime mod 2^64 */
hval *= PHP_FNV_64_PRIME;
}
}
/* return our new hash value */
return hval;
}
| 6,130 | 24.545833 | 96 |
c
|
php-src
|
php-src-master/ext/hash/hash_gost.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Michael Wallner <[email protected]> |
| Sara Golemon <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_hash.h"
#include "php_hash_gost.h"
#include "php_hash_gost_tables.h"
/* {{{ Gost()
* derived from gost_compress() by Markku-Juhani Saarinen <[email protected]>
*/
#define round(tables, k1, k2) \
t = (k1) + r; \
l ^= tables[0][t & 0xff] ^ tables[1][(t >> 8) & 0xff] ^ \
tables[2][(t >> 16) & 0xff] ^ tables[3][t >> 24]; \
t = (k2) + l; \
r ^= tables[0][t & 0xff] ^ tables[1][(t >> 8) & 0xff] ^ \
tables[2][(t >> 16) & 0xff] ^ tables[3][t >> 24];
#define R(tables, key, h, i, t, l, r) \
r = h[i]; \
l = h[i + 1]; \
round(tables, key[0], key[1]) \
round(tables, key[2], key[3]) \
round(tables, key[4], key[5]) \
round(tables, key[6], key[7]) \
round(tables, key[0], key[1]) \
round(tables, key[2], key[3]) \
round(tables, key[4], key[5]) \
round(tables, key[6], key[7]) \
round(tables, key[0], key[1]) \
round(tables, key[2], key[3]) \
round(tables, key[4], key[5]) \
round(tables, key[6], key[7]) \
round(tables, key[7], key[6]) \
round(tables, key[5], key[4]) \
round(tables, key[3], key[2]) \
round(tables, key[1], key[0]) \
t = r; \
r = l; \
l = t; \
#define X(w, u, v) \
w[0] = u[0] ^ v[0]; \
w[1] = u[1] ^ v[1]; \
w[2] = u[2] ^ v[2]; \
w[3] = u[3] ^ v[3]; \
w[4] = u[4] ^ v[4]; \
w[5] = u[5] ^ v[5]; \
w[6] = u[6] ^ v[6]; \
w[7] = u[7] ^ v[7];
#define P(key, w) \
key[0] = (w[0] & 0x000000ff) | ((w[2] & 0x000000ff) << 8) | \
((w[4] & 0x000000ff) << 16) | ((w[6] & 0x000000ff) << 24); \
key[1] = ((w[0] & 0x0000ff00) >> 8) | (w[2] & 0x0000ff00) | \
((w[4] & 0x0000ff00) << 8) | ((w[6] & 0x0000ff00) << 16); \
key[2] = ((w[0] & 0x00ff0000) >> 16) | ((w[2] & 0x00ff0000) >> 8) | \
(w[4] & 0x00ff0000) | ((w[6] & 0x00ff0000) << 8); \
key[3] = ((w[0] & 0xff000000) >> 24) | ((w[2] & 0xff000000) >> 16) | \
((w[4] & 0xff000000) >> 8) | (w[6] & 0xff000000); \
key[4] = (w[1] & 0x000000ff) | ((w[3] & 0x000000ff) << 8) | \
((w[5] & 0x000000ff) << 16) | ((w[7] & 0x000000ff) << 24); \
key[5] = ((w[1] & 0x0000ff00) >> 8) | (w[3] & 0x0000ff00) | \
((w[5] & 0x0000ff00) << 8) | ((w[7] & 0x0000ff00) << 16); \
key[6] = ((w[1] & 0x00ff0000) >> 16) | ((w[3] & 0x00ff0000) >> 8) | \
(w[5] & 0x00ff0000) | ((w[7] & 0x00ff0000) << 8); \
key[7] = ((w[1] & 0xff000000) >> 24) | ((w[3] & 0xff000000) >> 16) | \
((w[5] & 0xff000000) >> 8) | (w[7] & 0xff000000);
#define A(x, l, r) \
l = x[0] ^ x[2]; \
r = x[1] ^ x[3]; \
x[0] = x[2]; \
x[1] = x[3]; \
x[2] = x[4]; \
x[3] = x[5]; \
x[4] = x[6]; \
x[5] = x[7]; \
x[6] = l; \
x[7] = r;
#define AA(x, l, r) \
l = x[0]; \
r = x[2]; \
x[0] = x[4]; \
x[2] = x[6]; \
x[4] = l ^ r; \
x[6] = x[0] ^ r; \
l = x[1]; \
r = x[3]; \
x[1] = x[5]; \
x[3] = x[7]; \
x[5] = l ^ r; \
x[7] = x[1] ^ r;
#define C(x) \
x[0] ^= 0xff00ff00; \
x[1] ^= 0xff00ff00; \
x[2] ^= 0x00ff00ff; \
x[3] ^= 0x00ff00ff; \
x[4] ^= 0x00ffff00; \
x[5] ^= 0xff0000ff; \
x[6] ^= 0x000000ff; \
x[7] ^= 0xff00ffff;
#define S(s, l, r) \
s[i] = r; \
s[i + 1] = l;
#define SHIFT12(u, m, s) \
u[0] = m[0] ^ s[6]; \
u[1] = m[1] ^ s[7]; \
u[2] = m[2] ^ (s[0] << 16) ^ (s[0] >> 16) ^ (s[0] & 0xffff) ^ \
(s[1] & 0xffff) ^ (s[1] >> 16) ^ (s[2] << 16) ^ s[6] ^ (s[6] << 16) ^ \
(s[7] & 0xffff0000) ^ (s[7] >> 16); \
u[3] = m[3] ^ (s[0] & 0xffff) ^ (s[0] << 16) ^ (s[1] & 0xffff) ^ \
(s[1] << 16) ^ (s[1] >> 16) ^ (s[2] << 16) ^ (s[2] >> 16) ^ \
(s[3] << 16) ^ s[6] ^ (s[6] << 16) ^ (s[6] >> 16) ^ (s[7] & 0xffff) ^ \
(s[7] << 16) ^ (s[7] >> 16); \
u[4] = m[4] ^ \
(s[0] & 0xffff0000) ^ (s[0] << 16) ^ (s[0] >> 16) ^ \
(s[1] & 0xffff0000) ^ (s[1] >> 16) ^ (s[2] << 16) ^ (s[2] >> 16) ^ \
(s[3] << 16) ^ (s[3] >> 16) ^ (s[4] << 16) ^ (s[6] << 16) ^ \
(s[6] >> 16) ^(s[7] & 0xffff) ^ (s[7] << 16) ^ (s[7] >> 16); \
u[5] = m[5] ^ (s[0] << 16) ^ (s[0] >> 16) ^ (s[0] & 0xffff0000) ^ \
(s[1] & 0xffff) ^ s[2] ^ (s[2] >> 16) ^ (s[3] << 16) ^ (s[3] >> 16) ^ \
(s[4] << 16) ^ (s[4] >> 16) ^ (s[5] << 16) ^ (s[6] << 16) ^ \
(s[6] >> 16) ^ (s[7] & 0xffff0000) ^ (s[7] << 16) ^ (s[7] >> 16); \
u[6] = m[6] ^ s[0] ^ (s[1] >> 16) ^ (s[2] << 16) ^ s[3] ^ (s[3] >> 16) ^ \
(s[4] << 16) ^ (s[4] >> 16) ^ (s[5] << 16) ^ (s[5] >> 16) ^ s[6] ^ \
(s[6] << 16) ^ (s[6] >> 16) ^ (s[7] << 16); \
u[7] = m[7] ^ (s[0] & 0xffff0000) ^ (s[0] << 16) ^ (s[1] & 0xffff) ^ \
(s[1] << 16) ^ (s[2] >> 16) ^ (s[3] << 16) ^ s[4] ^ (s[4] >> 16) ^ \
(s[5] << 16) ^ (s[5] >> 16) ^ (s[6] >> 16) ^ (s[7] & 0xffff) ^ \
(s[7] << 16) ^ (s[7] >> 16);
#define SHIFT16(h, v, u) \
v[0] = h[0] ^ (u[1] << 16) ^ (u[0] >> 16); \
v[1] = h[1] ^ (u[2] << 16) ^ (u[1] >> 16); \
v[2] = h[2] ^ (u[3] << 16) ^ (u[2] >> 16); \
v[3] = h[3] ^ (u[4] << 16) ^ (u[3] >> 16); \
v[4] = h[4] ^ (u[5] << 16) ^ (u[4] >> 16); \
v[5] = h[5] ^ (u[6] << 16) ^ (u[5] >> 16); \
v[6] = h[6] ^ (u[7] << 16) ^ (u[6] >> 16); \
v[7] = h[7] ^ (u[0] & 0xffff0000) ^ (u[0] << 16) ^ (u[7] >> 16) ^ \
(u[1] & 0xffff0000) ^ (u[1] << 16) ^ (u[6] << 16) ^ (u[7] & 0xffff0000);
#define SHIFT61(h, v) \
h[0] = (v[0] & 0xffff0000) ^ (v[0] << 16) ^ (v[0] >> 16) ^ (v[1] >> 16) ^ \
(v[1] & 0xffff0000) ^ (v[2] << 16) ^ (v[3] >> 16) ^ (v[4] << 16) ^ \
(v[5] >> 16) ^ v[5] ^ (v[6] >> 16) ^ (v[7] << 16) ^ (v[7] >> 16) ^ \
(v[7] & 0xffff); \
h[1] = (v[0] << 16) ^ (v[0] >> 16) ^ (v[0] & 0xffff0000) ^ (v[1] & 0xffff) ^ \
v[2] ^ (v[2] >> 16) ^ (v[3] << 16) ^ (v[4] >> 16) ^ (v[5] << 16) ^ \
(v[6] << 16) ^ v[6] ^ (v[7] & 0xffff0000) ^ (v[7] >> 16); \
h[2] = (v[0] & 0xffff) ^ (v[0] << 16) ^ (v[1] << 16) ^ (v[1] >> 16) ^ \
(v[1] & 0xffff0000) ^ (v[2] << 16) ^ (v[3] >> 16) ^ v[3] ^ (v[4] << 16) ^ \
(v[5] >> 16) ^ v[6] ^ (v[6] >> 16) ^ (v[7] & 0xffff) ^ (v[7] << 16) ^ \
(v[7] >> 16); \
h[3] = (v[0] << 16) ^ (v[0] >> 16) ^ (v[0] & 0xffff0000) ^ \
(v[1] & 0xffff0000) ^ (v[1] >> 16) ^ (v[2] << 16) ^ (v[2] >> 16) ^ v[2] ^ \
(v[3] << 16) ^ (v[4] >> 16) ^ v[4] ^ (v[5] << 16) ^ (v[6] << 16) ^ \
(v[7] & 0xffff) ^ (v[7] >> 16); \
h[4] = (v[0] >> 16) ^ (v[1] << 16) ^ v[1] ^ (v[2] >> 16) ^ v[2] ^ \
(v[3] << 16) ^ (v[3] >> 16) ^ v[3] ^ (v[4] << 16) ^ (v[5] >> 16) ^ \
v[5] ^ (v[6] << 16) ^ (v[6] >> 16) ^ (v[7] << 16); \
h[5] = (v[0] << 16) ^ (v[0] & 0xffff0000) ^ (v[1] << 16) ^ (v[1] >> 16) ^ \
(v[1] & 0xffff0000) ^ (v[2] << 16) ^ v[2] ^ (v[3] >> 16) ^ v[3] ^ \
(v[4] << 16) ^ (v[4] >> 16) ^ v[4] ^ (v[5] << 16) ^ (v[6] << 16) ^ \
(v[6] >> 16) ^ v[6] ^ (v[7] << 16) ^ (v[7] >> 16) ^ (v[7] & 0xffff0000); \
h[6] = v[0] ^ v[2] ^ (v[2] >> 16) ^ v[3] ^ (v[3] << 16) ^ v[4] ^ \
(v[4] >> 16) ^ (v[5] << 16) ^ (v[5] >> 16) ^ v[5] ^ (v[6] << 16) ^ \
(v[6] >> 16) ^ v[6] ^ (v[7] << 16) ^ v[7]; \
h[7] = v[0] ^ (v[0] >> 16) ^ (v[1] << 16) ^ (v[1] >> 16) ^ (v[2] << 16) ^ \
(v[3] >> 16) ^ v[3] ^ (v[4] << 16) ^ v[4] ^ (v[5] >> 16) ^ v[5] ^ \
(v[6] << 16) ^ (v[6] >> 16) ^ (v[7] << 16) ^ v[7];
#define PASS(tables) \
X(w, u, v); \
P(key, w); \
R((tables), key, h, i, t, l, r); \
S(s, l, r); \
if (i != 6) { \
A(u, l, r); \
if (i == 2) { \
C(u); \
} \
AA(v, l, r); \
}
static inline void Gost(PHP_GOST_CTX *context, uint32_t data[8])
{
int i;
uint32_t l, r, t, key[8], u[8], v[8], w[8], s[8], *h = context->state, *m = data;
memcpy(u, context->state, sizeof(u));
memcpy(v, data, sizeof(v));
for (i = 0; i < 8; i += 2) {
PASS(*context->tables);
}
SHIFT12(u, m, s);
SHIFT16(h, v, u);
SHIFT61(h, v);
}
/* }}} */
static inline void GostTransform(PHP_GOST_CTX *context, const unsigned char input[32])
{
int i, j;
uint32_t data[8], temp = 0;
for (i = 0, j = 0; i < 8; ++i, j += 4) {
data[i] = ((uint32_t) input[j]) | (((uint32_t) input[j + 1]) << 8) |
(((uint32_t) input[j + 2]) << 16) | (((uint32_t) input[j + 3]) << 24);
context->state[i + 8] += data[i] + temp;
temp = context->state[i + 8] < data[i] ? 1 : (context->state[i + 8] == data[i] ? temp : 0);
}
Gost(context, data);
}
PHP_HASH_API void PHP_GOSTInit(PHP_GOST_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
memset(context, 0, sizeof(*context));
context->tables = &tables_test;
}
PHP_HASH_API void PHP_GOSTInitCrypto(PHP_GOST_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
PHP_GOSTInit(context, NULL);
context->tables = &tables_crypto;
}
static const uint32_t MAX32 = 0xffffffffLU;
PHP_HASH_API void PHP_GOSTUpdate(PHP_GOST_CTX *context, const unsigned char *input, size_t len)
{
if ((MAX32 - context->count[0]) < (len * 8)) {
context->count[1]++;
context->count[0] = MAX32 - context->count[0];
context->count[0] = (len * 8) - context->count[0];
} else {
context->count[0] += len * 8;
}
if (context->length + len < 32) {
memcpy(&context->buffer[context->length], input, len);
context->length += (unsigned char)len;
} else {
size_t i = 0, r = (context->length + len) % 32;
if (context->length) {
i = 32 - context->length;
memcpy(&context->buffer[context->length], input, i);
GostTransform(context, context->buffer);
}
for (; i + 32 <= len; i += 32) {
GostTransform(context, input + i);
}
memcpy(context->buffer, input + i, r);
ZEND_SECURE_ZERO(&context->buffer[r], 32 - r);
context->length = (unsigned char)r;
}
}
PHP_HASH_API void PHP_GOSTFinal(unsigned char digest[32], PHP_GOST_CTX *context)
{
uint32_t i, j, l[8] = {0};
if (context->length) {
GostTransform(context, context->buffer);
}
memcpy(l, context->count, sizeof(context->count));
Gost(context, l);
memcpy(l, &context->state[8], sizeof(l));
Gost(context, l);
for (i = 0, j = 0; j < 32; i++, j += 4) {
digest[j] = (unsigned char) (context->state[i] & 0xff);
digest[j + 1] = (unsigned char) ((context->state[i] >> 8) & 0xff);
digest[j + 2] = (unsigned char) ((context->state[i] >> 16) & 0xff);
digest[j + 3] = (unsigned char) ((context->state[i] >> 24) & 0xff);
}
ZEND_SECURE_ZERO(context, sizeof(*context));
}
static int php_gost_unserialize(php_hashcontext_object *hash, zend_long magic, const zval *zv)
{
PHP_GOST_CTX *ctx = (PHP_GOST_CTX *) hash->context;
int r = FAILURE;
if (magic == PHP_HASH_SERIALIZE_MAGIC_SPEC
&& (r = php_hash_unserialize_spec(hash, zv, PHP_GOST_SPEC)) == SUCCESS
&& ctx->length < sizeof(ctx->buffer)) {
return SUCCESS;
} else {
return r != SUCCESS ? r : -2000;
}
}
const php_hash_ops php_hash_gost_ops = {
"gost",
(php_hash_init_func_t) PHP_GOSTInit,
(php_hash_update_func_t) PHP_GOSTUpdate,
(php_hash_final_func_t) PHP_GOSTFinal,
php_hash_copy,
php_hash_serialize,
php_gost_unserialize,
PHP_GOST_SPEC,
32,
32,
sizeof(PHP_GOST_CTX),
1
};
const php_hash_ops php_hash_gost_crypto_ops = {
"gost-crypto",
(php_hash_init_func_t) PHP_GOSTInitCrypto,
(php_hash_update_func_t) PHP_GOSTUpdate,
(php_hash_final_func_t) PHP_GOSTFinal,
php_hash_copy,
php_hash_serialize,
php_gost_unserialize,
PHP_GOST_SPEC,
32,
32,
sizeof(PHP_GOST_CTX),
1
};
| 11,805 | 32.82808 | 98 |
c
|
php-src
|
php-src-master/ext/hash/hash_haval.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sara Golemon <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_hash.h"
#include "php_hash_haval.h"
static const unsigned char PADDING[128] ={
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static const uint32_t D0[8] = {
0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89 };
static const uint32_t K2[32] = {
0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917,
0x9216D5D9, 0x8979FB1B, 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96,
0xBA7C9045, 0xF12C7F99, 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69,
0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5 };
static const uint32_t K3[32] = {
0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, 0x8E79DCB0, 0x603A180E,
0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, 0xE65525F3, 0xAA55AB94,
0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF, 0x7C72E993,
0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C };
static const uint32_t K4[32] = {
0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991,
0x487CAC60, 0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5,
0x0F6D6FF3, 0x83F44239, 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A,
0x670C9C61, 0xABD388F0, 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4 };
static const uint32_t K5[32] = {
0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4,
0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, 0x4ED3AA62, 0x363F7706,
0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, 0x075372C9, 0x80991B7B,
0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6, 0x409F60C4 };
static const short I2[32] = { 5, 14, 26, 18, 11, 28, 7, 16, 0, 23, 20, 22, 1, 10, 4, 8,
30, 3, 21, 9, 17, 24, 29, 6, 19, 12, 15, 13, 2, 25, 31, 27 };
static const short I3[32] = { 19, 9, 4, 20, 28, 17, 8, 22, 29, 14, 25, 12, 24, 30, 16, 26,
31, 15, 7, 3, 1, 0, 18, 27, 13, 6, 21, 10, 23, 11, 5, 2 };
static const short I4[32] = { 24, 4, 0, 14, 2, 7, 28, 23, 26, 6, 30, 20, 18, 25, 19, 3,
22, 11, 31, 21, 8, 27, 12, 9, 1, 29, 5, 15, 17, 10, 16, 13 };
static const short I5[32] = { 27, 3, 21, 26, 17, 11, 20, 29, 19, 0, 12, 7, 13, 8, 31, 10,
5, 9, 14, 30, 18, 6, 28, 24, 2, 23, 16, 22, 4, 1, 25, 15 };
static const short M0[32] = { 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1,
0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1 };
static const short M1[32] = { 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2,
1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2 };
static const short M2[32] = { 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3,
2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3 };
static const short M3[32] = { 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4,
3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4 };
static const short M4[32] = { 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5,
4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5 };
static const short M5[32] = { 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6,
5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6 };
static const short M6[32] = { 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7,
6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 7 };
static const short M7[32] = { 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0,
7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0 };
/* {{{ Encode
Encodes input (uint32_t) into output (unsigned char). Assumes len is
a multiple of 4.
*/
static void Encode(unsigned char *output, uint32_t *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char) (input[i] & 0xff);
output[j + 1] = (unsigned char) ((input[i] >> 8) & 0xff);
output[j + 2] = (unsigned char) ((input[i] >> 16) & 0xff);
output[j + 3] = (unsigned char) ((input[i] >> 24) & 0xff);
}
}
/* }}} */
/* {{{ Decode
Decodes input (unsigned char) into output (uint32_t). Assumes len is
a multiple of 4.
*/
static void Decode(uint32_t *output, const unsigned char *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[i] = ((uint32_t) input[j]) | (((uint32_t) input[j + 1]) << 8) |
(((uint32_t) input[j + 2]) << 16) | (((uint32_t) input[j + 3]) << 24);
}
}
/* }}} */
#define F1(x6,x5,x4,x3,x2,x1,x0) ( ((x1) & (x4)) ^ ((x2) & (x5)) ^ ((x3) & (x6)) ^ ((x0) & (x1)) ^ (x0) )
#define F2(x6,x5,x4,x3,x2,x1,x0) ( ((x1) & (x2) & (x3)) ^ ((x2) & (x4) & (x5)) ^ ((x1) & (x2)) ^ ((x1) & (x4)) ^ \
((x2) & (x6)) ^ ((x3) & (x5)) ^ ((x4) & (x5)) ^ ((x0) & (x2)) ^ (x0) )
#define F3(x6,x5,x4,x3,x2,x1,x0) ( ((x1) & (x2) & (x3)) ^ ((x1) & (x4)) ^ ((x2) & (x5)) ^ ((x3) & (x6)) ^ ((x0) & (x3)) ^ (x0) )
#define F4(x6,x5,x4,x3,x2,x1,x0) ( ((x1) & (x2) & (x3)) ^ ((x2) & (x4) & (x5)) ^ ((x3) & (x4) & (x6)) ^ \
((x1) & (x4)) ^ ((x2) & (x6)) ^ ((x3) & (x4)) ^ ((x3) & (x5)) ^ \
((x3) & (x6)) ^ ((x4) & (x5)) ^ ((x4) & (x6)) ^ ((x0) & (x4)) ^ (x0) )
#define F5(x6,x5,x4,x3,x2,x1,x0) ( ((x1) & (x4)) ^ ((x2) & (x5)) ^ ((x3) & (x6)) ^ \
((x0) & (x1) & (x2) & (x3)) ^ ((x0) & (x5)) ^ (x0) )
#define ROTR(x,n) (((x) >> (n)) | ((x) << (32 - (n))))
/* {{{ PHP_3HAVALTransform */
static void PHP_3HAVALTransform(uint32_t state[8], const unsigned char block[128])
{
uint32_t E[8];
uint32_t x[32];
int i;
Decode(x, block, 128);
for(i = 0; i < 8; i++) {
E[i] = state[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F1(E[M1[i]],E[M0[i]],E[M3[i]],E[M5[i]],E[M6[i]],E[M2[i]],E[M4[i]]),7) + ROTR(E[M7[i]],11) + x[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F2(E[M4[i]],E[M2[i]],E[M1[i]],E[M0[i]],E[M5[i]],E[M3[i]],E[M6[i]]),7) + ROTR(E[M7[i]],11) + x[I2[i]] + K2[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F3(E[M6[i]],E[M1[i]],E[M2[i]],E[M3[i]],E[M4[i]],E[M5[i]],E[M0[i]]),7) + ROTR(E[M7[i]],11) + x[I3[i]] + K3[i];
}
/* Update digest */
for(i = 0; i < 8; i++) {
state[i] += E[i];
}
/* Zeroize sensitive information. */
ZEND_SECURE_ZERO((unsigned char*) x, sizeof(x));
}
/* }}} */
/* {{{ PHP_4HAVALTransform */
static void PHP_4HAVALTransform(uint32_t state[8], const unsigned char block[128])
{
uint32_t E[8];
uint32_t x[32];
int i;
Decode(x, block, 128);
for(i = 0; i < 8; i++) {
E[i] = state[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F1(E[M2[i]],E[M6[i]],E[M1[i]],E[M4[i]],E[M5[i]],E[M3[i]],E[M0[i]]),7) + ROTR(E[M7[i]],11) + x[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F2(E[M3[i]],E[M5[i]],E[M2[i]],E[M0[i]],E[M1[i]],E[M6[i]],E[M4[i]]),7) + ROTR(E[M7[i]],11) + x[I2[i]] + K2[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F3(E[M1[i]],E[M4[i]],E[M3[i]],E[M6[i]],E[M0[i]],E[M2[i]],E[M5[i]]),7) + ROTR(E[M7[i]],11) + x[I3[i]] + K3[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F4(E[M6[i]],E[M4[i]],E[M0[i]],E[M5[i]],E[M2[i]],E[M1[i]],E[M3[i]]),7) + ROTR(E[M7[i]],11) + x[I4[i]] + K4[i];
}
/* Update digest */
for(i = 0; i < 8; i++) {
state[i] += E[i];
}
/* Zeroize sensitive information. */
ZEND_SECURE_ZERO((unsigned char*) x, sizeof(x));
}
/* }}} */
/* {{{ PHP_5HAVALTransform */
static void PHP_5HAVALTransform(uint32_t state[8], const unsigned char block[128])
{
uint32_t E[8];
uint32_t x[32];
int i;
Decode(x, block, 128);
for(i = 0; i < 8; i++) {
E[i] = state[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F1(E[M3[i]],E[M4[i]],E[M1[i]],E[M0[i]],E[M5[i]],E[M2[i]],E[M6[i]]),7) + ROTR(E[M7[i]],11) + x[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F2(E[M6[i]],E[M2[i]],E[M1[i]],E[M0[i]],E[M3[i]],E[M4[i]],E[M5[i]]),7) + ROTR(E[M7[i]],11) + x[I2[i]] + K2[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F3(E[M2[i]],E[M6[i]],E[M0[i]],E[M4[i]],E[M3[i]],E[M1[i]],E[M5[i]]),7) + ROTR(E[M7[i]],11) + x[I3[i]] + K3[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F4(E[M1[i]],E[M5[i]],E[M3[i]],E[M2[i]],E[M0[i]],E[M4[i]],E[M6[i]]),7) + ROTR(E[M7[i]],11) + x[I4[i]] + K4[i];
}
for(i = 0; i < 32; i++) {
E[7 - (i % 8)] = ROTR(F5(E[M2[i]],E[M5[i]],E[M0[i]],E[M6[i]],E[M4[i]],E[M3[i]],E[M1[i]]),7) + ROTR(E[M7[i]],11) + x[I5[i]] + K5[i];
}
/* Update digest */
for(i = 0; i < 8; i++) {
state[i] += E[i];
}
/* Zeroize sensitive information. */
ZEND_SECURE_ZERO((unsigned char*) x, sizeof(x));
}
/* }}} */
#define PHP_HASH_HAVAL_INIT(p,b) \
const php_hash_ops php_hash_##p##haval##b##_ops = { \
"haval" #b "," #p, \
(php_hash_init_func_t) PHP_##p##HAVAL##b##Init, \
(php_hash_update_func_t) PHP_HAVALUpdate, \
(php_hash_final_func_t) PHP_HAVAL##b##Final, \
php_hash_copy, \
php_hash_serialize, \
php_hash_unserialize, \
PHP_HAVAL_SPEC, \
((b) / 8), 128, sizeof(PHP_HAVAL_CTX), 1 }; \
PHP_HASH_API void PHP_##p##HAVAL##b##Init(PHP_HAVAL_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args) \
{ int i; context->count[0] = context->count[1] = 0; \
for(i = 0; i < 8; i++) context->state[i] = D0[i]; \
context->passes = p; context->output = b; \
context->Transform = PHP_##p##HAVALTransform; }
PHP_HASH_HAVAL_INIT(3,128)
PHP_HASH_HAVAL_INIT(3,160)
PHP_HASH_HAVAL_INIT(3,192)
PHP_HASH_HAVAL_INIT(3,224)
PHP_HASH_HAVAL_INIT(3,256)
PHP_HASH_HAVAL_INIT(4,128)
PHP_HASH_HAVAL_INIT(4,160)
PHP_HASH_HAVAL_INIT(4,192)
PHP_HASH_HAVAL_INIT(4,224)
PHP_HASH_HAVAL_INIT(4,256)
PHP_HASH_HAVAL_INIT(5,128)
PHP_HASH_HAVAL_INIT(5,160)
PHP_HASH_HAVAL_INIT(5,192)
PHP_HASH_HAVAL_INIT(5,224)
PHP_HASH_HAVAL_INIT(5,256)
/* {{{ PHP_HAVALUpdate */
PHP_HASH_API void PHP_HAVALUpdate(PHP_HAVAL_CTX *context, const unsigned char *input, size_t inputLen)
{
unsigned int i, index, partLen;
/* Compute number of bytes mod 128 */
index = (unsigned int) ((context->count[0] >> 3) & 0x7F);
/* Update number of bits */
if ((context->count[0] += ((uint32_t) inputLen << 3)) < ((uint32_t) inputLen << 3)) {
context->count[1]++;
}
context->count[1] += ((uint32_t) inputLen >> 29);
partLen = 128 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen) {
memcpy((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen);
context->Transform(context->state, context->buffer);
for (i = partLen; i + 127 < inputLen; i += 128) {
context->Transform(context->state, &input[i]);
}
index = 0;
} else {
i = 0;
}
/* Buffer remaining input */
memcpy((unsigned char*) &context->buffer[index], (unsigned char*) &input[i], inputLen - i);
}
/* }}} */
#define PHP_HASH_HAVAL_VERSION 0x01
/* {{{ PHP_HAVAL128Final */
PHP_HASH_API void PHP_HAVAL128Final(unsigned char *digest, PHP_HAVAL_CTX * context)
{
unsigned char bits[10];
unsigned int index, padLen;
/* Version, Passes, and Digest Length */
bits[0] = (PHP_HASH_HAVAL_VERSION & 0x07) |
((context->passes & 0x07) << 3) |
((context->output & 0x03) << 6);
bits[1] = (context->output >> 2);
/* Save number of bits */
Encode(bits + 2, context->count, 8);
/* Pad out to 118 mod 128.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x7f);
padLen = (index < 118) ? (118 - index) : (246 - index);
PHP_HAVALUpdate(context, PADDING, padLen);
/* Append version, passes, digest length, and message length */
PHP_HAVALUpdate(context, bits, 10);
/* Store state in digest */
context->state[3] += (context->state[7] & 0xFF000000) |
(context->state[6] & 0x00FF0000) |
(context->state[5] & 0x0000FF00) |
(context->state[4] & 0x000000FF);
context->state[2] += (((context->state[7] & 0x00FF0000) |
(context->state[6] & 0x0000FF00) |
(context->state[5] & 0x000000FF)) << 8) |
((context->state[4] & 0xFF000000) >> 24);
context->state[1] += (((context->state[7] & 0x0000FF00) |
(context->state[6] & 0x000000FF)) << 16) |
(((context->state[5] & 0xFF000000) |
(context->state[4] & 0x00FF0000)) >> 16);
context->state[0] += ((context->state[7] & 0x000000FF) << 24) |
(((context->state[6] & 0xFF000000) |
(context->state[5] & 0x00FF0000) |
(context->state[4] & 0x0000FF00)) >> 8);
Encode(digest, context->state, 16);
/* Zeroize sensitive information.
*/
ZEND_SECURE_ZERO((unsigned char*) context, sizeof(*context));
}
/* }}} */
/* {{{ PHP_HAVAL160Final */
PHP_HASH_API void PHP_HAVAL160Final(unsigned char *digest, PHP_HAVAL_CTX * context)
{
unsigned char bits[10];
unsigned int index, padLen;
/* Version, Passes, and Digest Length */
bits[0] = (PHP_HASH_HAVAL_VERSION & 0x07) |
((context->passes & 0x07) << 3) |
((context->output & 0x03) << 6);
bits[1] = (context->output >> 2);
/* Save number of bits */
Encode(bits + 2, context->count, 8);
/* Pad out to 118 mod 128.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x7f);
padLen = (index < 118) ? (118 - index) : (246 - index);
PHP_HAVALUpdate(context, PADDING, padLen);
/* Append version, passes, digest length, and message length */
PHP_HAVALUpdate(context, bits, 10);
/* Store state in digest */
context->state[4] += ((context->state[7] & 0xFE000000) |
(context->state[6] & 0x01F80000) |
(context->state[5] & 0x0007F000)) >> 12;
context->state[3] += ((context->state[7] & 0x01F80000) |
(context->state[6] & 0x0007F000) |
(context->state[5] & 0x00000FC0)) >> 6;
context->state[2] += (context->state[7] & 0x0007F000) |
(context->state[6] & 0x00000FC0) |
(context->state[5] & 0x0000003F);
context->state[1] += ROTR((context->state[7] & 0x00000FC0) |
(context->state[6] & 0x0000003F) |
(context->state[5] & 0xFE000000), 25);
context->state[0] += ROTR((context->state[7] & 0x0000003F) |
(context->state[6] & 0xFE000000) |
(context->state[5] & 0x01F80000), 19);
Encode(digest, context->state, 20);
/* Zeroize sensitive information.
*/
ZEND_SECURE_ZERO((unsigned char*) context, sizeof(*context));
}
/* }}} */
/* {{{ PHP_HAVAL192Final */
PHP_HASH_API void PHP_HAVAL192Final(unsigned char *digest, PHP_HAVAL_CTX * context)
{
unsigned char bits[10];
unsigned int index, padLen;
/* Version, Passes, and Digest Length */
bits[0] = (PHP_HASH_HAVAL_VERSION & 0x07) |
((context->passes & 0x07) << 3) |
((context->output & 0x03) << 6);
bits[1] = (context->output >> 2);
/* Save number of bits */
Encode(bits + 2, context->count, 8);
/* Pad out to 118 mod 128.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x7f);
padLen = (index < 118) ? (118 - index) : (246 - index);
PHP_HAVALUpdate(context, PADDING, padLen);
/* Append version, passes, digest length, and message length */
PHP_HAVALUpdate(context, bits, 10);
/* Store state in digest */
context->state[5] += ((context->state[7] & 0xFC000000) | (context->state[6] & 0x03E00000)) >> 21;
context->state[4] += ((context->state[7] & 0x03E00000) | (context->state[6] & 0x001F0000)) >> 16;
context->state[3] += ((context->state[7] & 0x001F0000) | (context->state[6] & 0x0000FC00)) >> 10;
context->state[2] += ((context->state[7] & 0x0000FC00) | (context->state[6] & 0x000003E0)) >> 5;
context->state[1] += (context->state[7] & 0x000003E0) | (context->state[6] & 0x0000001F);
context->state[0] += ROTR((context->state[7] & 0x0000001F) | (context->state[6] & 0xFC000000), 26);
Encode(digest, context->state, 24);
/* Zeroize sensitive information.
*/
ZEND_SECURE_ZERO((unsigned char*) context, sizeof(*context));
}
/* }}} */
/* {{{ PHP_HAVAL224Final */
PHP_HASH_API void PHP_HAVAL224Final(unsigned char *digest, PHP_HAVAL_CTX * context)
{
unsigned char bits[10];
unsigned int index, padLen;
/* Version, Passes, and Digest Length */
bits[0] = (PHP_HASH_HAVAL_VERSION & 0x07) |
((context->passes & 0x07) << 3) |
((context->output & 0x03) << 6);
bits[1] = (context->output >> 2);
/* Save number of bits */
Encode(bits + 2, context->count, 8);
/* Pad out to 118 mod 128.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x7f);
padLen = (index < 118) ? (118 - index) : (246 - index);
PHP_HAVALUpdate(context, PADDING, padLen);
/* Append version, passes, digest length, and message length */
PHP_HAVALUpdate(context, bits, 10);
/* Store state in digest */
context->state[6] += context->state[7] & 0x0000000F;
context->state[5] += (context->state[7] >> 4) & 0x0000001F;
context->state[4] += (context->state[7] >> 9) & 0x0000000F;
context->state[3] += (context->state[7] >> 13) & 0x0000001F;
context->state[2] += (context->state[7] >> 18) & 0x0000000F;
context->state[1] += (context->state[7] >> 22) & 0x0000001F;
context->state[0] += (context->state[7] >> 27) & 0x0000001F;
Encode(digest, context->state, 28);
/* Zeroize sensitive information.
*/
ZEND_SECURE_ZERO((unsigned char*) context, sizeof(*context));
}
/* }}} */
/* {{{ PHP_HAVAL256Final */
PHP_HASH_API void PHP_HAVAL256Final(unsigned char *digest, PHP_HAVAL_CTX * context)
{
unsigned char bits[10];
unsigned int index, padLen;
/* Version, Passes, and Digest Length */
bits[0] = (PHP_HASH_HAVAL_VERSION & 0x07) |
((context->passes & 0x07) << 3) |
((context->output & 0x03) << 6);
bits[1] = (context->output >> 2);
/* Save number of bits */
Encode(bits + 2, context->count, 8);
/* Pad out to 118 mod 128.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x7f);
padLen = (index < 118) ? (118 - index) : (246 - index);
PHP_HAVALUpdate(context, PADDING, padLen);
/* Append version, passes, digest length, and message length */
PHP_HAVALUpdate(context, bits, 10);
/* Store state in digest */
Encode(digest, context->state, 32);
/* Zeroize sensitive information.
*/
ZEND_SECURE_ZERO((unsigned char*) context, sizeof(*context));
}
/* }}} */
| 19,280 | 35.106742 | 133 |
c
|
php-src
|
php-src-master/ext/hash/hash_joaat.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Martin Jansen <[email protected]> |
+----------------------------------------------------------------------+
*/
/* Implements Jenkins's one-at-a-time hashing algorithm as presented on
* http://www.burtleburtle.net/bob/hash/doobs.html.
*/
#include "php_hash.h"
#include "php_hash_joaat.h"
const php_hash_ops php_hash_joaat_ops = {
"joaat",
(php_hash_init_func_t) PHP_JOAATInit,
(php_hash_update_func_t) PHP_JOAATUpdate,
(php_hash_final_func_t) PHP_JOAATFinal,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_JOAAT_SPEC,
4,
4,
sizeof(PHP_JOAAT_CTX),
0
};
PHP_HASH_API void PHP_JOAATInit(PHP_JOAAT_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
context->state = 0;
}
PHP_HASH_API void PHP_JOAATUpdate(PHP_JOAAT_CTX *context, const unsigned char *input, size_t inputLen)
{
context->state = joaat_buf((void *)input, inputLen, context->state);
}
PHP_HASH_API void PHP_JOAATFinal(unsigned char digest[4], PHP_JOAAT_CTX * context)
{
uint32_t hval = context->state;
hval += (hval << 3);
hval ^= (hval >> 11);
hval += (hval << 15);
#ifdef WORDS_BIGENDIAN
memcpy(digest, &hval, 4);
#else
int i = 0;
unsigned char *c = (unsigned char *) &hval;
for (i = 0; i < 4; i++) {
digest[i] = c[3 - i];
}
#endif
context->state = 0;
}
/*
* joaat_buf - perform a Jenkins's one-at-a-time hash on a buffer
*
* input:
* buf - start of buffer to hash
* len - length of buffer in octets
*
* returns:
* 32 bit hash as a static hash type
*/
static uint32_t
joaat_buf(void *buf, size_t len, uint32_t hval)
{
size_t i;
unsigned char *input = (unsigned char *)buf;
for (i = 0; i < len; i++) {
hval += input[i];
hval += (hval << 10);
hval ^= (hval >> 6);
}
return hval;
}
| 2,588 | 26.83871 | 102 |
c
|
php-src
|
php-src-master/ext/hash/hash_md.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Taken from: ext/standard/md5.c |
+----------------------------------------------------------------------+
*/
#include "php_hash.h"
#include "php_hash_md.h"
const php_hash_ops php_hash_md5_ops = {
"md5",
(php_hash_init_func_t) PHP_MD5InitArgs,
(php_hash_update_func_t) PHP_MD5Update,
(php_hash_final_func_t) PHP_MD5Final,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_MD5_SPEC,
16,
64,
sizeof(PHP_MD5_CTX),
1
};
const php_hash_ops php_hash_md4_ops = {
"md4",
(php_hash_init_func_t) PHP_MD4InitArgs,
(php_hash_update_func_t) PHP_MD4Update,
(php_hash_final_func_t) PHP_MD4Final,
php_hash_copy,
php_hash_serialize,
php_hash_unserialize,
PHP_MD4_SPEC,
16,
64,
sizeof(PHP_MD4_CTX),
1
};
static int php_md2_unserialize(php_hashcontext_object *hash, zend_long magic, const zval *zv);
const php_hash_ops php_hash_md2_ops = {
"md2",
(php_hash_init_func_t) PHP_MD2InitArgs,
(php_hash_update_func_t) PHP_MD2Update,
(php_hash_final_func_t) PHP_MD2Final,
php_hash_copy,
php_hash_serialize,
php_md2_unserialize,
PHP_MD2_SPEC,
16,
16,
sizeof(PHP_MD2_CTX),
1
};
/* MD common stuff */
static const unsigned char PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* {{{ Encode
Encodes input (uint32_t) into output (unsigned char). Assumes len is
a multiple of 4.
*/
static void Encode(unsigned char *output, uint32_t *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char) (input[i] & 0xff);
output[j + 1] = (unsigned char) ((input[i] >> 8) & 0xff);
output[j + 2] = (unsigned char) ((input[i] >> 16) & 0xff);
output[j + 3] = (unsigned char) ((input[i] >> 24) & 0xff);
}
}
/* }}} */
/* {{{ Decode
Decodes input (unsigned char) into output (uint32_t). Assumes len is
a multiple of 4.
*/
static void Decode(uint32_t *output, const unsigned char *input, unsigned int len)
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((uint32_t) input[j]) | (((uint32_t) input[j + 1]) << 8) |
(((uint32_t) input[j + 2]) << 16) | (((uint32_t) input[j + 3]) << 24);
}
/* }}} */
/* MD4 */
#define MD4_F(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define MD4_G(x,y,z) (((x) & ((y) | (z))) | ((y) & (z)))
#define MD4_H(x,y,z) ((x) ^ (y) ^ (z))
#define ROTL32(s,v) (((v) << (s)) | ((v) >> (32 - (s))))
#define MD4_R1(a,b,c,d,k,s) a = ROTL32(s, a + MD4_F(b,c,d) + x[k])
#define MD4_R2(a,b,c,d,k,s) a = ROTL32(s, a + MD4_G(b,c,d) + x[k] + 0x5A827999)
#define MD4_R3(a,b,c,d,k,s) a = ROTL32(s, a + MD4_H(b,c,d) + x[k] + 0x6ED9EBA1)
static void MD4Transform(uint32_t state[4], const unsigned char block[64])
{
uint32_t a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode(x, block, 64);
/* Round 1 */
MD4_R1(a,b,c,d, 0, 3);
MD4_R1(d,a,b,c, 1, 7);
MD4_R1(c,d,a,b, 2,11);
MD4_R1(b,c,d,a, 3,19);
MD4_R1(a,b,c,d, 4, 3);
MD4_R1(d,a,b,c, 5, 7);
MD4_R1(c,d,a,b, 6,11);
MD4_R1(b,c,d,a, 7,19);
MD4_R1(a,b,c,d, 8, 3);
MD4_R1(d,a,b,c, 9, 7);
MD4_R1(c,d,a,b,10,11);
MD4_R1(b,c,d,a,11,19);
MD4_R1(a,b,c,d,12, 3);
MD4_R1(d,a,b,c,13, 7);
MD4_R1(c,d,a,b,14,11);
MD4_R1(b,c,d,a,15,19);
/* Round 2 */
MD4_R2(a,b,c,d, 0, 3);
MD4_R2(d,a,b,c, 4, 5);
MD4_R2(c,d,a,b, 8, 9);
MD4_R2(b,c,d,a,12,13);
MD4_R2(a,b,c,d, 1, 3);
MD4_R2(d,a,b,c, 5, 5);
MD4_R2(c,d,a,b, 9, 9);
MD4_R2(b,c,d,a,13,13);
MD4_R2(a,b,c,d, 2, 3);
MD4_R2(d,a,b,c, 6, 5);
MD4_R2(c,d,a,b,10, 9);
MD4_R2(b,c,d,a,14,13);
MD4_R2(a,b,c,d, 3, 3);
MD4_R2(d,a,b,c, 7, 5);
MD4_R2(c,d,a,b,11, 9);
MD4_R2(b,c,d,a,15,13);
/* Round 3 */
MD4_R3(a,b,c,d, 0, 3);
MD4_R3(d,a,b,c, 8, 9);
MD4_R3(c,d,a,b, 4,11);
MD4_R3(b,c,d,a,12,15);
MD4_R3(a,b,c,d, 2, 3);
MD4_R3(d,a,b,c,10, 9);
MD4_R3(c,d,a,b, 6,11);
MD4_R3(b,c,d,a,14,15);
MD4_R3(a,b,c,d, 1, 3);
MD4_R3(d,a,b,c, 9, 9);
MD4_R3(c,d,a,b, 5,11);
MD4_R3(b,c,d,a,13,15);
MD4_R3(a,b,c,d, 3, 3);
MD4_R3(d,a,b,c,11, 9);
MD4_R3(c,d,a,b, 7,11);
MD4_R3(b,c,d,a,15,15);
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
/* {{{ PHP_MD4InitArgs
* MD4 initialization. Begins an MD4 operation, writing a new context.
*/
PHP_HASH_API void PHP_MD4InitArgs(PHP_MD4_CTX * context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/* }}} */
/* {{{ PHP_MD4Update
MD4 block update operation. Continues an MD4 message-digest
operation, processing another message block, and updating the
context.
*/
PHP_HASH_API void PHP_MD4Update(PHP_MD4_CTX * context, const unsigned char *input, size_t inputLen)
{
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int) ((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((uint32_t) inputLen << 3))
< ((uint32_t) inputLen << 3))
context->count[1]++;
context->count[1] += ((uint32_t) inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen) {
memcpy((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen);
MD4Transform(context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64) {
MD4Transform(context->state, &input[i]);
}
index = 0;
} else {
i = 0;
}
/* Buffer remaining input */
memcpy((unsigned char*) & context->buffer[index], (unsigned char*) & input[i], inputLen - i);
}
/* }}} */
/* {{{ PHP_MD4Final
MD4 finalization. Ends an MD4 message-digest operation, writing
the message digest and zeroizing the context.
*/
PHP_HASH_API void PHP_MD4Final(unsigned char digest[16], PHP_MD4_CTX * context)
{
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
Encode(bits, context->count, 8);
/* Pad out to 56 mod 64.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
PHP_MD4Update(context, PADDING, padLen);
/* Append length (before padding) */
PHP_MD4Update(context, bits, 8);
/* Store state in digest */
Encode(digest, context->state, 16);
/* Zeroize sensitive information.
*/
ZEND_SECURE_ZERO((unsigned char*) context, sizeof(*context));
}
/* }}} */
/* MD2 */
static const unsigned char MD2_S[256] = {
41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, 19,
98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, 76, 130, 202,
30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, 138, 23, 229, 18,
190, 78, 196, 214, 218, 158, 222, 73, 160, 251, 245, 142, 187, 47, 238, 122,
169, 104, 121, 145, 21, 178, 7, 63, 148, 194, 16, 137, 11, 34, 95, 33,
128, 127, 93, 154, 90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3,
255, 25, 48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198,
79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241,
69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2,
27, 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, 234, 38,
44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, 129, 77, 82,
106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74,
120, 136, 149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57,
242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117, 75, 10,
49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 };
PHP_HASH_API void PHP_MD2InitArgs(PHP_MD2_CTX *context, ZEND_ATTRIBUTE_UNUSED HashTable *args)
{
memset(context, 0, sizeof(PHP_MD2_CTX));
}
static void MD2_Transform(PHP_MD2_CTX *context, const unsigned char *block)
{
unsigned char i,j,t = 0;
for(i = 0; i < 16; i++) {
context->state[16+i] = block[i];
context->state[32+i] = (context->state[16+i] ^ context->state[i]);
}
for(i = 0; i < 18; i++) {
for(j = 0; j < 48; j++) {
t = context->state[j] = context->state[j] ^ MD2_S[t];
}
t += i;
}
/* Update checksum -- must be after transform to avoid fouling up last message block */
t = context->checksum[15];
for(i = 0; i < 16; i++) {
t = context->checksum[i] ^= MD2_S[block[i] ^ t];
}
}
PHP_HASH_API void PHP_MD2Update(PHP_MD2_CTX *context, const unsigned char *buf, size_t len)
{
const unsigned char *p = buf, *e = buf + len;
if (context->in_buffer) {
if (context->in_buffer + len < 16) {
/* Not enough for block, just pass into buffer */
memcpy(context->buffer + context->in_buffer, p, len);
context->in_buffer += (char) len;
return;
}
/* Put buffered data together with inbound for a single block */
memcpy(context->buffer + context->in_buffer, p, 16 - context->in_buffer);
MD2_Transform(context, context->buffer);
p += 16 - context->in_buffer;
context->in_buffer = 0;
}
/* Process as many whole blocks as remain */
while ((p + 16) <= e) {
MD2_Transform(context, p);
p += 16;
}
/* Copy remaining data to buffer */
if (p < e) {
memcpy(context->buffer, p, e - p);
context->in_buffer = (char) (e - p);
}
}
PHP_HASH_API void PHP_MD2Final(unsigned char output[16], PHP_MD2_CTX *context)
{
memset(context->buffer + context->in_buffer, 16 - context->in_buffer, 16 - context->in_buffer);
MD2_Transform(context, context->buffer);
MD2_Transform(context, context->checksum);
memcpy(output, context->state, 16);
}
static int php_md2_unserialize(php_hashcontext_object *hash, zend_long magic, const zval *zv)
{
PHP_MD2_CTX *ctx = (PHP_MD2_CTX *) hash->context;
int r = FAILURE;
if (magic == PHP_HASH_SERIALIZE_MAGIC_SPEC
&& (r = php_hash_unserialize_spec(hash, zv, PHP_MD2_SPEC)) == SUCCESS
&& (unsigned char) ctx->in_buffer < sizeof(ctx->buffer)) {
return SUCCESS;
} else {
return r != SUCCESS ? r : -2000;
}
}
| 11,013 | 28.767568 | 99 |
c
|
php-src
|
php-src-master/ext/hash/hash_murmur.c
|
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Anatol Belski <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php_hash.h"
#include "php_hash_murmur.h"
#include "murmur/PMurHash.h"
#include "murmur/PMurHash128.h"
const php_hash_ops php_hash_murmur3a_ops = {
"murmur3a",
(php_hash_init_func_t) PHP_MURMUR3AInit,
(php_hash_update_func_t) PHP_MURMUR3AUpdate,
(php_hash_final_func_t) PHP_MURMUR3AFinal,
(php_hash_copy_func_t) PHP_MURMUR3ACopy,
php_hash_serialize,
php_hash_unserialize,
PHP_MURMUR3A_SPEC,
4,
4,
sizeof(PHP_MURMUR3A_CTX),
0
};
PHP_HASH_API void PHP_MURMUR3AInit(PHP_MURMUR3A_CTX *ctx, HashTable *args)
{
if (args) {
zval *seed = zend_hash_str_find_deref(args, "seed", sizeof("seed") - 1);
/* This might be a bit too restrictive, but thinking that a seed might be set
once and for all, it should be done a clean way. */
if (seed && IS_LONG == Z_TYPE_P(seed)) {
ctx->h = (uint32_t)Z_LVAL_P(seed);
} else {
ctx->h = 0;
}
} else {
ctx->h = 0;
}
ctx->carry = 0;
ctx->len = 0;
}
PHP_HASH_API void PHP_MURMUR3AUpdate(PHP_MURMUR3A_CTX *ctx, const unsigned char *in, size_t len)
{
ctx->len += len;
PMurHash32_Process(&ctx->h, &ctx->carry, in, len);
}
PHP_HASH_API void PHP_MURMUR3AFinal(unsigned char digest[4], PHP_MURMUR3A_CTX *ctx)
{
ctx->h = PMurHash32_Result(ctx->h, ctx->carry, ctx->len);
digest[0] = (unsigned char)((ctx->h >> 24) & 0xff);
digest[1] = (unsigned char)((ctx->h >> 16) & 0xff);
digest[2] = (unsigned char)((ctx->h >> 8) & 0xff);
digest[3] = (unsigned char)(ctx->h & 0xff);
}
PHP_HASH_API int PHP_MURMUR3ACopy(const php_hash_ops *ops, PHP_MURMUR3A_CTX *orig_context, PHP_MURMUR3A_CTX *copy_context)
{
copy_context->h = orig_context->h;
copy_context->carry = orig_context->carry;
copy_context->len = orig_context->len;
return SUCCESS;
}
const php_hash_ops php_hash_murmur3c_ops = {
"murmur3c",
(php_hash_init_func_t) PHP_MURMUR3CInit,
(php_hash_update_func_t) PHP_MURMUR3CUpdate,
(php_hash_final_func_t) PHP_MURMUR3CFinal,
(php_hash_copy_func_t) PHP_MURMUR3CCopy,
php_hash_serialize,
php_hash_unserialize,
PHP_MURMUR3C_SPEC,
16,
4,
sizeof(PHP_MURMUR3C_CTX),
0
};
PHP_HASH_API void PHP_MURMUR3CInit(PHP_MURMUR3C_CTX *ctx, HashTable *args)
{
if (args) {
zval *seed = zend_hash_str_find_deref(args, "seed", sizeof("seed") - 1);
/* This might be a bit too restrictive, but thinking that a seed might be set
once and for all, it should be done a clean way. */
if (seed && IS_LONG == Z_TYPE_P(seed)) {
uint32_t _seed = (uint32_t)Z_LVAL_P(seed);
ctx->h[0] = _seed;
ctx->h[1] = _seed;
ctx->h[2] = _seed;
ctx->h[3] = _seed;
} else {
memset(&ctx->h, 0, sizeof ctx->h);
}
} else {
memset(&ctx->h, 0, sizeof ctx->h);
}
memset(&ctx->carry, 0, sizeof ctx->carry);
ctx->len = 0;
}
PHP_HASH_API void PHP_MURMUR3CUpdate(PHP_MURMUR3C_CTX *ctx, const unsigned char *in, size_t len)
{
ctx->len += len;
PMurHash128x86_Process(ctx->h, ctx->carry, in, len);
}
PHP_HASH_API void PHP_MURMUR3CFinal(unsigned char digest[16], PHP_MURMUR3C_CTX *ctx)
{
uint32_t h[4] = {0, 0, 0, 0};
PMurHash128x86_Result(ctx->h, ctx->carry, ctx->len, h);
digest[0] = (unsigned char)((h[0] >> 24) & 0xff);
digest[1] = (unsigned char)((h[0] >> 16) & 0xff);
digest[2] = (unsigned char)((h[0] >> 8) & 0xff);
digest[3] = (unsigned char)(h[0] & 0xff);
digest[4] = (unsigned char)((h[1] >> 24) & 0xff);
digest[5] = (unsigned char)((h[1] >> 16) & 0xff);
digest[6] = (unsigned char)((h[1] >> 8) & 0xff);
digest[7] = (unsigned char)(h[1] & 0xff);
digest[8] = (unsigned char)((h[2] >> 24) & 0xff);
digest[9] = (unsigned char)((h[2] >> 16) & 0xff);
digest[10] = (unsigned char)((h[2] >> 8) & 0xff);
digest[11] = (unsigned char)(h[2] & 0xff);
digest[12] = (unsigned char)((h[3] >> 24) & 0xff);
digest[13] = (unsigned char)((h[3] >> 16) & 0xff);
digest[14] = (unsigned char)((h[3] >> 8) & 0xff);
digest[15] = (unsigned char)(h[3] & 0xff);
}
PHP_HASH_API int PHP_MURMUR3CCopy(const php_hash_ops *ops, PHP_MURMUR3C_CTX *orig_context, PHP_MURMUR3C_CTX *copy_context)
{
memcpy(©_context->h, &orig_context->h, sizeof orig_context->h);
memcpy(©_context->carry, &orig_context->carry, sizeof orig_context->carry);
copy_context->len = orig_context->len;
return SUCCESS;
}
const php_hash_ops php_hash_murmur3f_ops = {
"murmur3f",
(php_hash_init_func_t) PHP_MURMUR3FInit,
(php_hash_update_func_t) PHP_MURMUR3FUpdate,
(php_hash_final_func_t) PHP_MURMUR3FFinal,
(php_hash_copy_func_t) PHP_MURMUR3FCopy,
php_hash_serialize,
php_hash_unserialize,
PHP_MURMUR3F_SPEC,
16,
8,
sizeof(PHP_MURMUR3F_CTX),
0
};
PHP_HASH_API void PHP_MURMUR3FInit(PHP_MURMUR3F_CTX *ctx, HashTable *args)
{
if (args) {
zval *seed = zend_hash_str_find_deref(args, "seed", sizeof("seed") - 1);
/* This might be a bit too restrictive, but thinking that a seed might be set
once and for all, it should be done a clean way. */
if (seed && IS_LONG == Z_TYPE_P(seed)) {
uint64_t _seed = (uint64_t)Z_LVAL_P(seed);
ctx->h[0] = _seed;
ctx->h[1] = _seed;
} else {
memset(&ctx->h, 0, sizeof ctx->h);
}
} else {
memset(&ctx->h, 0, sizeof ctx->h);
}
memset(&ctx->carry, 0, sizeof ctx->carry);
ctx->len = 0;
}
PHP_HASH_API void PHP_MURMUR3FUpdate(PHP_MURMUR3F_CTX *ctx, const unsigned char *in, size_t len)
{
ctx->len += len;
PMurHash128x64_Process(ctx->h, ctx->carry, in, len);
}
PHP_HASH_API void PHP_MURMUR3FFinal(unsigned char digest[16], PHP_MURMUR3F_CTX *ctx)
{
uint64_t h[2] = {0, 0};
PMurHash128x64_Result(ctx->h, ctx->carry, ctx->len, h);
digest[0] = (unsigned char)((h[0] >> 56) & 0xff);
digest[1] = (unsigned char)((h[0] >> 48) & 0xff);
digest[2] = (unsigned char)((h[0] >> 40) & 0xff);
digest[3] = (unsigned char)((h[0] >> 32) & 0xff);
digest[4] = (unsigned char)((h[0] >> 24) & 0xff);
digest[5] = (unsigned char)((h[0] >> 16) & 0xff);
digest[6] = (unsigned char)((h[0] >> 8) & 0xff);
digest[7] = (unsigned char)(h[0] & 0xff);
digest[8] = (unsigned char)((h[1] >> 56) & 0xff);
digest[9] = (unsigned char)((h[1] >> 48) & 0xff);
digest[10] = (unsigned char)((h[1] >> 40) & 0xff);
digest[11] = (unsigned char)((h[1] >> 32) & 0xff);
digest[12] = (unsigned char)((h[1] >> 24) & 0xff);
digest[13] = (unsigned char)((h[1] >> 16) & 0xff);
digest[14] = (unsigned char)((h[1] >> 8) & 0xff);
digest[15] = (unsigned char)(h[1] & 0xff);
}
PHP_HASH_API int PHP_MURMUR3FCopy(const php_hash_ops *ops, PHP_MURMUR3F_CTX *orig_context, PHP_MURMUR3F_CTX *copy_context)
{
memcpy(©_context->h, &orig_context->h, sizeof orig_context->h);
memcpy(©_context->carry, &orig_context->carry, sizeof orig_context->carry);
copy_context->len = orig_context->len;
return SUCCESS;
}
| 7,607 | 32.663717 | 122 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.