From 76610c0a3af57b600211ea38bc28bcccabc6a86c Mon Sep 17 00:00:00 2001 From: Richard van der Hoff Date: Wed, 14 Dec 2016 11:43:00 +0000 Subject: Allocate memory for message blobs on the heap Messages can be very large, so we don't really want to allocate them on the stack. Switch to using the heap for them, and try to clean up some of the string handling while we're at it. --- javascript/olm_outbound_group_session.js | 44 ++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 14 deletions(-) (limited to 'javascript/olm_outbound_group_session.js') diff --git a/javascript/olm_outbound_group_session.js b/javascript/olm_outbound_group_session.js index 88a441d..01fee0b 100644 --- a/javascript/olm_outbound_group_session.js +++ b/javascript/olm_outbound_group_session.js @@ -63,20 +63,36 @@ OutboundGroupSession.prototype['create'] = restore_stack(function() { ); }); -OutboundGroupSession.prototype['encrypt'] = restore_stack(function(plaintext) { - var plaintext_array = array_from_string(plaintext); - var message_length = outbound_group_session_method( - Module['_olm_group_encrypt_message_length'] - )(this.ptr, plaintext_array.length); - var plaintext_buffer = stack(plaintext_array); - var message_buffer = stack(message_length + NULL_BYTE_PADDING_LENGTH); - outbound_group_session_method(Module['_olm_group_encrypt'])( - this.ptr, - plaintext_buffer, plaintext_array.length, - message_buffer, message_length - ); - return Pointer_stringify(message_buffer); -}); +OutboundGroupSession.prototype['encrypt'] = function(plaintext) { + var plaintext_buffer, message_buffer; + try { + var plaintext_length = Module['lengthBytesUTF8'](plaintext); + + var message_length = outbound_group_session_method( + Module['_olm_group_encrypt_message_length'] + )(this.ptr, plaintext_length); + + // need to allow space for the terminator (which stringToUTF8 always + // writes), hence + 1. + plaintext_buffer = malloc(plaintext_length + 1); + Module['stringToUTF8'](plaintext, plaintext_buffer, plaintext_length + 1); + + message_buffer = malloc(message_length + NULL_BYTE_PADDING_LENGTH); + outbound_group_session_method(Module['_olm_group_encrypt'])( + this.ptr, + plaintext_buffer, plaintext_length, + message_buffer, message_length + ); + return Module['UTF8ToString'](message_buffer); + } finally { + if (plaintext_buffer !== undefined) { + free(plaintext_buffer); + } + if (message_buffer !== undefined) { + free(message_buffer); + } + } +}; OutboundGroupSession.prototype['session_id'] = restore_stack(function() { var length = outbound_group_session_method( -- cgit v1.2.3