Skip to content

Commit

Permalink
sha1: make sha1module thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
colesbury committed Apr 23, 2023
1 parent 2f5c90a commit 22eca6e
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Modules/sha1module.c
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ struct sha1_state {
typedef struct {
PyObject_HEAD

_PyMutex mutex;
struct sha1_state hash_state;
} SHA1object;

Expand Down Expand Up @@ -314,6 +315,10 @@ static SHA1object *
newSHA1object(SHA1State *st)
{
SHA1object *sha = (SHA1object *)PyObject_GC_New(SHA1object, st->sha1_type);
if (!sha) {
return NULL;
}
memset(&sha->mutex, 0, sizeof(sha->mutex));
PyObject_GC_Track(sha);
return sha;
}
Expand Down Expand Up @@ -357,7 +362,9 @@ SHA1Type_copy_impl(SHA1object *self, PyTypeObject *cls)
if ((newobj = newSHA1object(st)) == NULL)
return NULL;

_PyMutex_lock(&self->mutex);
newobj->hash_state = self->hash_state;
_PyMutex_unlock(&self->mutex);
return (PyObject *)newobj;
}

Expand All @@ -374,7 +381,9 @@ SHA1Type_digest_impl(SHA1object *self)
unsigned char digest[SHA1_DIGESTSIZE];
struct sha1_state temp;

_PyMutex_lock(&self->mutex);
temp = self->hash_state;
_PyMutex_unlock(&self->mutex);
sha1_done(&temp, digest);
return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE);
}
Expand All @@ -393,7 +402,9 @@ SHA1Type_hexdigest_impl(SHA1object *self)
struct sha1_state temp;

/* Get the raw (binary) digest value */
_PyMutex_lock(&self->mutex);
temp = self->hash_state;
_PyMutex_unlock(&self->mutex);
sha1_done(&temp, digest);

return _Py_strhex((const char *)digest, SHA1_DIGESTSIZE);
Expand All @@ -416,7 +427,9 @@ SHA1Type_update(SHA1object *self, PyObject *obj)

GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);

_PyMutex_lock(&self->mutex);
sha1_process(&self->hash_state, buf.buf, buf.len);
_PyMutex_unlock(&self->mutex);

PyBuffer_Release(&buf);
Py_RETURN_NONE;
Expand Down

0 comments on commit 22eca6e

Please sign in to comment.