87164fef22b3406faf0755a4b41c30cc4bdcf19b
[m6w6/ext-http] / php_http_etag.c
1 #include "php_http.h"
2
3
4 #ifdef PHP_HTTP_HAVE_HASH
5 # include "php_hash.h"
6 #endif
7
8 #include <ext/standard/crc32.h>
9 #include <ext/standard/sha1.h>
10 #include <ext/standard/md5.h>
11
12 PHP_HTTP_API php_http_etag_t *php_http_etag_init(const char *mode TSRMLS_DC)
13 {
14 void *ctx;
15 php_http_etag_t *e;
16
17 #ifdef PHP_HTTP_HAVE_HASH
18 const php_hash_ops *eho = NULL;
19
20 if (mode && (eho = php_hash_fetch_ops(mode, strlen(mode)))) {
21 ctx = emalloc(eho->context_size);
22 eho->hash_init(ctx);
23 } else
24 #endif
25 if (mode && ((!strcasecmp(mode, "crc32")) || (!strcasecmp(mode, "crc32b")))) {
26 ctx = emalloc(sizeof(uint));
27 *((uint *) ctx) = ~0;
28 } else if (mode && !strcasecmp(mode, "sha1")) {
29 PHP_SHA1Init(ctx = emalloc(sizeof(PHP_SHA1_CTX)));
30 } else if (mode && !strcasecmp(mode, "md5")) {
31 PHP_MD5Init(ctx = emalloc(sizeof(PHP_MD5_CTX)));
32 } else {
33 return NULL;
34 }
35
36 e = emalloc(sizeof(*e));
37 e->ctx = ctx;
38 e->mode = estrdup(mode);
39 TSRMLS_SET_CTX(e->ts);
40
41 return e;
42 }
43
44 PHP_HTTP_API char *php_http_etag_finish(php_http_etag_t *e)
45 {
46 unsigned char digest[128] = {0};
47 char *etag = NULL;
48
49 #ifdef PHP_HTTP_HAVE_HASH
50 const php_hash_ops *eho = NULL;
51
52 if (e->mode && (eho = php_hash_fetch_ops(e->mode, strlen(e->mode)))) {
53 eho->hash_final(digest, e->ctx);
54 etag = php_http_etag_digest(digest, eho->digest_size);
55 } else
56 #endif
57 if (((!strcasecmp(e->mode, "crc32")) || (!strcasecmp(e->mode, "crc32b")))) {
58 *((uint *) e->ctx) = ~*((uint *) e->ctx);
59 etag = php_http_etag_digest((const unsigned char *) e->ctx, sizeof(uint));
60 } else if ((!strcasecmp(e->mode, "sha1"))) {
61 PHP_SHA1Final(digest, e->ctx);
62 etag = php_http_etag_digest(digest, 20);
63 } else {
64 PHP_MD5Final(digest, e->ctx);
65 etag = php_http_etag_digest(digest, 16);
66 }
67 efree(e->ctx);
68 efree(e->mode);
69 efree(e);
70
71 return etag;
72 }
73
74 PHP_HTTP_API size_t php_http_etag_update(php_http_etag_t *e, const char *data_ptr, size_t data_len)
75 {
76 #ifdef PHP_HTTP_HAVE_HASH
77 const php_hash_ops *eho = NULL;
78
79 if (e->mode && (eho = php_hash_fetch_ops(e->mode, strlen(e->mode)))) {
80 eho->hash_update(e->ctx, (const unsigned char *) data_ptr, data_len);
81 } else
82 #endif
83 if (((!strcasecmp(e->mode, "crc32")) || (!strcasecmp(e->mode, "crc32b")))) {
84 uint i, c = *((uint *) e->ctx);
85 for (i = 0; i < data_len; ++i) {
86 CRC32(c, data_ptr[i]);
87 }
88 *((uint *) e->ctx) = c;
89 } else if ((!strcasecmp(e->mode, "sha1"))) {
90 PHP_SHA1Update(e->ctx, (const unsigned char *) data_ptr, data_len);
91 } else {
92 PHP_MD5Update(e->ctx, (const unsigned char *) data_ptr, data_len);
93 }
94
95 return data_len;
96 }
97