Skip to content
Browse files

import from otr3-em

  • Loading branch information...
0 parents commit 27597b47a5eb33bc00fde190f8035ef624f040e7 @mnaamani committed Dec 5, 2012
Showing with 45,887 additions and 0 deletions.
  1. +340 −0 LICENSE
  2. +40 −0 Makefile
  3. +1 −0 index.js
  4. +714 −0 lib/async.js
  5. +1,588 −0 lib/bigint.js
  6. +344 −0 lib/libotr-js-bindings.js
  7. +41,317 −0 lib/libotr3.js
  8. +258 −0 lib/otr-module.js
  9. +288 −0 lib/seedrandom.js
  10. +21 −0 package.json
  11. +284 −0 src/jsapi.c
  12. +65 −0 src/jsapi.h
  13. +7 −0 src/otr_post.js
  14. +453 −0 src/otr_pre.js
  15. +142 −0 test/index.js
  16. +25 −0 test/simple.js
340 LICENSE
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
40 Makefile
@@ -0,0 +1,40 @@
+EMCC = $(HOME)/Dev/emscripten/emcc
+CRYPTO_BUILD = $(HOME)/projects/crypto-emscripten/build-otr3
+
+BUILD_DIR = lib
+
+EXPORTED_FUNCS= -s EXPORTED_FUNCTIONS="['_gcry_strerror','_malloc','_free','__gcry_mpi_new','__gcry_mpi_set','__gcry_mpi_release', \
+ '__gcry_mpi_scan','__gcry_mpi_print','_otrl_version','_otrl_userstate_create','_otrl_userstate_destroy', \
+ '_otrl_privkey_read','_otrl_privkey_fingerprint','_otrl_privkey_read_fingerprints','_otrl_privkey_write_fingerprints', \
+ '_otrl_privkey_generate', '_otrl_context_find', '_otrl_message_sending', '_otrl_message_free', '_otrl_message_fragment_and_send', \
+ '_otrl_message_disconnect', '_otrl_message_initiate_smp_q', '_otrl_message_initiate_smp', '_otrl_message_respond_smp', \
+ '_jsapi_message_receiving', '_jsapi_can_start_smp','_jsapi_privkey_get_next','_jsapi_privkey_get_accountname', \
+ '_jsapi_privkey_get_protocol', '_jsapi_userstate_get_privkey_root', '_jsapi_conncontext_get_protocol', \
+ '_jsapi_conncontext_get_username', '_jsapi_conncontext_get_accountname','_jsapi_conncontext_get_msgstate', \
+ '_jsapi_conncontext_get_protocol_version', '_jsapi_conncontext_get_smstate', '_jsapi_conncontext_get_active_fingerprint', \
+ '_jsapi_conncontext_get_trust', '_jsapi_initialise','_jsapi_messageappops_new']"
+
+OPTIMISATION_OFF= -O0 --closure 0 --llvm-opts 0 --minify 0 -s LINKABLE=1
+OPTIMISATION_ON= -O2 --closure 1 --llvm-opts 0 --minify 0 -s LINKABLE=1 $(EXPORTED_FUNCS)
+
+OPTIMISATION= $(OPTIMISATION_OFF)
+
+module:
+ mkdir -p $(BUILD_DIR)/
+ $(EMCC) src/jsapi.c -I$(CRYPTO_BUILD)/include -lgcrypt -lotr -lgpg-error -L$(CRYPTO_BUILD)/lib \
+ -o $(BUILD_DIR)/libotr3.js \
+ --pre-js src/otr_pre.js \
+ --post-js src/otr_post.js \
+ -s TOTAL_MEMORY=1048576 -s TOTAL_STACK=409600 \
+ $(OPTIMISATION)
+
+module-optimised:
+ mkdir -p $(BUILD_DIR)/
+ cp src/otr_post.js $(BUILD_DIR)/libotr3.js
+ $(EMCC) src/jsapi.c -I$(CRYPTO_BUILD)/include -lgcrypt -lotr -lgpg-error -L$(CRYPTO_BUILD)/lib \
+ -o $(BUILD_DIR)/_libotr3.js \
+ --pre-js src/otr_pre.js \
+ -s TOTAL_MEMORY=1048576 -s TOTAL_STACK=409600 \
+ $(OPTIMISATION_ON)
+ cat $(BUILD_DIR)/_libotr3.js >> $(BUILD_DIR)/libotr3.js
+ rm $(BUILD_DIR)/_libotr3.js
1 index.js
@@ -0,0 +1 @@
+module.exports = require("./lib/otr-module.js");
714 lib/async.js
@@ -0,0 +1,714 @@
+/*
+Copyright (c) 2010 Caolan McMahon
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/*global setTimeout: false, console: false */
+(function () {
+
+ var async = {};
+
+ // global on the server, window in the browser
+ var root = this,
+ previous_async = root.async;
+
+ if (typeof module !== 'undefined' && module.exports) {
+ module.exports = async;
+ }
+ else {
+ root.async = async;
+ }
+
+ async.noConflict = function () {
+ root.async = previous_async;
+ return async;
+ };
+
+ //// cross-browser compatiblity functions ////
+
+ var _forEach = function (arr, iterator) {
+ if (arr.forEach) {
+ return arr.forEach(iterator);
+ }
+ for (var i = 0; i < arr.length; i += 1) {
+ iterator(arr[i], i, arr);
+ }
+ };
+
+ var _map = function (arr, iterator) {
+ if (arr.map) {
+ return arr.map(iterator);
+ }
+ var results = [];
+ _forEach(arr, function (x, i, a) {
+ results.push(iterator(x, i, a));
+ });
+ return results;
+ };
+
+ var _reduce = function (arr, iterator, memo) {
+ if (arr.reduce) {
+ return arr.reduce(iterator, memo);
+ }
+ _forEach(arr, function (x, i, a) {
+ memo = iterator(memo, x, i, a);
+ });
+ return memo;
+ };
+
+ var _keys = function (obj) {
+ if (Object.keys) {
+ return Object.keys(obj);
+ }
+ var keys = [];
+ for (var k in obj) {
+ if (obj.hasOwnProperty(k)) {
+ keys.push(k);
+ }
+ }
+ return keys;
+ };
+
+ //// exported async module functions ////
+
+ //// nextTick implementation with browser-compatible fallback ////
+ if (typeof process === 'undefined' || !(process.nextTick)) {
+ async.nextTick = function (fn) {
+ setTimeout(fn, 0);
+ };
+ }
+ else {
+ async.nextTick = process.nextTick;
+ }
+
+ async.forEach = function (arr, iterator, callback) {
+ callback = callback || function () {};
+ if (!arr.length) {
+ return callback();
+ }
+ var completed = 0;
+ _forEach(arr, function (x) {
+ iterator(x, function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ if (completed === arr.length) {
+ callback();
+ }
+ }
+ });
+ });
+ };
+
+ async.forEachSeries = function (arr, iterator, callback) {
+ callback = callback || function () {};
+ if (!arr.length) {
+ return callback();
+ }
+ var completed = 0;
+ var iterate = function () {
+ iterator(arr[completed], function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ if (completed === arr.length) {
+ callback();
+ }
+ else {
+ iterate();
+ }
+ }
+ });
+ };
+ iterate();
+ };
+
+ async.forEachLimit = function (arr, limit, iterator, callback) {
+ callback = callback || function () {};
+ if (!arr.length || limit <= 0) {
+ return callback();
+ }
+ var completed = 0;
+ var started = 0;
+ var running = 0;
+
+ (function replenish () {
+ if (completed === arr.length) {
+ return callback();
+ }
+
+ while (running < limit && started < arr.length) {
+ iterator(arr[started], function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ running -= 1;
+ if (completed === arr.length) {
+ callback();
+ }
+ else {
+ replenish();
+ }
+ }
+ });
+ started += 1;
+ running += 1;
+ }
+ })();
+ };
+
+
+ var doParallel = function (fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [async.forEach].concat(args));
+ };
+ };
+ var doSeries = function (fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [async.forEachSeries].concat(args));
+ };
+ };
+
+
+ var _asyncMap = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (err, v) {
+ results[x.index] = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ };
+ async.map = doParallel(_asyncMap);
+ async.mapSeries = doSeries(_asyncMap);
+
+
+ // reduce only has a series version, as doing reduce in parallel won't
+ // work in many situations.
+ async.reduce = function (arr, memo, iterator, callback) {
+ async.forEachSeries(arr, function (x, callback) {
+ iterator(memo, x, function (err, v) {
+ memo = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, memo);
+ });
+ };
+ // inject alias
+ async.inject = async.reduce;
+ // foldl alias
+ async.foldl = async.reduce;
+
+ async.reduceRight = function (arr, memo, iterator, callback) {
+ var reversed = _map(arr, function (x) {
+ return x;
+ }).reverse();
+ async.reduce(reversed, memo, iterator, callback);
+ };
+ // foldr alias
+ async.foldr = async.reduceRight;
+
+ var _filter = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (v) {
+ if (v) {
+ results.push(x);
+ }
+ callback();
+ });
+ }, function (err) {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ };
+ async.filter = doParallel(_filter);
+ async.filterSeries = doSeries(_filter);
+ // select alias
+ async.select = async.filter;
+ async.selectSeries = async.filterSeries;
+
+ var _reject = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (v) {
+ if (!v) {
+ results.push(x);
+ }
+ callback();
+ });
+ }, function (err) {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ };
+ async.reject = doParallel(_reject);
+ async.rejectSeries = doSeries(_reject);
+
+ var _detect = function (eachfn, arr, iterator, main_callback) {
+ eachfn(arr, function (x, callback) {
+ iterator(x, function (result) {
+ if (result) {
+ main_callback(x);
+ main_callback = function () {};
+ }
+ else {
+ callback();
+ }
+ });
+ }, function (err) {
+ main_callback();
+ });
+ };
+ async.detect = doParallel(_detect);
+ async.detectSeries = doSeries(_detect);
+
+ async.some = function (arr, iterator, main_callback) {
+ async.forEach(arr, function (x, callback) {
+ iterator(x, function (v) {
+ if (v) {
+ main_callback(true);
+ main_callback = function () {};
+ }
+ callback();
+ });
+ }, function (err) {
+ main_callback(false);
+ });
+ };
+ // any alias
+ async.any = async.some;
+
+ async.every = function (arr, iterator, main_callback) {
+ async.forEach(arr, function (x, callback) {
+ iterator(x, function (v) {
+ if (!v) {
+ main_callback(false);
+ main_callback = function () {};
+ }
+ callback();
+ });
+ }, function (err) {
+ main_callback(true);
+ });
+ };
+ // all alias
+ async.all = async.every;
+
+ async.sortBy = function (arr, iterator, callback) {
+ async.map(arr, function (x, callback) {
+ iterator(x, function (err, criteria) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ callback(null, {value: x, criteria: criteria});
+ }
+ });
+ }, function (err, results) {
+ if (err) {
+ return callback(err);
+ }
+ else {
+ var fn = function (left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ };
+ callback(null, _map(results.sort(fn), function (x) {
+ return x.value;
+ }));
+ }
+ });
+ };
+
+ async.auto = function (tasks, callback) {
+ callback = callback || function () {};
+ var keys = _keys(tasks);
+ if (!keys.length) {
+ return callback(null);
+ }
+
+ var results = {};
+
+ var listeners = [];
+ var addListener = function (fn) {
+ listeners.unshift(fn);
+ };
+ var removeListener = function (fn) {
+ for (var i = 0; i < listeners.length; i += 1) {
+ if (listeners[i] === fn) {
+ listeners.splice(i, 1);
+ return;
+ }
+ }
+ };
+ var taskComplete = function () {
+ _forEach(listeners.slice(0), function (fn) {
+ fn();
+ });
+ };
+
+ addListener(function () {
+ if (_keys(results).length === keys.length) {
+ callback(null, results);
+ callback = function () {};
+ }
+ });
+
+ _forEach(keys, function (k) {
+ var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k];
+ var taskCallback = function (err) {
+ if (err) {
+ callback(err);
+ // stop subsequent errors hitting callback multiple times
+ callback = function () {};
+ }
+ else {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ taskComplete();
+ }
+ };
+ var requires = task.slice(0, Math.abs(task.length - 1)) || [];
+ var ready = function () {
+ return _reduce(requires, function (a, x) {
+ return (a && results.hasOwnProperty(x));
+ }, true);
+ };
+ if (ready()) {
+ task[task.length - 1](taskCallback, results);
+ }
+ else {
+ var listener = function () {
+ if (ready()) {
+ removeListener(listener);
+ task[task.length - 1](taskCallback, results);
+ }
+ };
+ addListener(listener);
+ }
+ });
+ };
+
+ async.waterfall = function (tasks, callback) {
+ callback = callback || function () {};
+ if (!tasks.length) {
+ return callback();
+ }
+ var wrapIterator = function (iterator) {
+ return function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ var args = Array.prototype.slice.call(arguments, 1);
+ var next = iterator.next();
+ if (next) {
+ args.push(wrapIterator(next));
+ }
+ else {
+ args.push(callback);
+ }
+ async.nextTick(function () {
+ iterator.apply(null, args);
+ });
+ }
+ };
+ };
+ wrapIterator(async.iterator(tasks))();
+ };
+
+ async.parallel = function (tasks, callback) {
+ callback = callback || function () {};
+ if (tasks.constructor === Array) {
+ async.map(tasks, function (fn, callback) {
+ if (fn) {
+ fn(function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ callback.call(null, err, args);
+ });
+ }
+ }, callback);
+ }
+ else {
+ var results = {};
+ async.forEach(_keys(tasks), function (k, callback) {
+ tasks[k](function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+
+ async.series = function (tasks, callback) {
+ callback = callback || function () {};
+ if (tasks.constructor === Array) {
+ async.mapSeries(tasks, function (fn, callback) {
+ if (fn) {
+ fn(function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ callback.call(null, err, args);
+ });
+ }
+ }, callback);
+ }
+ else {
+ var results = {};
+ async.forEachSeries(_keys(tasks), function (k, callback) {
+ tasks[k](function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+
+ async.iterator = function (tasks) {
+ var makeCallback = function (index) {
+ var fn = function () {
+ if (tasks.length) {
+ tasks[index].apply(null, arguments);
+ }
+ return fn.next();
+ };
+ fn.next = function () {
+ return (index < tasks.length - 1) ? makeCallback(index + 1): null;
+ };
+ return fn;
+ };
+ return makeCallback(0);
+ };
+
+ async.apply = function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function () {
+ return fn.apply(
+ null, args.concat(Array.prototype.slice.call(arguments))
+ );
+ };
+ };
+
+ var _concat = function (eachfn, arr, fn, callback) {
+ var r = [];
+ eachfn(arr, function (x, cb) {
+ fn(x, function (err, y) {
+ r = r.concat(y || []);
+ cb(err);
+ });
+ }, function (err) {
+ callback(err, r);
+ });
+ };
+ async.concat = doParallel(_concat);
+ async.concatSeries = doSeries(_concat);
+
+ async.whilst = function (test, iterator, callback) {
+ if (test()) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ async.whilst(test, iterator, callback);
+ });
+ }
+ else {
+ callback();
+ }
+ };
+
+ async.until = function (test, iterator, callback) {
+ if (!test()) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ async.until(test, iterator, callback);
+ });
+ }
+ else {
+ callback();
+ }
+ };
+
+ async.queue = function (worker, concurrency) {
+ var workers = 0;
+ var q = {
+ tasks: [],
+ concurrency: concurrency,
+ saturated: null,
+ empty: null,
+ drain: null,
+ push: function (data, callback) {
+ if(data.constructor !== Array) {
+ data = [data];
+ }
+ _forEach(data, function(task) {
+ q.tasks.push({
+ data: task,
+ callback: typeof callback === 'function' ? callback : null
+ });
+ if (q.saturated && q.tasks.length == concurrency) {
+ q.saturated();
+ }
+ async.nextTick(q.process);
+ });
+ },
+ process: function () {
+ if (workers < q.concurrency && q.tasks.length) {
+ var task = q.tasks.shift();
+ if(q.empty && q.tasks.length == 0) q.empty();
+ workers += 1;
+ worker(task.data, function () {
+ workers -= 1;
+ if (task.callback) {
+ task.callback.apply(task, arguments);
+ }
+ if(q.drain && q.tasks.length + workers == 0) q.drain();
+ q.process();
+ });
+ }
+ },
+ length: function () {
+ return q.tasks.length;
+ },
+ running: function () {
+ return workers;
+ }
+ };
+ return q;
+ };
+
+ var _console_fn = function (name) {
+ return function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ fn.apply(null, args.concat([function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (typeof console !== 'undefined') {
+ if (err) {
+ if (console.error) {
+ console.error(err);
+ }
+ }
+ else if (console[name]) {
+ _forEach(args, function (x) {
+ console[name](x);
+ });
+ }
+ }
+ }]));
+ };
+ };
+ async.log = _console_fn('log');
+ async.dir = _console_fn('dir');
+ /*async.info = _console_fn('info');
+ async.warn = _console_fn('warn');
+ async.error = _console_fn('error');*/
+
+ async.memoize = function (fn, hasher) {
+ var memo = {};
+ var queues = {};
+ hasher = hasher || function (x) {
+ return x;
+ };
+ var memoized = function () {
+ var args = Array.prototype.slice.call(arguments);
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (key in memo) {
+ callback.apply(null, memo[key]);
+ }
+ else if (key in queues) {
+ queues[key].push(callback);
+ }
+ else {
+ queues[key] = [callback];
+ fn.apply(null, args.concat([function () {
+ memo[key] = arguments;
+ var q = queues[key];
+ delete queues[key];
+ for (var i = 0, l = q.length; i < l; i++) {
+ q[i].apply(null, arguments);
+ }
+ }]));
+ }
+ };
+ memoized.unmemoized = fn;
+ return memoized;
+ };
+
+ async.unmemoize = function (fn) {
+ return function () {
+ return (fn.unmemoized || fn).apply(null, arguments);
+ }
+ };
+
+}());
1,588 lib/bigint.js
1,588 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
344 lib/libotr-js-bindings.js
@@ -0,0 +1,344 @@
+var libModule = require("./libotr3.js").getModule();//optimised and minified libotr,libgcrypt,libgpg-error
+var NODE_ASYNC = require("./async");
+
+var otrl_ = libModule.libotrl; //cwrap()'ed functions from libotr
+var gcry_ = libModule.libgcrypt; //cwrap()'ed functions from libgcrypt
+var jsapi_= libModule.jsapi;
+
+var _malloc = libModule.malloc;
+var _free = libModule.free;
+var getValue = libModule.getValue;
+var setValue = libModule.setValue;
+var Pointer_stringify = libModule.Pointer_stringify;
+
+libModule["ops_event"] = ops_event;
+libModule["ConnContext"] = ConnContext;
+
+var OPS_QUEUE;
+var MAO = []; //OtrlMessageAppOps instances and their callback handlers
+
+module.exports = {
+ "init": (function() {
+ jsapi_.initialise();
+ }),
+ "version":function(){
+ return otrl_.version()+"-emscripten";
+ },
+ "UserState":OtrlUserState,
+ "ConnContext":ConnContext,
+ "MessageAppOps":OtrlMessageAppOps,
+};
+
+//OtrlPrivKey
+function OtrlPrivKey(ptr){
+ this._pointer = ptr;
+};
+OtrlPrivKey.prototype.next = function(){
+ var ptr = jsapi_.privkey_get_next(this._pointer);
+ if(ptr) return new OtrlPrivKey(ptr);
+ return undefined;
+};
+OtrlPrivKey.prototype.accountname = function(){
+ return jsapi_.privkey_get_accountname(this._pointer);
+};
+OtrlPrivKey.prototype.protocol = function(){
+ return jsapi_.privkey_get_protocol(this._pointer);
+};
+
+//OtrlUserState
+function OtrlUserState(){
+ this._pointer = otrl_.userstate_create();
+};
+OtrlUserState.prototype.destroy = function(){
+ otrl_.userstate_destroy(this._pointer);
+};
+OtrlUserState.prototype.privkey_root = function(){
+ var ptr=jsapi_.userstate_get_privkey_root(this._pointer);
+ if(ptr) return new OtrlPrivKey(ptr);
+ return undefined;
+};
+OtrlUserState.prototype.accounts = function(){
+ var p = this.privkey_root();
+ var accounts = [];
+ var accountname,protocol;
+ var self = this;
+ while(p){
+ accountname = p.accountname();
+ protocol = p.protocol();
+ accounts.push({
+ "accountname":accountname,
+ "protocol":protocol,
+ "fingerprint":self.fingerprint(accountname,protocol)
+ });
+ p = p.next();
+ }
+ return accounts;
+};
+OtrlUserState.prototype.generateKey = function(filename,accountname,protocol,callback){
+ var self = this;
+ //cant do this async in pure JS. in a browser we could use web workers..background iframe??
+ //in titanium we can create multiple contexts...
+ if(typeof filename == 'string' && typeof accountname=='string' && typeof protocol=='string' && typeof callback == 'function'){
+ console.log("generating key... please wait.");
+ var err = otrl_.privkey_generate(this._pointer,filename,accountname,protocol);
+ try{
+ callback.apply(self, [err ? gcry_.strerror(err) : null] );
+ //callback(err?gcry._strerror(err):null);
+ }catch(e){
+ console.error("Fatal Exception -",e);
+ }
+ }else{
+ throw("invalid arguments to generateKey()");
+ }
+};
+OtrlUserState.prototype.fingerprint = function(accountname, protocol){
+ if( typeof accountname =='string' && typeof protocol == 'string'){
+ var fp = _malloc(45);
+ var res = otrl_.privkey_fingerprint(this._pointer,fp,accountname,protocol);
+ var human = (res? Pointer_stringify(fp):undefined);
+ _free(fp);
+ return human;
+ }else{
+ throw("invalid arguments to fingerprint()");
+ }
+};
+OtrlUserState.prototype.readKeysSync = function(filename){
+ //todo: can also take a string as file contents... url etc.. read it into
+ //virtual file system and load into userstate...
+ //or access real file system... ?
+ if(typeof filename=='string'){
+ var err = otrl_.privkey_read(this._pointer,filename);
+ return (err?gcry_.strerror(err):null);
+ }else{
+ throw("invalid arguments to readKeysSync()");
+ }
+};
+OtrlUserState.prototype.readFingerprintsSync = function(filename){
+ if(typeof filename == 'string'){
+ var err = otrl_.privkey_read_fingerprints(this._pointer,filename,0,0);
+ return (err?gcry_.strerror(err):undefined);
+ }else{
+ throw("invalid arguments to readFingerprintsSync()");
+ }
+};
+OtrlUserState.prototype.writeFingerprintsSync = function (filename){
+ if(typeof filename == 'string'){
+ var err = otrl_.privkey_write_fingerprints(this._pointer,filename);
+ return (err?gcry_.strerror(err):undefined);
+ }else{
+ throw("invalid arguments to writeFingerprintsSync()");
+ }
+};
+
+OtrlUserState.prototype.readKeys = function(){
+ throw("use 'readKeysSync()' not 'readKeys()'");
+};
+OtrlUserState.prototype.readFingerprints = function (){
+ throw("use 'readFingerprintsSync()' not 'readFingerprints()'");
+};
+OtrlUserState.prototype.writeFingerprints = function (){
+ throw("use 'writeFingerprintsSync' not 'writeFingerprints()'");
+};
+
+//ConnContext
+function ConnContext(userstate,accountname,protocol,recipient){
+ if( typeof userstate == 'object' &&
+ typeof accountname == 'string' &&
+ typeof protocol == 'string' &&
+ typeof recipient == 'string' ){
+
+ var addedp_addr = _malloc(4); //allocate(1, "i32", ALLOC_STACK);
+ this._pointer = otrl_.context_find(userstate._pointer,recipient,accountname,protocol,1,addedp_addr,0,0);
+ _free(addedp_addr);
+ }else{
+ if(arguments.length==1 && typeof arguments[0]=='number'){
+ //assume arguments[0] == pointer to existing context;
+ this._pointer = arguments[0];
+ }else{
+ throw("invalid arguments to ConnContext()");
+ }
+ }
+};
+
+ConnContext.prototype.protocol = function(){
+ return jsapi_.conncontext_get_protocol(this._pointer);
+};
+ConnContext.prototype.username = function(){
+ return jsapi_.conncontext_get_username(this._pointer);
+};
+ConnContext.prototype.accountname = function(){
+ return jsapi_.conncontext_get_accountname(this._pointer);
+};
+ConnContext.prototype.msgstate = function(){
+ return jsapi_.conncontext_get_msgstate(this._pointer);
+};
+ConnContext.prototype.protocol_version = function(){
+ return jsapi_.conncontext_get_protocol_version(this._pointer);
+};
+ConnContext.prototype.smstate = function(){
+ return jsapi_.conncontext_get_smstate(this._pointer);
+};
+ConnContext.prototype.fingerprint = function(){
+ var fp = _malloc(45);
+ jsapi_.conncontext_get_active_fingerprint(this._pointer,fp);
+ var human = Pointer_stringify(fp);
+ _free(fp);
+ return human;
+};
+ConnContext.prototype.trust = function(){
+ return jsapi_.conncontext_get_trust(this._pointer);
+};
+ConnContext.prototype.obj = function(){
+ return({
+ 'protocol':this.protocol(),
+ 'username':this.username(),
+ 'accountname':this.accountname(),
+ 'msgstate':this.msgstate(),
+ 'protocol_version':this.protocol_version(),
+ 'smstate':this.smstate(),
+ 'fingerprint':this.fingerprint(),
+ 'trust':this.trust()
+ });
+};
+
+//OtrlMessageAppOps
+function OtrlMessageAppOps( event_handler ){
+ //keep track of all created instances
+ //index into array will be passed around as opdata to tie
+ //the event_handler to the relevant instance.
+ if(!OPS_QUEUE) OPS_QUEUE = NODE_ASYNC.queue(ops_handle_event,1)
+
+ var self = this;
+
+ MAO.push({
+ instance:self,
+ });
+ this._event_handler = event_handler;
+ this._opsdata = _malloc(4);
+ setValue(this._opsdata,MAO.length-1,"i32");
+ this._pointer = jsapi_.messageappops_new();
+};
+
+function ops_handle_event(O,callback){
+ var instance = O._;
+ delete O._;
+ instance._event_handler(O);
+ callback();
+}
+
+OtrlMessageAppOps.prototype.messageSending = function(userstate,accountname,protocol,recipient,message){
+ if(!(
+ typeof userstate=='object' &&
+ typeof accountname=='string' &&
+ typeof protocol=='string' &&
+ typeof recipient=='string' &&
+ typeof message=='string'
+ )){
+ throw("invalid arguments to messageSending()");
+ }
+ var retvalue;
+ var messagep_ptr = _malloc(4);//char**
+
+ var err = otrl_.message_sending(userstate._pointer,this._pointer,this._opsdata,accountname,protocol,recipient,message,0,messagep_ptr,0,0);
+ var messagep = getValue(messagep_ptr,"i32");
+
+ if(err){
+ retvalue = undefined;
+ }else{
+ retvalue = Pointer_stringify(messagep);
+ }
+ if(messagep != 0 ) otrl_.message_free(messagep);
+ _free(messagep_ptr);
+ return retvalue;
+};
+OtrlMessageAppOps.prototype.messageReceiving = function(userstate,accountname,protocol,sender,message){
+ if(!(
+ typeof userstate=='object' &&
+ typeof accountname=='string' &&
+ typeof protocol=='string' &&
+ typeof sender=='string' &&
+ typeof message=='string'
+ )){
+ throw("invalid arguments to messageReceiving()");
+ }
+
+ var newmessagep_ptr = _malloc(4); //char**
+ var status = jsapi_.message_receiving(userstate._pointer,this._pointer,this._opsdata,accountname,protocol,sender,message,newmessagep_ptr);
+ var newmessagep = getValue(newmessagep_ptr,"i32");//char*
+
+ var retvalue;
+ if(status==1) retvalue = null;
+ if(status==0) {
+ retvalue = (newmessagep==0) ? message : Pointer_stringify(newmessagep);
+ }
+ if(newmessagep!=0) otrl_.message_free(newmessagep);
+ _free(newmessagep_ptr);
+ //console.log("messageReceiving returning from", sender,"with value", retvalue,"status=",status);
+ return retvalue;
+};
+OtrlMessageAppOps.prototype.fragmentAndSend = function(context,message){
+ if(!(
+ typeof context=='object' &&
+ typeof message=='string'
+ )){
+ throw("invalid arguments to fragmentAndSend()");
+ }
+ var err = otrl_.message_fragment_and_send(this._pointer,this._opsdata,context._pointer,message,0,0);//send all fragments
+ return gcry_.strerror(err);
+};
+OtrlMessageAppOps.prototype.disconnect = function(userstate,accountname,protocol,recipient){
+ if(!(
+ typeof userstate=='object' &&
+ typeof accountname=='string' &&
+ typeof protocol=='string' &&
+ typeof recipient=='string'
+ )){
+ throw("invalid arguments to disconnect()");
+ }
+
+ otrl_.message_disconnect(userstate._pointer,this._pointer,this._opsdata, accountname,protocol,recipient);
+};
+OtrlMessageAppOps.prototype.initSMP = function(userstate,context,secret,question){
+ if(!(
+ typeof userstate=='object' &&
+ typeof context=='object' &&
+ typeof secret=='string'
+ )){
+ throw("invalid arguments to initSMP()");
+ }
+
+ if(jsapi_.can_start_smp(context._pointer)){
+ if(question){
+ otrl_.message_initiate_smp_q(userstate._pointer,this._pointer,this._opsdata,context._pointer,question,secret,secret.length);
+ }else{
+ otrl_.message_initiate_smp(userstate._pointer,this._pointer,this._opsdata,context._pointer,secret,secret.length);
+ }
+ }
+};
+OtrlMessageAppOps.prototype.respondSMP = function(userstate,context,secret){
+ if(!(
+ typeof userstate=='object' &&
+ typeof context=='object' &&
+ typeof secret=='string'
+ )){
+ throw("invalid arguments to respondSMP()");
+ }
+ otrl_.message_respond_smp(userstate._pointer,this._pointer,this._opsdata,context._pointer,secret,secret.length);
+};
+
+function ops_event($opsdata, ev_obj, ev_name){
+ var $index = getValue($opsdata,"i32");
+ if(ev_name) ev_obj.EVENT = ev_name;
+
+ if(ev_name=='is_logged_in' || ev_name=='policy' || ev_name=='max_message_size'){
+ return MAO[$index].instance._event_handler(ev_obj);
+ }else{
+ //setTimeout(function(){
+ //console.log("ops_event:",ev_name);
+ //MAO[$index].handler(ev_obj);//async firing of the event!
+ ev_obj._ = MAO[$index].instance;
+ OPS_QUEUE.push(ev_obj);
+ //},5);
+ }
+}
+
41,317 lib/libotr3.js
41,317 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
258 lib/otr-module.js
@@ -0,0 +1,258 @@
+/*
+ * Off-the-Record Messaging bindings for nodejs
+ * Copyright (C) 2012 Mokhtar Naamani,
+ * <mokhtar.naamani@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+var debug_mode = false;
+exports.debugOn = function(){
+ debug_mode = true;
+};
+exports.debugOff = function(){
+ debug_mode = false;
+};
+function debug(msg){
+ if(debug_mode) console.error(msg);
+}
+
+//load node C++ native module
+var otr=require("./libotr-js-bindings.js");
+if(otr.init) otr.init();
+
+if(otr.version()!="3.2.1-emscripten"){
+ console.error("Warning. Excpecting libotr3.2.1-emscripten!");
+ process.exit();
+}
+
+var util = require('util');
+var events = require('events');
+
+//low level - wrappers to C API
+exports.version = function(){
+ return otr.version();
+};
+exports.UserState = otr.UserState;
+exports.ConnContext = otr.ConnContext;
+exports.MessageAppOps = otr.MessageAppOps;
+
+//high level - javascript API
+exports.User = User;
+exports.OTRChannel = OTRChannel;
+exports.POLICY = POLICY;
+
+util.inherits(OTRChannel, events.EventEmitter);
+
+function User( config ){
+ this.name = config.name;
+ this.state = new otr.UserState();
+ this.keys = config.keys;
+ this.fingerprints = config.fingerprints;
+ try{
+ this.state.readKeysSync(this.keys);
+ }catch(e){ console.error("Warning Reading Keys:",e);}
+ try{
+ this.state.readFingerprintsSync(this.fingerprints);
+ }catch(e){ console.error("Warning Reading Fingerprints:",e);}
+}
+
+User.prototype.generateKey = function(accountname,protocol,callback){
+ this.state.generateKey(this.keys,accountname,protocol,callback);
+}
+
+User.prototype.ConnContext = function(accountname, protocol, recipient){
+ return new otr.ConnContext(this.state,accountname,protocol,recipient);
+}
+
+User.prototype.writeFingerprints = function(){
+ console.error("Writing Fingerprints to:",this.fingerprints);
+ this.state.writeFingerprintsSync(this.fingerprints);
+}
+
+function OTRChannel(user, context, parameters){
+ events.EventEmitter.call(this);
+
+ this.user = user;
+ this.context = context;
+ this.parameters = parameters;
+ this.ops = new otr.MessageAppOps( OtrEventHandler(this) );
+
+}
+OTRChannel.prototype.connect = function(){
+ return this.send("?OTRv2?");
+};
+OTRChannel.prototype.send = function(message){
+ //message can be any object that can be serialsed to a string using it's .toString() method.
+ var msgout, err;
+ msgout = this.ops.messageSending(this.user.state, this.context.accountname(), this.context.protocol(), this.context.username(), message.toString());
+ if(msgout){
+ err=this.ops.fragmentAndSend(this.context,msgout);
+ return err;
+ }
+};
+OTRChannel.prototype.recv = function(message){
+ //message can be any object that can be serialsed to a string using it's .toString() method.
+ var msg = this.ops.messageReceiving(this.user.state, this.context.accountname(), this.context.protocol(), this.context.username(), message.toString());
+ if(msg) this.emit("message",msg);
+};
+OTRChannel.prototype.close = function(){
+ this.ops.disconnect(this.user.state,this.context.accountname(),this.context.protocol(),this.context.username());
+ this.emit("shutdown");
+};
+OTRChannel.prototype.start_smp = function(secret){
+ var sec = secret || this.parameters? this.parameters.secret:undefined || undefined;
+ if(!sec) throw( new Error("No Secret Provided"));
+ this.ops.initSMP(this.user.state, this.context, sec);
+};
+
+OTRChannel.prototype.start_smp_question = function(question,secret){
+ if(!question){
+ throw(new Error("No Question Provided"));
+ }
+ var sec = secret;
+ if(!sec){
+ sec = this.parameters ? this.parameters.secrets : undefined;
+ if(!sec) throw(new Error("No Secrets Provided"));
+ sec = sec[question];
+ }
+
+ if(!sec) throw(new Error("No Secret Matched for Question"));
+
+ this.ops.initSMP(this.user.state, this.context, sec,question);
+};
+
+OTRChannel.prototype.respond_smp = function(secret){
+ var sec = secret ? secret : undefined;
+ if(!sec){
+ sec = this.parameters ? this.parameters.secret : undefined;
+ }
+ if(!sec) throw( new Error("No Secret Provided"));
+ this.ops.respondSMP(this.user.state, this.context, sec);
+};
+OTRChannel.prototype.isEncrypted = function(){
+ return (this.context.msgstate()===1);
+};
+OTRChannel.prototype.isAuthenticated = function(){
+ return (this.context.trust()==="smp");
+};
+
+function OtrEventHandler( otrChannel ){
+ function emit(){
+ otrChannel.emit.apply(otrChannel,arguments);
+ }
+ return (function(o){
+ //console.error(o.EVENT);
+ switch(o.EVENT){
+ case "smp_request":
+ if(o.question) debug("SMP Question:"+o.question);
+ emit(o.EVENT,o.question);
+ return;
+ case "smp_complete":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "smp_failed":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "smp_aborted":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "is_logged_in":
+ //TODO:function callback. for now remote party is always assumed to be online
+ return 1;
+ case "gone_secure":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "gone_insecure":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "remote_disconnected":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "policy":
+ if(!otrChannel.parameters) return POLICY("DEFAULT");
+ if(typeof otrChannel.parameters.policy == 'number' ) return otrChannel.parameters.policy;//todo: validate policy
+ return POLICY("DEFAULT");
+ case "update_context_list":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "max_message_size":
+ return 0;
+ if(!otrChannel.parameters) return 0; //for UDP packets..
+ return otrChannel.parameters.MTU || 0;
+ case "inject_message":
+ //debug("INJECT:"+o.message);
+ emit(o.EVENT,o.message);
+ return;
+ case "create_privkey":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ case "display_otr_message":
+ debug("OTR_MESSAGE:"+o.message);
+ emit(o.EVENT,o.message);
+ return;
+ case "notify":
+ debug("OTR_NOTIFY:"+o.title+"-"+o.primary);
+ emit(o.EVENT,o.title,o.primary,o.secondary);
+ return;
+ case "log_message":
+ debug("OTR DEBUG:"+o.message);
+ emit(o.EVENT,o.message);
+ return;
+ case "new_fingerprint":
+ debug("NEW FINGERPRINT: "+o.fingerprint);
+ emit(o.EVENT,o.fingerprint);
+ return;
+ case "write_fingerprints":
+ debug(o.EVENT);
+ otrChannel.user.writeFingerprints();
+ return;
+ case "still_secure":
+ debug(o.EVENT);
+ emit(o.EVENT);
+ return;
+ default:
+ console.error("UNHANDLED EVENT:",o.EVENT);
+ return;
+ }
+ });
+}
+
+/* --- libotr-3.2.1/src/proto.h */
+var _policy = {
+ 'NEVER':0x00,
+ 'ALLOW_V1': 0x01,
+ 'ALLOW_V2': 0x02,
+ 'REQUIRE_ENCRYPTION': 0x04,
+ 'SEND_WHITESPACE_TAG': 0x08,
+ 'WHITESPACE_START_AKE': 0x10,
+ 'ERROR_START_AKE': 0x20
+};
+
+_policy['VERSION_MASK'] = _policy['ALLOW_V1']|_policy['ALLOW_V2'];
+_policy['OPPORTUNISTIC'] = _policy['ALLOW_V1']|_policy['ALLOW_V2']|_policy['SEND_WHITESPACE_TAG']|_policy['WHITESPACE_START_AKE']|_policy['ERROR_START_AKE'];
+_policy['MANUAL'] = _policy['ALLOW_V1']|_policy['ALLOW_V2'];
+_policy['ALWAYS'] = _policy['ALLOW_V1']|_policy['ALLOW_V2']|_policy['REQUIRE_ENCRYPTION']|_policy['WHITESPACE_START_AKE']|_policy['ERROR_START_AKE'];
+_policy['DEFAULT'] = _policy['OPPORTUNISTIC']
+
+function POLICY(p){
+ return _policy[p];
+};
288 lib/seedrandom.js
@@ -0,0 +1,288 @@
+// - https://github.com/arlolra/otr/blob/master/vendor/seedrandom.js
+;(function () {
+
+ var root = this
+
+ if (typeof exports !== 'undefined') {
+ module.exports = SeedRandom
+ } else {
+ root.SeedRandom = SeedRandom
+ }
+
+ function SeedRandom(Math) {
+ SR(
+ [], // pool: entropy pool starts empty
+ Math, // math: package containing random, pow, and seedrandom
+ 256, // width: each RC4 output is 0 <= x < 256
+ 6, // chunks: at least six RC4 outputs for each double
+ 52 // significance: there are 52 significant digits in a double
+ )
+ }
+
+ // seedrandom.js version 2.0.
+ // Author: David Bau 4/2/2011
+ //
+ // Defines a method Math.seedrandom() that, when called, substitutes
+ // an explicitly seeded RC4-based algorithm for Math.random(). Also
+ // supports automatic seeding from local or network sources of entropy.
+ //
+ // Usage:
+ //
+ // <script src=http://davidbau.com/encode/seedrandom-min.js></script>
+ //
+ // Math.seedrandom('yipee'); Sets Math.random to a function that is
+ // initialized using the given explicit seed.
+ //
+ // Math.seedrandom(); Sets Math.random to a function that is
+ // seeded using the current time, dom state,
+ // and other accumulated local entropy.
+ // The generated seed string is returned.
+ //
+ // Math.seedrandom('yowza', true);
+ // Seeds using the given explicit seed mixed
+ // together with accumulated entropy.
+ //
+ // <script src="http://bit.ly/srandom-512"></script>
+ // Seeds using physical random bits downloaded
+ // from random.org.
+ //
+ // <script src="https://jsonlib.appspot.com/urandom?callback=Math.seedrandom">
+ // </script> Seeds using urandom bits from call.jsonlib.com,
+ // which is faster than random.org.
+ //
+ // Examples:
+ //
+ // Math.seedrandom("hello"); // Use "hello" as the seed.
+ // document.write(Math.random()); // Always 0.5463663768140734
+ // document.write(Math.random()); // Always 0.43973793770592234
+ // var rng1 = Math.random; // Remember the current prng.
+ //
+ // var autoseed = Math.seedrandom(); // New prng with an automatic seed.
+ // document.write(Math.random()); // Pretty much unpredictable.
+ //
+ // Math.random = rng1; // Continue "hello" prng sequence.
+ // document.write(Math.random()); // Always 0.554769432473455
+ //
+ // Math.seedrandom(autoseed); // Restart at the previous seed.
+ // document.write(Math.random()); // Repeat the 'unpredictable' value.
+ //
+ // Notes:
+ //
+ // Each time seedrandom('arg') is called, entropy from the passed seed
+ // is accumulated in a pool to help generate future seeds for the
+ // zero-argument form of Math.seedrandom, so entropy can be injected over
+ // time by calling seedrandom with explicit data repeatedly.
+ //
+ // On speed - This javascript implementation of Math.random() is about
+ // 3-10x slower than the built-in Math.random() because it is not native
+ // code, but this is typically fast enough anyway. Seeding is more expensive,
+ // especially if you use auto-seeding. Some details (timings on Chrome 4):
+ //
+ // Our Math.random() - avg less than 0.002 milliseconds per call
+ // seedrandom('explicit') - avg less than 0.5 milliseconds per call
+ // seedrandom('explicit', true) - avg less than 2 milliseconds per call
+ // seedrandom() - avg about 38 milliseconds per call
+ //
+ // LICENSE (BSD):
+ //
+ // Copyright 2010 David Bau, 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.
+ //
+ // 3. Neither the name of this module 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ // OWNER 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.
+ //
+ /**
+ * All code is in an anonymous closure to keep the global namespace clean.
+ *
+ * @param {number=} overflow
+ * @param {number=} startdenom
+ */
+ function SR(pool, math, width, chunks, significance, overflow, startdenom) {
+
+ //
+ // seedrandom()
+ // This is the seedrandom function described above.
+ //
+ math['seedrandom'] = function seedrandom(seed, use_entropy) {
+ var key = [];
+ var arc4;
+
+ // Flatten the seed string or build one from local entropy if needed.
+ seed = mixkey(flatten(
+ use_entropy ? [seed, pool] :
+ arguments.length ? seed :
+ [new Date().getTime(), pool, root], 3), key);
+
+ // Use the seed to initialize an ARC4 generator.
+ arc4 = new ARC4(key);
+
+ // Mix the randomness into accumulated entropy.
+ mixkey(arc4.S, pool);
+
+ // Override Math.random
+
+ // This function returns a random double in [0, 1) that contains
+ // randomness in every bit of the mantissa of the IEEE 754 value.
+
+ math['random'] = function random() { // Closure to return a random double:
+ var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
+ var d = startdenom; // and denominator d = 2 ^ 48.
+ var x = 0; // and no 'extra last byte'.
+ while (n < significance) { // Fill up all significant digits by
+ n = (n + x) * width; // shifting numerator and
+ d *= width; // denominator and generating a
+ x = arc4.g(1); // new least-significant-byte.
+ }
+ while (n >= overflow) { // To avoid rounding up, before adding
+ n /= 2; // last byte, shift everything
+ d /= 2; // right using integer math until
+ x >>>= 1; // we have exactly the desired bits.
+ }
+ return (n + x) / d; // Form the number within [0, 1).
+ };
+
+ // Return the seed that was used
+ return seed;
+ };
+
+ //
+ // ARC4
+ //
+ // An ARC4 implementation. The constructor takes a key in the form of
+ // an array of at most (width) integers that should be 0 <= x < (width).
+ //
+ // The g(count) method returns a pseudorandom integer that concatenates
+ // the next (count) outputs from ARC4. Its return value is a number x
+ // that is in the range 0 <= x < (width ^ count).
+ //
+ /** @constructor */
+ function ARC4(key) {
+ var t, u, me = this, keylen = key.length;
+ var i = 0, j = me.i = me.j = me.m = 0;
+ me.S = [];
+ me.c = [];
+
+ // The empty key [] is treated as [0].
+ if (!keylen) { key = [keylen++]; }
+
+ // Set up S using the standard key scheduling algorithm.
+ while (i < width) { me.S[i] = i++; }
+ for (i = 0; i < width; i++) {
+ t = me.S[i];
+ j = lowbits(j + t + key[i % keylen]);
+ u = me.S[j];
+ me.S[i] = u;
+ me.S[j] = t;
+ }
+
+ // The "g" method returns the next (count) outputs as one number.
+ me.g = function getnext(count) {
+ var s = me.S;
+ var i = lowbits(me.i + 1); var t = s[i];
+ var j = lowbits(me.j + t); var u = s[j];
+ s[i] = u;
+ s[j] = t;
+ var r = s[lowbits(t + u)];
+ while (--count) {
+ i = lowbits(i + 1); t = s[i];
+ j = lowbits(j + t); u = s[j];
+ s[i] = u;
+ s[j] = t;
+ r = r * width + s[lowbits(t + u)];
+ }
+ me.i = i;
+ me.j = j;
+ return r;
+ };
+ // For robust unpredictability discard an initial batch of values.
+ // See http://www.rsa.com/rsalabs/node.asp?id=2009
+ me.g(width);
+ }
+
+ //
+ // flatten()
+ // Converts an object tree to nested arrays of strings.
+ //
+ /** @param {Object=} result
+ * @param {string=} prop
+ * @param {string=} typ */
+ function flatten(obj, depth, result, prop, typ) {
+ result = [];
+ typ = typeof(obj);
+ if (depth && typ == 'object') {
+ for (prop in obj) {
+ if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage)
+ try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
+ }
+ }
+ }
+ return (result.length ? result : obj + (typ != 'string' ? '\0' : ''));
+ }
+
+ //
+ // mixkey()
+ // Mixes a string seed into a key that is an array of integers, and
+ // returns a shortened string seed that is equivalent to the result key.
+ //
+ /** @param {number=} smear
+ * @param {number=} j */
+ function mixkey(seed, key, smear, j) {
+ seed += ''; // Ensure the seed is a string
+ smear = 0;
+ for (j = 0; j < seed.length; j++) {
+ key[lowbits(j)] =
+ lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
+ }
+ seed = '';
+ for (j in key) { seed += String.fromCharCode(key[j]); }
+ return seed;
+ }
+
+ //
+ // lowbits()
+ // A quick "n mod width" for width a power of 2.
+ //
+ function lowbits(n) { return n & (width - 1); }
+
+ //
+ // The following constants are related to IEEE 754 limits.
+ //
+ startdenom = math.pow(width, chunks);
+ significance = math.pow(2, significance);
+ overflow = significance * 2;
+
+ //
+ // When seedrandom.js is loaded, we immediately mix a few bits
+ // from the built-in RNG into the entropy pool. Because we do
+ // not want to intefere with determinstic PRNG state later,
+ // seedrandom will not call math.random on its own again after
+ // initialization.
+ //
+ mixkey(math.random(), pool);
+
+ // End anonymous scope, and pass initial values.
+ }
+
+}).call(this)
21 package.json
@@ -0,0 +1,21 @@
+{
+ "name": "otr3-em",
+ "version": "v0.0.1",
+ "main": "index.js",
+ "description": "Off-the-Record Messaging Protocol [emscripten libotr3.2.1]",
+ "homepage": "https://github.com/mnaamani/otr3-em",
+ "author":{
+ "name":"Mokhtar Naamani",
+ "email":"mokhtar.naamani@gmail.com",
+ "url":"https://github.com/mnaamani"
+ },
+ "repository":{
+ "type":"git",
+ "url":"git@github.com:mnaamani/otr3-em.git"
+ },
+ "dependencies":
+ {
+ "async":"*"
+ },
+ "license": "GPLv2"
+}
284 src/jsapi.c
@@ -0,0 +1,284 @@
+#include "jsapi.h"
+
+void jsapi_initialise(){
+ printf("Initialising libgcrypt...\n");
+ /* Version check should be the very first call because it
+ makes sure that important subsystems are intialized. */
+ if (!gcry_check_version (GCRYPT_VERSION))
+ {
+ fputs ("=!= libgcrypt version mismatch\n", stderr);
+ exit (2);
+ }
+
+ gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+ printf("Initialising libotr...\n");
+ OTRL_INIT;
+}
+
+OtrlPrivKey* jsapi_userstate_get_privkey_root(OtrlUserState us){
+ return us->privkey_root;
+}
+OtrlPrivKey* jsapi_privkey_get_next(OtrlPrivKey* p){
+ return p->next;
+}
+char* jsapi_privkey_get_accountname(OtrlPrivKey* p){
+ return p->accountname;
+}
+char* jsapi_privkey_get_protocol(OtrlPrivKey* p){
+ return p->protocol;
+}
+
+char* jsapi_conncontext_get_protocol(ConnContext* ctx){
+ return ctx->protocol;
+}
+char* jsapi_conncontext_get_username(ConnContext* ctx){
+ return ctx->username;
+}
+char* jsapi_conncontext_get_accountname(ConnContext* ctx){
+ return ctx->accountname;
+}
+int jsapi_conncontext_get_msgstate(ConnContext* ctx){
+ return ctx->msgstate;
+}
+int jsapi_conncontext_get_protocol_version(ConnContext* ctx){
+ return ctx->protocol_version;
+}
+int jsapi_conncontext_get_smstate(ConnContext* ctx){
+ return ctx->smstate->sm_prog_state;
+}
+void jsapi_conncontext_get_active_fingerprint(ConnContext* ctx, char* human){
+ human[0]='\0';
+ if(ctx->active_fingerprint==NULL) return;
+ otrl_privkey_hash_to_human(human, ctx->active_fingerprint->fingerprint);
+}
+char* jsapi_conncontext_get_trust(ConnContext* ctx){
+ if(ctx->active_fingerprint == NULL) return NULL;
+ return ctx->active_fingerprint->trust;
+}
+
+//MessageAppOps
+OtrlPolicy msgops_callback_policy(void *opdata,ConnContext *context){
+ return _msgops_callback_policy(opdata,context);
+}
+
+void msgops_callback_create_privkey(void *opdata, const char *accountname,
+ const char *protocol){
+ _msgops_callback_create_privkey(opdata,accountname,protocol);
+}
+int msgops_callback_is_logged_in(void *opdata, const char *accountname,
+ const char *protocol, const char *recipient){
+ return _msgops_callback_is_logged_in(opdata,accountname,protocol,recipient);
+}
+void msgops_callback_inject_message(void *opdata, const char *accountname,
+ const char *protocol, const char *recipient, const char *message){
+ _msgops_callback_inject_message(opdata,accountname,protocol,recipient,message);
+}
+
+void msgops_callback_notify(void *opdata, OtrlNotifyLevel level,
+ const char *accountname, const char *protocol,
+ const char *username, const char *title,
+ const char *primary, const char *secondary){
+ _msgops_callback_notify(opdata,level,accountname,protocol,username,title,primary,secondary);
+}
+
+int msgops_callback_display_otr_message(void *opdata, const char *accountname,
+ const char *protocol, const char *username, const char *msg){
+ return _msgops_callback_display_otr_message(opdata,accountname,protocol,username,msg);
+}
+void msgops_callback_update_context_list(void *opdata){
+ _msgops_callback_update_context_list(opdata);
+}
+
+const char* msgops_callback_protocol_name(void *opdata, const char *protocol){
+ return protocol;
+}
+
+void msgops_callback_protocol_name_free(void *opdata, const char *protocol_name){
+ return;
+}
+
+void msgops_callback_new_fingerprint(void *opdata, OtrlUserState us,
+ const char *accountname, const char *protocol,
+ const char *username, unsigned char fingerprint[20]){
+ char human[45];
+ otrl_privkey_hash_to_human(human, fingerprint);
+ _msgops_callback_new_fingerprint(opdata,us,accountname,protocol,username,human);
+}
+
+void msgops_callback_write_fingerprints(void *opdata){
+ _msgops_callback_write_fingerprints(opdata);
+}
+
+void msgops_callback_gone_secure(void *opdata, ConnContext *context){
+ _msgops_callback_gone_secure(opdata,context);
+}
+
+void msgops_callback_gone_insecure(void *opdata, ConnContext *context){
+ _msgops_callback_gone_insecure(opdata,context);
+}
+
+void msgops_callback_still_secure(void *opdata, ConnContext *context, int is_reply){
+ _msgops_callback_still_secure(opdata,context,is_reply);
+}
+
+void msgops_callback_log_message(void *opdata, const char *message){
+ _msgops_callback_log_message(opdata,message);
+}
+
+int msgops_callback_max_message_size(void *opdata, ConnContext *context){
+ return _msgops_callback_max_message_size(opdata,context);
+}
+
+const char * msgops_callback_account_name(void *opdata, const char *account, const char *protocol){
+ return account;
+}
+
+void msgops_callback_account_name_free(void *opdata, const char *account_name){
+ return;
+}
+
+OtrlMessageAppOps* jsapi_messageappops_new(){
+
+ OtrlMessageAppOps *ops = malloc(sizeof(OtrlMessageAppOps));
+
+ ops->policy = msgops_callback_policy;
+ ops->create_privkey = msgops_callback_create_privkey;
+ ops->is_logged_in = msgops_callback_is_logged_in;
+ ops->inject_message = msgops_callback_inject_message;
+ ops->notify = msgops_callback_notify;
+ ops->display_otr_message = msgops_callback_display_otr_message;
+ ops->update_context_list = msgops_callback_update_context_list;
+ ops->protocol_name = msgops_callback_protocol_name;
+ ops->protocol_name_free = msgops_callback_protocol_name_free;
+ ops->new_fingerprint = msgops_callback_new_fingerprint;
+ ops->write_fingerprints = msgops_callback_write_fingerprints;
+ ops->gone_secure = msgops_callback_gone_secure;
+ ops->gone_insecure = msgops_callback_gone_insecure;
+ ops->still_secure = msgops_callback_still_secure;
+ ops->log_message = msgops_callback_log_message;
+ //ops->max_message_size = msgops_callback_max_message_size;
+ ops->max_message_size = NULL;//disables fragmentation!
+ ops->account_name_free = msgops_callback_account_name_free;
+ ops->account_name = msgops_callback_account_name;
+
+ return ops;
+}
+
+int jsapi_message_receiving (OtrlUserState userstate,OtrlMessageAppOps *messageops, void *opsdata,
+ char *accountname, char *protocol, char *sender, char *message, char** newmessage){
+
+ NextExpectedSMP nextMsg;
+ ConnContext *context;
+ OtrlTLV *tlvs = NULL;
+ OtrlTLV *tlv = NULL;
+
+ //printf("jsapi_message_receiving from %s: %s\n",sender,message);
+
+ int status = otrl_message_receiving(userstate, messageops, opsdata,
+ accountname, protocol, sender, message, newmessage, &tlvs,NULL,NULL);
+
+ context = otrl_context_find(userstate, sender, accountname, protocol, 0, NULL, NULL, NULL);
+
+ //below incoming tlv processing code borrowed from pidgin-otr-3.2.1/otr-plugin.c
+
+ if (context) {
+ //LOOK FOR REMOTE SIDE DISCONNECT
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_DISCONNECTED);
+ if(tlv){
+ _msgops_callback_remote_disconnected(opsdata,context);
+ }else{
+ //LOOK FOR SMP TLVs
+ nextMsg = context->smstate->nextExpected;
+
+ if (context->smstate->sm_prog_state == OTRL_SMP_PROG_CHEATED) {
+ //puts("message receiving OTRL_SMP_PROG_CHEATED!");
+ _msgops_callback_smp_failed(opsdata, context);
+ otrl_message_abort_smp(userstate, messageops, opsdata, context);
+ context->smstate->nextExpected = OTRL_SMP_EXPECT1;
+ context->smstate->sm_prog_state = OTRL_SMP_PROG_OK;
+
+ } else {
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP1Q);
+ if (tlv) {
+ //puts("OTRL_TLV_SMP1Q");
+ if (nextMsg != OTRL_SMP_EXPECT1){
+ otrl_message_abort_smp(userstate, messageops, opsdata, context);
+ _msgops_callback_smp_aborted(opsdata, context);
+ }else {
+ char *question = (char *)tlv->data;
+ char *eoq = (char*)memchr(question, '\0', tlv->len);
+ if (eoq) {
+ _msgops_callback_smp_request(opsdata,context,question);
+ }
+ }
+ }
+
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP1);
+ if (tlv) {
+ //puts("OTRL_TLV_SMP1");
+ if (nextMsg != OTRL_SMP_EXPECT1){
+ otrl_message_abort_smp(userstate, messageops, opsdata, context);
+ _msgops_callback_smp_aborted(opsdata, context);
+ }else {
+ _msgops_callback_smp_request(opsdata,context,NULL);
+ }
+ }
+
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP2);
+ if (tlv) {
+ //puts("OTRL_TLV_SMP2");
+ if (nextMsg != OTRL_SMP_EXPECT2){
+ otrl_message_abort_smp(userstate, messageops, opsdata, context);
+ _msgops_callback_smp_aborted(opsdata, context);
+ }else {
+ context->smstate->nextExpected = OTRL_SMP_EXPECT4;
+ }
+ }
+
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP3);
+ if (tlv) {
+ //puts("OTRL_TLV_SMP3");
+ if (nextMsg != OTRL_SMP_EXPECT3){
+ otrl_message_abort_smp(userstate, messageops, opsdata, context);
+ _msgops_callback_smp_aborted(opsdata, context);
+ }else {
+ context->smstate->nextExpected = OTRL_SMP_EXPECT1;
+ if(context->smstate->sm_prog_state==1) _msgops_callback_smp_complete(opsdata, context);
+ else _msgops_callback_smp_failed(opsdata, context);
+ }
+ }
+
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP4);
+ if (tlv) {
+ //puts("OTRL_TLV_SMP4");
+ if (nextMsg != OTRL_SMP_EXPECT4){
+ otrl_message_abort_smp(userstate, messageops, opsdata, context);
+ _msgops_callback_smp_aborted(opsdata, context);
+ }else {
+ context->smstate->nextExpected = OTRL_SMP_EXPECT1;
+ if(context->smstate->sm_prog_state==1) _msgops_callback_smp_complete(opsdata, context);
+ else _msgops_callback_smp_failed(opsdata, context);
+ }
+ }
+
+ tlv = otrl_tlv_find(tlvs, OTRL_TLV_SMP_ABORT);
+ if (tlv) {
+ //puts("OTRL_TLV_SMP_ABORT");
+ context->smstate->nextExpected = OTRL_SMP_EXPECT1;
+ _msgops_callback_smp_aborted(opsdata, context);
+ }
+ }//if SMP TLVs
+ }//if disconnect TLV
+
+ }else{
+ //puts("message receving but no valid context!");
+ }
+
+ if(tlvs!=NULL) otrl_tlv_free(tlvs);
+ return status;
+}
+
+int jsapi_can_start_smp(ConnContext* ctx){
+ if (ctx->smstate->nextExpected == OTRL_SMP_EXPECT1 ) return 1;
+ return 0;
+}
65 src/jsapi.h
@@ -0,0 +1,65 @@
+#include <gcrypt.h>
+#include <libotr/proto.h>
+#include <libotr/userstate.h>
+#include <libotr/privkey.h>
+#include <libotr/tlv.h>
+#include <libotr/message.h>
+#include <emscripten/emscripten.h>
+
+void jsapi_initialise();
+OtrlPrivKey* jsapi_userstate_get_privkey_root(OtrlUserState us);
+OtrlPrivKey* jsapi_privkey_get_next(OtrlPrivKey* p);
+char* jsapi_privkey_get_accountname(OtrlPrivKey* p);
+char* jsapi_privkey_get_protocol(OtrlPrivKey* p);
+char* jsapi_conncontext_get_protocol(ConnContext* ctx);
+char* jsapi_conncontext_get_username(ConnContext* ctx);
+char* jsapi_conncontext_get_accountname(ConnContext* ctx);
+int jsapi_conncontext_get_msgstate(ConnContext* ctx);
+int jsapi_conncontext_get_protocol_version(ConnContext* ctx);
+int jsapi_conncontext_get_smstate(ConnContext* ctx);
+void jsapi_conncontext_get_active_fingerprint(ConnContext* ctx, char* human);
+char* jsapi_conncontext_get_trust(ConnContext* ctx);
+
+OtrlPolicy msgops_callback_policy(void *opdata,ConnContext *context);
+
+void msgops_callback_create_privkey(void *opdata, const char *accountname,
+ const char *protocol);
+
+int msgops_callback_is_logged_in(void *opdata, const char *accountname,
+ const char *protocol, const char *recipient);
+
+void msgops_callback_inject_message(void *opdata, const char *accountname,
+ const char *protocol, const char *recipient, const char *message);
+
+void msgops_callback_notify(void *opdata, OtrlNotifyLevel level,
+ const char *accountname, const char *protocol,
+ const char *username, const char *title,
+ const char *primary, const char *secondary);
+
+int msgops_callback_display_otr_message(void *opdata, const char *accountname,
+ const char *protocol, const char *username, const char *msg);
+
+void msgops_callback_update_context_list(void *opdata);
+
+const char* msgops_callback_protocol_name(void *opdata, const char *protocol);
+
+void msgops_callback_protocol_name_free(void *opdata, const char *protocol_name);
+
+void msgops_callback_new_fingerprint(void *opdata, OtrlUserState us,
+ const char *accountname, const char *protocol,
+ const char *username, unsigned char fingerprint[20]);
+
+void msgops_callback_write_fingerprints(void *opdata);
+void msgops_callback_gone_secure(void *opdata, ConnContext *context);
+void msgops_callback_gone_insecure(void *opdata, ConnContext *context);
+void msgops_callback_still_secure(void *opdata, ConnContext *context, int is_reply);
+void msgops_callback_log_message(void *opdata, const char *message);
+int msgops_callback_max_message_size(void *opdata, ConnContext *context);
+const char * msgops_callback_account_name(void *opdata, const char *account, const char *protocol);
+void msgops_callback_account_name_free(void *opdata, const char *account_name);
+OtrlMessageAppOps* jsapi_messageappops_new();
+
+int jsapi_message_receiving (OtrlUserState userstate,OtrlMessageAppOps *messageops, void *opsdata,
+ char *accountname, char *protocol, char *sender, char *message, char** newmessage) EMSCRIPTEN_KEEPALIVE;
+
+int jsapi_can_start_smp(ConnContext* ctx);
7 src/otr_post.js
@@ -0,0 +1,7 @@
+var globalScope = this;
+
+if( typeof require !== "undefined" ){
+ module.exports.getModule=function(){
+ return globalScope.Module;
+ }
+}
453 src/otr_pre.js
@@ -0,0 +1,453 @@
+var Module = {};
+
+Module["preRun"]=[];
+/*