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