diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
deleted file mode 100644
index a16498d..0000000
--- a/.github/workflows/android.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-name: Android CI
-
-on: [push]
-
-jobs:
- build:
-
- runs-on: ubuntu-18.04
-
- steps:
- - uses: actions/checkout@v2
- - name: set up JDK 1.8
- uses: actions/setup-java@v1
- with:
- java-version: 1.8
- - name: Build with Gradle
- run: ./gradlew build
diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml
deleted file mode 100644
index 3dbc8dd..0000000
--- a/.github/workflows/gradle.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-# This workflow uses actions that are not certified by GitHub.
-# They are provided by a third-party and are governed by
-# separate terms of service, privacy policy, and support
-# documentation.
-# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
-# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle
-
-name: Java CI with Gradle
-
-on:
- push:
- branches: [ "master" ]
- pull_request:
- branches: [ "master" ]
-
-permissions:
- contents: read
-
-jobs:
- build:
-
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v3
- - name: Set up JDK 11
- uses: actions/setup-java@v3
- with:
- java-version: '11'
- distribution: 'temurin'
- - name: Build with Gradle
- uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1
- with:
- arguments: build
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index f66d216..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,37 +0,0 @@
-#OSX
-.DS_Store
-
-#Android generated
-bin
-gen
-target
-out
-
-#Eclipse
-.project
-.classpath
-.settings
-
-#IntelliJ IDEA
-.idea
-*.iml
-classes
-
-#Maven
-target
-release.properties
-pom.xml.*
-gen-external-apklibs
-
-#Command line
-local.properties
-build.xml
-proguard-project.txt
-
-#Gradle
-.gradle
-
-#app/build
-app/build/**
-app/src/main/obj/**
-build/intermediates/**
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index e0a5902..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,75 +0,0 @@
-Node-android's license follows:
-
-====
-
-Copyright tomzhou (iwebpp@gmail.com) and other Node-android contributors. All rights reserved.
-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.
-
-====
-
-This license applies to all parts of Node-android that are not externally
-maintained libraries. The externally maintained libraries used by Node-android are:
-
-- libuvpp, libuvpp's license follows:
- """
- libuvpp's license follows:
-
- ====
-
- Copyright Joyent, Inc, yunhong gu, tom zhou(iwebpp@gmail.com) and other Node contributors. All rights reserved.
- 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.
-
- ====
-
- This license applies to all parts of libuv that are not externally
- maintained libraries.
-
- The externally maintained libraries used by libuv are:
-
- - tree.h (from FreeBSD), copyright Niels Provos. Two clause BSD license.
-
- - ngx_queue.h (from Nginx), copyright Igor Sysoev. Two clause BSD license.
-
- - c-ares, copyright Daniel Stenberg and others. MIT licensed.
-
- - libev, located at ev/ is copyright Marc Alexander Lehmann, and
- dual-licensed under the MIT license and GPL2.
-
- - libeio, located at eio/ is copyright Marc Alexander Lehmann, and
- dual-licensed under the MIT license and GPL2.
-
- - UDT4, copyright yunhong gu, and under BSD license.
- """
-- libuv JNI code, Oracle libuv JNI code under GPL V2
diff --git a/README.md b/README.md
deleted file mode 100644
index 05c0884..0000000
--- a/README.md
+++ /dev/null
@@ -1,83 +0,0 @@
-node-android
-===============
-
-
-
-Run Node.js on Android by rewrite Node.js in Java with the compatible API.
-
-
-third-party: [libuvpp](https://github.com/InstantWebP2P/libuvpp), libuv-java JNI code by Oracle.
-
-
-### Build
-
- Clone the code, open Android Studio (1.*) and import the project.
-
- For Eclipse ADT user, refer to [ADT branch](https://github.com/InstantWebP2P/node-android/tree/adt)
-
-
-### Javascript code injection
-
-```bash
-> adb shell am start -a android.intent.action.VIEW -n com.iwebpp.nodeandroid/.MainActivity -e js "var run = function () { return 'hello world'; } run();"
-```
-
-### Features
-
-* Node.js 0.10.x compatible API by rewrite NodeJS in Java
-* Multi-threading: run separate node context in Java thread
-* [libUV native support](https://github.com/InstantWebP2P/node-android/tree/master/app/src/main/java/com/iwebpp/libuvpp)
-* Timer, set/clear Timeout/Interval
-* EventEmitter
-* Stream
-* [HttpParser - Rewrite Http-parser.c in java](https://github.com/InstantWebP2P/node-android/blob/master/app/src/main/java/com/iwebpp/node/HttpParser.java)
-* HTTP
-* [HTTPP - Run Http over Udp](https://github.com/InstantWebP2P/node-android/blob/master/app/src/main/java/com/iwebpp/node/http/httpp.java)
-* TCP
-* [UDT - Udp Transport](https://github.com/InstantWebP2P/node-android/blob/master/app/src/main/java/com/iwebpp/node/net/UDT.java)
-* DNS
-* URL
-* IPv6
-* [NodeJS alike API](https://github.com/InstantWebP2P/node-android/tree/master/app/src/main/java/com/iwebpp/node)
-* [WebSocket, WebSocketServer](https://github.com/InstantWebP2P/node-android/tree/master/app/src/main/java/com/iwebpp/wspp)
-* Connect middleware
-* [Crypto: NaCL support, public box,secret box,signature/verify](https://github.com/InstantWebP2P/node-android/blob/master/app/src/main/java/com/iwebpp/crypto/TweetNaclFast.java)
-* [SecureWebSocket over NaCL](https://github.com/InstantWebP2P/node-android/blob/master/app/src/main/java/com/iwebpp/wspp/SecureWebSocket.java)
-* [NaCL Cert](https://github.com/InstantWebP2P/node-android/blob/master/app/src/main/java/com/iwebpp/crypto/NaclCert.java)
-
-
-### JS runtime
-
-* Rhino supported
-* Exposed node-android packages: com.iwebpp.node.http, com.iwebpp.node.stream, com.iwebpp.node.net, etc
-* Exposed node-android classes: com.iwebpp.node.EventEmitter2, com.iwebpp.node.Dns, com.iwebpp.node.Url, etc
-* Exposed node-android native context in JS standard scope as NodeCurrentContext alias NCC
-* Exposed Android API: android.util.Log
-* NodeJS compatible internal modules are available in JS standard scope
-* Exposed WebSocket classes: com.iwebpp.wspp.WebSocket, com.iwebpp.wspp.WebSocketServer
-
-### JS usage
-
-* In case Rhino, create class 'MyScript' extends from com.iwebpp.node.js.rhino.Host
-* Implement 'public String content()' in 'MyScript' to return user script
-* Execute JS engine in a separate Java Thread with 'MyScript.execute()'
-* When authoring script, please use NodeCurrentContext(alias NCC) in node-android API
-* [JS API usages details](https://github.com/InstantWebP2P/node-android/tree/master/app/src/main/java/com/iwebpp/node/js)
-
-
-### TODO
-
-* API doc, more demos
-* JS runtime CommonJS/AMD compliance
-
-
-### Support us
-
-* Welcome contributing on document, codes, tests and issues
-
-
-### License
-
-(see LICENSE file)
-
-Copyright (c) 2014-present Tom Zhou(appnet.link@gmail.com)
diff --git a/app/build.gradle b/app/build.gradle
deleted file mode 100644
index 8196d41..0000000
--- a/app/build.gradle
+++ /dev/null
@@ -1,49 +0,0 @@
-apply plugin: 'com.android.application'
-apply plugin: 'android-native-dependencies'
-
-android {
- compileSdkVersion 21
- buildToolsVersion '28.0.3'
-
- // prevent ndk from building automagically
- android {
- sourceSets.main {
- jniLibs.srcDir 'src/main/libs'
- jni.srcDirs = [] //disable automatic ndk-build
- }
-
- }
-
- defaultConfig {
- applicationId "com.iwebpp.nodeandroid"
- minSdkVersion 8
- targetSdkVersion 21
-
- // Android Studio 1.0.* deprecated ndk support, do a manual command line build instead
-// ndk {
-// moduleName "uvpp-prebuilt"
-// }
- }
-
- buildTypes {
- debug {
-
- }
-
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
- }
- }
-
- android {
- lintOptions {
- abortOnError false
- }
- }
-}
-
-dependencies {
- implementation 'com.android.support:appcompat-v7:21.0.3'
- implementation fileTree(dir: 'libs', include: ['*.jar'])
-}
diff --git a/app/libs/js.jar b/app/libs/js.jar
deleted file mode 100755
index a8b9417..0000000
Binary files a/app/libs/js.jar and /dev/null differ
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
deleted file mode 100644
index 9127171..0000000
--- a/app/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/app/src/main/java/com/iwebpp/EventHandler.java b/app/src/main/java/com/iwebpp/EventHandler.java
deleted file mode 100644
index d01612f..0000000
--- a/app/src/main/java/com/iwebpp/EventHandler.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/**
- * Copyright (c) 2014 Tom Zhou
- * @author tomzhou
- *
- */
-
-
-package com.iwebpp;
-
-import java.nio.ByteBuffer;
-import java.util.Hashtable;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import com.iwebpp.node.EventEmitter;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-
-/*
- * @description
- * Node.js EvenEmitter implementation with Android Handler
- * */
-public class EventHandler
-extends SimpleDebug
-implements EventEmitter {
- private final static String TAG = "EventHandler";
- private msgHdl hdl;
- private Map> events;
- private Map maxEvents;
-
- // @description message handler
- private class msgHdl extends Handler {
-
- /* (non-Javadoc)
- * @see android.os.Handler#handleMessage(android.os.Message)
- */
- public void handleMessage (Message msg) {
- Bundle bdl = msg.getData();
- String event = bdl.getString("event");
- Object data = msg.obj;
-
- if (events.containsKey(event)) {
- for (Listener cb : events.get(event))
- try {
- // always create new one to share in case ByteBuffer, etc
- if (data!=null && data instanceof ByteBuffer) {
- ByteBuffer bb = ((ByteBuffer)data).slice();
- cb.onEvent(bb);
- } else
- cb.onEvent(data);
- } catch (Exception e) {
- e.printStackTrace();
- error(TAG, "Exception event "+event+","+e);
- }
- } else {
- warn(TAG, "unknown event "+event);
- }
- }
-
- }
-
- public EventHandler() {
- this.hdl = new msgHdl();
- this.events = new Hashtable>();
- this.maxEvents = new Hashtable();
- }
-
- @Override
- public boolean emit(final String event, final Object data) throws Exception {
- Message msg = hdl.obtainMessage();
- Bundle bdl = new Bundle();
-
- // event string
- bdl.putString("event", event);
- msg.setData(bdl);
-
- // data object
- msg.obj = data;
-
- return hdl.sendMessage(msg) && events.containsKey(event);
- }
-
- @Override
- public boolean emit(String event) throws Exception {
- return emit(event, null);
- }
-
- @Override
- public EventEmitter on(final String event, final Listener cb) {
- return addListener(event, cb);
- }
-
- @Override
- public EventEmitter once(final String event, final Listener ocb) {
- return addListener(event, new Listener(){
-
- @Override
- public void onEvent(final Object data) throws Exception {
- ocb.onEvent(data);
-
- // remove listener
- removeListener(event, this);
- }
-
- });
- }
-
- @Override
- public EventEmitter addListener(final String event, final Listener cb) {
- // check maxListens
- if (maxEvents.containsKey(event) &&
- maxEvents.get(event) < listenerCount(event)) {
- warn(TAG, "exceed maxListeners@"+event+" at="+this);
-
- ///return this;
- }
-
- if (!events.containsKey(event))
- events.put(event, new LinkedList());
-
- events.get(event).add(cb);
-
- return this;
- }
-
- @Override
- public EventEmitter addListener(String event, Listener cb, int priority) {
- // check maxListens
- if (maxEvents.containsKey(event) &&
- maxEvents.get(event) < listenerCount(event)) {
- warn(TAG, "exceed maxListeners@"+event+" at="+this);
-
- ///return this;
- }
-
- if (!events.containsKey(event))
- events.put(event, new LinkedList());
-
- if (priority < listenerCount(event))
- events.get(event).add(priority, cb);
- else
- events.get(event).add(cb);
-
- return this;
- }
-
- @Override
- public EventEmitter removeListener(final String event, final Listener cb) {
- if (events.containsKey(event) && events.get(event).contains(cb))
- events.get(event).remove(cb);
-
- return this;
- }
-
- @Override
- public EventEmitter removeListener(final String event) {
- if (events.containsKey(event))
- events.get(event).clear();
-
- return this;
- }
-
- @Override
- public EventEmitter removeListener() {
- events.clear();
- return this;
- }
-
- @Override
- public EventEmitter removeAllListeners() {
- events.clear();
- return this;
- }
-
- @Override
- public EventEmitter setMaxListeners(final String event, final int n) {
- this.maxEvents.put(event, n);
- return this;
- }
-
- @Override
- public List listeners(final String event) {
- return events.containsKey(event) ? events.get(event) : null;
- }
-
- @Override
- public int listenerCount(final String event) {
- return events.containsKey(event) ? events.get(event).size() : 0;
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/SimpleDebug.java b/app/src/main/java/com/iwebpp/SimpleDebug.java
deleted file mode 100644
index c344b54..0000000
--- a/app/src/main/java/com/iwebpp/SimpleDebug.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.iwebpp;
-
-import android.util.Log;
-
-public class SimpleDebug {
-
- public enum DebugLevel {
- NO (0),
- ERROR (1),
- WARN (2),
- DEBUG (3),
- INFO (4);
-
- private int level;
-
- private DebugLevel(int lvl) {
- this.level = lvl;
- }
-
- public int level() {
- return this.level;
- }
- }
-
- /* default debug level as warn */
- private static DebugLevel DEBUG_LEVEL = DebugLevel.WARN;
-
- public SimpleDebug() {}
-
- /*
- * @description
- * Simple Debug implementation
- * */
- public static void setDebugLevel(DebugLevel lvl) {
- DEBUG_LEVEL = lvl;
- }
-
- public static DebugLevel getDebugLevel() {
- return DEBUG_LEVEL;
- }
-
- public static int e(String tag, String message) {
- if (DEBUG_LEVEL.level() >= DebugLevel.ERROR.level())
- return Log.e(tag, message);
-
- return -2;
- }
- public int error(String tag, String message) {
- return e(tag, message);
- }
-
- public static int w(String tag, String message) {
- if (DEBUG_LEVEL.level() >= DebugLevel.WARN.level())
- return Log.w(tag, message);
-
- return -2;
- }
- public static int warn(String tag, String message) {
- return w(tag, message);
- }
-
- public static int d(String tag, String message) {
- if (DEBUG_LEVEL.level() >= DebugLevel.DEBUG.level())
- return Log.d(tag, message);
-
- return -2;
- }
- public static int debug(String tag, String message) {
- return d(tag, message);
- }
-
- public static int i(String tag, String message) {
- if (DEBUG_LEVEL.level() >= DebugLevel.INFO.level())
- return Log.i(tag, message);
-
- return -2;
- }
- public static int info(String tag, String message) {
- return i(tag, message);
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/crypto/NaclCert.java b/app/src/main/java/com/iwebpp/crypto/NaclCert.java
deleted file mode 100644
index d8b879b..0000000
--- a/app/src/main/java/com/iwebpp/crypto/NaclCert.java
+++ /dev/null
@@ -1,819 +0,0 @@
-// Copyright (c) 2014-present Tom Zhou
-
-
-package com.iwebpp.crypto;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import com.iwebpp.SimpleDebug;
-
-public final class NaclCert extends SimpleDebug {
- private final static String TAG = "NaclCert";
-
- private final static String CERT_VERSION = "1.0";
-
-
- // Root CA cert, CA name to Cert map
- public final static Map rootCACert;
- static {
- rootCACert = new Hashtable();
-
- try {
- // default CA cert by iwebpp.com
- SelfCert ca_iwebpp = SelfCert.parse("{\"desc\":{\"version\":\"1.0\",\"type\":\"self\",\"ca\":\"iwebpp.com\",\"tte\":4570381246341,\"publickey\":[237,135,86,100,145,128,37,184,250,64,66,132,116,123,207,51,182,199,59,95,17,186,93,249,220,212,109,77,200,222,157,67],\"signtime\":1416781246454,\"gid\":\"d2f971fc-98ad-4dea-ada2-74ebc129ed99\"},\"sign\":{\"signature\":[214,154,215,247,146,167,144,7,25,170,129,182,224,231,13,239,250,159,139,23,184,249,151,12,153,188,61,76,32,215,218,31,185,251,224,222,15,3,17,53,121,125,166,143,167,52,148,146,85,94,234,202,196,157,211,142,134,74,109,78,7,123,177,2]}}");
- rootCACert.put("iwebpp.com", ca_iwebpp);
-
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- // Test CA info, including cert and secretkey, CA name to CA info map
- public final static Map testCA;
- static {
- testCA = new Hashtable();
-
- try {
- // test CA by iwebpp.com
- CAInfo ca_iwebpp = CAInfo.parse("{\"cert\":{\"desc\":{\"version\":\"1.0\",\"type\":\"self\",\"ca\":\"iwebpp.com\",\"tte\":1732375104475,\"publickey\":[16,239,203,168,67,4,190,200,68,163,63,140,27,142,10,25,65,227,92,199,166,33,30,92,73,221,145,174,220,55,82,34],\"signtime\":1417015104534,\"gid\":\"8d0fdd95-566c-4917-b158-36bace3254c7\"},\"sign\":{\"signature\":[84,224,227,61,149,247,74,147,167,225,148,123,103,7,168,101,136,193,121,64,93,37,82,154,3,116,119,206,5,56,96,74,87,195,58,110,233,117,52,57,237,80,91,39,25,223,50,114,201,72,159,158,75,0,230,13,33,34,134,167,171,129,52,0]}},\"secretkey\":[146,248,181,166,252,192,146,133,46,43,69,244,31,182,120,173,115,43,14,89,157,78,77,216,13,240,28,84,186,40,174,232,16,239,203,168,67,4,190,200,68,163,63,140,27,142,10,25,65,227,92,199,166,33,30,92,73,221,145,174,220,55,82,34]}");
- testCA.put("iwebpp.com", ca_iwebpp);
-
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- // Beans
- public static class ReqDescSignBySelf {
- public String version;
- public String type;
- public long tte;
- public String ca;
- public byte[] publickey;
- }
-
- public static class ReqDescSignByCa {
- public String version;
- public String type;
- public long tte;
- public String ca;
- public byte[] publickey;
-
- public List names;
- public List ips;
- public List macs;
- }
-
- public static class AppendDesc {
- public String gid;
- public long signtime;
- }
-
- public static class DescSignBySelf {
- public ReqDescSignBySelf reqdesc;
- public AppendDesc append;
-
- public DescSignBySelf() {
- reqdesc = new ReqDescSignBySelf();
- append = new AppendDesc();
- }
-
- public JSONObject toJSON() throws JSONException {
- JSONObject json = new JSONObject();
-
- // put reqdesc
- json.put("version", reqdesc.version);
- json.put("type", reqdesc.type);
- json.put("tte", reqdesc.tte);
- json.put("ca", reqdesc.ca);
-
- // publickey
- JSONArray pka = new JSONArray();
- for (int i = 0; i < reqdesc.publickey.length; i ++)
- pka.put(i, reqdesc.publickey[i]&0xff);
-
- json.put("publickey", pka);
-
- // put append
- json.put("gid", append.gid);
- json.put("signtime", append.signtime);
-
- return json;
- }
-
- public String stringify() throws JSONException {
- String jstr = toJSON().toString();
-
- debug(TAG, "DescSignBySelf->:" + jstr);
-
- return jstr;
- }
-
- public static DescSignBySelf parse(String jstr) throws JSONException {
- debug(TAG, "DescSignBySelf<-:" + jstr);
-
- JSONObject json = new JSONObject(jstr);
-
- return parse(json);
- }
-
- public static DescSignBySelf parse(JSONObject json) throws JSONException {
- DescSignBySelf desc = new DescSignBySelf();
-
- // parse reqdesc
- desc.reqdesc.version = json.getString("version");
- desc.reqdesc.type = json.getString("type");
- desc.reqdesc.tte = json.getLong("tte");
- desc.reqdesc.ca = json.getString("ca");
-
- // publickey
- JSONArray pka = json.getJSONArray("publickey");
- byte[] pkb = new byte[pka.length()];
- for (int i = 0; i < pka.length(); i ++)
- pkb[i] = (byte) (pka.getInt(i)&0xff);
-
- desc.reqdesc.publickey = pkb;
-
- // parse append
- desc.append.gid = json.getString("gid");
- desc.append.signtime = json.getLong("signtime");
-
- return desc;
- }
- }
-
- public static class DescSignByCa {
- public ReqDescSignByCa reqdesc;
- public AppendDesc append;
-
- public DescSignByCa() {
- reqdesc = new ReqDescSignByCa();
- append = new AppendDesc();
- }
-
- public JSONObject toJSON() throws JSONException {
- JSONObject json = new JSONObject();
-
- // put reqdesc
- json.put("version", reqdesc.version);
- json.put("type", reqdesc.type);
- json.put("tte", reqdesc.tte);
- json.put("ca", reqdesc.ca);
-
- // publickey
- JSONArray pka = new JSONArray();
- for (int i = 0; i < reqdesc.publickey.length; i ++)
- pka.put(i, reqdesc.publickey[i]&0xff);
-
- json.put("publickey", pka);
-
- // names
- JSONArray namea = new JSONArray();
- if (reqdesc.names!=null)
- for (String name : reqdesc.names)
- namea.put(name);
-
- json.put("names", namea);
-
- // ips
- JSONArray ipa = new JSONArray();
- if (reqdesc.ips!=null)
- for (String ip : reqdesc.ips)
- ipa.put(ip);
-
- json.put("ips", ipa);
-
- // macs
- JSONArray maca = new JSONArray();
- if (reqdesc.macs!=null)
- for (String mac : reqdesc.macs)
- maca.put(mac);
-
- json.put("macs", maca);
-
- // put append
- json.put("gid", append.gid);
- json.put("signtime", append.signtime);
-
- return json;
- }
-
- public String stringify() throws JSONException {
- String jstr = toJSON().toString();
-
- debug(TAG, "DescSignByCa->:" + jstr);
-
- return jstr;
- }
-
- public static DescSignByCa parse(String jstr) throws JSONException {
- debug(TAG, "DescSignByCa<-:" + jstr);
-
- JSONObject json = new JSONObject(jstr);
-
- return parse(json);
- }
-
- public static DescSignByCa parse(JSONObject json) throws JSONException {
- DescSignByCa desc = new DescSignByCa();
-
- // parse reqdesc
- desc.reqdesc.version = json.getString("version");
- desc.reqdesc.type = json.getString("type");
- desc.reqdesc.tte = json.getLong("tte");
- desc.reqdesc.ca = json.getString("ca");
-
- // publickey
- JSONArray pka = json.getJSONArray("publickey");
- byte[] pkb = new byte[pka.length()];
- for (int i = 0; i < pka.length(); i ++)
- pkb[i] = (byte) (pka.getInt(i)&0xff);
-
- desc.reqdesc.publickey = pkb;
-
- // names
- JSONArray namea = json.getJSONArray("names");
- List names = new ArrayList();
- for (int i = 0; i < namea.length(); i ++)
- names.add(namea.getString(i));
-
- desc.reqdesc.names = names;
-
- // ips
- JSONArray ipa = json.getJSONArray("ips");
- List ips = new ArrayList();
- if (ipa != null)
- for (int i = 0; i < ipa.length(); i ++)
- ips.add(ipa.getString(i));
-
- desc.reqdesc.ips = ips;
-
- // macs
- JSONArray maca = json.getJSONArray("macs");
- List macs = new ArrayList();
- if (maca != null)
- for (int i = 0; i < maca.length(); i ++)
- macs.add(maca.getString(i));
-
- desc.reqdesc.macs = macs;
-
- // parse append
- desc.append.gid = json.getString("gid");
- desc.append.signtime = json.getLong("signtime");
-
- return desc;
- }
-
- }
-
- public static class Signature {
- public byte [] signature;
-
- public JSONObject toJSON() throws JSONException {
- JSONObject json = new JSONObject();
-
- JSONArray siga = new JSONArray();
- for (int i = 0; i < signature.length; i ++)
- siga.put(i, signature[i]&0xff);
-
- json.put("signature", siga);
-
- return json;
- }
-
- public String stringify() throws JSONException {
- String jstr = toJSON().toString();
-
- debug(TAG, "Signature->:" + jstr);
-
- return jstr;
- }
-
- public static Signature parse(String jstr) throws JSONException {
- debug(TAG, "Signature<-:" + jstr);
-
- JSONObject json = new JSONObject(jstr);
-
- return parse(json);
- }
-
- public static Signature parse(JSONObject json) throws JSONException {
- Signature sig = new Signature();
-
- JSONArray siga = json.getJSONArray("signature");
- byte[] sigb = new byte[siga.length()];
- for (int i = 0; i < siga.length(); i ++)
- sigb[i] = (byte) (siga.getInt(i)&0xff);
-
- sig.signature = sigb;
-
- return sig;
- }
- }
-
- public static class SelfCert {
- public DescSignBySelf desc;
- public Signature sign;
-
- public SelfCert() {
- desc = new DescSignBySelf();
- sign = new Signature();
- }
-
- public JSONObject toJSON() throws JSONException {
- JSONObject json = new JSONObject();
-
- json.put("desc", desc.toJSON());
- json.put("sign", sign.toJSON());
-
- return json;
- }
-
- public String stringify() throws JSONException {
- String jstr = toJSON().toString();
-
- debug(TAG, "SelfCert->:" + jstr);
-
- return jstr;
- }
-
- public static SelfCert parse(JSONObject json) throws JSONException {
- SelfCert cert = new SelfCert();
- cert.desc = DescSignBySelf.parse(json.getJSONObject("desc"));
- cert.sign = Signature.parse(json.getJSONObject("sign"));
-
- return cert;
- }
-
- public static SelfCert parse(String jstr) throws JSONException {
- debug(TAG, "SelfCert<-:" + jstr);
-
- JSONObject json = new JSONObject(jstr);
-
- return parse(json);
- }
- }
-
- public static class Cert {
- public DescSignByCa desc;
- public Signature sign;
-
- public Cert() {
- desc = new DescSignByCa();
- sign = new Signature();
- }
-
- public JSONObject toJSON() throws JSONException {
- JSONObject json = new JSONObject();
-
- json.put("desc", desc.toJSON());
- json.put("sign", sign.toJSON());
-
- return json;
- }
-
- public String stringify() throws JSONException {
- String jstr = toJSON().toString();
-
- debug(TAG, "Cert->:" + jstr);
-
- return jstr;
- }
-
- public static Cert parse(JSONObject json) throws JSONException {
- Cert cert = new Cert();
- cert.desc = DescSignByCa.parse(json.getJSONObject("desc"));
- cert.sign = Signature.parse(json.getJSONObject("sign"));
-
- return cert;
- }
-
- public static Cert parse(String jstr) throws JSONException {
- debug(TAG, "Cert<-:" + jstr);
-
- JSONObject json = new JSONObject(jstr);
-
- return parse(json);
- }
- }
-
- // @description Generate SelfCert
- // @param req, self reqdesc
- // @param cakey, nacl sign secretkey
- // @return cert on success, null on fail
- public static SelfCert generate(ReqDescSignBySelf req, byte[] cakey) throws Exception {
- SelfCert cert = new SelfCert();
-
- // check type
- if (!req.type.equalsIgnoreCase("self")) {
- e(TAG, "Invalid cert request type");
- return null;
- }
-
- // check version
- if (!req.version.equalsIgnoreCase(CERT_VERSION)) {
- e(TAG, "Invalid cert request version");
- return null;
- }
-
- // check time-to-expire
- if (req.tte < System.currentTimeMillis()) {
- e(TAG, "Invalid cert time-to-expire, smaller than current time");
- return null;
- }
-
- // check CA sign secret key
- if (cakey.length != TweetNaclFast.Signature.secretKeyLength) {
- e(TAG, "Invalid CA secret key");
- return null;
- }
-
- // append fields
- AppendDesc apnd = new AppendDesc();
- apnd.signtime = System.currentTimeMillis();
- apnd.gid = UUID.randomUUID().toString();
-
- // full self desc
- DescSignBySelf desc = new DescSignBySelf();
- desc.reqdesc = req;
- desc.append = apnd;
-
- // stringify desc
- String descstr = desc.stringify();
- d(TAG, "\ngenerate for "+descstr);
- byte[] descbuf = descstr.getBytes("utf-8");
-
- // sign signature
- TweetNaclFast.Signature sig = new TweetNaclFast.Signature(null, cakey);
-
- byte[] sm = sig.sign(descbuf);
-
- cert.desc = desc;
-
- cert.sign = new Signature();
- cert.sign.signature = new byte[TweetNaclFast.Signature.signatureLength];
- for (int i = 0; i < cert.sign.signature.length; i ++)
- cert.sign.signature[i] = sm[i];
-
- return cert;
- }
-
- // @description Generate Cert
- // @param req, CA reqdesc
- // @param cakey, nacl sign secretkey
- // @param cacert, nacl sign self cert
- // @return cert on success, null on fail
- public static Cert generate(ReqDescSignByCa req, byte[] cakey, SelfCert ca) throws Exception {
- Cert cert = new Cert();
-
- // check type
- if (!req.type.equalsIgnoreCase("ca")) {
- e(TAG, "Invalid cert request type");
- return null;
- }
-
- // check version
- if (!req.version.equalsIgnoreCase(CERT_VERSION)) {
- e(TAG, "Invalid cert request version");
- return null;
- }
-
- // check time-to-expire
- if (req.tte < System.currentTimeMillis()) {
- e(TAG, "Invalid cert time-to-expire, smaller than current time");
- return null;
- }
-
- // check CA sign secret key
- if (cakey.length != TweetNaclFast.Signature.secretKeyLength) {
- e(TAG, "Invalid CA secret key");
- return null;
- }
-
- // check CA
- if (!validate(ca)) {
- e(TAG, "Invalid CA cert");
- return null;
- }
-
- // override CA field
- req.ca = ca.desc.reqdesc.ca;
-
- // check tte
- if (req.tte > ca.desc.reqdesc.tte) {
- e(TAG, "Invalid cert time-to-expire, bigger than CA");
- return null;
- }
-
- // append fields
- AppendDesc apnd = new AppendDesc();
- apnd.signtime = System.currentTimeMillis();
- apnd.gid = UUID.randomUUID().toString();
-
- // full CA desc
- DescSignByCa desc = new DescSignByCa();
- desc.reqdesc = req;
- desc.append = apnd;
-
- // stringify desc
- String descstr = desc.stringify();
- d(TAG, "\ngenerate for "+descstr);
- byte[] descbuf = descstr.getBytes("utf-8");
-
- // sign signature
- TweetNaclFast.Signature sig = new TweetNaclFast.Signature(null, cakey);
-
- byte[] sm = sig.sign(descbuf);
-
- cert.desc = desc;
-
- cert.sign = new Signature();
- cert.sign.signature = new byte[TweetNaclFast.Signature.signatureLength];
- for (int i = 0; i < cert.sign.signature.length; i ++)
- cert.sign.signature[i] = sm[i];
-
- return cert;
- }
-
- // @description Validate SelfCert
- // @param cert, selfcert
- // @return true on success, false on fail
- public static boolean validate(SelfCert cert) throws Exception {
- boolean ret = true;
-
- // check type
- if (!cert.desc.reqdesc.type.equalsIgnoreCase("self")) {
- e(TAG, "Invalid cert request type");
- return false;
- }
-
- // check version
- if (!cert.desc.reqdesc.version.equalsIgnoreCase(CERT_VERSION)) {
- e(TAG, "Invalid cert version");
- return false;
- }
-
- // check time-to-expire
- if (cert.desc.reqdesc.tte < System.currentTimeMillis()) {
- e(TAG, "nacl cert expired");
- return false;
- }
-
- // nacl sign public key
- byte[] signPublicKey = cert.desc.reqdesc.publickey;
-
- // stringify desc
- String descstr = cert.desc.stringify();
- d(TAG, "\nvalidate for self-signed:"+descstr);
- byte[] descbuf = descstr.getBytes("utf-8");
-
- // extract signature
- byte[] signature = cert.sign.signature;
- // check signature length
- if (!(signature!=null && signature.length==TweetNaclFast.Signature.signatureLength)) {
- w(TAG, "Invalid signature length");
- return false;
- }
-
- // verify signature
- TweetNaclFast.Signature sig = new TweetNaclFast.Signature(signPublicKey, null);
-
- byte[] sm = new byte[signature.length + descbuf.length];
- for (int i = 0; i < signature.length; i ++)
- sm[i] = signature[i];
- for (int i = 0; i < descbuf.length; i ++)
- sm[i+signature.length] = descbuf[i];
-
- if (null == sig.open(sm)) {
- w(TAG, "Verify signature failed");
- return false;
- }
-
- return ret;
- }
-
- // @description Validate Cert
- // @param cert, cert signed by CA
- // @param ca, CA cert signed by self
- // @return true on success, false on fail
- public static boolean validate(Cert cert, SelfCert ca) throws Exception {
- boolean ret = true;
-
- // check type
- if (!cert.desc.reqdesc.type.equalsIgnoreCase("ca")) {
- e(TAG, "Invalid cert request type");
- return false;
- }
-
- // check version
- if (!cert.desc.reqdesc.version.equalsIgnoreCase(CERT_VERSION)) {
- e(TAG, "Invalid cert version");
- return false;
- }
-
- // check time-to-expire
- if (cert.desc.reqdesc.tte < System.currentTimeMillis()) {
- e(TAG, "nacl cert expired");
- return false;
- }
-
- // check CA
- if (!validate(ca)) {
- e(TAG, "Invalid CA cert");
- return false;
- }
-
- // check CA name
- if (!cert.desc.reqdesc.ca.equalsIgnoreCase(ca.desc.reqdesc.ca)) {
- e(TAG, "CA not matched");
- return false;
- }
-
- // check CA time-to-expire
- if (cert.desc.reqdesc.tte > ca.desc.reqdesc.tte) {
- e(TAG, "Invalid cert time-to-expire, bigger than CA");
- return false;
- }
-
- // extract nacl sign publicKey
- byte[] casignPublicKey = ca.desc.reqdesc.publickey;
-
- // stringify desc
- String descstr = cert.desc.stringify();
- d(TAG, "\nvalidate for CA-signed:"+descstr);
- byte[] descbuf = descstr.getBytes("utf-8");
-
- // extract signature
- byte[] signature = cert.sign.signature;
- // check signature length
- if (!(signature!=null && signature.length==TweetNaclFast.Signature.signatureLength)) {
- w(TAG, "Invalid signature length");
- return false;
- }
-
- // verify signature
- TweetNaclFast.Signature sig = new TweetNaclFast.Signature(casignPublicKey, null);
-
- byte[] sm = new byte[signature.length + descbuf.length];
- for (int i = 0; i < signature.length; i ++)
- sm[i] = signature[i];
- for (int i = 0; i < descbuf.length; i ++)
- sm[i+signature.length] = descbuf[i];
-
- if (null == sig.open(sm)) {
- w(TAG, "Verify signature failed");
- return false;
- }
-
- return ret;
- }
-
- // @description Check domain
- public static boolean checkDomain(Cert cert, String expectDomain) {
- boolean ret = false;
-
- if (cert.desc.reqdesc.names!=null)
- for (String name : cert.desc.reqdesc.names)
- if (name.equalsIgnoreCase(expectDomain)) {
- ret = true;
- break;
- }
-
- return ret;
- }
-
- // @description Check IP
- public static boolean checkIP(Cert cert, String expectIP) {
- boolean ret = false;
-
- if (cert.desc.reqdesc.ips!=null)
- for (String ip : cert.desc.reqdesc.ips)
- if (ip.equalsIgnoreCase(expectIP)) {
- ret = true;
- break;
- }
-
- return ret;
- }
-
- // @description Check MAC
- public static boolean checkMAC(Cert cert, String expectMAC) {
- boolean ret = false;
-
- if (cert.desc.reqdesc.macs!=null)
- for (String mac : cert.desc.reqdesc.macs)
- if (mac.equalsIgnoreCase(expectMAC)) {
- ret = true;
- break;
- }
-
- return ret;
- }
-
- // @description Generate self-sign CA
- public static class CAInfo {
- public String ca; // CA name
- public long tte; // time-to-expire as ms
-
- public SelfCert cert; // self-signed cert
- public byte[] secretkey; // Nacl sign secret key
-
-
- public String toString() {
- String str = "ca:"+ca+"\n";
- str += "tte:"+tte+"\n";
- if (cert!=null)
- try {
- str += cert.stringify();
- } catch (JSONException e) {
- ///e.printStackTrace();
- }
- if (secretkey!=null) str += "secretkey:"+secretkey.toString();
-
- return str;
- }
-
- public JSONObject toJSON() throws JSONException {
- JSONObject json = new JSONObject();
-
- // cert
- json.put("cert", cert.toJSON());
-
- // secretkey
- JSONArray ska = new JSONArray();
- for (int i = 0; i < secretkey.length; i ++)
- ska.put(i, secretkey[i]&0xff);
- json.put("secretkey", ska);
-
- return json;
- }
-
- public String stringify() throws JSONException {
- String jstr = toJSON().toString();
-
- debug(TAG, "CAInfo->:" + jstr);
-
- return jstr;
- }
-
- public static CAInfo parse(JSONObject json) throws JSONException {
- CAInfo ca = new CAInfo();
-
- // self-cert
- ca.cert = SelfCert.parse(json.getJSONObject("cert"));
- ca.ca = ca.cert.desc.reqdesc.ca;
- ca.tte = ca.cert.desc.reqdesc.tte;
-
- // secretkey
- JSONArray ska = json.getJSONArray("secretkey");
- ca.secretkey = new byte[ska.length()];
- for (int i = 0; i < ska.length(); i ++)
- ca.secretkey[i] = (byte) (ska.getInt(i) & 0xff);
-
- return ca;
- }
-
- public static CAInfo parse(String jstr) throws JSONException {
- debug(TAG, "CAInfo<-:" + jstr);
-
- JSONObject json = new JSONObject(jstr);
-
- return parse(json);
- }
-
- }
- public static CAInfo generateCA(CAInfo info) throws Exception {
- // prepare self-sign reqdesc
- ReqDescSignBySelf reqdesc = new ReqDescSignBySelf();
- reqdesc.version = CERT_VERSION;
- reqdesc.type = "self";
- reqdesc.ca = info.ca;
- reqdesc.tte = info.tte;
-
- // genereate Sign keypair
- TweetNaclFast.Signature.KeyPair skp = TweetNaclFast.Signature.keyPair();
- reqdesc.publickey = skp.getPublicKey();
-
- // generate cert
- SelfCert cert = generate(reqdesc, skp.getSecretKey());
-
- // fill cert and secret key in CAInfo
- info.cert = cert;
- info.secretkey = skp.getSecretKey();
-
- return info;
- }
-
- public static Cert generate(ReqDescSignByCa req, CAInfo ca) throws Exception {
- return generate(req, ca.secretkey, ca.cert);
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/crypto/README.md b/app/src/main/java/com/iwebpp/crypto/README.md
deleted file mode 100644
index 488ae1a..0000000
--- a/app/src/main/java/com/iwebpp/crypto/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-### Java port of [tweetnacl-js](https://github.com/dchest/tweetnacl-js)
-
-
-### API/Usage
-
-#### Public key authenticated encryption
-
-* get key pair: Box.KeyPair kp = Box.keyPair(), kp = Box.keyPair_fromSecretKey(sk)
-* new Box object: Box box = new Box(theirPublicKey, mySecretKey, Nonce);
-* encryption: cipher = box.box(message);
-* decryption: message = box.open(cipher);
-* Nonce MUST be unique for ever message passed between same peers
-
-
-#### Secret key authenticated encryption
-
-* get shared key: crypto random, what you have
-* new SecretBox object: SecretBox sbox = new SecretBox(sharedKey, Nonce);
-* encryption: cipher = sbox.box(message);
-* decryption: message = sbox.open(cipher);
-* Nonce MUST be unique for ever message passed between same peers
-
-
-### Signature
-
-* get key pair: Signature.KeyPair kp = Signature.keyPair(), kp = Signature.keyPair_fromSecretKey(sk);
-* new Signature object: Signature sig = new Signature(theirPublicKey, mySecretKey);
-* sign: signedMessage = sig.sign(message);
-* verify: message = sig.open(signedMessage);
-* Nonce MUST be unique for ever message passed between same peers
-
-
-### Hash
-
-* generate SHA-512: byte [] tag = Hash.sha512(message);
-
-
-### Refer to com.iwebpp.crypto.tests for details
-
-
-### NaclCert spec refer to https://github.com/InstantWebP2P/nacl-cert
-
-
-### License MIT
-
diff --git a/app/src/main/java/com/iwebpp/crypto/TweetNacl.java b/app/src/main/java/com/iwebpp/crypto/TweetNacl.java
deleted file mode 100644
index 98486dd..0000000
--- a/app/src/main/java/com/iwebpp/crypto/TweetNacl.java
+++ /dev/null
@@ -1,2378 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.crypto;
-
-import java.io.UnsupportedEncodingException;
-import java.security.SecureRandom;
-import java.util.concurrent.atomic.AtomicLong;
-
-
-/*
- * @description
- * TweetNacl.c Java porting
- * */
-public final class TweetNacl {
-
- private final static String TAG = "TweetNacl";
-
- /*
- * @description
- * Box algorithm, Public-key authenticated encryption
- * */
- public static final class Box {
-
- private final static String TAG = "Box";
-
- private AtomicLong nonce;
-
- private byte [] theirPublicKey;
- private byte [] mySecretKey;
- private byte [] sharedKey;
-
- public Box(byte [] theirPublicKey, byte [] mySecretKey) {
- this(theirPublicKey, mySecretKey, 68);
- }
-
- public Box(byte [] theirPublicKey, byte [] mySecretKey, long nonce) {
- this.theirPublicKey = theirPublicKey;
- this.mySecretKey = mySecretKey;
-
- this.nonce = new AtomicLong(nonce);
-
- // generate pre-computed shared key
- before();
- }
-
- public void setNonce(long nonce) {
- this.nonce.set(nonce);
- }
- public long getNonce() {
- return this.nonce.get();
- }
- public long incrNonce() {
- return this.nonce.incrementAndGet();
- }
- private byte[] generateNonce() {
- // generate nonce
- long nonce = this.nonce.get();
-
- byte [] n = new byte[nonceLength];
- for (int i = 0; i < nonceLength; i += 8) {
- n[i+0] = (byte) (nonce>>> 0);
- n[i+1] = (byte) (nonce>>> 8);
- n[i+2] = (byte) (nonce>>>16);
- n[i+3] = (byte) (nonce>>>24);
- n[i+4] = (byte) (nonce>>>32);
- n[i+5] = (byte) (nonce>>>40);
- n[i+6] = (byte) (nonce>>>48);
- n[i+7] = (byte) (nonce>>>56);
- }
-
- return n;
- }
-
- /*
- * @description
- * Encrypt and authenticates message using peer's public key,
- * our secret key, and the given nonce, which must be unique
- * for each distinct message for a key pair.
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.box.overheadLength longer than the original message.
- * */
- ///public byte_buf_t box(byte [] message) {
- public byte [] box(byte [] message) {
-
- return box(message, generateNonce());
-
- }
-
- /*
- * @description
- * Encrypt and authenticates message using peer's public key,
- * our secret key, and the explicitly provided nonce.
- * Caller is responsible for ensuring that nonce is unique
- * for each distinct message for a key pair.
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.box.overheadLength longer than the original message.
- * */
- ///public byte_buf_t box(byte [] message) {
- public byte [] box(byte [] message, byte [] theNonce) {
-
- // check message
- if (!(message!=null && message.length>0 &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // message buffer
- byte [] m = new byte[message.length + zerobytesLength];
-
- // cipher buffer
- byte [] c = new byte[m.length];
-
- for (int i = 0; i < message.length; i ++)
- m[i+zerobytesLength] = message[i];
-
- if (0 != crypto_box(c, m, m.length, theNonce, theirPublicKey, mySecretKey))
- return null;
-
- // wrap byte_buf_t on c offset@boxzerobytesLength
- ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength);
- byte [] ret = new byte[c.length-boxzerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = c[i+boxzerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Authenticates and decrypts the given box with peer's public key,
- * our secret key, and the given nonce.
- *
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box) {
-
- return open(box, generateNonce());
-
- }
-
- /*
- * @description
- * Authenticates and decrypts the given box with peer's public key,
- * our secret key, and the explicitly provided nonce.
- *
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box, byte [] theNonce) {
- // check message
- if (!(box!=null && box.length>boxzerobytesLength &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // cipher buffer
- byte [] c = new byte[box.length + boxzerobytesLength];
-
- // message buffer
- byte [] m = new byte[c.length];
-
- for (int i = 0; i < box.length; i++)
- c[i+boxzerobytesLength] = box[i];
-
- if (0 != crypto_box_open(m, c, c.length, theNonce, theirPublicKey, mySecretKey))
- return null;
-
- // wrap byte_buf_t on m offset@zerobytesLength
- ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength);
- byte [] ret = new byte[m.length-zerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = m[i+zerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Returns a precomputed shared key
- * which can be used in nacl.box.after and nacl.box.open.after.
- * */
- public byte [] before() {
- if (this.sharedKey == null) {
- this.sharedKey = new byte[sharedKeyLength];
- crypto_box_beforenm(this.sharedKey, this.theirPublicKey, this.mySecretKey);
- }
-
- return this.sharedKey;
- }
-
- /*
- * @description
- * Same as nacl.box, but uses a shared key precomputed with nacl.box.before.
- * */
- public byte [] after(byte [] message) {
-
- return after(message, generateNonce());
-
- }
-
- /*
- * @description
- * Same as nacl.box, but uses a shared key precomputed with nacl.box.before
- * and explicitly provided nonce
- * */
- public byte [] after(byte [] message, byte [] theNonce) {
- // check message
- if (!(message!=null && message.length>0 &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // message buffer
- byte [] m = new byte[message.length + zerobytesLength];
-
- // cipher buffer
- byte [] c = new byte[m.length];
-
- for (int i = 0; i < message.length; i ++)
- m[i+zerobytesLength] = message[i];
-
- if (0 != crypto_box_afternm(c, m, m.length, theNonce, sharedKey))
- return null;
-
- // wrap byte_buf_t on c offset@boxzerobytesLength
- ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength);
- byte [] ret = new byte[c.length-boxzerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = c[i+boxzerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Same as nacl.box.open,
- * but uses a shared key pre-computed with nacl.box.before.
- * */
- public byte [] open_after(byte [] box) {
-
- return open_after(box, generateNonce());
-
- }
-
- /*
- * @description
- * Same as nacl.box.open,
- * but uses a shared key pre-computed with nacl.box.before,
- * and explicitly passed nonce
- * */
- public byte [] open_after(byte [] box, byte [] theNonce) {
- // check message
- if (!(box!=null && box.length>boxzerobytesLength &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // cipher buffer
- byte [] c = new byte[box.length + boxzerobytesLength];
-
- // message buffer
- byte [] m = new byte[c.length];
-
- for (int i = 0; i < box.length; i++)
- c[i+boxzerobytesLength] = box[i];
-
- if (crypto_box_open_afternm(m, c, c.length, theNonce, sharedKey) != 0)
- return null;
-
- // wrap byte_buf_t on m offset@zerobytesLength
- ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength);
- byte [] ret = new byte[m.length-zerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = m[i+zerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Length of public key in bytes.
- * */
- public static final int publicKeyLength = 32;
-
- /*
- * @description
- * Length of secret key in bytes.
- * */
- public static final int secretKeyLength = 32;
-
- /*
- * @description
- * Length of precomputed shared key in bytes.
- * */
- public static final int sharedKeyLength = 32;
-
- /*
- * @description
- * Length of nonce in bytes.
- * */
- public static final int nonceLength = 24;
-
- /*
- * @description
- * zero bytes in case box
- * */
- public static final int zerobytesLength = 32;
- /*
- * @description
- * zero bytes in case open box
- * */
- public static final int boxzerobytesLength = 16;
-
- /*
- * @description
- * Length of overhead added to box compared to original message.
- * */
- public static final int overheadLength = 16;
-
- public static class KeyPair {
- private byte [] publicKey;
- private byte [] secretKey;
-
- public KeyPair() {
- publicKey = new byte[publicKeyLength];
- secretKey = new byte[secretKeyLength];
- }
-
- public byte [] getPublicKey() {
- return publicKey;
- }
-
- public byte [] getSecretKey() {
- return secretKey;
- }
- }
-
- /*
- * @description
- * Generates a new random key pair for box and
- * returns it as an object with publicKey and secretKey members:
- * */
- public static KeyPair keyPair() {
- KeyPair kp = new KeyPair();
-
- crypto_box_keypair(kp.getPublicKey(), kp.getSecretKey());
- return kp;
- }
-
- public static KeyPair keyPair_fromSecretKey(byte [] secretKey) {
- KeyPair kp = new KeyPair();
- byte [] sk = kp.getSecretKey();
- byte [] pk = kp.getPublicKey();
-
- // copy sk
- for (int i = 0; i < sk.length; i ++)
- sk[i] = secretKey[i];
-
- crypto_scalarmult_base(pk, sk);
- return kp;
- }
-
- }
-
- /*
- * @description
- * Secret Box algorithm, secret key
- * */
- public static class SecretBox {
-
- private final static String TAG = "SecretBox";
-
- private AtomicLong nonce;
-
- private byte [] key;
-
- public SecretBox(byte [] key) {
- this(key, 68);
- }
-
- public SecretBox(byte [] key, long nonce) {
- this.key = key;
-
- this.nonce = new AtomicLong(nonce);
- }
-
- public void setNonce(long nonce) {
- this.nonce.set(nonce);
- }
- public long getNonce() {
- return this.nonce.get();
- }
- public long incrNonce() {
- return this.nonce.incrementAndGet();
- }
- private byte[] generateNonce() {
- // generate nonce
- long nonce = this.nonce.get();
-
- byte [] n = new byte[nonceLength];
- for (int i = 0; i < nonceLength; i += 8) {
- n[i+0] = (byte) (nonce>>> 0);
- n[i+1] = (byte) (nonce>>> 8);
- n[i+2] = (byte) (nonce>>>16);
- n[i+3] = (byte) (nonce>>>24);
- n[i+4] = (byte) (nonce>>>32);
- n[i+5] = (byte) (nonce>>>40);
- n[i+6] = (byte) (nonce>>>48);
- n[i+7] = (byte) (nonce>>>56);
- }
-
- return n;
- }
-
- /*
- * @description
- * Encrypt and authenticates message using the key and the nonce.
- * The nonce must be unique for each distinct message for this key.
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.secretbox.overheadLength longer than the original message.
- * */
- ///public byte_buf_t box(byte [] message) {
- public byte [] box(byte [] message) {
-
- return box(message, generateNonce());
-
- }
-
- /*
- * @description
- * Encrypt and authenticates message using the key
- * and the explicitly passed nonce.
- * The nonce must be unique for each distinct message for this key.
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.secretbox.overheadLength longer than the original message.
- * */
- ///public byte_buf_t box(byte [] message) {
- public byte [] box(byte [] message, byte [] theNonce) {
- // check message
- if (!(message!=null && message.length>0 &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // message buffer
- byte [] m = new byte[message.length + zerobytesLength];
-
- // cipher buffer
- byte [] c = new byte[m.length];
-
- for (int i = 0; i < message.length; i ++)
- m[i+zerobytesLength] = message[i];
-
- if (0 != crypto_secretbox(c, m, m.length, theNonce, key))
- return null;
-
- // TBD optimizing ...
- // wrap byte_buf_t on c offset@boxzerobytesLength
- ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength);
- byte [] ret = new byte[c.length-boxzerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = c[i+boxzerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Authenticates and decrypts the given secret box
- * using the key and the nonce.
- *
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box) {
-
- return open(box, generateNonce());
-
- }
-
- /*
- * @description
- * Authenticates and decrypts the given secret box
- * using the key and the explicitly passed nonce.
- *
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box, byte [] theNonce) {
- // check message
- if (!(box!=null && box.length>boxzerobytesLength &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // cipher buffer
- byte [] c = new byte[box.length + boxzerobytesLength];
-
- // message buffer
- byte [] m = new byte[c.length];
-
- for (int i = 0; i < box.length; i++)
- c[i+boxzerobytesLength] = box[i];
-
- if (0 != crypto_secretbox_open(m, c, c.length, theNonce, key))
- return null;
-
- // wrap byte_buf_t on m offset@zerobytesLength
- ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength);
- byte [] ret = new byte[m.length-zerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = m[i+zerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Length of key in bytes.
- * */
- public static final int keyLength = 32;
-
- /*
- * @description
- * Length of nonce in bytes.
- * */
- public static final int nonceLength = 24;
-
- /*
- * @description
- * Length of overhead added to secret box compared to original message.
- * */
- public static final int overheadLength = 16;
-
- /*
- * @description
- * zero bytes in case box
- * */
- public static final int zerobytesLength = 32;
- /*
- * @description
- * zero bytes in case open box
- * */
- public static final int boxzerobytesLength = 16;
-
- }
-
- /*
- * @description
- * Scalar multiplication, Implements curve25519.
- * */
- public static final class ScalarMult {
-
- private final static String TAG = "ScalarMult";
-
- /*
- * @description
- * Multiplies an integer n by a group element p and
- * returns the resulting group element.
- * */
- public static byte [] scalseMult(byte [] n, byte [] p) {
- if (!(n.length==scalarLength && p.length==groupElementLength))
- return null;
-
- byte [] q = new byte [scalarLength];
-
- crypto_scalarmult(q, n, p);
-
- return q;
- }
-
- /*
- * @description
- * Multiplies an integer n by a standard group element and
- * returns the resulting group element.
- * */
- public static byte [] scalseMult_base(byte [] n) {
- if (!(n.length==scalarLength))
- return null;
-
- byte [] q = new byte [scalarLength];
-
- crypto_scalarmult_base(q, n);
-
- return q;
- }
-
- /*
- * @description
- * Length of scalar in bytes.
- * */
- public static final int scalarLength = 32;
-
- /*
- * @description
- * Length of group element in bytes.
- * */
- public static final int groupElementLength = 32;
-
- }
-
-
- /*
- * @description
- * Hash algorithm, Implements SHA-512.
- * */
- public static final class Hash {
-
- private final static String TAG = "Hash";
-
- /*
- * @description
- * Returns SHA-512 hash of the message.
- * */
- public static byte[] sha512(byte [] message) {
- if (!(message!=null && message.length>0))
- return null;
-
- byte [] out = new byte[hashLength];
-
- crypto_hash(out, message);
-
- return out;
- }
- public static byte[] sha512(String message) throws UnsupportedEncodingException {
- return sha512(message.getBytes("utf-8"));
- }
-
- /*
- * @description
- * Length of hash in bytes.
- * */
- public static final int hashLength = 64;
-
- }
-
-
- /*
- * @description
- * Signature algorithm, Implements ed25519.
- * */
- public static final class Signature {
-
- private final static String TAG = "Signature";
-
- private byte [] theirPublicKey;
- private byte [] mySecretKey;
-
- public Signature(byte [] theirPublicKey, byte [] mySecretKey) {
- this.theirPublicKey = theirPublicKey;
- this.mySecretKey = mySecretKey;
- }
-
- /*
- * @description
- * Signs the message using the secret key and returns a signed message.
- * */
- public byte [] sign(byte [] message) {
- // signed message
- byte [] sm = new byte[message.length + signatureLength];
-
- crypto_sign(sm, -1, message, message.length, mySecretKey);
-
- return sm;
- }
-
- /*
- * @description
- * Verifies the signed message and returns the message without signature.
- * Returns null if verification failed.
- * */
- public byte [] open(byte [] signedMessage) {
- // check sm length
- if (!(signedMessage!=null && signedMessage.length>signatureLength))
- return null;
-
- // temp buffer
- byte [] tmp = new byte[signedMessage.length];
-
- if (0 != crypto_sign_open(tmp, -1, signedMessage, signedMessage.length, theirPublicKey))
- return null;
-
- // message
- byte [] msg = new byte[signedMessage.length-signatureLength];
- for (int i = 0; i < msg.length; i ++)
- msg[i] = signedMessage[i+signatureLength];
-
- return msg;
- }
-
- /*
- * @description
- * Signs the message using the secret key and returns a signature.
- * */
- public byte [] detached(byte [] message) {
-
- return null;
- }
-
- /*
- * @description
- * Verifies the signature for the message and
- * returns true if verification succeeded or false if it failed.
- * */
- public boolean detached_verify(byte [] message, byte [] signature) {
-
- return false;
- }
-
- /*
- * @description
- * Generates new random key pair for signing and
- * returns it as an object with publicKey and secretKey members
- * */
- public static class KeyPair {
- private byte [] publicKey;
- private byte [] secretKey;
-
- public KeyPair() {
- publicKey = new byte[publicKeyLength];
- secretKey = new byte[secretKeyLength];
- }
-
- public byte [] getPublicKey() {
- return publicKey;
- }
-
- public byte [] getSecretKey() {
- return secretKey;
- }
- }
-
- /*
- * @description
- * Signs the message using the secret key and returns a signed message.
- * */
- public static KeyPair keyPair() {
- KeyPair kp = new KeyPair();
-
- crypto_sign_keypair(kp.getPublicKey(), kp.getSecretKey(), false);
- return kp;
- }
-
- public static KeyPair keyPair_fromSecretKey(byte [] secretKey) {
- KeyPair kp = new KeyPair();
- byte [] pk = kp.getPublicKey();
- byte [] sk = kp.getSecretKey();
-
- // copy sk
- for (int i = 0; i < kp.getSecretKey().length; i ++)
- sk[i] = secretKey[i];
-
- // copy pk from sk
- for (int i = 0; i < kp.getPublicKey().length; i ++)
- pk[i] = secretKey[32+i]; // hard-copy
-
- return kp;
- }
-
- public static KeyPair keyPair_fromSeed(byte [] seed) {
- KeyPair kp = new KeyPair();
- byte [] pk = kp.getPublicKey();
- byte [] sk = kp.getSecretKey();
-
- // copy sk
- for (int i = 0; i < seedLength; i ++)
- sk[i] = seed[i];
-
- // generate pk from sk
- crypto_sign_keypair(pk, sk, true);
-
- return kp;
- }
-
- /*
- * @description
- * Length of signing public key in bytes.
- * */
- public static final int publicKeyLength = 32;
-
- /*
- * @description
- * Length of signing secret key in bytes.
- * */
- public static final int secretKeyLength = 64;
-
- /*
- * @description
- * Length of seed for nacl.sign.keyPair.fromSeed in bytes.
- * */
- public static final int seedLength = 32;
-
- /*
- * @description
- * Length of signature in bytes.
- * */
- public static final int signatureLength = 64;
- }
-
-
- ////////////////////////////////////////////////////////////////////////////////////
- /*
- * @description
- * Codes below are ported from TweetNacl.c/TweetNacl.h
- * */
-
- private static final byte [] _0 = new byte[16];
- private static final byte [] _9 = new byte[32];
- static {
- for (int i = 0; i < _0.length; i ++) _0[i] = 0;
-
- for (int i = 0; i < _9.length; i ++) _9[i] = 0; _9[0] = 9;
- }
-
- private static final long [] gf0 = new long[16];
- private static final long [] gf1 = new long[16];
- private static final long [] _121665 = new long[16];
- static {
- for (int i = 0; i < gf0.length; i ++) gf0[i] = 0;
-
- for (int i = 0; i < gf1.length; i ++) gf1[i] = 0; gf1[0] = 1;
-
- for (int i = 0; i < _121665.length; i ++) _121665[i] = 0; _121665[0] = 0xDB41; _121665[1] = 1;
- }
-
- private static final long [] D = new long [] {
- 0x78a3, 0x1359, 0x4dca, 0x75eb,
- 0xd8ab, 0x4141, 0x0a4d, 0x0070,
- 0xe898, 0x7779, 0x4079, 0x8cc7,
- 0xfe73, 0x2b6f, 0x6cee, 0x5203
- };
- private static final long [] D2 = new long [] {
- 0xf159, 0x26b2, 0x9b94, 0xebd6,
- 0xb156, 0x8283, 0x149a, 0x00e0,
- 0xd130, 0xeef3, 0x80f2, 0x198e,
- 0xfce7, 0x56df, 0xd9dc, 0x2406
- };
- private static final long [] X = new long [] {
- 0xd51a, 0x8f25, 0x2d60, 0xc956,
- 0xa7b2, 0x9525, 0xc760, 0x692c,
- 0xdc5c, 0xfdd6, 0xe231, 0xc0a4,
- 0x53fe, 0xcd6e, 0x36d3, 0x2169
- };
- private static final long [] Y = new long [] {
- 0x6658, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666
- };
- private static final long [] I = new long [] {
- 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee,
- 0xe478, 0xad2f, 0x1806, 0x2f43,
- 0xd7a7, 0x3dfb, 0x0099, 0x2b4d,
- 0xdf0b, 0x4fc1, 0x2480, 0x2b83
- };
-
- private static int L32(int x, int c)
- {
- return (x << c) | ((x&0xffffffff) >>> (32 - c));
- }
-
- private static int ld32(byte [] x, final int xoff, final int xlen)
- {
- int u = (x[3+xoff]&0xff);
- u = (u<<8)|(x[2+xoff]&0xff);
- u = (u<<8)|(x[1+xoff]&0xff);
- return (u<<8)|(x[0+xoff]&0xff);
- }
-
- private static long dl64(byte [] x, final int xoff, final int xlen) {
- int i;
- long u=0;
- for (i = 0; i < 8; i ++) u=(u<<8)|(x[i+xoff]&0xff);
- return u;
- }
-
- private static void st32(byte [] x, final int xoff, final int xlen, int u)
- {
- int i;
- for (i = 0; i < 4; i ++) { x[i+xoff] = (byte)(u&0xff); u >>>= 8; }
- }
-
- private static void ts64(byte [] x, final int xoff, final int xlen, long u)
- {
- int i;
- for (i = 7;i >= 0;--i) { x[i+xoff] = (byte)(u&0xff); u >>>= 8; }
- }
-
- private static int vn(
- byte [] x, final int xoff, final int xlen,
- byte [] y, final int yoff, final int ylen,
- int n)
- {
- int i,d = 0;
- for (i = 0; i < n; i ++) d |= (x[i+xoff]^y[i+yoff]) & 0xff;
- return (1 & ((d - 1) >>> 8)) - 1;
- }
-
- private static int crypto_verify_16(
- byte [] x, final int xoff, final int xlen,
- byte [] y, final int yoff, final int ylen)
- {
- return vn(x,xoff,xlen,y,yoff,ylen,16);
- }
- public static int crypto_verify_16(byte [] x, byte [] y)
- {
- return crypto_verify_16(x, 0, x.length, y, 0, y.length);
- }
-
- private static int crypto_verify_32(
- byte [] x, final int xoff, final int xlen,
- byte [] y, final int yoff, final int ylen)
- {
- return vn(x,xoff,xlen,y,yoff,ylen,32);
- }
- public static int crypto_verify_32(byte [] x, byte [] y)
- {
- return crypto_verify_32(x, 0, x.length, y, 0, y.length);
- }
-
- private static void core(byte [] out, byte [] in, byte [] k, byte [] c, int h)
- {
- int [] w = new int[16], x = new int[16], y = new int[16], t = new int[4];
- int i,j,m;
-
- for (i = 0; i < 4; i ++) {
- x[5*i] = ld32(c, 4*i, 4);
- x[1+i] = ld32(k, 4*i, 4);
- x[6+i] = ld32(in, 4*i, 4);
- x[11+i] = ld32(k, 16+4*i, 4);
- }
-
- for (i = 0; i < 16; i ++) y[i] = x[i];
-
- for (i = 0; i < 20; i ++) {
- for (j = 0; j < 4; j ++) {
- for (m = 0; m < 4; m ++) t[m] = x[(5*j+4*m)%16];
- t[1] ^= L32(t[0]+t[3], 7);
- t[2] ^= L32(t[1]+t[0], 9);
- t[3] ^= L32(t[2]+t[1],13);
- t[0] ^= L32(t[3]+t[2],18);
- for (m = 0; m < 4; m ++) w[4*j+(j+m)%4] = t[m];
- }
- for (m = 0; m < 16; m ++) x[m] = w[m];
- }
-
- if (h != 0) {
- for (i = 0; i < 16; i ++) x[i] += y[i];
- for (i = 0; i < 4; i ++) {
- x[5*i] -= ld32(c, 4*i, 4);
- x[6+i] -= ld32(in, 4*i, 4);
- }
- for (i = 0; i < 4; i ++) {
- st32(out, 4*i, 4, x[5*i]);
- st32(out, 16+4*i, 4, x[6+i]);
- }
- } else
- for (i = 0; i < 16; i ++) st32(out, 4*i, 4, x[i] + y[i]);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg];
- ///L/og.d(TAG, "core -> "+dbgt);
- }
-
- public static int crypto_core_salsa20(byte [] out, byte [] in, byte [] k, byte [] c)
- {
- core(out,in,k,c,0);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg];
- ///L/og.d(TAG, "crypto_core_salsa20 -> "+dbgt);
-
- return 0;
- }
-
- public static int crypto_core_hsalsa20(byte [] out, byte [] in, byte [] k, byte [] c)
- {
- core(out,in,k,c,1);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg];
- ///L/og.d(TAG, "crypto_core_hsalsa20 -> "+dbgt);
-
- return 0;
- }
-
- private static final byte[] sigma = { 101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107 };
- /*static {
- try {
- sigma = "expand 32-byte k".getBytes("utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }*/
-
- private static int crypto_stream_salsa20_xor(byte [] c, byte [] m, long b, byte [] n,final int noff,final int nlen, byte [] k)
- {
- byte[] z = new byte[16], x = new byte[64];
- int u,i;
- if (0==b) return 0;
-
- for (i = 0; i < 16; i ++) z[i] = 0;
- for (i = 0; i < 8; i ++) z[i] = n[i+noff];
-
- int coffset = 0;
- int moffset = 0;
- while (b >= 64) {
- crypto_core_salsa20(x,z,k,sigma);
- for (i = 0; i < 64; i ++) c[i+coffset] = (byte) (((m!=null?m[i+moffset]:0) ^ x[i]) & 0xff);
- u = 1;
- for (i = 8;i < 16;++i) {
- u += (int) (z[i]&0xff);
- z[i] = (byte) (u&0xff);
- u >>>= 8;
- }
- b -= 64;
- coffset += 64;
- if (m!=null) moffset += 64;
- }
- if (b!=0) {
- crypto_core_salsa20(x,z,k,sigma);
- for (i = 0; i < b; i ++) c[i+coffset] = (byte) (((m!=null?m[i+moffset]:0) ^ x[i]) & 0xff);
- }
- return 0;
- }
- public static int crypto_stream_salsa20_xor(byte [] c, byte [] m, long b, byte [] n, byte [] k) {
- return crypto_stream_salsa20_xor(c, m, b, n,0,n.length, k);
- }
-
- private static int crypto_stream_salsa20(byte [] c, long d, byte [] n,final int noff,final int nlen, byte [] k)
- {
- return crypto_stream_salsa20_xor(c,null,d, n,noff,nlen, k);
- }
- public static int crypto_stream_salsa20(byte [] c, long d, byte [] n, byte [] k) {
- return crypto_stream_salsa20(c, d, n,0,n.length, k);
- }
-
- public static int crypto_stream(byte [] c, long d, byte [] n, byte [] k)
- {
- byte[] s = new byte[32];
- crypto_core_hsalsa20(s,n,k,sigma);
- return crypto_stream_salsa20(c,d, n,16,n.length-16, s);
- }
-
- public static int crypto_stream_xor(byte []c,byte []m,long d,byte []n,byte []k)
- {
- byte[] s = new byte[32];
- crypto_core_hsalsa20(s,n,k,sigma);
- return crypto_stream_salsa20_xor(c,m,d, n,16,n.length-16, s);
- }
-
-/* !!! Use TweetNaclFast.java onetimeauth function
- private static void add1305(int [] h,int [] c)
- {
- int j;
- int u = 0;
- for (j = 0; j < 17; j ++) {
- u = (u + ((h[j] + c[j]) | 0)) | 0;
- h[j] = u & 255;
- u >>>= 8;
- }
- }
-
- private final static int minusp[] = { 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252 };
-
- private static int crypto_onetimeauth(
- byte[] out,final int outoff,final int outlen,
- byte[] m,final int moff,final int mlen,
- long n,
- byte [] k)
- {
- int i,j;
- int s,u;
- int [] x = new int[17], r = new int [17],
- h = new int[17], c = new int [17], g = new int[17];
-
- for (j = 0; j < 17; j ++) r[j] = h[j] = 0;
-
- for (j = 0; j < 16; j ++) r[j] = k[j] & 0xff;
-
- r[3]&=15;
- r[4]&=252;
- r[7]&=15;
- r[8]&=252;
- r[11]&=15;
- r[12]&=252;
- r[15]&=15;
-
- int moffset = moff;
- while (n > 0) {
- for (j = 0; j < 17; j ++) c[j] = 0;
- for (j = 0;(j < 16) && (j < n);++j) c[j] = m[j+moffset] & 0xff;
- c[j] = 1;
-
- moffset += j;
-
- n -= j;
- add1305(h,c);
- for (i = 0; i < 17; i ++) {
- x[i] = 0;
- for (j = 0; j < 17; j ++) x[i] += h[j] * ((j <= i) ? r[i - j] : 320 * r[i + 17 - j]);
- for (j = 0; j < 17; j++) x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j])|0))) | 0) | 0;
- }
- for (i = 0; i < 17; i ++) h[i] = x[i];
- u = 0;
- for (j = 0; j < 16; j ++) {
- u = (u + h[j]) | 0;
- h[j] = u & 255;
- u >>>= 8;
- }
- u = (u + h[16]) | 0; h[16] = u & 3;
- u = (5 * (u >>> 2)) | 0;
- for (j = 0; j < 16; j ++) {
- u = (u + h[j]) | 0;
- h[j] = u & 255;
- u >>>= 8;
- }
- u = (u + h[16]) | 0; h[16] = u;
- }
-
- for (j = 0; j < 17; j ++) g[j] = h[j];
- add1305(h,minusp);
- s = (-(h[16] >>> 7) | 0);
- for (j = 0; j < 17; j ++) h[j] ^= s & (g[j] ^ h[j]);
-
- for (j = 0; j < 16; j ++) c[j] = k[j + 16] & 0xff;
- c[16] = 0;
- add1305(h,c);
- for (j = 0; j < 16; j ++) out[j+outoff] = (byte) (h[j]&0xff);
-
- return 0;
- }*/
-
- /*
- * Port of Andrew Moon's Poly1305-donna-16. Public domain.
- * https://github.com/floodyberry/poly1305-donna
- */
- public static class poly1305 {
-
- private byte[] buffer;
- private int[] r;
- private int[] h;
- private int[] pad;
- private int leftover;
- private int fin;
-
- public poly1305(byte [] key) {
- this.buffer = new byte[16];
- this.r = new int[10];
- this.h = new int[10];
- this.pad = new int[8];
- this.leftover = 0;
- this.fin = 0;
-
- int t0, t1, t2, t3, t4, t5, t6, t7;
-
- t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
- t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
- t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
- t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
- t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
- this.r[5] = ((t4 >>> 1)) & 0x1ffe;
- t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
- t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
- t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
- this.r[9] = ((t7 >>> 5)) & 0x007f;
-
- this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
- this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
- this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
- this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
- this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
- this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
- this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
- this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
- }
-
- public poly1305 blocks(byte [] m, int mpos, int bytes) {
- int hibit = this.fin!=0 ? 0 : (1 << 11);
- int t0, t1, t2, t3, t4, t5, t6, t7, c;
- int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
-
- int h0 = this.h[0],
- h1 = this.h[1],
- h2 = this.h[2],
- h3 = this.h[3],
- h4 = this.h[4],
- h5 = this.h[5],
- h6 = this.h[6],
- h7 = this.h[7],
- h8 = this.h[8],
- h9 = this.h[9];
-
- int r0 = this.r[0],
- r1 = this.r[1],
- r2 = this.r[2],
- r3 = this.r[3],
- r4 = this.r[4],
- r5 = this.r[5],
- r6 = this.r[6],
- r7 = this.r[7],
- r8 = this.r[8],
- r9 = this.r[9];
-
- while (bytes >= 16) {
- t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
- t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
- t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
- t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
- t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
- h5 += ((t4 >>> 1)) & 0x1fff;
- t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
- t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
- t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
- h9 += ((t7 >>> 5)) | hibit;
-
- c = 0;
-
- d0 = c;
- d0 += h0 * r0;
- d0 += h1 * (5 * r9);
- d0 += h2 * (5 * r8);
- d0 += h3 * (5 * r7);
- d0 += h4 * (5 * r6);
- c = (d0 >>> 13); d0 &= 0x1fff;
- d0 += h5 * (5 * r5);
- d0 += h6 * (5 * r4);
- d0 += h7 * (5 * r3);
- d0 += h8 * (5 * r2);
- d0 += h9 * (5 * r1);
- c += (d0 >>> 13); d0 &= 0x1fff;
-
- d1 = c;
- d1 += h0 * r1;
- d1 += h1 * r0;
- d1 += h2 * (5 * r9);
- d1 += h3 * (5 * r8);
- d1 += h4 * (5 * r7);
- c = (d1 >>> 13); d1 &= 0x1fff;
- d1 += h5 * (5 * r6);
- d1 += h6 * (5 * r5);
- d1 += h7 * (5 * r4);
- d1 += h8 * (5 * r3);
- d1 += h9 * (5 * r2);
- c += (d1 >>> 13); d1 &= 0x1fff;
-
- d2 = c;
- d2 += h0 * r2;
- d2 += h1 * r1;
- d2 += h2 * r0;
- d2 += h3 * (5 * r9);
- d2 += h4 * (5 * r8);
- c = (d2 >>> 13); d2 &= 0x1fff;
- d2 += h5 * (5 * r7);
- d2 += h6 * (5 * r6);
- d2 += h7 * (5 * r5);
- d2 += h8 * (5 * r4);
- d2 += h9 * (5 * r3);
- c += (d2 >>> 13); d2 &= 0x1fff;
-
- d3 = c;
- d3 += h0 * r3;
- d3 += h1 * r2;
- d3 += h2 * r1;
- d3 += h3 * r0;
- d3 += h4 * (5 * r9);
- c = (d3 >>> 13); d3 &= 0x1fff;
- d3 += h5 * (5 * r8);
- d3 += h6 * (5 * r7);
- d3 += h7 * (5 * r6);
- d3 += h8 * (5 * r5);
- d3 += h9 * (5 * r4);
- c += (d3 >>> 13); d3 &= 0x1fff;
-
- d4 = c;
- d4 += h0 * r4;
- d4 += h1 * r3;
- d4 += h2 * r2;
- d4 += h3 * r1;
- d4 += h4 * r0;
- c = (d4 >>> 13); d4 &= 0x1fff;
- d4 += h5 * (5 * r9);
- d4 += h6 * (5 * r8);
- d4 += h7 * (5 * r7);
- d4 += h8 * (5 * r6);
- d4 += h9 * (5 * r5);
- c += (d4 >>> 13); d4 &= 0x1fff;
-
- d5 = c;
- d5 += h0 * r5;
- d5 += h1 * r4;
- d5 += h2 * r3;
- d5 += h3 * r2;
- d5 += h4 * r1;
- c = (d5 >>> 13); d5 &= 0x1fff;
- d5 += h5 * r0;
- d5 += h6 * (5 * r9);
- d5 += h7 * (5 * r8);
- d5 += h8 * (5 * r7);
- d5 += h9 * (5 * r6);
- c += (d5 >>> 13); d5 &= 0x1fff;
-
- d6 = c;
- d6 += h0 * r6;
- d6 += h1 * r5;
- d6 += h2 * r4;
- d6 += h3 * r3;
- d6 += h4 * r2;
- c = (d6 >>> 13); d6 &= 0x1fff;
- d6 += h5 * r1;
- d6 += h6 * r0;
- d6 += h7 * (5 * r9);
- d6 += h8 * (5 * r8);
- d6 += h9 * (5 * r7);
- c += (d6 >>> 13); d6 &= 0x1fff;
-
- d7 = c;
- d7 += h0 * r7;
- d7 += h1 * r6;
- d7 += h2 * r5;
- d7 += h3 * r4;
- d7 += h4 * r3;
- c = (d7 >>> 13); d7 &= 0x1fff;
- d7 += h5 * r2;
- d7 += h6 * r1;
- d7 += h7 * r0;
- d7 += h8 * (5 * r9);
- d7 += h9 * (5 * r8);
- c += (d7 >>> 13); d7 &= 0x1fff;
-
- d8 = c;
- d8 += h0 * r8;
- d8 += h1 * r7;
- d8 += h2 * r6;
- d8 += h3 * r5;
- d8 += h4 * r4;
- c = (d8 >>> 13); d8 &= 0x1fff;
- d8 += h5 * r3;
- d8 += h6 * r2;
- d8 += h7 * r1;
- d8 += h8 * r0;
- d8 += h9 * (5 * r9);
- c += (d8 >>> 13); d8 &= 0x1fff;
-
- d9 = c;
- d9 += h0 * r9;
- d9 += h1 * r8;
- d9 += h2 * r7;
- d9 += h3 * r6;
- d9 += h4 * r5;
- c = (d9 >>> 13); d9 &= 0x1fff;
- d9 += h5 * r4;
- d9 += h6 * r3;
- d9 += h7 * r2;
- d9 += h8 * r1;
- d9 += h9 * r0;
- c += (d9 >>> 13); d9 &= 0x1fff;
-
- c = (((c << 2) + c)) | 0;
- c = (c + d0) | 0;
- d0 = c & 0x1fff;
- c = (c >>> 13);
- d1 += c;
-
- h0 = d0;
- h1 = d1;
- h2 = d2;
- h3 = d3;
- h4 = d4;
- h5 = d5;
- h6 = d6;
- h7 = d7;
- h8 = d8;
- h9 = d9;
-
- mpos += 16;
- bytes -= 16;
- }
- this.h[0] = h0;
- this.h[1] = h1;
- this.h[2] = h2;
- this.h[3] = h3;
- this.h[4] = h4;
- this.h[5] = h5;
- this.h[6] = h6;
- this.h[7] = h7;
- this.h[8] = h8;
- this.h[9] = h9;
-
- return this;
- }
-
- public poly1305 finish(byte [] mac, int macpos) {
- int [] g = new int[10];
- int c, mask, f, i;
-
- if (this.leftover != 0) {
- i = this.leftover;
- this.buffer[i++] = 1;
- for (; i < 16; i++) this.buffer[i] = 0;
- this.fin = 1;
- this.blocks(this.buffer, 0, 16);
- }
-
- c = this.h[1] >>> 13;
- this.h[1] &= 0x1fff;
- for (i = 2; i < 10; i++) {
- this.h[i] += c;
- c = this.h[i] >>> 13;
- this.h[i] &= 0x1fff;
- }
- this.h[0] += (c * 5);
- c = this.h[0] >>> 13;
- this.h[0] &= 0x1fff;
- this.h[1] += c;
- c = this.h[1] >>> 13;
- this.h[1] &= 0x1fff;
- this.h[2] += c;
-
- g[0] = this.h[0] + 5;
- c = g[0] >>> 13;
- g[0] &= 0x1fff;
- for (i = 1; i < 10; i++) {
- g[i] = this.h[i] + c;
- c = g[i] >>> 13;
- g[i] &= 0x1fff;
- }
- g[9] -= (1 << 13); g[9] &= 0xffff;
-
- mask = (g[9] >>> ((2 * 8) - 1)) - 1; mask &= 0xffff;
- for (i = 0; i < 10; i++) g[i] &= mask;
- mask = ~mask;
- for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
-
- this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
- this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
- this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
- this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
- this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
- this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
- this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
- this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
-
- f = this.h[0] + this.pad[0];
- this.h[0] = f & 0xffff;
- for (i = 1; i < 8; i++) {
- f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
- this.h[i] = f & 0xffff;
- }
-
- mac[macpos+ 0] = (byte) ((this.h[0] >>> 0) & 0xff);
- mac[macpos+ 1] = (byte) ((this.h[0] >>> 8) & 0xff);
- mac[macpos+ 2] = (byte) ((this.h[1] >>> 0) & 0xff);
- mac[macpos+ 3] = (byte) ((this.h[1] >>> 8) & 0xff);
- mac[macpos+ 4] = (byte) ((this.h[2] >>> 0) & 0xff);
- mac[macpos+ 5] = (byte) ((this.h[2] >>> 8) & 0xff);
- mac[macpos+ 6] = (byte) ((this.h[3] >>> 0) & 0xff);
- mac[macpos+ 7] = (byte) ((this.h[3] >>> 8) & 0xff);
- mac[macpos+ 8] = (byte) ((this.h[4] >>> 0) & 0xff);
- mac[macpos+ 9] = (byte) ((this.h[4] >>> 8) & 0xff);
- mac[macpos+10] = (byte) ((this.h[5] >>> 0) & 0xff);
- mac[macpos+11] = (byte) ((this.h[5] >>> 8) & 0xff);
- mac[macpos+12] = (byte) ((this.h[6] >>> 0) & 0xff);
- mac[macpos+13] = (byte) ((this.h[6] >>> 8) & 0xff);
- mac[macpos+14] = (byte) ((this.h[7] >>> 0) & 0xff);
- mac[macpos+15] = (byte) ((this.h[7] >>> 8) & 0xff);
-
- return this;
- }
-
- public poly1305 update(byte [] m, int mpos, int bytes) {
- int i, want;
-
- if (this.leftover != 0) {
- want = (16 - this.leftover);
- if (want > bytes)
- want = bytes;
- for (i = 0; i < want; i++)
- this.buffer[this.leftover + i] = m[mpos+i];
- bytes -= want;
- mpos += want;
- this.leftover += want;
- if (this.leftover < 16)
- return this;
- this.blocks(buffer, 0, 16);
- this.leftover = 0;
- }
-
- if (bytes >= 16) {
- want = bytes - (bytes % 16);
- this.blocks(m, mpos, want);
- mpos += want;
- bytes -= want;
- }
-
- if (bytes != 0) {
- for (i = 0; i < bytes; i++)
- this.buffer[this.leftover + i] = m[mpos+i];
- this.leftover += bytes;
- }
-
- return this;
- }
-
- }
-
- private static int crypto_onetimeauth(
- byte[] out,final int outpos,final int outlen,
- byte[] m,final int mpos,final int mlen,
- int n,
- byte [] k)
- {
- poly1305 s = new poly1305(k);
- s.update(m, mpos, n);
- s.finish(out, outpos);
-
- /*String dbgt = "";
- for (int dbg = 0; dbg < out.length-outpos; dbg ++) dbgt += " "+out[dbg+outpos];
- Log.d(TAG, "crypto_onetimeauth -> "+dbgt);
- */
-
- return 0;
- }
-
- public static int crypto_onetimeauth(byte [] out, byte [] m, int n , byte [] k) {
- return crypto_onetimeauth(out,0,out.length, m,0,m.length, n, k);
- }
-
- private static int crypto_onetimeauth_verify(
- byte[] h,final int hoff,final int hlen,
- byte[] m,final int moff,final int mlen,
- int n,
- byte [] k)
- {
- byte[] x = new byte[16];
- crypto_onetimeauth(x,0,x.length, m,moff,mlen, n,k);
- return crypto_verify_16(h,hoff,hlen, x,0,x.length);
- }
- public static int crypto_onetimeauth_verify(byte [] h, byte [] m, int n, byte [] k) {
- return crypto_onetimeauth_verify(h,0,h.length, m,0,m.length, n, k);
- }
- public static int crypto_onetimeauth_verify(byte [] h, byte [] m, byte [] k) {
- return crypto_onetimeauth_verify(h, m, m!=null? m.length:0, k);
- }
-
- public static int crypto_secretbox(byte [] c, byte [] m, int d, byte [] n, byte [] k)
- {
- int i;
-
- if (d < 32) return -1;
-
- crypto_stream_xor(c,m,d,n,k);
- crypto_onetimeauth(c,16,c.length-16, c,32,c.length-32, d - 32, c);
-
- ///for (i = 0; i < 16; i ++) c[i] = 0;
-
- return 0;
- }
-
- public static int crypto_secretbox_open(byte []m,byte []c,int d,byte []n,byte []k)
- {
- int i;
- byte[] x = new byte[32];
-
- if (d < 32) return -1;
-
- crypto_stream(x,32,n,k);
- if (crypto_onetimeauth_verify(c,16,16, c,32,c.length-32, d-32, x) != 0) return -1;
- crypto_stream_xor(m,c,d,n,k);
-
- ///for (i = 0; i < 32; i ++) m[i] = 0;
-
- return 0;
- }
-
- private static void set25519(long [] r, long [] a)
- {
- int i;
- for (i = 0; i < 16; i ++) r[i]=a[i];
- }
-
- private static void car25519(long [] o,final int ooff,final int olen)
- {
- int i;
- long c;
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o.get(dbg);
- ///L/og.d(TAG, "car25519 pre -> "+dbgt);
-
- for (i = 0; i < 16; i ++) {
- o[i+ooff] += (1L<<16);
-
- c = o[i+ooff]>>16;
-
- o[(i+1)*((i<15) ? 1 : 0)+ooff] += c-1+37*(c-1)*((i==15) ? 1 : 0);
-
- o[i+ooff] -= (c<<16);
- }
-
- ///dbgt = "";
- ///for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o.get(dbg);
- ///L/og.d(TAG, "car25519 -> "+dbgt);
-
- }
-
- private static void sel25519(
- long[] p,final int poff,final int plen,
- long[] q,final int qoff,final int qlen,
- int b)
- {
- int i;
- long t,c=~(b-1);
-
- for (i = 0; i < 16; i ++) {
- t = c & (p[i+poff] ^ q[i+qoff]);
- p[i+poff] ^= t;
- q[i+qoff] ^= t;
- }
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < p.length; dbg ++) dbgt += " "+p.get(dbg);
- ///L/og.d(TAG, "sel25519 -> "+dbgt);
-
- }
-
- private static void pack25519(byte [] o, long [] n,final int noff,final int nlen)
- {
- int i,j,b;
- long [] m = new long[16], t = new long[16];
-
- for (i = 0; i < 16; i ++) t[i] = n[i+noff];
-
- car25519(t,0,t.length);
- car25519(t,0,t.length);
- car25519(t,0,t.length);
-
- for (j = 0; j < 2; j ++) {
- m[0]=t[0]-0xffed;
-
- for(i=1;i<15;i++) {
- m[i]=t[i]-0xffff-((m[i-1] >> 16)&1);
- m[i-1]&=0xffff;
- }
-
- m[15]=t[15]-0x7fff-((m[14] >> 16)&1);
- b=(int) ((m[15] >> 16)&1);
- m[14]&=0xffff;
-
- sel25519(t,0,t.length, m,0,m.length, 1-b);
- }
-
- for (i = 0; i < 16; i ++) {
- o[2*i]=(byte) (t[i]&0xff);
- o[2*i+1]=(byte) (t[i] >> 8);
- }
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o[dbg];
- ///L/og.d(TAG, "pack25519 -> "+dbgt);
- }
-
- private static int neq25519(long [] a, long [] b)
- {
- byte[] c = new byte[32], d = new byte[32];
-
- pack25519(c, a,0,a.length);
- pack25519(d, b,0,b.length);
-
- return crypto_verify_32(c,0,c.length, d,0,d.length);
- }
-
- private static byte par25519(long [] a)
- {
- byte[] d = new byte[32];
-
- pack25519(d, a,0,a.length);
-
- return (byte) (d[0]&1);
- }
-
- private static void unpack25519(long [] o, byte [] n)
- {
- int i;
-
- for (i = 0; i < 16; i ++) o[i]=(n[2*i]&0xff)+((long)((n[2*i+1]<<8)&0xffff));
-
- o[15]&=0x7fff;
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o[dbg];
- ///L/og.d(TAG, "unpack25519 -> "+dbgt);
- }
-
- private static void A(
- long [] o,final int ooff,final int olen,
- long [] a,final int aoff,final int alen,
- long [] b,final int boff,final int blen)
- {
- int i;
- for (i = 0; i < 16; i ++) o[i+ooff] = a[i+aoff] + b[i+boff];
- }
-
- private static void Z(
- long [] o,final int ooff,final int olen,
- long [] a,final int aoff,final int alen,
- long [] b,final int boff,final int blen)
- {
- int i;
- for (i = 0; i < 16; i ++) o[i+ooff] = a[i+aoff] - b[i+boff];
- }
-
- private static void M(
- long [] o,final int ooff,final int olen,
- long [] a,final int aoff,final int alen,
- long [] b,final int boff,final int blen)
- {
- int i,j;
- long [] t = new long[31];
-
- for (i = 0; i < 31; i ++) t[i]=0;
-
- for (i = 0; i < 16; i ++) for (j = 0; j < 16; j ++) t[i+j]+=a[i+aoff]*b[j+boff];
-
- for (i = 0; i < 15; i ++) t[i]+=38*t[i+16];
-
- for (i = 0; i < 16; i ++) o[i+ooff]=t[i];
-
- car25519(o,ooff,olen);
- car25519(o,ooff,olen);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o.get(dbg);
- ///L/og.d(TAG, "M -> "+dbgt);
- }
-
- private static void S(
- long [] o,final int ooff,final int olen,
- long [] a,final int aoff,final int alen)
- {
- M(o,ooff,olen, a,aoff,alen, a,aoff,alen);
- }
-
- private static void inv25519(
- long [] o,final int ooff,final int olen,
- long [] i,final int ioff,final int ilen)
- {
- long [] c = new long[16];
- int a;
-
- for (a = 0; a < 16; a ++) c[a]=i[a+ioff];
-
- for(a=253;a>=0;a--) {
- S(c,0,c.length, c,0,c.length);
- if(a!=2&&a!=4) M(c,0,c.length, c,0,c.length, i,ioff,ilen);
- }
-
- for (a = 0; a < 16; a ++) o[a+ooff] = c[a];
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o.get(dbg);
- ///L/og.d(TAG, "inv25519 -> "+dbgt);
- }
-
- private static void pow2523(long [] o,long [] i)
- {
- long [] c = new long[16];
- int a;
-
- for (a = 0; a < 16; a ++) c[a]=i[a];
-
- for(a=250;a>=0;a--) {
- S(c,0,c.length, c,0,c.length);
- if(a!=1) M(c,0,c.length, c,0,c.length, i,0,i.length);
- }
-
- for (a = 0; a < 16; a ++) o[a]=c[a];
- }
-
- public static int crypto_scalarmult(byte []q,byte []n,byte []p)
- {
- byte[] z = new byte[32];
- long[] x = new long[80];
- int r,i;
-
- long [] a = new long[16], b = new long[16], c = new long[16],
- d = new long[16], e = new long[16], f = new long[16];
-
- for (i = 0; i < 31; i ++) z[i]=n[i];
-
- z[31]=(byte) (((n[31]&127)|64) & 0xff);
- z[0]&=248;
-
- unpack25519(x,p);
-
- for (i = 0; i < 16; i ++) {
- b[i]=x[i];
- d[i]=a[i]=c[i]=0;
- }
- a[0]=d[0]=1;
-
- for(i=254;i>=0;--i) {
- r=(z[i>>>3]>>>(i&7))&1;
- sel25519(a,0,a.length, b,0,b.length, r);
- sel25519(c,0,c.length, d,0,d.length, r);
- A(e,0,e.length, a,0,a.length, c,0,c.length);
- Z(a,0,a.length, a,0,a.length, c,0,c.length);
- A(c,0,c.length, b,0,b.length, d,0,d.length);
- Z(b,0,b.length, b,0,b.length, d,0,d.length);
- S(d,0,d.length, e,0,e.length);
- S(f,0,f.length, a,0,a.length);
- M(a,0,a.length, c,0,c.length, a,0,a.length);
- M(c,0,c.length, b,0,b.length, e,0,e.length);
- A(e,0,e.length, a,0,a.length, c,0,c.length);
- Z(a,0,a.length, a,0,a.length, c,0,c.length);
- S(b,0,b.length, a,0,a.length);
- Z(c,0,c.length, d,0,d.length, f,0,f.length);
- M(a,0,a.length, c,0,c.length, _121665,0,_121665.length);
- A(a,0,a.length, a,0,a.length, d,0,d.length);
- M(c,0,c.length, c,0,c.length, a,0,a.length);
- M(a,0,a.length, d,0,d.length, f,0,f.length);
- M(d,0,d.length, b,0,b.length, x,0,x.length);
- S(b,0,b.length, e,0,e.length);
- sel25519(a,0,a.length, b,0,b.length, r);
- sel25519(c,0,c.length, d,0,d.length, r);
- }
-
- for (i = 0; i < 16; i ++) {
- x[i+16]=a[i];
- x[i+32]=c[i];
- x[i+48]=b[i];
- x[i+64]=d[i];
- }
-
- inv25519(x, 32, x.length-32, x, 32, x.length-32);
-
- M(x,16,x.length-16, x,16,x.length-16, x,32,x.length-32);
-
- pack25519(q, x,16,x.length-16);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < q.length; dbg ++) dbgt += " "+q[dbg];
- ///L/og.d(TAG, "crypto_scalarmult -> "+dbgt);
-
- return 0;
- }
-
- public static int crypto_scalarmult_base(byte []q,byte []n)
- {
- return crypto_scalarmult(q,n,_9);
- }
-
- public static int crypto_box_keypair(byte [] y, byte [] x)
- {
- randombytes(x,32);
- return crypto_scalarmult_base(y,x);
- }
-
- public static int crypto_box_beforenm(byte []k,byte []y,byte []x)
- {
- byte[] s = new byte[32];
- crypto_scalarmult(s,x,y);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < s.length; dbg ++) dbgt += " "+s[dbg];
- ///L/og.d(TAG, "crypto_box_beforenm -> "+dbgt);
-
- return crypto_core_hsalsa20(k,_0,s,sigma);
- }
-
- public static int crypto_box_afternm(byte []c,byte []m,int d,byte []n,byte []k)
- {
- return crypto_secretbox(c,m,d,n,k);
- }
-
- public static int crypto_box_open_afternm(byte []m,byte []c,int d,byte []n,byte []k)
- {
- return crypto_secretbox_open(m,c,d,n,k);
- }
-
- public static int crypto_box(byte []c,byte []m,int d,byte []n,byte []y,byte []x)
- {
- byte[] k = new byte[32];
-
- ///L/og.d(TAG, "crypto_box start ...");
-
- crypto_box_beforenm(k,y,x);
- return crypto_box_afternm(c,m,d,n,k);
- }
-
- public static int crypto_box_open(byte []m,byte []c,int d,byte []n,byte []y,byte []x)
- {
- byte[] k = new byte[32];
- crypto_box_beforenm(k,y,x);
- return crypto_box_open_afternm(m,c,d,n,k);
- }
-
- private static long R(long x,int c) { return (x >>> c) | (x << (64 - c)); }
-
- private static long Ch( long x,long y,long z) { return (x & y) ^ (~x & z); }
- private static long Maj(long x,long y,long z) { return (x & y) ^ (x & z) ^ (y & z); }
-
- private static long Sigma0(long x) { return R(x,28) ^ R(x,34) ^ R(x,39); }
- private static long Sigma1(long x) { return R(x,14) ^ R(x,18) ^ R(x,41); }
- private static long sigma0(long x) { return R(x, 1) ^ R(x, 8) ^ (x >>> 7); }
- private static long sigma1(long x) { return R(x,19) ^ R(x,61) ^ (x >>> 6); }
-
- private static final long K[] = {
- 0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL,
- 0x3956c25bf348b538L, 0x59f111f1b605d019L, 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L,
- 0xd807aa98a3030242L, 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
- 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L, 0xc19bf174cf692694L,
- 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L, 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L,
- 0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
- 0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L,
- 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L, 0x06ca6351e003826fL, 0x142929670a0e6e70L,
- 0x27b70a8546d22ffcL, 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
- 0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L, 0x92722c851482353bL,
- 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L, 0xc24b8b70d0f89791L, 0xc76c51a30654be30L,
- 0xd192e819d6ef5218L, 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
- 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L,
- 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL, 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L,
- 0x748f82ee5defb2fcL, 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
- 0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL,
- 0xca273eceea26619cL, 0xd186b8c721c0c207L, 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L,
- 0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL,
- 0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL,
- 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL, 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L
- };
-
- // TBD... long length n
- ///int crypto_hashblocks(byte [] x, byte [] m, long n)
- private static int crypto_hashblocks(byte [] x, byte [] m,final int moff,final int mlen, int n)
- {
- long [] z = new long [8], b = new long [8], a = new long [8], w = new long [16];
- long t;
- int i,j;
-
- for (i = 0; i < 8; i ++) z[i] = a[i] = dl64(x, 8*i, x.length-8*i);
-
- int moffset = moff;
-
- while (n >= 128) {
- for (i = 0; i < 16; i ++) w[i] = dl64(m, 8*i+moffset, mlen-8*i);
-
- for (i = 0; i < 80; i ++) {
- for (j = 0; j < 8; j ++) b[j] = a[j];
-
- t = a[7] + Sigma1(a[4]) + Ch(a[4],a[5],a[6]) + K[i] + w[i%16];
- b[7] = t + Sigma0(a[0]) + Maj(a[0],a[1],a[2]);
- b[3] += t;
-
- for (j = 0; j < 8; j ++) a[(j+1)%8] = b[j];
-
- if (i%16 == 15)
- for (j = 0; j < 16; j ++)
- w[j] += w[(j+9)%16] + sigma0(w[(j+1)%16]) + sigma1(w[(j+14)%16]);
- }
-
- for (i = 0; i < 8; i ++) { a[i] += z[i]; z[i] = a[i]; }
-
- moffset += 128;
- n -= 128;
- }
-
- for (i = 0; i < 8; i ++) ts64(x,8*i,x.length-8*i, z[i]);
-
- return n;
- }
- public static int crypto_hashblocks(byte [] x, byte [] m, int n) {
- return crypto_hashblocks(x, m,0,m.length, n);
- }
-
- private final static byte iv[] = {
- 0x6a,0x09,(byte) 0xe6,0x67,(byte) 0xf3,(byte) 0xbc,(byte) 0xc9,0x08,
- (byte) 0xbb,0x67,(byte) 0xae,(byte) 0x85,(byte) 0x84,(byte) 0xca,(byte) 0xa7,0x3b,
- 0x3c,0x6e,(byte) 0xf3,0x72,(byte) 0xfe,(byte) 0x94,(byte) 0xf8,0x2b,
- (byte) 0xa5,0x4f,(byte) 0xf5,0x3a,0x5f,0x1d,0x36,(byte) 0xf1,
- 0x51,0x0e,0x52,0x7f,(byte) 0xad,(byte) 0xe6,(byte) 0x82,(byte) 0xd1,
- (byte) 0x9b,0x05,0x68,(byte) 0x8c,0x2b,0x3e,0x6c,0x1f,
- 0x1f,(byte) 0x83,(byte) 0xd9,(byte) 0xab,(byte) 0xfb,0x41,(byte) 0xbd,0x6b,
- 0x5b,(byte) 0xe0,(byte) 0xcd,0x19,0x13,0x7e,0x21,0x79
- } ;
-
- // TBD 64bits of n
- ///int crypto_hash(byte [] out, byte [] m, long n)
- private static int crypto_hash(byte [] out, byte [] m,final int moff,final int mlen, int n)
- {
- byte[] h = new byte[64], x = new byte [256];
- long b = n;
- int i;
-
- for (i = 0; i < 64; i ++) h[i] = iv[i];
-
- crypto_hashblocks(h, m,moff,mlen, n);
- ///m += n;
- n &= 127;
- ///m -= n;
-
- for (i = 0; i < 256; i ++) x[i] = 0;
-
- for (i = 0; i < n; i ++) x[i] = m[i+moff];
- x[n] = (byte) 128;
-
- n = 256-128*(n<112?1:0);
- x[n-9] = (byte) (b >>> 61);
- ts64(x,n-8,x.length-(n-8), b<<3);
- crypto_hashblocks(h, x,0,x.length, n);
-
- for (i = 0; i < 64; i ++) out[i] = h[i];
-
- return 0;
- }
- public static int crypto_hash(byte [] out, byte [] m, int n) {
- return crypto_hash(out, m,0,m.length, n);
- }
- public static int crypto_hash(byte [] out, byte [] m) {
- return crypto_hash(out, m, m!=null? m.length : 0);
- }
-
- // gf: long[16]
- ///private static void add(gf p[4],gf q[4])
- private static void add(long [] p[], long [] q[])
- {
- long [] a = new long[16];
- long [] b = new long[16];
- long [] c = new long[16];
- long [] d = new long[16];
- long [] t = new long[16];
- long [] e = new long[16];
- long [] f = new long[16];
- long [] g = new long[16];
- long [] h = new long[16];
-
-
- long [] p0 = p[0];
- long [] p1 = p[1];
- long [] p2 = p[2];
- long [] p3 = p[3];
-
- long [] q0 = q[0];
- long [] q1 = q[1];
- long [] q2 = q[2];
- long [] q3 = q[3];
-
- Z(a,0,a.length, p1,0,p1.length, p0,0,p0.length);
- Z(t,0,t.length, q1,0,q1.length, q0,0,q0.length);
- M(a,0,a.length, a,0,a.length, t,0,t.length);
- A(b,0,b.length, p0,0,p0.length, p1,0,p1.length);
- A(t,0,t.length, q0,0,q0.length, q1,0,q1.length);
- M(b,0,b.length, b,0,b.length, t,0,t.length);
- M(c,0,c.length, p3,0,p3.length, q3,0,q3.length);
- M(c,0,c.length, c,0,c.length, D2,0,D2.length);
- M(d,0,d.length, p2,0,p2.length, q2,0,q2.length);
-
- A(d,0,d.length, d,0,d.length, d,0,d.length);
- Z(e,0,e.length, b,0,b.length, a,0,a.length);
- Z(f,0,f.length, d,0,d.length, c,0,c.length);
- A(g,0,g.length, d,0,d.length, c,0,c.length);
- A(h,0,h.length, b,0,b.length, a,0,a.length);
-
- M(p0,0,p0.length, e,0,e.length, f,0,f.length);
- M(p1,0,p1.length, h,0,h.length, g,0,g.length);
- M(p2,0,p2.length, g,0,g.length, f,0,f.length);
- M(p3,0,p3.length, e,0,e.length, h,0,h.length);
- }
-
- private static void cswap(long [] p[], long [] q[], byte b)
- {
- int i;
-
- for (i = 0; i < 4; i ++)
- sel25519(p[i],0,p[i].length, q[i],0,q[i].length, b);
- }
-
- private static void pack(byte [] r, long [] p[])
- {
- long [] tx = new long[16];
- long [] ty = new long[16];
- long [] zi = new long[16];
-
- inv25519(zi,0,zi.length, p[2],0,p[2].length);
-
- M(tx,0,tx.length, p[0],0,p[0].length, zi,0,zi.length);
- M(ty,0,ty.length, p[1],0,p[1].length, zi,0,zi.length);
-
- pack25519(r, ty,0,ty.length);
-
- r[31] ^= par25519(tx) << 7;
- }
-
- private static void scalarmult(long [] p[], long [] q[], byte[] s,final int soff,final int slen)
- {
- int i;
-
- set25519(p[0],gf0);
- set25519(p[1],gf1);
- set25519(p[2],gf1);
- set25519(p[3],gf0);
-
- for (i = 255;i >= 0;--i) {
- byte b = (byte) ((s[i/8+soff] >> (i&7))&1);
-
- cswap(p,q,b);
- add(q,p);
- add(p,p);
- cswap(p,q,b);
- }
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < p.length; dbg ++) for (int dd = 0; dd < p[dbg].length; dd ++) dbgt += " "+p[dbg][dd];
- ///L/og.d(TAG, "scalarmult -> "+dbgt);
- }
-
- private static void scalarbase(long [] p[], byte[] s,final int soff,final int slen)
- {
- long [] [] q = new long [4] [];
-
- q[0] = new long [16];
- q[1] = new long [16];
- q[2] = new long [16];
- q[3] = new long [16];
-
- set25519(q[0],X);
- set25519(q[1],Y);
- set25519(q[2],gf1);
- M(q[3],0,q[3].length, X,0,X.length, Y,0,Y.length);
- scalarmult(p,q, s,soff,slen);
- }
-
- public static int crypto_sign_keypair(byte [] pk, byte [] sk, boolean seeded) {
- byte [] d = new byte[64];
- long [] [] p = new long [4] [];
-
- p[0] = new long [16];
- p[1] = new long [16];
- p[2] = new long [16];
- p[3] = new long [16];
-
- int i;
-
- if (!seeded) randombytes(sk, 32);
- crypto_hash(d, sk,0,sk.length, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- scalarbase(p, d,0,d.length);
- pack(pk, p);
-
- for (i = 0; i < 32; i++) sk[i+32] = pk[i];
- return 0;
- }
-
- private static final long L[] = {
- 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
- 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0x10
- };
-
- private static void modL(byte[] r,final int roff,final int rlen, long x[])
- {
- long carry;
- int i, j;
-
- for (i = 63;i >= 32;--i) {
- carry = 0;
- for (j = i - 32;j < i - 12;++j) {
- x[j] += carry - 16 * x[i] * L[j - (i - 32)];
- carry = (x[j] + 128) >> 8;
- x[j] -= carry << 8;
- }
- x[j] += carry;
- x[i] = 0;
- }
- carry = 0;
-
- for (j = 0; j < 32; j ++) {
- x[j] += carry - (x[31] >> 4) * L[j];
- carry = x[j] >> 8;
- x[j] &= 255;
- }
-
- for (j = 0; j < 32; j ++) x[j] -= carry * L[j];
-
- for (i = 0; i < 32; i ++) {
- x[i+1] += x[i] >> 8;
- r[i+roff] = (byte) (x[i] & 255);
- }
- }
-
- private static void reduce(byte [] r)
- {
- long[] x = new long [64];
- int i;
-
- for (i = 0; i < 64; i ++) x[i] = (long) (r[i]&0xff);
-
- for (i = 0; i < 64; i ++) r[i] = 0;
-
- modL(r,0,r.length, x);
- }
-
- // TBD... 64bits of n
- ///int crypto_sign(byte [] sm, long * smlen, byte [] m, long n, byte [] sk)
- public static int crypto_sign(byte [] sm, long dummy /* *smlen not used*/, byte [] m, int/*long*/ n, byte [] sk)
- {
- byte[] d = new byte[64], h = new byte[64], r = new byte[64];
-
- int i, j;
- long [] x = new long[64];
-
- long [] [] p = new long [4] [];
- p[0] = new long [16];
- p[1] = new long [16];
- p[2] = new long [16];
- p[3] = new long [16];
-
- crypto_hash(d, sk,0,sk.length, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- ///*smlen = n+64;
-
- for (i = 0; i < n; i ++) sm[64 + i] = m[i];
-
- for (i = 0; i < 32; i ++) sm[32 + i] = d[32 + i];
-
- crypto_hash(r, sm,32,sm.length-32, n+32);
- reduce(r);
- scalarbase(p, r,0,r.length);
- pack(sm,p);
-
- for (i = 0; i < 32; i ++) sm[i+32] = sk[i+32];
- crypto_hash(h, sm,0,sm.length, n + 64);
- reduce(h);
-
- for (i = 0; i < 64; i ++) x[i] = 0;
-
- for (i = 0; i < 32; i ++) x[i] = (long) (r[i]&0xff);
-
- for (i = 0; i < 32; i ++) for (j = 0; j < 32; j ++) x[i+j] += (h[i]&0xff) * (long) (d[j]&0xff);
-
- modL(sm,32,sm.length-32, x);
-
- return 0;
- }
-
- private static int unpackneg(long [] r[], byte p[])
- {
- long [] t = new long [16];
- long [] chk = new long [16];
- long [] num = new long [16];
- long [] den = new long [16];
- long [] den2 = new long [16];
- long [] den4 = new long [16];
- long [] den6 = new long [16];
-
- set25519(r[2],gf1);
- unpack25519(r[1], p);
- S(num,0,num.length, r[1],0,r[1].length);
- M(den,0,den.length, num,0,num.length, D,0,D.length);
- Z(num,0,num.length, num,0,num.length, r[2],0,r[2].length);
- A(den,0,den.length, r[2],0,r[2].length, den,0,den.length);
-
- S(den2,0,den2.length, den,0,den.length);
- S(den4,0,den4.length, den2,0,den2.length);
- M(den6,0,den6.length, den4,0,den4.length, den2,0,den2.length);
- M(t,0,t.length, den6,0,den6.length, num,0,num.length);
- M(t,0,t.length, t,0,t.length, den,0,den.length);
-
- pow2523(t, t);
- M(t,0,t.length, t,0,t.length, num,0,num.length);
- M(t,0,t.length, t,0,t.length, den,0,den.length);
- M(t,0,t.length, t,0,t.length, den,0,den.length);
- M(r[0],0,r[0].length, t,0,t.length, den,0,den.length);
-
- S(chk,0,chk.length, r[0],0,r[0].length);
- M(chk,0,chk.length, chk,0,chk.length, den,0,den.length);
- if (neq25519(chk, num)!=0) M(r[0],0,r[0].length, r[0],0,r[0].length, I,0,I.length);
-
- S(chk,0,chk.length, r[0],0,r[0].length);
- M(chk,0,chk.length, chk,0,chk.length, den,0,den.length);
- if (neq25519(chk, num)!=0) return -1;
-
- if (par25519(r[0]) == (p[31]>>7)) Z(r[0],0,r[0].length, gf0,0,gf0.length, r[0],0,r[0].length);
-
- M(r[3],0,r[3].length, r[0],0,r[0].length, r[1],0,r[1].length);
- return 0;
- }
-
- /// TBD 64bits of mlen
- ///int crypto_sign_open(byte []m,long *mlen,byte []sm,long n,byte []pk)
- public static int crypto_sign_open(byte [] m, long dummy /* *mlen not used*/, byte [] sm, int/*long*/ n, byte []pk)
- {
- int i;
- byte[] t = new byte[32], h = new byte[64];
-
- long [] [] p = new long [4] [];
- p[0] = new long [16];
- p[1] = new long [16];
- p[2] = new long [16];
- p[3] = new long [16];
-
- long [] [] q = new long [4] [];
- q[0] = new long [16];
- q[1] = new long [16];
- q[2] = new long [16];
- q[3] = new long [16];
-
- ///*mlen = -1;
-
- if (n < 64) return -1;
-
- if (unpackneg(q,pk)!=0) return -1;
-
- for (i = 0; i < n; i ++) m[i] = sm[i];
-
- for (i = 0; i < 32; i ++) m[i+32] = pk[i];
-
- crypto_hash(h, m,0,m.length, n);
-
- reduce(h);
- scalarmult(p,q, h,0,h.length);
-
- scalarbase(q, sm,32,sm.length-32);
- add(p,q);
- pack(t,p);
-
- n -= 64;
- if (crypto_verify_32(sm,0,sm.length, t,0,t.length)!=0) {
- // optimizing it
- ///for (i = 0; i < n; i ++) m[i] = 0;
- return -1;
- }
-
- // TBD optimizing ...
- ///for (i = 0; i < n; i ++) m[i] = sm[i + 64];
- ///*mlen = n;
-
- return 0;
- }
-
- /*
- * @description
- * Java SecureRandom generator
- * */
- private static final SecureRandom jrandom = new SecureRandom();
-
- public static void randombytes(byte [] x, int len) {
- int ret = len % 8;
- long rnd;
-
- for (int i = 0; i < len-ret; i += 8) {
- rnd = jrandom.nextLong();
-
- x[i+0] = (byte) (rnd >>> 0);
- x[i+1] = (byte) (rnd >>> 8);
- x[i+2] = (byte) (rnd >>> 16);
- x[i+3] = (byte) (rnd >>> 24);
- x[i+4] = (byte) (rnd >>> 32);
- x[i+5] = (byte) (rnd >>> 40);
- x[i+6] = (byte) (rnd >>> 48);
- x[i+7] = (byte) (rnd >>> 56);
- }
-
- if (ret > 0) {
- rnd = jrandom.nextLong();
- for (int i = len-ret; i < len; i ++)
- x[i] = (byte) (rnd >>> 8*i);
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/crypto/TweetNaclFast.java b/app/src/main/java/com/iwebpp/crypto/TweetNaclFast.java
deleted file mode 100755
index ba7a606..0000000
--- a/app/src/main/java/com/iwebpp/crypto/TweetNaclFast.java
+++ /dev/null
@@ -1,3414 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.crypto;
-
-import java.io.UnsupportedEncodingException;
-import java.security.SecureRandom;
-import android.util.Base64;
-import java.lang.System;
-import java.util.concurrent.atomic.AtomicLong;
-
-
-/*
- * @description
- * TweetNacl.c Java porting
- * */
-public final class TweetNaclFast {
-
- private final static String TAG = "TweetNaclFast";
-
- /*
- * @description
- * Box algorithm, Public-key authenticated encryption
- * */
- public static final class Box {
-
- private final static String TAG = "Box";
-
- private AtomicLong nonce;
-
- private byte [] theirPublicKey;
- private byte [] mySecretKey;
- private byte [] sharedKey;
-
- public Box(byte [] theirPublicKey, byte [] mySecretKey) {
- this(theirPublicKey, mySecretKey, 68);
- }
-
- public Box(byte [] theirPublicKey, byte [] mySecretKey, long nonce) {
- this.theirPublicKey = theirPublicKey;
- this.mySecretKey = mySecretKey;
-
- this.nonce = new AtomicLong(nonce);
-
- // generate pre-computed shared key
- before();
- }
-
- public void setNonce(long nonce) {
- this.nonce.set(nonce);
- }
- public long getNonce() {
- return this.nonce.get();
- }
- public long incrNonce() {
- return this.nonce.incrementAndGet();
- }
- private byte[] generateNonce() {
- // generate nonce
- long nonce = this.nonce.get();
-
- byte [] n = new byte[nonceLength];
- for (int i = 0; i < nonceLength; i += 8) {
- n[i+0] = (byte) (nonce>>> 0);
- n[i+1] = (byte) (nonce>>> 8);
- n[i+2] = (byte) (nonce>>>16);
- n[i+3] = (byte) (nonce>>>24);
- n[i+4] = (byte) (nonce>>>32);
- n[i+5] = (byte) (nonce>>>40);
- n[i+6] = (byte) (nonce>>>48);
- n[i+7] = (byte) (nonce>>>56);
- }
-
- return n;
- }
-
- /*
- * @description
- * Encrypt and authenticates message using peer's public key,
- * our secret key, and the given nonce, which must be unique
- * for each distinct message for a key pair.
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.box.overheadLength longer than the original message.
- * */
- public byte [] box(byte [] message) {
- if (message==null) return null;
- return box(message, 0, message.length);
- }
-
- public byte [] box(byte [] message, final int moff) {
- if (!(message!=null && message.length>moff)) return null;
- return box(message, moff, message.length-moff);
- }
-
- public byte [] box(byte [] message, final int moff, final int mlen) {
- if (!(message!=null && message.length>=(moff+mlen))) return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return after(message, moff, mlen);
- }
-
- /*
- * @description
- * Encrypt and authenticates message using peer's public key,
- * our secret key, and the given nonce, which must be unique
- * for each distinct message for a key pair.
- *
- * Explicitly pass the nonce
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.box.overheadLength longer than the original message.
- * */
- public byte [] box(byte [] message, byte [] theNonce) {
- if (message==null) return null;
- return box(message, 0, message.length, theNonce);
- }
-
- public byte [] box(byte [] message, final int moff, byte [] theNonce) {
- if (!(message!=null && message.length>moff)) return null;
- return box(message, moff, message.length-moff, theNonce);
- }
-
- public byte [] box(byte [] message, final int moff, final int mlen, byte [] theNonce) {
- if (!(message!=null && message.length>=(moff+mlen) &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return after(message, moff, mlen, theNonce);
- }
-
- /*
- * @description
- * Authenticates and decrypts the given box with peer's public key,
- * our secret key, and the given nonce.
- *
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box) {
- if (box==null) return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return open_after(box, 0, box.length);
- }
- public byte [] open(byte [] box, final int boxoff) {
- if (!(box!=null && box.length>boxoff)) return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return open_after(box, boxoff, box.length-boxoff);
- }
- public byte [] open(byte [] box, final int boxoff, final int boxlen) {
- if (!(box!=null && box.length>=(boxoff+boxlen))) return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return open_after(box, boxoff, boxlen);
- }
-
-
- /*
- * @description
- * Authenticates and decrypts the given box with peer's public key,
- * our secret key, and the given nonce.
- * Explicit passing of nonce
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box, byte [] theNonce) {
- if (!(box!=null &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return open_after(box, 0, box.length, theNonce);
- }
- public byte [] open(byte [] box, final int boxoff, byte [] theNonce) {
- if (!(box!=null && box.length>boxoff &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return open_after(box, boxoff, box.length-boxoff, theNonce);
- }
- public byte [] open(byte [] box, final int boxoff, final int boxlen, byte [] theNonce) {
- if (!(box!=null && box.length>=(boxoff+boxlen) &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // prepare shared key
- if (this.sharedKey == null) before();
-
- return open_after(box, boxoff, boxlen, theNonce);
- }
-
-
- /*
- * @description
- * Returns a precomputed shared key
- * which can be used in nacl.box.after and nacl.box.open.after.
- * */
- public byte [] before() {
- if (this.sharedKey == null) {
- this.sharedKey = new byte[sharedKeyLength];
- crypto_box_beforenm(this.sharedKey, this.theirPublicKey, this.mySecretKey);
- }
-
- return this.sharedKey;
- }
-
- /*
- * @description
- * Same as nacl.box, but uses a shared key precomputed with nacl.box.before.
- * */
- public byte [] after(byte [] message, final int moff, final int mlen) {
- return after(message, moff, mlen, generateNonce());
- }
-
- /*
- * @description
- * Same as nacl.box, but uses a shared key precomputed with nacl.box.before,
- * and passes a nonce explicitly.
- * */
- public byte [] after(byte [] message, final int moff, final int mlen, byte [] theNonce) {
- // check message
- if (!(message!=null && message.length>=(moff+mlen) &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // message buffer
- byte [] m = new byte[mlen + zerobytesLength];
-
- // cipher buffer
- byte [] c = new byte[m.length];
-
- for (int i = 0; i < mlen; i ++)
- m[i+zerobytesLength] = message[i+moff];
-
- if (0 != crypto_box_afternm(c, m, m.length, theNonce, sharedKey))
- return null;
-
- // wrap byte_buf_t on c offset@boxzerobytesLength
- ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength);
- byte [] ret = new byte[c.length-boxzerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = c[i+boxzerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Same as nacl.box.open,
- * but uses a shared key pre-computed with nacl.box.before.
- * */
- public byte [] open_after(byte [] box, final int boxoff, final int boxlen) {
- return open_after(box, boxoff, boxlen, generateNonce());
- }
-
- public byte [] open_after(byte [] box, final int boxoff, final int boxlen, byte [] theNonce) {
- // check message
- if (!(box!=null && box.length>=(boxoff+boxlen) && boxlen>=boxzerobytesLength))
- return null;
-
- // cipher buffer
- byte [] c = new byte[boxlen + boxzerobytesLength];
-
- // message buffer
- byte [] m = new byte[c.length];
-
- for (int i = 0; i < boxlen; i++)
- c[i+boxzerobytesLength] = box[i+boxoff];
-
- if (crypto_box_open_afternm(m, c, c.length, theNonce, sharedKey) != 0)
- return null;
-
- // wrap byte_buf_t on m offset@zerobytesLength
- ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength);
- byte [] ret = new byte[m.length-zerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = m[i+zerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Length of public key in bytes.
- * */
- public static final int publicKeyLength = 32;
-
- /*
- * @description
- * Length of secret key in bytes.
- * */
- public static final int secretKeyLength = 32;
-
- /*
- * @description
- * Length of precomputed shared key in bytes.
- * */
- public static final int sharedKeyLength = 32;
-
- /*
- * @description
- * Length of nonce in bytes.
- * */
- public static final int nonceLength = 24;
-
- /*
- * @description
- * zero bytes in case box
- * */
- public static final int zerobytesLength = 32;
- /*
- * @description
- * zero bytes in case open box
- * */
- public static final int boxzerobytesLength = 16;
-
- /*
- * @description
- * Length of overhead added to box compared to original message.
- * */
- public static final int overheadLength = 16;
-
- public static class KeyPair {
- private byte [] publicKey;
- private byte [] secretKey;
-
- public KeyPair() {
- publicKey = new byte[publicKeyLength];
- secretKey = new byte[secretKeyLength];
- }
-
- public byte [] getPublicKey() {
- return publicKey;
- }
-
- public byte [] getSecretKey() {
- return secretKey;
- }
- }
-
- /*
- * @description
- * Generates a new random key pair for box and
- * returns it as an object with publicKey and secretKey members:
- * */
- public static KeyPair keyPair() {
- KeyPair kp = new KeyPair();
-
- crypto_box_keypair(kp.getPublicKey(), kp.getSecretKey());
- return kp;
- }
-
- public static KeyPair keyPair_fromSecretKey(byte [] secretKey) {
- KeyPair kp = new KeyPair();
- byte [] sk = kp.getSecretKey();
- byte [] pk = kp.getPublicKey();
-
- // copy sk
- for (int i = 0; i < sk.length; i ++)
- sk[i] = secretKey[i];
-
- crypto_scalarmult_base(pk, sk);
- return kp;
- }
-
- }
-
- /*
- * @description
- * Secret Box algorithm, secret key
- * */
- public static class SecretBox {
-
- private final static String TAG = "SecretBox";
-
- private AtomicLong nonce;
-
- private byte [] key;
-
- public SecretBox(byte [] key) {
- this(key, 68);
- }
-
- public SecretBox(byte [] key, long nonce) {
- this.key = key;
-
- this.nonce = new AtomicLong(nonce);
- }
-
- public void setNonce(long nonce) {
- this.nonce.set(nonce);
- }
- public long getNonce() {
- return this.nonce.get();
- }
- public long incrNonce() {
- return this.nonce.incrementAndGet();
- }
- private byte[] generateNonce() {
- // generate nonce
- long nonce = this.nonce.get();
-
- byte [] n = new byte[nonceLength];
- for (int i = 0; i < nonceLength; i += 8) {
- n[i+0] = (byte) (nonce>>> 0);
- n[i+1] = (byte) (nonce>>> 8);
- n[i+2] = (byte) (nonce>>>16);
- n[i+3] = (byte) (nonce>>>24);
- n[i+4] = (byte) (nonce>>>32);
- n[i+5] = (byte) (nonce>>>40);
- n[i+6] = (byte) (nonce>>>48);
- n[i+7] = (byte) (nonce>>>56);
- }
-
- return n;
- }
-
- /*
- * @description
- * Encrypt and authenticates message using the key and the nonce.
- * The nonce must be unique for each distinct message for this key.
- *
- * Returns an encrypted and authenticated message,
- * which is nacl.secretbox.overheadLength longer than the original message.
- * */
- public byte [] box(byte [] message) {
- if (message==null) return null;
- return box(message, 0, message.length);
- }
-
- public byte [] box(byte [] message, final int moff) {
- if (!(message!=null && message.length>moff)) return null;
- return box(message, moff, message.length-moff);
- }
-
- public byte [] box(byte [] message, final int moff, final int mlen) {
- // check message
- if (!(message!=null && message.length>=(moff+mlen)))
- return null;
- return box(message, moff, message.length-moff, generateNonce());
- }
-
- public byte [] box(byte [] message, byte [] theNonce) {
- if (message==null) return null;
- return box(message, 0, message.length, theNonce);
- }
-
- public byte [] box(byte [] message, final int moff, byte [] theNonce) {
- if (!(message!=null && message.length>moff)) return null;
- return box(message, moff, message.length-moff, theNonce);
- }
-
- public byte [] box(byte [] message, final int moff, final int mlen, byte [] theNonce) {
- // check message
- if (!(message!=null && message.length>=(moff+mlen) &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // message buffer
- byte [] m = new byte[mlen + zerobytesLength];
-
- // cipher buffer
- byte [] c = new byte[m.length];
-
- for (int i = 0; i < mlen; i ++)
- m[i+zerobytesLength] = message[i+moff];
-
- if (0 != crypto_secretbox(c, m, m.length, theNonce, key))
- return null;
-
- // TBD optimizing ...
- // wrap byte_buf_t on c offset@boxzerobytesLength
- ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength);
- byte [] ret = new byte[c.length-boxzerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = c[i+boxzerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Authenticates and decrypts the given secret box
- * using the key and the nonce.
- *
- * Returns the original message, or null if authentication fails.
- * */
- public byte [] open(byte [] box) {
- if (box==null) return null;
- return open(box, 0, box.length);
- }
-
- public byte [] open(byte [] box, final int boxoff) {
- if (!(box!=null && box.length>boxoff)) return null;
- return open(box, boxoff, box.length-boxoff);
- }
-
- public byte [] open(byte [] box, final int boxoff, final int boxlen) {
- // check message
- if (!(box!=null && box.length>=(boxoff+boxlen) && boxlen>=boxzerobytesLength))
- return null;
- return open(box, boxoff, box.length-boxoff, generateNonce());
- }
-
- public byte [] open(byte [] box, byte [] theNonce) {
- if (box==null) return null;
- return open(box, 0, box.length, theNonce);
- }
-
- public byte [] open(byte [] box, final int boxoff, byte [] theNonce) {
- if (!(box!=null && box.length>boxoff)) return null;
- return open(box, boxoff, box.length-boxoff, theNonce);
- }
-
- public byte [] open(byte [] box, final int boxoff, final int boxlen, byte [] theNonce) {
- // check message
- if (!(box!=null && box.length>=(boxoff+boxlen) && boxlen>=boxzerobytesLength &&
- theNonce!=null && theNonce.length==nonceLength))
- return null;
-
- // cipher buffer
- byte [] c = new byte[boxlen + boxzerobytesLength];
-
- // message buffer
- byte [] m = new byte[c.length];
-
- for (int i = 0; i < boxlen; i++)
- c[i+boxzerobytesLength] = box[i+boxoff];
-
- if (0 != crypto_secretbox_open(m, c, c.length, theNonce, key))
- return null;
-
- // wrap byte_buf_t on m offset@zerobytesLength
- ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength);
- byte [] ret = new byte[m.length-zerobytesLength];
-
- for (int i = 0; i < ret.length; i ++)
- ret[i] = m[i+zerobytesLength];
-
- return ret;
- }
-
- /*
- * @description
- * Length of key in bytes.
- * */
- public static final int keyLength = 32;
-
- /*
- * @description
- * Length of nonce in bytes.
- * */
- public static final int nonceLength = 24;
-
- /*
- * @description
- * Length of overhead added to secret box compared to original message.
- * */
- public static final int overheadLength = 16;
-
- /*
- * @description
- * zero bytes in case box
- * */
- public static final int zerobytesLength = 32;
- /*
- * @description
- * zero bytes in case open box
- * */
- public static final int boxzerobytesLength = 16;
-
- }
-
- /*
- * @description
- * Scalar multiplication, Implements curve25519.
- * */
- public static final class ScalarMult {
-
- private final static String TAG = "ScalarMult";
-
- /*
- * @description
- * Multiplies an integer n by a group element p and
- * returns the resulting group element.
- * */
- public static byte [] scalseMult(byte [] n, byte [] p) {
- if (!(n.length==scalarLength && p.length==groupElementLength))
- return null;
-
- byte [] q = new byte [scalarLength];
-
- crypto_scalarmult(q, n, p);
-
- return q;
- }
-
- /*
- * @description
- * Multiplies an integer n by a standard group element and
- * returns the resulting group element.
- * */
- public static byte [] scalseMult_base(byte [] n) {
- if (!(n.length==scalarLength))
- return null;
-
- byte [] q = new byte [scalarLength];
-
- crypto_scalarmult_base(q, n);
-
- return q;
- }
-
- /*
- * @description
- * Length of scalar in bytes.
- * */
- public static final int scalarLength = 32;
-
- /*
- * @description
- * Length of group element in bytes.
- * */
- public static final int groupElementLength = 32;
-
- }
-
-
- /*
- * @description
- * Hash algorithm, Implements SHA-512.
- * */
- public static final class Hash {
-
- private final static String TAG = "Hash";
-
- /*
- * @description
- * Returns SHA-512 hash of the message.
- * */
- public static byte[] sha512(byte [] message) {
- if (!(message!=null && message.length>0))
- return null;
-
- byte [] out = new byte[hashLength];
-
- crypto_hash(out, message);
-
- return out;
- }
- public static byte[] sha512(String message) throws UnsupportedEncodingException {
- return sha512(message.getBytes("utf-8"));
- }
-
- /*
- * @description
- * Length of hash in bytes.
- * */
- public static final int hashLength = 64;
-
- }
-
-
- /*
- * @description
- * Signature algorithm, Implements ed25519.
- * */
- public static final class Signature {
-
- private final static String TAG = "Signature";
-
- private byte [] theirPublicKey;
- private byte [] mySecretKey;
-
- public Signature(byte [] theirPublicKey, byte [] mySecretKey) {
- this.theirPublicKey = theirPublicKey;
- this.mySecretKey = mySecretKey;
- }
-
- /*
- * @description
- * Signs the message using the secret key and returns a signed message.
- * */
- public byte [] sign(byte [] message) {
- if (message==null) return null;
-
- return sign(message, 0, message.length);
- }
- public byte [] sign(byte [] message, final int moff) {
- if (!(message!=null && message.length>moff)) return null;
-
- return sign(message, moff, message.length-moff);
- }
- public byte [] sign(byte [] message, final int moff, final int mlen) {
- // check message
- if (!(message!=null && message.length>=(moff+mlen)))
- return null;
-
- // signed message
- byte [] sm = new byte[mlen + signatureLength];
-
- crypto_sign(sm, -1, message, moff, mlen, mySecretKey);
-
- return sm;
- }
-
- /*
- * @description
- * Verifies the signed message and returns the message without signature.
- * Returns null if verification failed.
- * */
- public byte [] open(byte [] signedMessage) {
- if (signedMessage==null) return null;
-
- return open(signedMessage, 0, signedMessage.length);
- }
- public byte [] open(byte [] signedMessage, final int smoff) {
- if (!(signedMessage!=null && signedMessage.length>smoff)) return null;
-
- return open(signedMessage, smoff, signedMessage.length-smoff);
- }
- public byte [] open(byte [] signedMessage, final int smoff, final int smlen) {
- // check sm length
- if (!(signedMessage!=null && signedMessage.length>=(smoff+smlen) && smlen>=signatureLength))
- return null;
-
- // temp buffer
- byte [] tmp = new byte[smlen];
-
- if (0 != crypto_sign_open(tmp, -1, signedMessage, smoff, smlen, theirPublicKey))
- return null;
-
- // message
- byte [] msg = new byte[smlen-signatureLength];
- for (int i = 0; i < msg.length; i ++)
- msg[i] = signedMessage[smoff+ i+signatureLength];
-
- return msg;
- }
-
- /*
- * @description
- * Signs the message using the secret key and returns a signature.
- * */
- public byte [] detached(byte [] message) {
-
- return null;
- }
-
- /*
- * @description
- * Verifies the signature for the message and
- * returns true if verification succeeded or false if it failed.
- * */
- public boolean detached_verify(byte [] message, byte [] signature) {
-
- return false;
- }
-
- /*
- * @description
- * Generates new random key pair for signing and
- * returns it as an object with publicKey and secretKey members
- * */
- public static class KeyPair {
- private byte [] publicKey;
- private byte [] secretKey;
-
- public KeyPair() {
- publicKey = new byte[publicKeyLength];
- secretKey = new byte[secretKeyLength];
- }
-
- public byte [] getPublicKey() {
- return publicKey;
- }
-
- public byte [] getSecretKey() {
- return secretKey;
- }
- }
-
- /*
- * @description
- * Signs the message using the secret key and returns a signed message.
- * */
- public static KeyPair keyPair() {
- KeyPair kp = new KeyPair();
-
- crypto_sign_keypair(kp.getPublicKey(), kp.getSecretKey(), false);
- return kp;
- }
- public static KeyPair keyPair_fromSecretKey(byte [] secretKey) {
- KeyPair kp = new KeyPair();
- byte [] pk = kp.getPublicKey();
- byte [] sk = kp.getSecretKey();
-
- // copy sk
- for (int i = 0; i < kp.getSecretKey().length; i ++)
- sk[i] = secretKey[i];
-
- // copy pk from sk
- for (int i = 0; i < kp.getPublicKey().length; i ++)
- pk[i] = secretKey[32+i]; // hard-copy
-
- return kp;
- }
-
- public static KeyPair keyPair_fromSeed(byte [] seed) {
- KeyPair kp = new KeyPair();
- byte [] pk = kp.getPublicKey();
- byte [] sk = kp.getSecretKey();
-
- // copy sk
- for (int i = 0; i < seedLength; i ++)
- sk[i] = seed[i];
-
- // generate pk from sk
- crypto_sign_keypair(pk, sk, true);
-
- return kp;
- }
-
- /*
- * @description
- * Length of signing public key in bytes.
- * */
- public static final int publicKeyLength = 32;
-
- /*
- * @description
- * Length of signing secret key in bytes.
- * */
- public static final int secretKeyLength = 64;
-
- /*
- * @description
- * Length of seed for nacl.sign.keyPair.fromSeed in bytes.
- * */
- public static final int seedLength = 32;
-
- /*
- * @description
- * Length of signature in bytes.
- * */
- public static final int signatureLength = 64;
- }
-
-
- ////////////////////////////////////////////////////////////////////////////////////
- /*
- * @description
- * Codes below are ported tweetnacl-fast.js from TweetNacl.c/TweetNacl.h
- * */
-
- private static final byte [] _0 = new byte[16];
- private static final byte [] _9 = new byte[32];
- static {
- ///for (int i = 0; i < _0.length; i ++) _0[i] = 0;
-
- ///for (int i = 0; i < _9.length; i ++) _9[i] = 0;
- _9[0] = 9;
- }
-
- private static final long [] gf0 = new long[16];
- private static final long [] gf1 = new long[16];
- private static final long [] _121665 = new long[16];
- static {
- ///for (int i = 0; i < gf0.length; i ++) gf0[i] = 0;
-
- ///for (int i = 0; i < gf1.length; i ++) gf1[i] = 0;
- gf1[0] = 1;
-
- ///for (int i = 0; i < _121665.length; i ++) _121665[i] = 0;
- _121665[0] = 0xDB41; _121665[1] = 1;
- }
-
- private static final long [] D = new long [] {
- 0x78a3, 0x1359, 0x4dca, 0x75eb,
- 0xd8ab, 0x4141, 0x0a4d, 0x0070,
- 0xe898, 0x7779, 0x4079, 0x8cc7,
- 0xfe73, 0x2b6f, 0x6cee, 0x5203
- };
- private static final long [] D2 = new long [] {
- 0xf159, 0x26b2, 0x9b94, 0xebd6,
- 0xb156, 0x8283, 0x149a, 0x00e0,
- 0xd130, 0xeef3, 0x80f2, 0x198e,
- 0xfce7, 0x56df, 0xd9dc, 0x2406
- };
- private static final long [] X = new long [] {
- 0xd51a, 0x8f25, 0x2d60, 0xc956,
- 0xa7b2, 0x9525, 0xc760, 0x692c,
- 0xdc5c, 0xfdd6, 0xe231, 0xc0a4,
- 0x53fe, 0xcd6e, 0x36d3, 0x2169
- };
- private static final long [] Y = new long [] {
- 0x6658, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666,
- 0x6666, 0x6666, 0x6666, 0x6666
- };
- private static final long [] I = new long [] {
- 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee,
- 0xe478, 0xad2f, 0x1806, 0x2f43,
- 0xd7a7, 0x3dfb, 0x0099, 0x2b4d,
- 0xdf0b, 0x4fc1, 0x2480, 0x2b83
- };
-
- private static void ts64(byte [] x, final int xoff, long u)
- {
- ///int i;
- ///for (i = 7;i >= 0;--i) { x[i+xoff] = (byte)(u&0xff); u >>>= 8; }
-
- x[7+xoff] = (byte)(u&0xff); u >>>= 8;
- x[6+xoff] = (byte)(u&0xff); u >>>= 8;
- x[5+xoff] = (byte)(u&0xff); u >>>= 8;
- x[4+xoff] = (byte)(u&0xff); u >>>= 8;
- x[3+xoff] = (byte)(u&0xff); u >>>= 8;
- x[2+xoff] = (byte)(u&0xff); u >>>= 8;
- x[1+xoff] = (byte)(u&0xff); u >>>= 8;
- x[0+xoff] = (byte)(u&0xff); ///u >>>= 8;
- }
-
- private static int vn(
- byte [] x, final int xoff,
- byte [] y, final int yoff,
- int n)
- {
- int i,d = 0;
- for (i = 0; i < n; i ++) d |= (x[i+xoff]^y[i+yoff]) & 0xff;
- return (1 & ((d - 1) >>> 8)) - 1;
- }
-
- private static int crypto_verify_16(
- byte [] x, final int xoff,
- byte [] y, final int yoff)
- {
- return vn(x,xoff,y,yoff,16);
- }
- public static int crypto_verify_16(byte [] x, byte [] y)
- {
- return crypto_verify_16(x,0, y,0);
- }
-
- private static int crypto_verify_32(
- byte [] x, final int xoff,
- byte [] y, final int yoff)
- {
- return vn(x,xoff,y,yoff,32);
- }
- public static int crypto_verify_32(byte [] x, byte [] y)
- {
- return crypto_verify_32(x,0, y,0);
- }
-
- private static void core_salsa20(byte [] o, byte [] p, byte [] k, byte [] c) {
- int j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
- j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
- j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
- j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
- j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
- j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
- j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
- j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
- j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
- j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
- j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
- j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
- j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
- j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
- j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
- j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
-
- int x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
- x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
- x15 = j15, u;
-
- for (int i = 0; i < 20; i += 2) {
- u = x0 + x12 | 0;
- x4 ^= u<<7 | u>>>(32-7);
- u = x4 + x0 | 0;
- x8 ^= u<<9 | u>>>(32-9);
- u = x8 + x4 | 0;
- x12 ^= u<<13 | u>>>(32-13);
- u = x12 + x8 | 0;
- x0 ^= u<<18 | u>>>(32-18);
-
- u = x5 + x1 | 0;
- x9 ^= u<<7 | u>>>(32-7);
- u = x9 + x5 | 0;
- x13 ^= u<<9 | u>>>(32-9);
- u = x13 + x9 | 0;
- x1 ^= u<<13 | u>>>(32-13);
- u = x1 + x13 | 0;
- x5 ^= u<<18 | u>>>(32-18);
-
- u = x10 + x6 | 0;
- x14 ^= u<<7 | u>>>(32-7);
- u = x14 + x10 | 0;
- x2 ^= u<<9 | u>>>(32-9);
- u = x2 + x14 | 0;
- x6 ^= u<<13 | u>>>(32-13);
- u = x6 + x2 | 0;
- x10 ^= u<<18 | u>>>(32-18);
-
- u = x15 + x11 | 0;
- x3 ^= u<<7 | u>>>(32-7);
- u = x3 + x15 | 0;
- x7 ^= u<<9 | u>>>(32-9);
- u = x7 + x3 | 0;
- x11 ^= u<<13 | u>>>(32-13);
- u = x11 + x7 | 0;
- x15 ^= u<<18 | u>>>(32-18);
-
- u = x0 + x3 | 0;
- x1 ^= u<<7 | u>>>(32-7);
- u = x1 + x0 | 0;
- x2 ^= u<<9 | u>>>(32-9);
- u = x2 + x1 | 0;
- x3 ^= u<<13 | u>>>(32-13);
- u = x3 + x2 | 0;
- x0 ^= u<<18 | u>>>(32-18);
-
- u = x5 + x4 | 0;
- x6 ^= u<<7 | u>>>(32-7);
- u = x6 + x5 | 0;
- x7 ^= u<<9 | u>>>(32-9);
- u = x7 + x6 | 0;
- x4 ^= u<<13 | u>>>(32-13);
- u = x4 + x7 | 0;
- x5 ^= u<<18 | u>>>(32-18);
-
- u = x10 + x9 | 0;
- x11 ^= u<<7 | u>>>(32-7);
- u = x11 + x10 | 0;
- x8 ^= u<<9 | u>>>(32-9);
- u = x8 + x11 | 0;
- x9 ^= u<<13 | u>>>(32-13);
- u = x9 + x8 | 0;
- x10 ^= u<<18 | u>>>(32-18);
-
- u = x15 + x14 | 0;
- x12 ^= u<<7 | u>>>(32-7);
- u = x12 + x15 | 0;
- x13 ^= u<<9 | u>>>(32-9);
- u = x13 + x12 | 0;
- x14 ^= u<<13 | u>>>(32-13);
- u = x14 + x13 | 0;
- x15 ^= u<<18 | u>>>(32-18);
- }
- x0 = x0 + j0 | 0;
- x1 = x1 + j1 | 0;
- x2 = x2 + j2 | 0;
- x3 = x3 + j3 | 0;
- x4 = x4 + j4 | 0;
- x5 = x5 + j5 | 0;
- x6 = x6 + j6 | 0;
- x7 = x7 + j7 | 0;
- x8 = x8 + j8 | 0;
- x9 = x9 + j9 | 0;
- x10 = x10 + j10 | 0;
- x11 = x11 + j11 | 0;
- x12 = x12 + j12 | 0;
- x13 = x13 + j13 | 0;
- x14 = x14 + j14 | 0;
- x15 = x15 + j15 | 0;
-
- o[ 0] = (byte) (x0 >>> 0 & 0xff);
- o[ 1] = (byte) (x0 >>> 8 & 0xff);
- o[ 2] = (byte) (x0 >>> 16 & 0xff);
- o[ 3] = (byte) (x0 >>> 24 & 0xff);
-
- o[ 4] = (byte) (x1 >>> 0 & 0xff);
- o[ 5] = (byte) (x1 >>> 8 & 0xff);
- o[ 6] = (byte) (x1 >>> 16 & 0xff);
- o[ 7] = (byte) (x1 >>> 24 & 0xff);
-
- o[ 8] = (byte) (x2 >>> 0 & 0xff);
- o[ 9] = (byte) (x2 >>> 8 & 0xff);
- o[10] = (byte) (x2 >>> 16 & 0xff);
- o[11] = (byte) (x2 >>> 24 & 0xff);
-
- o[12] = (byte) (x3 >>> 0 & 0xff);
- o[13] = (byte) (x3 >>> 8 & 0xff);
- o[14] = (byte) (x3 >>> 16 & 0xff);
- o[15] = (byte) (x3 >>> 24 & 0xff);
-
- o[16] = (byte) (x4 >>> 0 & 0xff);
- o[17] = (byte) (x4 >>> 8 & 0xff);
- o[18] = (byte) (x4 >>> 16 & 0xff);
- o[19] = (byte) (x4 >>> 24 & 0xff);
-
- o[20] = (byte) (x5 >>> 0 & 0xff);
- o[21] = (byte) (x5 >>> 8 & 0xff);
- o[22] = (byte) (x5 >>> 16 & 0xff);
- o[23] = (byte) (x5 >>> 24 & 0xff);
-
- o[24] = (byte) (x6 >>> 0 & 0xff);
- o[25] = (byte) (x6 >>> 8 & 0xff);
- o[26] = (byte) (x6 >>> 16 & 0xff);
- o[27] = (byte) (x6 >>> 24 & 0xff);
-
- o[28] = (byte) (x7 >>> 0 & 0xff);
- o[29] = (byte) (x7 >>> 8 & 0xff);
- o[30] = (byte) (x7 >>> 16 & 0xff);
- o[31] = (byte) (x7 >>> 24 & 0xff);
-
- o[32] = (byte) (x8 >>> 0 & 0xff);
- o[33] = (byte) (x8 >>> 8 & 0xff);
- o[34] = (byte) (x8 >>> 16 & 0xff);
- o[35] = (byte) (x8 >>> 24 & 0xff);
-
- o[36] = (byte) (x9 >>> 0 & 0xff);
- o[37] = (byte) (x9 >>> 8 & 0xff);
- o[38] = (byte) (x9 >>> 16 & 0xff);
- o[39] = (byte) (x9 >>> 24 & 0xff);
-
- o[40] = (byte) (x10 >>> 0 & 0xff);
- o[41] = (byte) (x10 >>> 8 & 0xff);
- o[42] = (byte) (x10 >>> 16 & 0xff);
- o[43] = (byte) (x10 >>> 24 & 0xff);
-
- o[44] = (byte) (x11 >>> 0 & 0xff);
- o[45] = (byte) (x11 >>> 8 & 0xff);
- o[46] = (byte) (x11 >>> 16 & 0xff);
- o[47] = (byte) (x11 >>> 24 & 0xff);
-
- o[48] = (byte) (x12 >>> 0 & 0xff);
- o[49] = (byte) (x12 >>> 8 & 0xff);
- o[50] = (byte) (x12 >>> 16 & 0xff);
- o[51] = (byte) (x12 >>> 24 & 0xff);
-
- o[52] = (byte) (x13 >>> 0 & 0xff);
- o[53] = (byte) (x13 >>> 8 & 0xff);
- o[54] = (byte) (x13 >>> 16 & 0xff);
- o[55] = (byte) (x13 >>> 24 & 0xff);
-
- o[56] = (byte) (x14 >>> 0 & 0xff);
- o[57] = (byte) (x14 >>> 8 & 0xff);
- o[58] = (byte) (x14 >>> 16 & 0xff);
- o[59] = (byte) (x14 >>> 24 & 0xff);
-
- o[60] = (byte) (x15 >>> 0 & 0xff);
- o[61] = (byte) (x15 >>> 8 & 0xff);
- o[62] = (byte) (x15 >>> 16 & 0xff);
- o[63] = (byte) (x15 >>> 24 & 0xff);
-
- /*String dbgt = "";
- for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o[dbg];
- Log.d(TAG, "core_salsa20 -> "+dbgt);
-*/
- }
-
- private static void core_hsalsa20(byte [] o, byte [] p, byte [] k, byte [] c) {
- int j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
- j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
- j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
- j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
- j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
- j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
- j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
- j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
- j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
- j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
- j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
- j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
- j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
- j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
- j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
- j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
-
- int x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
- x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
- x15 = j15, u;
-
- for (int i = 0; i < 20; i += 2) {
- u = x0 + x12 | 0;
- x4 ^= u<<7 | u>>>(32-7);
- u = x4 + x0 | 0;
- x8 ^= u<<9 | u>>>(32-9);
- u = x8 + x4 | 0;
- x12 ^= u<<13 | u>>>(32-13);
- u = x12 + x8 | 0;
- x0 ^= u<<18 | u>>>(32-18);
-
- u = x5 + x1 | 0;
- x9 ^= u<<7 | u>>>(32-7);
- u = x9 + x5 | 0;
- x13 ^= u<<9 | u>>>(32-9);
- u = x13 + x9 | 0;
- x1 ^= u<<13 | u>>>(32-13);
- u = x1 + x13 | 0;
- x5 ^= u<<18 | u>>>(32-18);
-
- u = x10 + x6 | 0;
- x14 ^= u<<7 | u>>>(32-7);
- u = x14 + x10 | 0;
- x2 ^= u<<9 | u>>>(32-9);
- u = x2 + x14 | 0;
- x6 ^= u<<13 | u>>>(32-13);
- u = x6 + x2 | 0;
- x10 ^= u<<18 | u>>>(32-18);
-
- u = x15 + x11 | 0;
- x3 ^= u<<7 | u>>>(32-7);
- u = x3 + x15 | 0;
- x7 ^= u<<9 | u>>>(32-9);
- u = x7 + x3 | 0;
- x11 ^= u<<13 | u>>>(32-13);
- u = x11 + x7 | 0;
- x15 ^= u<<18 | u>>>(32-18);
-
- u = x0 + x3 | 0;
- x1 ^= u<<7 | u>>>(32-7);
- u = x1 + x0 | 0;
- x2 ^= u<<9 | u>>>(32-9);
- u = x2 + x1 | 0;
- x3 ^= u<<13 | u>>>(32-13);
- u = x3 + x2 | 0;
- x0 ^= u<<18 | u>>>(32-18);
-
- u = x5 + x4 | 0;
- x6 ^= u<<7 | u>>>(32-7);
- u = x6 + x5 | 0;
- x7 ^= u<<9 | u>>>(32-9);
- u = x7 + x6 | 0;
- x4 ^= u<<13 | u>>>(32-13);
- u = x4 + x7 | 0;
- x5 ^= u<<18 | u>>>(32-18);
-
- u = x10 + x9 | 0;
- x11 ^= u<<7 | u>>>(32-7);
- u = x11 + x10 | 0;
- x8 ^= u<<9 | u>>>(32-9);
- u = x8 + x11 | 0;
- x9 ^= u<<13 | u>>>(32-13);
- u = x9 + x8 | 0;
- x10 ^= u<<18 | u>>>(32-18);
-
- u = x15 + x14 | 0;
- x12 ^= u<<7 | u>>>(32-7);
- u = x12 + x15 | 0;
- x13 ^= u<<9 | u>>>(32-9);
- u = x13 + x12 | 0;
- x14 ^= u<<13 | u>>>(32-13);
- u = x14 + x13 | 0;
- x15 ^= u<<18 | u>>>(32-18);
- }
-
- o[ 0] = (byte) (x0 >>> 0 & 0xff);
- o[ 1] = (byte) (x0 >>> 8 & 0xff);
- o[ 2] = (byte) (x0 >>> 16 & 0xff);
- o[ 3] = (byte) (x0 >>> 24 & 0xff);
-
- o[ 4] = (byte) (x5 >>> 0 & 0xff);
- o[ 5] = (byte) (x5 >>> 8 & 0xff);
- o[ 6] = (byte) (x5 >>> 16 & 0xff);
- o[ 7] = (byte) (x5 >>> 24 & 0xff);
-
- o[ 8] = (byte) (x10 >>> 0 & 0xff);
- o[ 9] = (byte) (x10 >>> 8 & 0xff);
- o[10] = (byte) (x10 >>> 16 & 0xff);
- o[11] = (byte) (x10 >>> 24 & 0xff);
-
- o[12] = (byte) (x15 >>> 0 & 0xff);
- o[13] = (byte) (x15 >>> 8 & 0xff);
- o[14] = (byte) (x15 >>> 16 & 0xff);
- o[15] = (byte) (x15 >>> 24 & 0xff);
-
- o[16] = (byte) (x6 >>> 0 & 0xff);
- o[17] = (byte) (x6 >>> 8 & 0xff);
- o[18] = (byte) (x6 >>> 16 & 0xff);
- o[19] = (byte) (x6 >>> 24 & 0xff);
-
- o[20] = (byte) (x7 >>> 0 & 0xff);
- o[21] = (byte) (x7 >>> 8 & 0xff);
- o[22] = (byte) (x7 >>> 16 & 0xff);
- o[23] = (byte) (x7 >>> 24 & 0xff);
-
- o[24] = (byte) (x8 >>> 0 & 0xff);
- o[25] = (byte) (x8 >>> 8 & 0xff);
- o[26] = (byte) (x8 >>> 16 & 0xff);
- o[27] = (byte) (x8 >>> 24 & 0xff);
-
- o[28] = (byte) (x9 >>> 0 & 0xff);
- o[29] = (byte) (x9 >>> 8 & 0xff);
- o[30] = (byte) (x9 >>> 16 & 0xff);
- o[31] = (byte) (x9 >>> 24 & 0xff);
-
-
- /*String dbgt = "";
- for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o[dbg];
- Log.d(TAG, "core_hsalsa20 -> "+dbgt);
-*/
- }
-
- public static int crypto_core_salsa20(byte [] out, byte [] in, byte [] k, byte [] c)
- {
- ///core(out,in,k,c,0);
- core_salsa20(out,in,k,c);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg];
- ///L/og.d(TAG, "crypto_core_salsa20 -> "+dbgt);
-
- return 0;
- }
-
- public static int crypto_core_hsalsa20(byte [] out, byte [] in, byte [] k, byte [] c)
- {
- ///core(out,in,k,c,1);
- core_hsalsa20(out,in,k,c);
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg];
- ///L/og.d(TAG, "crypto_core_hsalsa20 -> "+dbgt);
-
- return 0;
- }
-
- // "expand 32-byte k"
- private static final byte[] sigma = {101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107};
-
- /*static {
- try {
- sigma = "expand 32-byte k".getBytes("utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }*/
-
- private static int crypto_stream_salsa20_xor(byte [] c,int cpos, byte [] m,int mpos, long b, byte [] n, byte [] k)
- {
- byte [] z = new byte[16], x = new byte[64];
- int u, i;
- for (i = 0; i < 16; i++) z[i] = 0;
- for (i = 0; i < 8; i++) z[i] = n[i];
- while (b >= 64) {
- crypto_core_salsa20(x,z,k,sigma);
- for (i = 0; i < 64; i++) c[cpos+i] = (byte) ((m[mpos+i] ^ x[i]) & 0xff);
- u = 1;
- for (i = 8; i < 16; i++) {
- u = u + (z[i] & 0xff) | 0;
- z[i] = (byte) (u & 0xff);
- u >>>= 8;
- }
- b -= 64;
- cpos += 64;
- mpos += 64;
- }
- if (b > 0) {
- crypto_core_salsa20(x,z,k,sigma);
- for (i = 0; i < b; i++) c[cpos+i] = (byte) ((m[mpos+i] ^ x[i]) & 0xff);
- }
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < c.length-cpos; dbg ++) dbgt += " "+c[dbg +cpos];
- ///Log.d(TAG, "crypto_stream_salsa20_xor, c -> "+dbgt);
-
- return 0;
- }
-
- public static int crypto_stream_salsa20(byte [] c,int cpos, long b, byte [] n, byte [] k) {
- byte [] z = new byte[16], x = new byte[64];
- int u, i;
- for (i = 0; i < 16; i++) z[i] = 0;
- for (i = 0; i < 8; i++) z[i] = n[i];
- while (b >= 64) {
- crypto_core_salsa20(x,z,k,sigma);
- for (i = 0; i < 64; i++) c[cpos+i] = x[i];
- u = 1;
- for (i = 8; i < 16; i++) {
- u = u + (z[i] & 0xff) | 0;
- z[i] = (byte) (u & 0xff);
- u >>>= 8;
- }
- b -= 64;
- cpos += 64;
- }
- if (b > 0) {
- crypto_core_salsa20(x,z,k,sigma);
- for (i = 0; i < b; i++) c[cpos+i] = x[i];
- }
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < c.length-cpos; dbg ++) dbgt += " "+c[dbg +cpos];
- ///Log.d(TAG, "crypto_stream_salsa20, c -> "+dbgt);
-
- return 0;
- }
-
- public static int crypto_stream(byte [] c,int cpos, long d, byte [] n, byte [] k) {
- byte [] s = new byte[32];
- crypto_core_hsalsa20(s,n,k,sigma);
- byte [] sn = new byte[8];
- for (int i = 0; i < 8; i++) sn[i] = n[i+16];
- return crypto_stream_salsa20(c,cpos,d,sn,s);
- }
-
- public static int crypto_stream_xor(byte [] c,int cpos, byte [] m,int mpos, long d, byte [] n, byte [] k) {
- byte [] s = new byte[32];
-
- /*String dbgt = "";
- for (int dbg = 0; dbg < n.length; dbg ++) dbgt += " "+n[dbg];
- Log.d(TAG, "crypto_stream_xor, nonce -> "+dbgt);
-
- dbgt = "";
- for (int dbg = 0; dbg < k.length; dbg ++) dbgt += " "+k[dbg];
- Log.d(TAG, "crypto_stream_xor, shk -> "+dbgt);
- */
-
- crypto_core_hsalsa20(s,n,k,sigma);
- byte [] sn = new byte[8];
- for (int i = 0; i < 8; i++) sn[i] = n[i+16];
- return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
- }
-
- /*
- * Port of Andrew Moon's Poly1305-donna-16. Public domain.
- * https://github.com/floodyberry/poly1305-donna
- */
- public static class poly1305 {
-
- private byte[] buffer;
- private int[] r;
- private int[] h;
- private int[] pad;
- private int leftover;
- private int fin;
-
- public poly1305(byte [] key) {
- this.buffer = new byte[16];
- this.r = new int[10];
- this.h = new int[10];
- this.pad = new int[8];
- this.leftover = 0;
- this.fin = 0;
-
- int t0, t1, t2, t3, t4, t5, t6, t7;
-
- t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
- t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
- t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
- t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
- t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
- this.r[5] = ((t4 >>> 1)) & 0x1ffe;
- t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
- t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
- t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
- this.r[9] = ((t7 >>> 5)) & 0x007f;
-
- this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
- this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
- this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
- this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
- this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
- this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
- this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
- this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
- }
-
- public poly1305 blocks(byte [] m, int mpos, int bytes) {
- int hibit = this.fin!=0 ? 0 : (1 << 11);
- int t0, t1, t2, t3, t4, t5, t6, t7, c;
- int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
-
- int h0 = this.h[0],
- h1 = this.h[1],
- h2 = this.h[2],
- h3 = this.h[3],
- h4 = this.h[4],
- h5 = this.h[5],
- h6 = this.h[6],
- h7 = this.h[7],
- h8 = this.h[8],
- h9 = this.h[9];
-
- int r0 = this.r[0],
- r1 = this.r[1],
- r2 = this.r[2],
- r3 = this.r[3],
- r4 = this.r[4],
- r5 = this.r[5],
- r6 = this.r[6],
- r7 = this.r[7],
- r8 = this.r[8],
- r9 = this.r[9];
-
- while (bytes >= 16) {
- t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
- t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
- t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
- t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
- t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
- h5 += ((t4 >>> 1)) & 0x1fff;
- t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
- t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
- t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
- h9 += ((t7 >>> 5)) | hibit;
-
- c = 0;
-
- d0 = c;
- d0 += h0 * r0;
- d0 += h1 * (5 * r9);
- d0 += h2 * (5 * r8);
- d0 += h3 * (5 * r7);
- d0 += h4 * (5 * r6);
- c = (d0 >>> 13); d0 &= 0x1fff;
- d0 += h5 * (5 * r5);
- d0 += h6 * (5 * r4);
- d0 += h7 * (5 * r3);
- d0 += h8 * (5 * r2);
- d0 += h9 * (5 * r1);
- c += (d0 >>> 13); d0 &= 0x1fff;
-
- d1 = c;
- d1 += h0 * r1;
- d1 += h1 * r0;
- d1 += h2 * (5 * r9);
- d1 += h3 * (5 * r8);
- d1 += h4 * (5 * r7);
- c = (d1 >>> 13); d1 &= 0x1fff;
- d1 += h5 * (5 * r6);
- d1 += h6 * (5 * r5);
- d1 += h7 * (5 * r4);
- d1 += h8 * (5 * r3);
- d1 += h9 * (5 * r2);
- c += (d1 >>> 13); d1 &= 0x1fff;
-
- d2 = c;
- d2 += h0 * r2;
- d2 += h1 * r1;
- d2 += h2 * r0;
- d2 += h3 * (5 * r9);
- d2 += h4 * (5 * r8);
- c = (d2 >>> 13); d2 &= 0x1fff;
- d2 += h5 * (5 * r7);
- d2 += h6 * (5 * r6);
- d2 += h7 * (5 * r5);
- d2 += h8 * (5 * r4);
- d2 += h9 * (5 * r3);
- c += (d2 >>> 13); d2 &= 0x1fff;
-
- d3 = c;
- d3 += h0 * r3;
- d3 += h1 * r2;
- d3 += h2 * r1;
- d3 += h3 * r0;
- d3 += h4 * (5 * r9);
- c = (d3 >>> 13); d3 &= 0x1fff;
- d3 += h5 * (5 * r8);
- d3 += h6 * (5 * r7);
- d3 += h7 * (5 * r6);
- d3 += h8 * (5 * r5);
- d3 += h9 * (5 * r4);
- c += (d3 >>> 13); d3 &= 0x1fff;
-
- d4 = c;
- d4 += h0 * r4;
- d4 += h1 * r3;
- d4 += h2 * r2;
- d4 += h3 * r1;
- d4 += h4 * r0;
- c = (d4 >>> 13); d4 &= 0x1fff;
- d4 += h5 * (5 * r9);
- d4 += h6 * (5 * r8);
- d4 += h7 * (5 * r7);
- d4 += h8 * (5 * r6);
- d4 += h9 * (5 * r5);
- c += (d4 >>> 13); d4 &= 0x1fff;
-
- d5 = c;
- d5 += h0 * r5;
- d5 += h1 * r4;
- d5 += h2 * r3;
- d5 += h3 * r2;
- d5 += h4 * r1;
- c = (d5 >>> 13); d5 &= 0x1fff;
- d5 += h5 * r0;
- d5 += h6 * (5 * r9);
- d5 += h7 * (5 * r8);
- d5 += h8 * (5 * r7);
- d5 += h9 * (5 * r6);
- c += (d5 >>> 13); d5 &= 0x1fff;
-
- d6 = c;
- d6 += h0 * r6;
- d6 += h1 * r5;
- d6 += h2 * r4;
- d6 += h3 * r3;
- d6 += h4 * r2;
- c = (d6 >>> 13); d6 &= 0x1fff;
- d6 += h5 * r1;
- d6 += h6 * r0;
- d6 += h7 * (5 * r9);
- d6 += h8 * (5 * r8);
- d6 += h9 * (5 * r7);
- c += (d6 >>> 13); d6 &= 0x1fff;
-
- d7 = c;
- d7 += h0 * r7;
- d7 += h1 * r6;
- d7 += h2 * r5;
- d7 += h3 * r4;
- d7 += h4 * r3;
- c = (d7 >>> 13); d7 &= 0x1fff;
- d7 += h5 * r2;
- d7 += h6 * r1;
- d7 += h7 * r0;
- d7 += h8 * (5 * r9);
- d7 += h9 * (5 * r8);
- c += (d7 >>> 13); d7 &= 0x1fff;
-
- d8 = c;
- d8 += h0 * r8;
- d8 += h1 * r7;
- d8 += h2 * r6;
- d8 += h3 * r5;
- d8 += h4 * r4;
- c = (d8 >>> 13); d8 &= 0x1fff;
- d8 += h5 * r3;
- d8 += h6 * r2;
- d8 += h7 * r1;
- d8 += h8 * r0;
- d8 += h9 * (5 * r9);
- c += (d8 >>> 13); d8 &= 0x1fff;
-
- d9 = c;
- d9 += h0 * r9;
- d9 += h1 * r8;
- d9 += h2 * r7;
- d9 += h3 * r6;
- d9 += h4 * r5;
- c = (d9 >>> 13); d9 &= 0x1fff;
- d9 += h5 * r4;
- d9 += h6 * r3;
- d9 += h7 * r2;
- d9 += h8 * r1;
- d9 += h9 * r0;
- c += (d9 >>> 13); d9 &= 0x1fff;
-
- c = (((c << 2) + c)) | 0;
- c = (c + d0) | 0;
- d0 = c & 0x1fff;
- c = (c >>> 13);
- d1 += c;
-
- h0 = d0;
- h1 = d1;
- h2 = d2;
- h3 = d3;
- h4 = d4;
- h5 = d5;
- h6 = d6;
- h7 = d7;
- h8 = d8;
- h9 = d9;
-
- mpos += 16;
- bytes -= 16;
- }
- this.h[0] = h0;
- this.h[1] = h1;
- this.h[2] = h2;
- this.h[3] = h3;
- this.h[4] = h4;
- this.h[5] = h5;
- this.h[6] = h6;
- this.h[7] = h7;
- this.h[8] = h8;
- this.h[9] = h9;
-
- return this;
- }
-
- public poly1305 finish(byte [] mac, int macpos) {
- int [] g = new int[10];
- int c, mask, f, i;
-
- if (this.leftover != 0) {
- i = this.leftover;
- this.buffer[i++] = 1;
- for (; i < 16; i++) this.buffer[i] = 0;
- this.fin = 1;
- this.blocks(this.buffer, 0, 16);
- }
-
- c = this.h[1] >>> 13;
- this.h[1] &= 0x1fff;
- for (i = 2; i < 10; i++) {
- this.h[i] += c;
- c = this.h[i] >>> 13;
- this.h[i] &= 0x1fff;
- }
- this.h[0] += (c * 5);
- c = this.h[0] >>> 13;
- this.h[0] &= 0x1fff;
- this.h[1] += c;
- c = this.h[1] >>> 13;
- this.h[1] &= 0x1fff;
- this.h[2] += c;
-
- g[0] = this.h[0] + 5;
- c = g[0] >>> 13;
- g[0] &= 0x1fff;
- for (i = 1; i < 10; i++) {
- g[i] = this.h[i] + c;
- c = g[i] >>> 13;
- g[i] &= 0x1fff;
- }
- g[9] -= (1 << 13); g[9] &= 0xffff;
-
-
- /*
- backport from tweetnacl-fast.js https://github.com/dchest/tweetnacl-js/releases/tag/v0.14.3
- <<<
- "The issue was not properly detecting if st->h was >= 2^130 - 5,
- coupled with [testing mistake] not catching the failure.
- The chance of the bug affecting anything in the real world is essentially zero luckily,
- but it's good to have it fixed."
- >>>
- */
- ///change mask = (g[9] >>> ((2 * 8) - 1)) - 1; to as
- mask = (c ^ 1) - 1;
- mask &= 0xffff;
- ///////////////////////////////////////
-
-
- for (i = 0; i < 10; i++) g[i] &= mask;
- mask = ~mask;
- for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
-
- this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
- this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
- this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
- this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
- this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
- this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
- this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
- this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
-
- f = this.h[0] + this.pad[0];
- this.h[0] = f & 0xffff;
- for (i = 1; i < 8; i++) {
- f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
- this.h[i] = f & 0xffff;
- }
-
- mac[macpos+ 0] = (byte) ((this.h[0] >>> 0) & 0xff);
- mac[macpos+ 1] = (byte) ((this.h[0] >>> 8) & 0xff);
- mac[macpos+ 2] = (byte) ((this.h[1] >>> 0) & 0xff);
- mac[macpos+ 3] = (byte) ((this.h[1] >>> 8) & 0xff);
- mac[macpos+ 4] = (byte) ((this.h[2] >>> 0) & 0xff);
- mac[macpos+ 5] = (byte) ((this.h[2] >>> 8) & 0xff);
- mac[macpos+ 6] = (byte) ((this.h[3] >>> 0) & 0xff);
- mac[macpos+ 7] = (byte) ((this.h[3] >>> 8) & 0xff);
- mac[macpos+ 8] = (byte) ((this.h[4] >>> 0) & 0xff);
- mac[macpos+ 9] = (byte) ((this.h[4] >>> 8) & 0xff);
- mac[macpos+10] = (byte) ((this.h[5] >>> 0) & 0xff);
- mac[macpos+11] = (byte) ((this.h[5] >>> 8) & 0xff);
- mac[macpos+12] = (byte) ((this.h[6] >>> 0) & 0xff);
- mac[macpos+13] = (byte) ((this.h[6] >>> 8) & 0xff);
- mac[macpos+14] = (byte) ((this.h[7] >>> 0) & 0xff);
- mac[macpos+15] = (byte) ((this.h[7] >>> 8) & 0xff);
-
- return this;
- }
-
- public poly1305 update(byte [] m, int mpos, int bytes) {
- int i, want;
-
- if (this.leftover != 0) {
- want = (16 - this.leftover);
- if (want > bytes)
- want = bytes;
- for (i = 0; i < want; i++)
- this.buffer[this.leftover + i] = m[mpos+i];
- bytes -= want;
- mpos += want;
- this.leftover += want;
- if (this.leftover < 16)
- return this;
- this.blocks(buffer, 0, 16);
- this.leftover = 0;
- }
-
- if (bytes >= 16) {
- want = bytes - (bytes % 16);
- this.blocks(m, mpos, want);
- mpos += want;
- bytes -= want;
- }
-
- if (bytes != 0) {
- for (i = 0; i < bytes; i++)
- this.buffer[this.leftover + i] = m[mpos+i];
- this.leftover += bytes;
- }
-
- return this;
- }
-
- }
-
- private static int crypto_onetimeauth(
- byte[] out,final int outpos,
- byte[] m,final int mpos,
- int n,
- byte [] k)
- {
- poly1305 s = new poly1305(k);
- s.update(m, mpos, n);
- s.finish(out, outpos);
-
- /*String dbgt = "";
- for (int dbg = 0; dbg < out.length-outpos; dbg ++) dbgt += " "+out[dbg+outpos];
- Log.d(TAG, "crypto_onetimeauth -> "+dbgt);
- */
-
- return 0;
- }
- public static int crypto_onetimeauth(byte [] out, byte [] m, int /*long*/ n , byte [] k) {
- return crypto_onetimeauth(out,0, m,0, n, k);
- }
-
- private static int crypto_onetimeauth_verify(
- byte[] h,final int hoff,
- byte[] m,final int moff,
- int /*long*/ n,
- byte [] k)
- {
- byte [] x = new byte[16];
- crypto_onetimeauth(x,0,m,moff,n,k);
- return crypto_verify_16(h,hoff,x,0);
- }
- public static int crypto_onetimeauth_verify(byte [] h, byte [] m, int /*long*/ n, byte [] k) {
- return crypto_onetimeauth_verify(h,0, m,0, n, k);
- }
- public static int crypto_onetimeauth_verify(byte [] h, byte [] m, byte [] k) {
- return crypto_onetimeauth_verify(h, m, m!=null? m.length:0, k);
- }
-
- public static int crypto_secretbox(byte [] c, byte [] m, int /*long*/ d, byte [] n, byte [] k)
- {
- int i;
- if (d < 32) return -1;
- crypto_stream_xor(c,0,m,0,d,n,k);
- crypto_onetimeauth(c,16, c,32, d-32, c);
- ///for (i = 0; i < 16; i++) c[i] = 0;
- return 0;
- }
-
- public static int crypto_secretbox_open(byte []m,byte []c,int /*long*/ d,byte []n,byte []k)
- {
- int i;
- byte[] x = new byte[32];
- if (d < 32) return -1;
- crypto_stream(x,0,32,n,k);
- if (crypto_onetimeauth_verify(c,16, c,32, d-32, x) != 0) return -1;
- crypto_stream_xor(m,0,c,0,d,n,k);
- ///for (i = 0; i < 32; i++) m[i] = 0;
- return 0;
- }
-
- private static void set25519(long [] r, long [] a)
- {
- int i;
- for (i = 0; i < 16; i ++) r[i]=a[i];
- }
-
- private static void car25519(long [] o)
- {
- int i;
- long v, c = 1;
- for (i = 0; i < 16; i++) {
- v = o[i] + c + 65535;
- c = v>>16;
- o[i] = v - c * 65536;
- }
- o[0] += c-1 + 37 * (c-1);
- }
-
- private static void sel25519(
- long[] p,
- long[] q,
- int b)
- {
- sel25519(p,0, q,0, b);
- }
- private static void sel25519(
- long[] p,final int poff,
- long[] q,final int qoff,
- int b)
- {
- long t, c = ~(b-1);
- for (int i = 0; i < 16; i++) {
- t = c & (p[i+poff] ^ q[i+qoff]);
- p[i+poff] ^= t;
- q[i+qoff] ^= t;
- }
- }
-
- private static void pack25519(byte [] o, long [] n,final int noff)
- {
- int i, j, b;
- long [] m = new long[16], t = new long[16];
- for (i = 0; i < 16; i++) t[i] = n[i+noff];
- car25519(t);
- car25519(t);
- car25519(t);
- for (j = 0; j < 2; j++) {
- m[0] = t[0] - 0xffed;
- for (i = 1; i < 15; i++) {
- m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
- m[i-1] &= 0xffff;
- }
- m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
- b = (int) ((m[15]>>16) & 1);
- m[14] &= 0xffff;
- sel25519(t,0, m,0, 1-b);
- }
- for (i = 0; i < 16; i++) {
- o[2*i] = (byte) (t[i] & 0xff);
- o[2*i+1] = (byte) (t[i]>>8);
- }
- }
-
- private static int neq25519(long [] a, long [] b) {
- return neq25519(a,0, b,0);
- }
- private static int neq25519(long [] a,final int aoff, long [] b,final int boff)
- {
- byte [] c = new byte[32], d = new byte[32];
- pack25519(c, a,aoff);
- pack25519(d, b,boff);
- return crypto_verify_32(c, 0, d, 0);
- }
-
- private static byte par25519(long [] a)
- {
- return par25519(a,0);
- }
- private static byte par25519(long [] a,final int aoff)
- {
- byte [] d = new byte[32];
- pack25519(d, a,aoff);
- return (byte) (d[0] & 1);
- }
-
- private static void unpack25519(long [] o, byte [] n)
- {
- int i;
- for (i = 0; i < 16; i ++) o[i]=(n[2*i]&0xff)+((long)((n[2*i+1]<<8)&0xffff));
- o[15] &= 0x7fff;
- }
-
- private static void A(
- long [] o,
- long [] a,
- long [] b)
- {
- A(o,0, a,0, b,0);
- }
- private static void A(
- long [] o,final int ooff,
- long [] a,final int aoff,
- long [] b,final int boff)
- {
- int i;
- for (i = 0; i < 16; i ++) o[i+ooff] = a[i+aoff] + b[i+boff];
- }
-
- private static void Z(
- long [] o,
- long [] a,
- long [] b)
- {
- Z(o,0, a,0, b,0);
- }
- private static void Z(
- long [] o,final int ooff,
- long [] a,final int aoff,
- long [] b,final int boff)
- {
- int i;
- for (i = 0; i < 16; i ++) o[i+ooff] = a[i+aoff] - b[i+boff];
- }
-
- private static void M(
- long [] o,
- long [] a,
- long [] b)
- {
- M(o,0, a,0, b,0);
- }
- private static void M(
- long [] o,final int ooff,
- long [] a,final int aoff,
- long [] b,final int boff)
- {
- long v, c,
- t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
- t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
- t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
- t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
- b0 = b[0 +boff],
- b1 = b[1 +boff],
- b2 = b[2 +boff],
- b3 = b[3 +boff],
- b4 = b[4 +boff],
- b5 = b[5 +boff],
- b6 = b[6 +boff],
- b7 = b[7 +boff],
- b8 = b[8 +boff],
- b9 = b[9 +boff],
- b10 = b[10 +boff],
- b11 = b[11 +boff],
- b12 = b[12 +boff],
- b13 = b[13 +boff],
- b14 = b[14 +boff],
- b15 = b[15 +boff];
-
- v = a[0 +aoff];
- t0 += v * b0;
- t1 += v * b1;
- t2 += v * b2;
- t3 += v * b3;
- t4 += v * b4;
- t5 += v * b5;
- t6 += v * b6;
- t7 += v * b7;
- t8 += v * b8;
- t9 += v * b9;
- t10 += v * b10;
- t11 += v * b11;
- t12 += v * b12;
- t13 += v * b13;
- t14 += v * b14;
- t15 += v * b15;
- v = a[1 +aoff];
- t1 += v * b0;
- t2 += v * b1;
- t3 += v * b2;
- t4 += v * b3;
- t5 += v * b4;
- t6 += v * b5;
- t7 += v * b6;
- t8 += v * b7;
- t9 += v * b8;
- t10 += v * b9;
- t11 += v * b10;
- t12 += v * b11;
- t13 += v * b12;
- t14 += v * b13;
- t15 += v * b14;
- t16 += v * b15;
- v = a[2 +aoff];
- t2 += v * b0;
- t3 += v * b1;
- t4 += v * b2;
- t5 += v * b3;
- t6 += v * b4;
- t7 += v * b5;
- t8 += v * b6;
- t9 += v * b7;
- t10 += v * b8;
- t11 += v * b9;
- t12 += v * b10;
- t13 += v * b11;
- t14 += v * b12;
- t15 += v * b13;
- t16 += v * b14;
- t17 += v * b15;
- v = a[3 +aoff];
- t3 += v * b0;
- t4 += v * b1;
- t5 += v * b2;
- t6 += v * b3;
- t7 += v * b4;
- t8 += v * b5;
- t9 += v * b6;
- t10 += v * b7;
- t11 += v * b8;
- t12 += v * b9;
- t13 += v * b10;
- t14 += v * b11;
- t15 += v * b12;
- t16 += v * b13;
- t17 += v * b14;
- t18 += v * b15;
- v = a[4 +aoff];
- t4 += v * b0;
- t5 += v * b1;
- t6 += v * b2;
- t7 += v * b3;
- t8 += v * b4;
- t9 += v * b5;
- t10 += v * b6;
- t11 += v * b7;
- t12 += v * b8;
- t13 += v * b9;
- t14 += v * b10;
- t15 += v * b11;
- t16 += v * b12;
- t17 += v * b13;
- t18 += v * b14;
- t19 += v * b15;
- v = a[5 +aoff];
- t5 += v * b0;
- t6 += v * b1;
- t7 += v * b2;
- t8 += v * b3;
- t9 += v * b4;
- t10 += v * b5;
- t11 += v * b6;
- t12 += v * b7;
- t13 += v * b8;
- t14 += v * b9;
- t15 += v * b10;
- t16 += v * b11;
- t17 += v * b12;
- t18 += v * b13;
- t19 += v * b14;
- t20 += v * b15;
- v = a[6 +aoff];
- t6 += v * b0;
- t7 += v * b1;
- t8 += v * b2;
- t9 += v * b3;
- t10 += v * b4;
- t11 += v * b5;
- t12 += v * b6;
- t13 += v * b7;
- t14 += v * b8;
- t15 += v * b9;
- t16 += v * b10;
- t17 += v * b11;
- t18 += v * b12;
- t19 += v * b13;
- t20 += v * b14;
- t21 += v * b15;
- v = a[7 +aoff];
- t7 += v * b0;
- t8 += v * b1;
- t9 += v * b2;
- t10 += v * b3;
- t11 += v * b4;
- t12 += v * b5;
- t13 += v * b6;
- t14 += v * b7;
- t15 += v * b8;
- t16 += v * b9;
- t17 += v * b10;
- t18 += v * b11;
- t19 += v * b12;
- t20 += v * b13;
- t21 += v * b14;
- t22 += v * b15;
- v = a[8 +aoff];
- t8 += v * b0;
- t9 += v * b1;
- t10 += v * b2;
- t11 += v * b3;
- t12 += v * b4;
- t13 += v * b5;
- t14 += v * b6;
- t15 += v * b7;
- t16 += v * b8;
- t17 += v * b9;
- t18 += v * b10;
- t19 += v * b11;
- t20 += v * b12;
- t21 += v * b13;
- t22 += v * b14;
- t23 += v * b15;
- v = a[9 +aoff];
- t9 += v * b0;
- t10 += v * b1;
- t11 += v * b2;
- t12 += v * b3;
- t13 += v * b4;
- t14 += v * b5;
- t15 += v * b6;
- t16 += v * b7;
- t17 += v * b8;
- t18 += v * b9;
- t19 += v * b10;
- t20 += v * b11;
- t21 += v * b12;
- t22 += v * b13;
- t23 += v * b14;
- t24 += v * b15;
- v = a[10 +aoff];
- t10 += v * b0;
- t11 += v * b1;
- t12 += v * b2;
- t13 += v * b3;
- t14 += v * b4;
- t15 += v * b5;
- t16 += v * b6;
- t17 += v * b7;
- t18 += v * b8;
- t19 += v * b9;
- t20 += v * b10;
- t21 += v * b11;
- t22 += v * b12;
- t23 += v * b13;
- t24 += v * b14;
- t25 += v * b15;
- v = a[11 +aoff];
- t11 += v * b0;
- t12 += v * b1;
- t13 += v * b2;
- t14 += v * b3;
- t15 += v * b4;
- t16 += v * b5;
- t17 += v * b6;
- t18 += v * b7;
- t19 += v * b8;
- t20 += v * b9;
- t21 += v * b10;
- t22 += v * b11;
- t23 += v * b12;
- t24 += v * b13;
- t25 += v * b14;
- t26 += v * b15;
- v = a[12 +aoff];
- t12 += v * b0;
- t13 += v * b1;
- t14 += v * b2;
- t15 += v * b3;
- t16 += v * b4;
- t17 += v * b5;
- t18 += v * b6;
- t19 += v * b7;
- t20 += v * b8;
- t21 += v * b9;
- t22 += v * b10;
- t23 += v * b11;
- t24 += v * b12;
- t25 += v * b13;
- t26 += v * b14;
- t27 += v * b15;
- v = a[13 +aoff];
- t13 += v * b0;
- t14 += v * b1;
- t15 += v * b2;
- t16 += v * b3;
- t17 += v * b4;
- t18 += v * b5;
- t19 += v * b6;
- t20 += v * b7;
- t21 += v * b8;
- t22 += v * b9;
- t23 += v * b10;
- t24 += v * b11;
- t25 += v * b12;
- t26 += v * b13;
- t27 += v * b14;
- t28 += v * b15;
- v = a[14 +aoff];
- t14 += v * b0;
- t15 += v * b1;
- t16 += v * b2;
- t17 += v * b3;
- t18 += v * b4;
- t19 += v * b5;
- t20 += v * b6;
- t21 += v * b7;
- t22 += v * b8;
- t23 += v * b9;
- t24 += v * b10;
- t25 += v * b11;
- t26 += v * b12;
- t27 += v * b13;
- t28 += v * b14;
- t29 += v * b15;
- v = a[15 +aoff];
- t15 += v * b0;
- t16 += v * b1;
- t17 += v * b2;
- t18 += v * b3;
- t19 += v * b4;
- t20 += v * b5;
- t21 += v * b6;
- t22 += v * b7;
- t23 += v * b8;
- t24 += v * b9;
- t25 += v * b10;
- t26 += v * b11;
- t27 += v * b12;
- t28 += v * b13;
- t29 += v * b14;
- t30 += v * b15;
-
- t0 += 38 * t16;
- t1 += 38 * t17;
- t2 += 38 * t18;
- t3 += 38 * t19;
- t4 += 38 * t20;
- t5 += 38 * t21;
- t6 += 38 * t22;
- t7 += 38 * t23;
- t8 += 38 * t24;
- t9 += 38 * t25;
- t10 += 38 * t26;
- t11 += 38 * t27;
- t12 += 38 * t28;
- t13 += 38 * t29;
- t14 += 38 * t30;
- // t15 left as is
-
- // first car
- c = 1;
- v = t0 + c + 65535; c = v >> 16; t0 = v - c * 65536;
- v = t1 + c + 65535; c = v >> 16; t1 = v - c * 65536;
- v = t2 + c + 65535; c = v >> 16; t2 = v - c * 65536;
- v = t3 + c + 65535; c = v >> 16; t3 = v - c * 65536;
- v = t4 + c + 65535; c = v >> 16; t4 = v - c * 65536;
- v = t5 + c + 65535; c = v >> 16; t5 = v - c * 65536;
- v = t6 + c + 65535; c = v >> 16; t6 = v - c * 65536;
- v = t7 + c + 65535; c = v >> 16; t7 = v - c * 65536;
- v = t8 + c + 65535; c = v >> 16; t8 = v - c * 65536;
- v = t9 + c + 65535; c = v >> 16; t9 = v - c * 65536;
- v = t10 + c + 65535; c = v >> 16; t10 = v - c * 65536;
- v = t11 + c + 65535; c = v >> 16; t11 = v - c * 65536;
- v = t12 + c + 65535; c = v >> 16; t12 = v - c * 65536;
- v = t13 + c + 65535; c = v >> 16; t13 = v - c * 65536;
- v = t14 + c + 65535; c = v >> 16; t14 = v - c * 65536;
- v = t15 + c + 65535; c = v >> 16; t15 = v - c * 65536;
- t0 += c-1 + 37 * (c-1);
-
- // second car
- c = 1;
- v = t0 + c + 65535; c = v >> 16; t0 = v - c * 65536;
- v = t1 + c + 65535; c = v >> 16; t1 = v - c * 65536;
- v = t2 + c + 65535; c = v >> 16; t2 = v - c * 65536;
- v = t3 + c + 65535; c = v >> 16; t3 = v - c * 65536;
- v = t4 + c + 65535; c = v >> 16; t4 = v - c * 65536;
- v = t5 + c + 65535; c = v >> 16; t5 = v - c * 65536;
- v = t6 + c + 65535; c = v >> 16; t6 = v - c * 65536;
- v = t7 + c + 65535; c = v >> 16; t7 = v - c * 65536;
- v = t8 + c + 65535; c = v >> 16; t8 = v - c * 65536;
- v = t9 + c + 65535; c = v >> 16; t9 = v - c * 65536;
- v = t10 + c + 65535; c = v >> 16; t10 = v - c * 65536;
- v = t11 + c + 65535; c = v >> 16; t11 = v - c * 65536;
- v = t12 + c + 65535; c = v >> 16; t12 = v - c * 65536;
- v = t13 + c + 65535; c = v >> 16; t13 = v - c * 65536;
- v = t14 + c + 65535; c = v >> 16; t14 = v - c * 65536;
- v = t15 + c + 65535; c = v >> 16; t15 = v - c * 65536;
- t0 += c-1 + 37 * (c-1);
-
- o[ 0 +ooff] = t0;
- o[ 1 +ooff] = t1;
- o[ 2 +ooff] = t2;
- o[ 3 +ooff] = t3;
- o[ 4 +ooff] = t4;
- o[ 5 +ooff] = t5;
- o[ 6 +ooff] = t6;
- o[ 7 +ooff] = t7;
- o[ 8 +ooff] = t8;
- o[ 9 +ooff] = t9;
- o[10 +ooff] = t10;
- o[11 +ooff] = t11;
- o[12 +ooff] = t12;
- o[13 +ooff] = t13;
- o[14 +ooff] = t14;
- o[15 +ooff] = t15;
- }
-
- private static void S(
- long [] o,
- long [] a)
- {
- S(o,0, a,0);
- }
- private static void S(
- long [] o,final int ooff,
- long [] a,final int aoff)
- {
- M(o,ooff, a,aoff, a,aoff);
- }
-
- private static void inv25519(
- long [] o,final int ooff,
- long [] i,final int ioff)
- {
- long [] c = new long[16];
- int a;
- for (a = 0; a < 16; a++) c[a] = i[a+ioff];
- for (a = 253; a >= 0; a--) {
- S(c,0, c,0);
- if(a != 2 && a != 4) M(c,0, c,0, i,ioff);
- }
- for (a = 0; a < 16; a++) o[a+ooff] = c[a];
-}
-
- private static void pow2523(long [] o,long [] i)
- {
- long [] c = new long[16];
- int a;
-
- for (a = 0; a < 16; a ++) c[a]=i[a];
-
- for(a=250;a>=0;a--) {
- S(c,0, c,0);
- if(a!=1) M(c,0, c,0, i,0);
- }
-
- for (a = 0; a < 16; a ++) o[a]=c[a];
- }
-
- public static int crypto_scalarmult(byte []q,byte []n,byte []p)
- {
- byte [] z = new byte[32];
- long [] x = new long[80];
- int r, i;
- long [] a = new long[16], b = new long[16], c = new long[16],
- d = new long[16], e = new long[16], f = new long[16];
- for (i = 0; i < 31; i++) z[i] = n[i];
- z[31]=(byte) (((n[31]&127)|64) & 0xff);
- z[0]&=248;
- unpack25519(x,p);
- for (i = 0; i < 16; i++) {
- b[i]=x[i];
- d[i]=a[i]=c[i]=0;
- }
- a[0]=d[0]=1;
- for (i=254;i>=0;--i) {
- r=(z[i>>>3]>>>(i&7))&1;
- sel25519(a,b,r);
- sel25519(c,d,r);
- A(e,a,c);
- Z(a,a,c);
- A(c,b,d);
- Z(b,b,d);
- S(d,e);
- S(f,a);
- M(a,c,a);
- M(c,b,e);
- A(e,a,c);
- Z(a,a,c);
- S(b,a);
- Z(c,d,f);
- M(a,c,_121665);
- A(a,a,d);
- M(c,c,a);
- M(a,d,f);
- M(d,b,x);
- S(b,e);
- sel25519(a,b,r);
- sel25519(c,d,r);
- }
- for (i = 0; i < 16; i++) {
- x[i+16]=a[i];
- x[i+32]=c[i];
- x[i+48]=b[i];
- x[i+64]=d[i];
- }
- inv25519(x,32, x,32);
- M(x,16, x,16, x,32);
- pack25519(q, x,16);
-
- return 0;
-}
-
- public static int crypto_scalarmult_base(byte []q,byte []n)
- {
- return crypto_scalarmult(q,n,_9);
- }
-
- public static int crypto_box_keypair(byte [] y, byte [] x)
- {
- randombytes(x,32);
- return crypto_scalarmult_base(y,x);
- }
-
- public static int crypto_box_beforenm(byte []k,byte []y,byte []x)
- {
- byte[] s = new byte[32];
- crypto_scalarmult(s,x,y);
-
- /*String dbgt = "";
- for (int dbg = 0; dbg < s.length; dbg ++) dbgt += " "+s[dbg];
- Log.d(TAG, "crypto_box_beforenm -> "+dbgt);
-
- dbgt = "";
- for (int dbg = 0; dbg < x.length; dbg ++) dbgt += " "+x[dbg];
- Log.d(TAG, "crypto_box_beforenm, x -> "+dbgt);
-
- dbgt = "";
- for (int dbg = 0; dbg < y.length; dbg ++) dbgt += " "+y[dbg];
- Log.d(TAG, "crypto_box_beforenm, y -> "+dbgt);
- */
-
- return crypto_core_hsalsa20(k, _0, s, sigma);
- }
-
- public static int crypto_box_afternm(byte []c,byte []m,int /*long*/ d,byte []n,byte []k)
- {
- return crypto_secretbox(c,m,d,n,k);
- }
-
- public static int crypto_box_open_afternm(byte []m,byte []c,int /*long*/ d,byte []n,byte []k)
- {
- return crypto_secretbox_open(m,c,d,n,k);
- }
-
- public static int crypto_box(byte []c,byte []m,int /*long*/ d,byte []n,byte []y,byte []x)
- {
- byte[] k = new byte[32];
-
- ///L/og.d(TAG, "crypto_box start ...");
-
- crypto_box_beforenm(k,y,x);
- return crypto_box_afternm(c,m,d,n,k);
- }
-
- public static int crypto_box_open(byte []m,byte []c,int /*long*/ d,byte []n,byte []y,byte []x)
- {
- byte[] k = new byte[32];
- crypto_box_beforenm(k,y,x);
- return crypto_box_open_afternm(m,c,d,n,k);
- }
-
- private static final long K[] = {
- 0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL,
- 0x3956c25bf348b538L, 0x59f111f1b605d019L, 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L,
- 0xd807aa98a3030242L, 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
- 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L, 0xc19bf174cf692694L,
- 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L, 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L,
- 0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
- 0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L,
- 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L, 0x06ca6351e003826fL, 0x142929670a0e6e70L,
- 0x27b70a8546d22ffcL, 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
- 0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L, 0x92722c851482353bL,
- 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L, 0xc24b8b70d0f89791L, 0xc76c51a30654be30L,
- 0xd192e819d6ef5218L, 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
- 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L,
- 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL, 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L,
- 0x748f82ee5defb2fcL, 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
- 0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL,
- 0xca273eceea26619cL, 0xd186b8c721c0c207L, 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L,
- 0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL,
- 0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL,
- 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL, 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L
- };
-
- private static int crypto_hashblocks_hl(int [] hh,int [] hl, byte [] m,final int moff, int n) {
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < n; dbg ++) dbgt += " "+m[dbg+moff];
- ///Log.d(TAG, "crypto_hashblocks_hl m/"+n + "-> "+dbgt);
-
- int [] wh = new int[16], wl = new int[16];
- int bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
- bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
- th, tl, h, l, i, j, a, b, c, d;
-
- int ah0 = hh[0],
- ah1 = hh[1],
- ah2 = hh[2],
- ah3 = hh[3],
- ah4 = hh[4],
- ah5 = hh[5],
- ah6 = hh[6],
- ah7 = hh[7],
-
- al0 = hl[0],
- al1 = hl[1],
- al2 = hl[2],
- al3 = hl[3],
- al4 = hl[4],
- al5 = hl[5],
- al6 = hl[6],
- al7 = hl[7];
-
- int pos = 0;
- while (n >= 128) {
- for (i = 0; i < 16; i++) {
- j = 8 * i + pos;
- wh[i] = ((m[j+0+moff]&0xff) << 24) | ((m[j+1+moff]&0xff) << 16) | ((m[j+2+moff]&0xff) << 8) | ((m[j+3+moff]&0xff) << 0);
- wl[i] = ((m[j+4+moff]&0xff) << 24) | ((m[j+5+moff]&0xff) << 16) | ((m[j+6+moff]&0xff) << 8) | ((m[j+7+moff]&0xff) << 0);
- }
- for (i = 0; i < 80; i++) {
- bh0 = ah0;
- bh1 = ah1;
- bh2 = ah2;
- bh3 = ah3;
- bh4 = ah4;
- bh5 = ah5;
- bh6 = ah6;
- bh7 = ah7;
-
- bl0 = al0;
- bl1 = al1;
- bl2 = al2;
- bl3 = al3;
- bl4 = al4;
- bl5 = al5;
- bl6 = al6;
- bl7 = al7;
-
- // add
- h = ah7;
- l = al7;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- // Sigma1
- h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
- l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- // Ch
- h = (ah4 & ah5) ^ (~ah4 & ah6);
- l = (al4 & al5) ^ (~al4 & al6);
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- // K
- ///h = K[i*2];
- ///l = K[i*2+1];
- h = (int) ((K[i]>>>32) & 0xffffffff);
- l = (int) ((K[i]>>> 0) & 0xffffffff);
-
- ///Log.d(TAG, "i"+i + ",h:0x"+Integer.toHexString(h) + ",l:0x"+Integer.toHexString(l));
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- // w
- h = wh[i%16];
- l = wl[i%16];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- th = c & 0xffff | d << 16;
- tl = a & 0xffff | b << 16;
-
- // add
- h = th;
- l = tl;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- // Sigma0
- h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
- l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- // Maj
- h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
- l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- bh7 = (c & 0xffff) | (d << 16);
- bl7 = (a & 0xffff) | (b << 16);
-
- // add
- h = bh3;
- l = bl3;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = th;
- l = tl;
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- bh3 = (c & 0xffff) | (d << 16);
- bl3 = (a & 0xffff) | (b << 16);
-
- ah1 = bh0;
- ah2 = bh1;
- ah3 = bh2;
- ah4 = bh3;
- ah5 = bh4;
- ah6 = bh5;
- ah7 = bh6;
- ah0 = bh7;
-
- al1 = bl0;
- al2 = bl1;
- al3 = bl2;
- al4 = bl3;
- al5 = bl4;
- al6 = bl5;
- al7 = bl6;
- al0 = bl7;
-
- if (i%16 == 15) {
- for (j = 0; j < 16; j++) {
- // add
- h = wh[j];
- l = wl[j];
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = wh[(j+9)%16];
- l = wl[(j+9)%16];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- // sigma0
- th = wh[(j+1)%16];
- tl = wl[(j+1)%16];
- h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
- l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- // sigma1
- th = wh[(j+14)%16];
- tl = wl[(j+14)%16];
- h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
- l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- wh[j] = (c & 0xffff) | (d << 16);
- wl[j] = (a & 0xffff) | (b << 16);
- }
- }
- }
-
- // add
- h = ah0;
- l = al0;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[0];
- l = hl[0];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[0] = ah0 = (c & 0xffff) | (d << 16);
- hl[0] = al0 = (a & 0xffff) | (b << 16);
-
- h = ah1;
- l = al1;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[1];
- l = hl[1];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[1] = ah1 = (c & 0xffff) | (d << 16);
- hl[1] = al1 = (a & 0xffff) | (b << 16);
-
- h = ah2;
- l = al2;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[2];
- l = hl[2];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[2] = ah2 = (c & 0xffff) | (d << 16);
- hl[2] = al2 = (a & 0xffff) | (b << 16);
-
- h = ah3;
- l = al3;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[3];
- l = hl[3];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[3] = ah3 = (c & 0xffff) | (d << 16);
- hl[3] = al3 = (a & 0xffff) | (b << 16);
-
- h = ah4;
- l = al4;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[4];
- l = hl[4];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[4] = ah4 = (c & 0xffff) | (d << 16);
- hl[4] = al4 = (a & 0xffff) | (b << 16);
-
- h = ah5;
- l = al5;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[5];
- l = hl[5];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[5] = ah5 = (c & 0xffff) | (d << 16);
- hl[5] = al5 = (a & 0xffff) | (b << 16);
-
- h = ah6;
- l = al6;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[6];
- l = hl[6];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[6] = ah6 = (c & 0xffff) | (d << 16);
- hl[6] = al6 = (a & 0xffff) | (b << 16);
-
- h = ah7;
- l = al7;
-
- a = l & 0xffff; b = l >>> 16;
- c = h & 0xffff; d = h >>> 16;
-
- h = hh[7];
- l = hl[7];
-
- a += l & 0xffff; b += l >>> 16;
- c += h & 0xffff; d += h >>> 16;
-
- b += a >>> 16;
- c += b >>> 16;
- d += c >>> 16;
-
- hh[7] = ah7 = (c & 0xffff) | (d << 16);
- hl[7] = al7 = (a & 0xffff) | (b << 16);
-
- pos += 128;
- n -= 128;
-
- /*dbgt = "";
- for (int dbg = 0; dbg < hh.length; dbg ++) dbgt += " "+hh[dbg];
- Log.d(TAG, "\ncrypto_hashblocks_hl hh -> "+dbgt);
-
- dbgt = "";
- for (int dbg = 0; dbg < hl.length; dbg ++) dbgt += " "+hl[dbg];
- Log.d(TAG, "\ncrypto_hashblocks_hl hl -> "+dbgt);*/
- }
-
- return n;
- }
-
- // TBD 64bits of n
- ///int crypto_hash(byte [] out, byte [] m, long n)
- public static int crypto_hash(byte [] out, byte [] m,final int moff, int n)
- {
- int [] hh = new int[8],
- hl = new int[8];
- byte [] x = new byte[256];
- int i, b = n;
- long u;
-
- hh[0] = 0x6a09e667;
- hh[1] = 0xbb67ae85;
- hh[2] = 0x3c6ef372;
- hh[3] = 0xa54ff53a;
- hh[4] = 0x510e527f;
- hh[5] = 0x9b05688c;
- hh[6] = 0x1f83d9ab;
- hh[7] = 0x5be0cd19;
-
- hl[0] = 0xf3bcc908;
- hl[1] = 0x84caa73b;
- hl[2] = 0xfe94f82b;
- hl[3] = 0x5f1d36f1;
- hl[4] = 0xade682d1;
- hl[5] = 0x2b3e6c1f;
- hl[6] = 0xfb41bd6b;
- hl[7] = 0x137e2179;
-
- if (n >= 128) {
- crypto_hashblocks_hl(hh, hl, m,moff, n);
- n %= 128;
- }
-
- for (i = 0; i < n; i++) x[i] = m[b-n+i +moff];
- x[n] = (byte) 128;
-
- n = 256-128*(n<112?1:0);
- x[n-9] = 0;
-
- ts64(x, n-8, b<<3/*(b / 0x20000000) | 0, b << 3*/);
-
- crypto_hashblocks_hl(hh, hl, x,0, n);
-
- for (i = 0; i < 8; i++) {
- u = hh[i]; u <<= 32; u |= hl[i]&0xffffffffL;
- ts64(out, 8*i, u);
- }
-
- return 0;
- }
- public static int crypto_hash(byte [] out, byte [] m) {
- return crypto_hash(out, m,0, m!=null? m.length : 0);
- }
-
- // gf: long[16]
- ///private static void add(gf p[4],gf q[4])
- private static void add(long [] p[], long [] q[])
- {
- long [] a = new long[16];
- long [] b = new long[16];
- long [] c = new long[16];
- long [] d = new long[16];
- long [] t = new long[16];
- long [] e = new long[16];
- long [] f = new long[16];
- long [] g = new long[16];
- long [] h = new long[16];
-
-
- long [] p0 = p[0];
- long [] p1 = p[1];
- long [] p2 = p[2];
- long [] p3 = p[3];
-
- long [] q0 = q[0];
- long [] q1 = q[1];
- long [] q2 = q[2];
- long [] q3 = q[3];
-
- Z(a,0, p1,0, p0,0);
- Z(t,0, q1,0, q0,0);
- M(a,0, a,0, t,0);
- A(b,0, p0,0, p1,0);
- A(t,0, q0,0, q1,0);
- M(b,0, b,0, t,0);
- M(c,0, p3,0, q3,0);
- M(c,0, c,0, D2,0);
- M(d,0, p2,0, q2,0);
-
- A(d,0, d,0, d,0);
- Z(e,0, b,0, a,0);
- Z(f,0, d,0, c,0);
- A(g,0, d,0, c,0);
- A(h,0, b,0, a,0);
-
- M(p0,0, e,0, f,0);
- M(p1,0, h,0, g,0);
- M(p2,0, g,0, f,0);
- M(p3,0, e,0, h,0);
- }
-
- private static void cswap(long [] p[], long [] q[], byte b)
- {
- int i;
-
- for (i = 0; i < 4; i ++)
- sel25519(p[i],0, q[i],0, b);
- }
-
- private static void pack(byte [] r, long [] p[])
- {
- long [] tx = new long[16];
- long [] ty = new long[16];
- long [] zi = new long[16];
-
- inv25519(zi,0, p[2],0);
-
- M(tx,0, p[0],0, zi,0);
- M(ty,0, p[1],0, zi,0);
-
- pack25519(r, ty,0);
-
- r[31] ^= par25519(tx,0) << 7;
- }
-
- private static void scalarmult(long [] p[], long [] q[], byte[] s,final int soff)
- {
- int i;
-
- set25519(p[0],gf0);
- set25519(p[1],gf1);
- set25519(p[2],gf1);
- set25519(p[3],gf0);
-
- for (i = 255;i >= 0;--i) {
- byte b = (byte) ((s[i/8+soff] >>> (i&7))&1);
-
- cswap(p,q,b);
- add(q,p);
- add(p,p);
- cswap(p,q,b);
- }
-
- ///String dbgt = "";
- ///for (int dbg = 0; dbg < p.length; dbg ++) for (int dd = 0; dd < p[dbg].length; dd ++) dbgt += " "+p[dbg][dd];
- ///L/og.d(TAG, "scalarmult -> "+dbgt);
- }
-
- private static void scalarbase(long [] p[], byte[] s,final int soff)
- {
- long [] [] q = new long [4] [];
-
- q[0] = new long [16];
- q[1] = new long [16];
- q[2] = new long [16];
- q[3] = new long [16];
-
- set25519(q[0],X);
- set25519(q[1],Y);
- set25519(q[2],gf1);
- M(q[3],0, X,0, Y,0);
- scalarmult(p,q, s,soff);
- }
-
- public static int crypto_sign_keypair(byte [] pk, byte [] sk, boolean seeded) {
- byte [] d = new byte[64];
- long [] [] p = new long [4] [];
-
- p[0] = new long [16];
- p[1] = new long [16];
- p[2] = new long [16];
- p[3] = new long [16];
-
- int i;
-
- if (!seeded) randombytes(sk, 32);
- crypto_hash(d, sk,0, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- scalarbase(p, d,0);
- pack(pk, p);
-
- for (i = 0; i < 32; i++) sk[i+32] = pk[i];
- return 0;
- }
-
- private static final long L[] = {
- 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
- 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0x10
- };
-
- private static void modL(byte[] r,final int roff, long x[])
- {
- long carry;
- int i, j;
-
- for (i = 63;i >= 32;--i) {
- carry = 0;
- for (j = i - 32;j < i - 12;++j) {
- x[j] += carry - 16 * x[i] * L[j - (i - 32)];
- carry = (x[j] + 128) >> 8;
- x[j] -= carry << 8;
- }
- x[j] += carry;
- x[i] = 0;
- }
- carry = 0;
-
- for (j = 0; j < 32; j ++) {
- x[j] += carry - (x[31] >> 4) * L[j];
- carry = x[j] >> 8;
- x[j] &= 255;
- }
-
- for (j = 0; j < 32; j ++) x[j] -= carry * L[j];
-
- for (i = 0; i < 32; i ++) {
- x[i+1] += x[i] >> 8;
- r[i+roff] = (byte) (x[i] & 255);
- }
- }
-
- private static void reduce(byte [] r)
- {
- long[] x = new long [64];
- int i;
-
- for (i = 0; i < 64; i ++) x[i] = (long) (r[i]&0xff);
-
- for (i = 0; i < 64; i ++) r[i] = 0;
-
- modL(r,0, x);
- }
-
- // TBD... 64bits of n
- ///int crypto_sign(byte [] sm, long * smlen, byte [] m, long n, byte [] sk)
- public static int crypto_sign(byte [] sm, long dummy /* *smlen not used*/, byte [] m,final int moff, int/*long*/ n, byte [] sk)
- {
- byte[] d = new byte[64], h = new byte[64], r = new byte[64];
-
- int i, j;
- long [] x = new long[64];
-
- long [] [] p = new long [4] [];
- p[0] = new long [16];
- p[1] = new long [16];
- p[2] = new long [16];
- p[3] = new long [16];
-
- crypto_hash(d, sk,0, 32);
- d[0] &= 248;
- d[31] &= 127;
- d[31] |= 64;
-
- ///*smlen = n+64;
-
- for (i = 0; i < n; i ++) sm[64 + i] = m[i+moff];
-
- for (i = 0; i < 32; i ++) sm[32 + i] = d[32 + i];
-
- crypto_hash(r, sm,32, n+32);
- reduce(r);
- scalarbase(p, r,0);
- pack(sm,p);
-
- for (i = 0; i < 32; i ++) sm[i+32] = sk[i+32];
- crypto_hash(h, sm,0, n + 64);
- reduce(h);
-
- for (i = 0; i < 64; i ++) x[i] = 0;
-
- for (i = 0; i < 32; i ++) x[i] = (long) (r[i]&0xff);
-
- for (i = 0; i < 32; i ++) for (j = 0; j < 32; j ++) x[i+j] += (h[i]&0xff) * (long) (d[j]&0xff);
-
- modL(sm,32, x);
-
- return 0;
- }
-
- private static int unpackneg(long [] r[], byte p[])
- {
- long [] t = new long [16];
- long [] chk = new long [16];
- long [] num = new long [16];
- long [] den = new long [16];
- long [] den2 = new long [16];
- long [] den4 = new long [16];
- long [] den6 = new long [16];
-
- set25519(r[2], gf1);
- unpack25519(r[1], p);
- S(num, r[1]);
- M(den, num, D);
- Z(num, num, r[2]);
- A(den, r[2], den);
-
- S(den2, den);
- S(den4, den2);
- M(den6, den4, den2);
- M(t, den6, num);
- M(t, t, den);
-
- pow2523(t, t);
- M(t, t, num);
- M(t, t, den);
- M(t, t, den);
- M(r[0], t, den);
-
- S(chk, r[0]);
- M(chk, chk, den);
- if (neq25519(chk, num)!=0) M(r[0], r[0], I);
-
- S(chk, r[0]);
- M(chk, chk, den);
- if (neq25519(chk, num)!=0) return -1;
-
- if (par25519(r[0]) == (p[31]>>>7)) Z(r[0], gf0, r[0]);
-
- M(r[3], r[0], r[1]);
-
- return 0;
- }
-
- /// TBD 64bits of mlen
- ///int crypto_sign_open(byte []m,long *mlen,byte []sm,long n,byte []pk)
- public static int crypto_sign_open(byte [] m, long dummy /* *mlen not used*/, byte [] sm,final int smoff, int/*long*/ n, byte []pk)
- {
- int i;
- byte[] t = new byte[32], h = new byte[64];
-
- long [] [] p = new long [4] [];
- p[0] = new long [16];
- p[1] = new long [16];
- p[2] = new long [16];
- p[3] = new long [16];
-
- long [] [] q = new long [4] [];
- q[0] = new long [16];
- q[1] = new long [16];
- q[2] = new long [16];
- q[3] = new long [16];
-
- ///*mlen = -1;
-
- if (n < 64) return -1;
-
- if (unpackneg(q,pk)!=0) return -1;
-
- for (i = 0; i < n; i ++) m[i] = sm[i+smoff];
-
- for (i = 0; i < 32; i ++) m[i+32] = pk[i];
-
- crypto_hash(h, m,0, n);
-
- reduce(h);
- scalarmult(p,q, h,0);
-
- scalarbase(q, sm,32+smoff);
- add(p,q);
- pack(t,p);
-
- n -= 64;
- if (crypto_verify_32(sm,smoff, t,0)!=0) {
- // optimizing it
- ///for (i = 0; i < n; i ++) m[i] = 0;
- return -1;
- }
-
- // TBD optimizing ...
- ///for (i = 0; i < n; i ++) m[i] = sm[i + 64 + smoff];
- ///*mlen = n;
-
- return 0;
- }
-
- /*
- * @description
- * Java SecureRandom generator
- * */
- private static final SecureRandom jrandom = new SecureRandom();
-
- public static byte[] randombytes(byte [] x) {
- jrandom.nextBytes(x);
- return x;
- }
-
- public static byte[] randombytes(int len) {
- return randombytes(new byte[len]);
- }
-
- public static byte[] randombytes(byte [] x, int len) {
- byte [] b = randombytes(len);
- System.arraycopy(b, 0, x, 0, len);
- return x;
- }
-
-/*
- public static byte[] randombytes(byte [] x, int len) {
- int ret = len % 8;
- long rnd;
-
- for (int i = 0; i < len-ret; i += 8) {
- rnd = jrandom.nextLong();
-
- x[i+0] = (byte) (rnd >>> 0);
- x[i+1] = (byte) (rnd >>> 8);
- x[i+2] = (byte) (rnd >>> 16);
- x[i+3] = (byte) (rnd >>> 24);
- x[i+4] = (byte) (rnd >>> 32);
- x[i+5] = (byte) (rnd >>> 40);
- x[i+6] = (byte) (rnd >>> 48);
- x[i+7] = (byte) (rnd >>> 56);
- }
-
- if (ret > 0) {
- rnd = jrandom.nextLong();
- for (int i = len-ret; i < len; i ++)
- x[i] = (byte) (rnd >>> 8*i);
- }
- return x;
- }
-*/
-
- public static byte[] makeBoxNonce() {
- return randombytes(Box.nonceLength);
- }
-
- public static byte[] makeSecretBoxNonce() {
- return randombytes(SecretBox.nonceLength);
- }
-
- public static String base64EncodeToString(byte [] b) {
- return Base64.encodeToString(b, Base64.NO_PADDING);
- }
- // byte[] Base64.getUrlEncoder().withoutPadding().encode(b);
-
- public static byte[] base64Decode(String s) {
- return Base64.decode(s, Base64.NO_PADDING);
- }
- // byte[] Base64.getUrlDecoder().decode(byte[] b)
-
- public static String hexEncodeToString( byte [] raw ) {
- String HEXES = "0123456789ABCDEF";
- final StringBuilder hex = new StringBuilder( 2 * raw.length );
- for ( final byte b : raw ) {
- hex.append(HEXES.charAt((b & 0xF0) >> 4))
- .append(HEXES.charAt((b & 0x0F)));
- }
- return hex.toString();
- }
-
- public static byte[] hexDecode(String s) {
- byte[] b = new byte[s.length() / 2];
- for (int i = 0; i < s.length(); i += 2) {
- b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
- + Character.digit(s.charAt(i+1), 16));
- }
- return b;
- }
-
- // public static boolean java.util.Arrays.equals(array1, array2);
-
-}
diff --git a/app/src/main/java/com/iwebpp/crypto/tests/NaclCertTest.java b/app/src/main/java/com/iwebpp/crypto/tests/NaclCertTest.java
deleted file mode 100644
index 2f256c4..0000000
--- a/app/src/main/java/com/iwebpp/crypto/tests/NaclCertTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package com.iwebpp.crypto.tests;
-
-import java.util.ArrayList;
-
-import com.iwebpp.crypto.NaclCert;
-import com.iwebpp.crypto.TweetNaclFast;
-
-import android.util.Log;
-
-import junit.framework.TestCase;
-
-public final class NaclCertTest extends TestCase {
- private static final String TAG = "NaclCertTest";
-
- public void testSelfCert() throws Exception {
-
- NaclCert.CAInfo info = new NaclCert.CAInfo();
-
- info.ca = "iwebpp.com";
- info.tte = System.currentTimeMillis() + 3600000L*24*365000;
- NaclCert.CAInfo ca = NaclCert.generateCA(info);
- Log.d(TAG, "\n\ttestSelfCert/ca:"+ca.toString());
-
- // verify self-cert
- if (!NaclCert.validate(info.cert)) {
- Log.e(TAG, "\n\ttestSelfCert/ca verify failed\n");
- } else
- Log.d(TAG, "\n\ttestSelfCert/cert verify success\n");
-
- assertTrue (NaclCert.validate(info.cert));
- }
-
- public void testCaCert() throws Exception {
- NaclCert.CAInfo info = new NaclCert.CAInfo();
-
- info.ca = "iwebpp.com";
- info.tte = System.currentTimeMillis() + 3600000L*24*365000;
- NaclCert.CAInfo ca = NaclCert.generateCA(info);
- if (info.tte != (info.tte&0xffffffffffffL)) {
- Log.w(TAG, "tte overflow: "+info.tte);
- }
-
- // Generate Nacl Box keypair
- TweetNaclFast.Box.KeyPair bkp = TweetNaclFast.Box.keyPair();
-
- // prepare reqdesc
- NaclCert.ReqDescSignByCa desc = new NaclCert.ReqDescSignByCa();
- desc.version = "1.0";
- desc.type = "ca";
- desc.tte = System.currentTimeMillis() + 3600000L*24*365;
- desc.publickey = bkp.getPublicKey();
-
- // domains
- desc.names = new ArrayList();
- desc.names.add("51dese.com");
- desc.names.add("ruyier.com");
-
- // ips
- desc.ips = new ArrayList();
- desc.ips.add("127.0.0.1");
- desc.ips.add("10.1.1.1");
-
- NaclCert.Cert cert = NaclCert.generate(desc, ca.secretkey, ca.cert);
- if (cert!=null)
- Log.d(TAG, "\n\ttestCaCert/cert:"+cert.stringify());
- else {
- Log.d(TAG, "\n\ttestCaCert/cert generate failed");
- }
-
- assert cert != null;
-
- // validate cert
- if (!NaclCert.validate(cert, ca.cert)) {
- Log.e(TAG, "\n\ttestCaCert/cert verify failed\n");
- } else
- Log.d(TAG, "\n\ttestCaCert/cert verify success\n");
-
- assertTrue (NaclCert.validate(cert, ca.cert));
-
- // expect fail
- NaclCert.CAInfo info2 = new NaclCert.CAInfo();
-
- info2.ca = "iwebpp.com";
- info2.tte = System.currentTimeMillis() + 3600000L*24*365000;
- NaclCert.CAInfo ca2 = NaclCert.generateCA(info2);
- Log.d(TAG, "\nCA1.cert:"+ca.cert.toJSON().toString());
- Log.d(TAG, "\nCA2.cert:"+ca2.cert.toJSON().toString());
-
- // validate cert
- if (NaclCert.validate(cert, ca2.cert)) {
- Log.e(TAG, "\n\ttestCaCert/cert verify faked\n");
- } else
- Log.d(TAG, "\n\ttestCaCert/cert verify success\n");
-
- assertFalse (NaclCert.validate(cert, ca2.cert));
- }
-}
diff --git a/app/src/main/java/com/iwebpp/crypto/tests/TweetNaclFastTest.java b/app/src/main/java/com/iwebpp/crypto/tests/TweetNaclFastTest.java
deleted file mode 100755
index 4d1ecc7..0000000
--- a/app/src/main/java/com/iwebpp/crypto/tests/TweetNaclFastTest.java
+++ /dev/null
@@ -1,566 +0,0 @@
-package com.iwebpp.crypto.tests;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import android.util.Log;
-
-import com.iwebpp.crypto.TweetNaclFast;
-
-public final class TweetNaclFastTest {
- private static final String TAG = "TweetNaclFastTest";
-
- /**
- * Curve25519 test vectors to help ensure correctness and interoperability
- * copied from Kalium project (https://github.com/abstractj/kalium)
- */
-
- public static final String BOB_PRIVATE_KEY = "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb";
- public static final String BOB_PUBLIC_KEY = "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f";
-
- public static final String ALICE_PRIVATE_KEY = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a";
- public static final String ALICE_PUBLIC_KEY = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a";
- public static final String ALICE_MULT_BOB = "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
-
- public static final String BOX_NONCE = "69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37";
- public static final String BOX_MESSAGE = "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffc" +
- "e5ecbaaf33bd751a1ac728d45e6c61296cdc3c01233561f41db66cce314adb31" +
- "0e3be8250c46f06dceea3a7fa1348057e2f6556ad6b1318a024a838f21af1fde" +
- "048977eb48f59ffd4924ca1c60902e52f0a089bc76897040e082f93776384864" +
- "5e0705";
- public static final String BOX_CIPHERTEXT = "f3ffc7703f9400e52a7dfb4b3d3305d98e993b9f48681273c29650ba32fc76ce" +
- "48332ea7164d96a4476fb8c531a1186ac0dfc17c98dce87b4da7f011ec48c972" +
- "71d2c20f9b928fe2270d6fb863d51738b48eeee314a7cc8ab932164548e526ae" +
- "90224368517acfeabd6bb3732bc0e9da99832b61ca01b6de56244a9e88d5f9b3" +
- "7973f622a43d14a6599b1f654cb45a74e355a5";
-
- public static final String SECRET_KEY = "1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389";
-
- public static final String SIGN_PRIVATE = "b18e1d0045995ec3d010c387ccfeb984d783af8fbb0f40fa7db126d889f6dadd";
- public static final String SIGN_MESSAGE = "916c7d1d268fc0e77c1bef238432573c39be577bbea0998936add2b50a653171" +
- "ce18a542b0b7f96c1691a3be6031522894a8634183eda38798a0c5d5d79fbd01" +
- "dd04a8646d71873b77b221998a81922d8105f892316369d5224c9983372d2313" +
- "c6b1f4556ea26ba49d46e8b561e0fc76633ac9766e68e21fba7edca93c4c7460" +
- "376d7f3ac22ff372c18f613f2ae2e856af40";
- public static final String SIGN_SIGNATURE = "6bd710a368c1249923fc7a1610747403040f0cc30815a00f9ff548a896bbda0b" +
- "4eb2ca19ebcf917f0f34200a9edbad3901b64ab09cc5ef7b9bcc3c40c0ff7509";
- public static final String SIGN_PUBLIC = "77f48b59caeda77751ed138b0ec667ff50f8768c25d48309a8f386a2bad187fb";
-
- private boolean testBoxKalium() throws UnsupportedEncodingException {
-
- Log.d(TAG, "testBoxKalium: test vectors from Kalium project");
-
- // explicit nonce
- byte [] theNonce = TweetNaclFast.hexDecode(BOX_NONCE);
- Log.d(TAG, "BOX_NONCE: " + "\"" + TweetNaclFast.hexEncodeToString(theNonce) + "\"");
-
-
- // keypair A
- byte [] ska = TweetNaclFast.hexDecode(ALICE_PRIVATE_KEY);
- TweetNaclFast.Box.KeyPair ka = TweetNaclFast.Box.keyPair_fromSecretKey(ska);
-
- Log.d(TAG, "ska: " + "\"" + TweetNaclFast.hexEncodeToString(ka.getSecretKey()) + "\"");
- Log.d(TAG, "pka: " + "\"" + TweetNaclFast.hexEncodeToString(ka.getPublicKey()) + "\"");
-
- // keypair B
- byte [] skb = TweetNaclFast.hexDecode(BOB_PRIVATE_KEY);
- TweetNaclFast.Box.KeyPair kb = TweetNaclFast.Box.keyPair_fromSecretKey(skb);
-
- Log.d(TAG, "skb: " + "\"" + TweetNaclFast.hexEncodeToString(kb.getSecretKey()) + "\"");
- Log.d(TAG, "pkb: " + "\"" + TweetNaclFast.hexEncodeToString(kb.getPublicKey()) + "\"");
-
- // peer A -> B
- TweetNaclFast.Box pabFast = new TweetNaclFast.Box(kb.getPublicKey(), ka.getSecretKey());
-
- // peer B -> A
- TweetNaclFast.Box pbaFast = new TweetNaclFast.Box(ka.getPublicKey(), kb.getSecretKey());
-
- // messages
-
- Log.d(TAG, "BOX_MESSAGE: \n" + BOX_MESSAGE.toUpperCase());
- Log.d(TAG, "BOX_CIPHERTEXT: \n" + BOX_CIPHERTEXT.toUpperCase());
-
- // cipher A -> B
- byte [] cabFast = pabFast.box(TweetNaclFast.hexDecode(BOX_MESSAGE), theNonce);
- Log.d(TAG, "cabFast: \n" + TweetNaclFast.hexEncodeToString(cabFast));
-
- if(BOX_CIPHERTEXT.toUpperCase().equals(TweetNaclFast.hexEncodeToString(cabFast))) {
- Log.d(TAG, "\n TweetNaclFast is compatible with Kalium test vector for Box::box");
- } else {
- Log.d(TAG, "\n\n!!! TweetNaclFast Box::box/open failed Kalium compatibility !!!\n");
- return false;
- }
-
- byte [] mbaFastFast = pbaFast.open(cabFast, theNonce);
- Log.d(TAG, "mbaFastFast: \n" + TweetNaclFast.hexEncodeToString(mbaFastFast));
-
- if(BOX_MESSAGE.toUpperCase().equals(TweetNaclFast.hexEncodeToString(mbaFastFast))) {
- Log.d(TAG, "\n TweetNaclFast is compatible with Kalium test vector for Box::open");
- } else {
- Log.d(TAG, "\n\n!!! TweetNaclFast Box::box/open failed Kalium compatibility !!!\n");
- return false;
- }
-
- return true;
- }
-
-
- private boolean testBox() throws UnsupportedEncodingException {
- // keypair A
- byte [] ska = new byte[32]; for (int i = 0; i < 32; i ++) ska[i] = 0;
- TweetNaclFast.Box.KeyPair ka = TweetNaclFast.Box.keyPair_fromSecretKey(ska);
-
- String skat = "";
- for (int i = 0; i < ka.getSecretKey().length; i ++)
- skat += " "+ka.getSecretKey()[i];
- Log.d(TAG, "skat: "+skat);
-
-
- String pkat = "";
- for (int i = 0; i < ka.getPublicKey().length; i ++)
- pkat += " "+ka.getPublicKey()[i];
- Log.d(TAG, "pkat: "+pkat);
-
- // keypair B
- byte [] skb = new byte[32]; for (int i = 0; i < 32; i ++) skb[i] = 1;
- TweetNaclFast.Box.KeyPair kb = TweetNaclFast.Box.keyPair_fromSecretKey(skb);
-
- String skbt = "";
- for (int i = 0; i < kb.getSecretKey().length; i ++)
- skbt += " "+kb.getSecretKey()[i];
- Log.d(TAG, "skbt: "+skbt);
-
- String pkbt = "";
- for (int i = 0; i < kb.getPublicKey().length; i ++)
- pkbt += " "+kb.getPublicKey()[i];
- Log.d(TAG, "pkbt: "+pkbt);
-
- // peer A -> B
- TweetNaclFast.Box pab = new TweetNaclFast.Box(kb.getPublicKey(), ka.getSecretKey(), 0);
-
- // peer B -> A
- TweetNaclFast.Box pba = new TweetNaclFast.Box(ka.getPublicKey(), kb.getSecretKey(), 0);
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- byte [] cab = pab.box(m0.getBytes("utf-8"));
- String cabt = "";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, "cabt: "+cabt);
-
- byte [] mba = pba.open(cab);
- String mbat = "";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, "mbat: "+mbat);
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "box/open string success @" + m0);
- } else {
- Log.e(TAG, "box/open string failed @" + m0 + " / " + nm0);
- }
-
- // cipher B -> A
- byte [] b0 = new byte[6];
-
- Log.d(TAG, "box@" + System.currentTimeMillis());
- byte [] cba = pba.box(b0);
- byte [] mab = pab.open(cba);
- Log.d(TAG, "open@" + System.currentTimeMillis());
-
- if (b0.length == mab.length) {
- int rc = 0;
-
- for (int i = 0; i < b0.length; i ++)
- if (!(b0[i] == mab[i])) {
- rc = -1;
- Log.e(TAG, "box/open binary failed @" + b0[i] + " / " + mab[i]);
- }
-
- if (rc == 0)
- Log.d(TAG, "box/open binary success @" + b0);
- } else {
- Log.e(TAG, "box/open binary failed @" + b0 + " / " + mab);
- }
-
- return true;
- }
-
- private boolean testBoxNonce() throws UnsupportedEncodingException {
-
- // explicit nonce
- byte [] theNonce = TweetNaclFast.makeBoxNonce();
- byte [] theNonce2 = TweetNaclFast.base64Decode(
- TweetNaclFast.base64EncodeToString(theNonce));
- Log.d(TAG, "BoxNonce Base64 test Equal: " + "\"" + java.util.Arrays.equals(theNonce, theNonce2) + "\"");
- byte [] theNonce3 = TweetNaclFast.hexDecode(
- TweetNaclFast.hexEncodeToString(theNonce));
- Log.d(TAG, "BoxNonce Hex test Equal: " + "\"" + java.util.Arrays.equals(theNonce, theNonce3) + "\"");
- String theNoncet = "";
- for (int i = 0; i < theNonce.length; i ++)
- theNoncet += " "+theNonce[i];
- Log.d(TAG, "BoxNonce: "+theNoncet);
- Log.d(TAG, "BoxNonce: " + "\"" + TweetNaclFast.base64EncodeToString(theNonce) + "\"");
- Log.d(TAG, "BoxNonce: " + "\"" + TweetNaclFast.hexEncodeToString(theNonce) + "\"");
-
-
-
- // keypair A
- byte [] ska = new byte[32]; for (int i = 0; i < 32; i ++) ska[i] = 0;
- TweetNaclFast.Box.KeyPair ka = TweetNaclFast.Box.keyPair_fromSecretKey(ska);
-
- String skat = "";
- for (int i = 0; i < ka.getSecretKey().length; i ++)
- skat += " "+ka.getSecretKey()[i];
- Log.d(TAG, "skat: "+skat);
-
- String pkat = "";
- for (int i = 0; i < ka.getPublicKey().length; i ++)
- pkat += " "+ka.getPublicKey()[i];
- Log.d(TAG, "pkat: "+pkat);
-
- // keypair B
- byte [] skb = new byte[32]; for (int i = 0; i < 32; i ++) skb[i] = 1;
- TweetNaclFast.Box.KeyPair kb = TweetNaclFast.Box.keyPair_fromSecretKey(skb);
-
- String skbt = "";
- for (int i = 0; i < kb.getSecretKey().length; i ++)
- skbt += " "+kb.getSecretKey()[i];
- Log.d(TAG, "skbt: "+skbt);
-
- String pkbt = "";
- for (int i = 0; i < kb.getPublicKey().length; i ++)
- pkbt += " "+kb.getPublicKey()[i];
- Log.d(TAG, "pkbt: "+pkbt);
-
- // peer A -> B
- TweetNaclFast.Box pab = new TweetNaclFast.Box(kb.getPublicKey(), ka.getSecretKey());
-
- // peer B -> A
- TweetNaclFast.Box pba = new TweetNaclFast.Box(ka.getPublicKey(), kb.getSecretKey());
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- byte [] cab = pab.box(m0.getBytes("utf-8"), theNonce);
- String cabt = "";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, "cabt: "+cabt);
-
- byte [] mba = pba.open(cab, theNonce);
- String mbat = "";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, "mbat: "+mbat);
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "box/open string success (with nonce) @" + m0);
- } else {
- Log.e(TAG, "box/open string failed (with nonce) @" + m0 + " / " + nm0);
- }
-
- // cipher B -> A
- byte [] b0 = new byte[6];
-
- Log.d(TAG, "box@" + System.currentTimeMillis());
- byte [] cba = pba.box(b0, theNonce);
- byte [] mab = pab.open(cba, theNonce);
- Log.d(TAG, "open@" + System.currentTimeMillis());
-
- if (b0.length == mab.length) {
- int rc = 0;
-
- for (int i = 0; i < b0.length; i ++)
- if (!(b0[i] == mab[i])) {
- rc = -1;
- Log.e(TAG, "box/open binary failed (with nonce) @" + b0[i] + " / " + mab[i]);
- }
-
- if (rc == 0)
- Log.d(TAG, "box/open binary success (with nonce) @" + b0);
- } else {
- Log.e(TAG, "box/open binary failed (with nonce) @" + b0 + " / " + mab);
- }
-
- return true;
- }
-
- private boolean testSecretBox() throws UnsupportedEncodingException {
- // shared key
- byte [] shk = new byte[TweetNaclFast.SecretBox.keyLength];
- for (int i = 0; i < shk.length; i ++)
- shk[i] = 0x66;
-
- // peer A -> B
- TweetNaclFast.SecretBox pab = new TweetNaclFast.SecretBox(shk, 0);
-
- // peer B -> A
- TweetNaclFast.SecretBox pba = new TweetNaclFast.SecretBox(shk, 0);
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- Log.d(TAG, "streess on secret box@"+m0);
-
- for (int t = 0; t < 19; t ++, m0 += m0) {
- byte [] mb0 = m0.getBytes("utf-8");
-
- Log.d(TAG, "\n\n\tstreess/"+(mb0.length/1000.0) +"kB: " + t + " times");
-
- /*String mb0t = "mb0/"+mb0.length + ": ";
- for (int i = 0; i < mb0.length; i ++)
- mb0t += " "+mb0[i];
- Log.d(TAG, mb0t);
-*/
- Log.d(TAG, "secret box ...@" + System.currentTimeMillis());
- byte [] cab = pab.box(mb0);
- Log.d(TAG, "... secret box@" + System.currentTimeMillis());
-
- /*String cabt = "cab/"+cab.length + ": ";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, cabt);
-*/
- Log.d(TAG, "\nsecret box open ...@" + System.currentTimeMillis());
- byte [] mba = pba.open(cab);
- Log.d(TAG, "... secret box open@" + System.currentTimeMillis());
-
- /*
- String mbat = "mba/"+mba.length + ": ";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, mbat);
-*/
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "\tsecret box/open succes");
- } else {
- Log.e(TAG, "\tsecret box/open failed @" + m0 + " / " + nm0);
- return false;
- }
- }
-
- return true;
- }
-
- private boolean testSecretBoxNonce() throws UnsupportedEncodingException {
-
- // explicit nonce
- byte [] theNonce = TweetNaclFast.makeSecretBoxNonce();
- String theNoncet = "";
- for (int i = 0; i < theNonce.length; i ++)
- theNoncet += " "+theNonce[i];
- Log.d(TAG, "SecretBoxNonce: "+theNoncet);
-
- // shared key
- byte [] shk = new byte[TweetNaclFast.SecretBox.keyLength];
- for (int i = 0; i < shk.length; i ++)
- shk[i] = 0x66;
-
- // peer A -> B
- TweetNaclFast.SecretBox pab = new TweetNaclFast.SecretBox(shk);
-
- // peer B -> A
- TweetNaclFast.SecretBox pba = new TweetNaclFast.SecretBox(shk);
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- Log.d(TAG, "stress on secret box with explicit nonce@"+m0);
-
- for (int t = 0; t < 19; t ++, m0 += m0) {
- byte [] mb0 = m0.getBytes("utf-8");
-
- Log.d(TAG, "\n\n\tstress/"+(mb0.length/1000.0) +"kB: " + t + " times");
-
- /*String mb0t = "mb0/"+mb0.length + ": ";
- for (int i = 0; i < mb0.length; i ++)
- mb0t += " "+mb0[i];
- Log.d(TAG, mb0t);
-*/
- Log.d(TAG, "secret box ...@" + System.currentTimeMillis());
- byte [] cab = pab.box(mb0, theNonce);
- Log.d(TAG, "... secret box@" + System.currentTimeMillis());
-
- /*String cabt = "cab/"+cab.length + ": ";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, cabt);
-*/
- Log.d(TAG, "\nsecret box open ...@" + System.currentTimeMillis());
- byte [] mba = pba.open(cab, theNonce);
- Log.d(TAG, "... secret box open@" + System.currentTimeMillis());
-
- /*
- String mbat = "mba/"+mba.length + ": ";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, mbat);
-*/
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "\tsecret box/open succes (with nonce)");
- } else {
- Log.e(TAG, "\tsecret box/open failed (with nonce) @" + m0 + " / " + nm0);
- return false;
- }
- }
-
- return true;
- }
-
- private boolean testSign() throws UnsupportedEncodingException {
- // keypair A
- TweetNaclFast.Signature.KeyPair ka = TweetNaclFast.Signature.keyPair();
-
- // keypair B
- TweetNaclFast.Signature.KeyPair kb = TweetNaclFast.Signature.keyPair();
-
- // peer A -> B
- TweetNaclFast.Signature pab = new TweetNaclFast.Signature(kb.getPublicKey(), ka.getSecretKey());
-
- // peer B -> A
- TweetNaclFast.Signature pba = new TweetNaclFast.Signature(ka.getPublicKey(), kb.getSecretKey());
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // signature A -> B
- Log.d(TAG, "\nsign...@" + System.currentTimeMillis());
- byte [] sab = pab.sign(m0.getBytes("utf-8"));
- Log.d(TAG, "...sign@" + System.currentTimeMillis());
-
- String sgt = "sign@"+m0 + ": ";
- for (int i = 0; i < TweetNaclFast.Signature.signatureLength; i ++)
- sgt += " "+sab[i];
- Log.d(TAG, sgt);
-
- Log.d(TAG, "verify...@" + System.currentTimeMillis());
- byte [] oba = pba.open(sab);
- Log.d(TAG, "...verify@" + System.currentTimeMillis());
-
- if (oba == null) {
- Log.e(TAG, "verify failed @" + m0);
- } else {
- String nm0 = new String(oba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "sign success @" + m0);
- } else {
- Log.e(TAG, "sign failed @" + m0 + " / " + nm0);
- }
- }
-
- // keypair C
- byte [] seed = new byte[TweetNaclFast.Signature.seedLength]; for (int i = 0; i < seed.length; i ++) seed[i] = 0x66;
-
- TweetNaclFast.Signature.KeyPair kc = TweetNaclFast.Signature.keyPair_fromSeed(seed);
-
- String skct = "";
- for (int i = 0; i < kc.getSecretKey().length; i ++)
- skct += " "+kc.getSecretKey()[i];
- Log.d(TAG, "skct: "+skct);
-
- String pkct = "";
- for (int i = 0; i < kc.getPublicKey().length; i ++)
- pkct += " "+kc.getPublicKey()[i];
- Log.d(TAG, "pkct: "+pkct);
-
- // self-signed
- TweetNaclFast.Signature pcc = new TweetNaclFast.Signature(kc.getPublicKey(), kc.getSecretKey());
-
- Log.d(TAG, "\nself-sign...@" + System.currentTimeMillis());
- byte [] scc = pcc.sign(m0.getBytes("utf-8"));
- Log.d(TAG, "...self-sign@" + System.currentTimeMillis());
-
- String ssc = "self-sign@"+m0 + ": ";
- for (int i = 0; i < TweetNaclFast.Signature.signatureLength; i ++)
- ssc += " "+scc[i];
- Log.d(TAG, ssc);
-
- Log.d(TAG, "self-verify...@" + System.currentTimeMillis());
- byte [] occ = pcc.open(scc);
- Log.d(TAG, "...self-verify@" + System.currentTimeMillis());
-
- if (occ == null) {
- Log.e(TAG, "self-verify failed @" + m0);
- } else {
- String nm0 = new String(occ, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "self-sign success @" + m0);
- } else {
- Log.e(TAG, "self-sign failed @" + m0 + " / " + nm0);
- }
- }
-
- return true;
- }
-
- /*
- * SHA-512
- * */
- private boolean testHash() throws UnsupportedEncodingException {
- String m0 = "Helloword, Am Tom ...";
- byte [] b0 = m0.getBytes("utf-8");
-
- Log.d(TAG, "\nsha512...@" + System.currentTimeMillis());
- byte [] hash = TweetNaclFast.Hash.sha512(b0);
- Log.d(TAG, "...sha512@" + System.currentTimeMillis());
-
- String hst = "sha512@"+m0 + "/"+b0.length + ": ";
- for (int i = 0; i < hash.length; i ++)
- hst += " "+hash[i];
- Log.d(TAG, hst);
-
- return true;
- }
-
- /*
- * bench test using tweetnacl.c, tweetnacl.js result
- * */
- private boolean testBench() {
-
- return true;
- }
-
- public void start() {
- (new Thread(new Runnable() {
- public void run() {
- Log.d(TAG, "start test");
-
- try {
- testSecretBox();
- testSecretBoxNonce();
- testBox();
- testBoxNonce();
- testBoxKalium();
-
- testHash();
- testSign();
-
- ///testBench();
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- })).start();
-
- }
-
- public static void main(String[] args) {
- TweetNaclFastTest t = new TweetNaclFastTest();
- t.start();
- }
-
-
-}
diff --git a/app/src/main/java/com/iwebpp/crypto/tests/TweetNaclTest.java b/app/src/main/java/com/iwebpp/crypto/tests/TweetNaclTest.java
deleted file mode 100755
index 1dc92b1..0000000
--- a/app/src/main/java/com/iwebpp/crypto/tests/TweetNaclTest.java
+++ /dev/null
@@ -1,466 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.crypto.tests;
-
-import android.util.Log;
-
-import java.io.UnsupportedEncodingException;
-import com.iwebpp.crypto.TweetNacl;
-import static com.iwebpp.crypto.TweetNacl.Box.nonceLength;
-
-public final class TweetNaclTest {
- private static final String TAG = "TweetNaclTest";
-
- private boolean testBox() throws UnsupportedEncodingException {
- // keypair A
- byte [] ska = new byte[32]; for (int i = 0; i < 32; i ++) ska[i] = 0;
- TweetNacl.Box.KeyPair ka = TweetNacl.Box.keyPair_fromSecretKey(ska);
-
- String skat = "";
- for (int i = 0; i < ka.getSecretKey().length; i ++)
- skat += " "+ka.getSecretKey()[i];
- Log.d(TAG, "skat: "+skat);
-
- String pkat = "";
- for (int i = 0; i < ka.getPublicKey().length; i ++)
- pkat += " "+ka.getPublicKey()[i];
- Log.d(TAG, "pkat: "+pkat);
-
- // keypair B
- byte [] skb = new byte[32]; for (int i = 0; i < 32; i ++) skb[i] = 1;
- TweetNacl.Box.KeyPair kb = TweetNacl.Box.keyPair_fromSecretKey(skb);
-
- String skbt = "";
- for (int i = 0; i < kb.getSecretKey().length; i ++)
- skbt += " "+kb.getSecretKey()[i];
- Log.d(TAG, "skbt: "+skbt);
-
- String pkbt = "";
- for (int i = 0; i < kb.getPublicKey().length; i ++)
- pkbt += " "+kb.getPublicKey()[i];
- Log.d(TAG, "pkbt: "+pkbt);
-
- // peer A -> B
- TweetNacl.Box pab = new TweetNacl.Box(kb.getPublicKey(), ka.getSecretKey(), 0);
-
- // peer B -> A
- TweetNacl.Box pba = new TweetNacl.Box(ka.getPublicKey(), kb.getSecretKey(), 0);
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- byte [] cab = pab.box(m0.getBytes("utf-8"));
- String cabt = "";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, "cabt: "+cabt);
-
- byte [] mba = pba.open(cab);
- String mbat = "";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, "mbat: "+mbat);
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "box/open string success @" + m0);
- } else {
- Log.e(TAG, "box/open string failed @" + m0 + " / " + nm0);
- }
-
- // cipher B -> A
- byte [] b0 = new byte[6];
-
- Log.d(TAG, "box@" + System.currentTimeMillis());
- byte [] cba = pba.box(b0);
- byte [] mab = pab.open(cba);
- Log.d(TAG, "open@" + System.currentTimeMillis());
-
- if (b0.length == mab.length) {
- int rc = 0;
-
- for (int i = 0; i < b0.length; i ++)
- if (!(b0[i] == mab[i])) {
- rc = -1;
- Log.e(TAG, "box/open binary failed @" + b0[i] + " / " + mab[i]);
- }
-
- if (rc == 0)
- Log.d(TAG, "box/open binary success @" + b0);
- } else {
- Log.e(TAG, "box/open binary failed @" + b0 + " / " + mab);
- }
-
- return true;
- }
-
- private boolean testBoxNonce() throws UnsupportedEncodingException {
-
- // explicit nonce
- byte [] theNonce = new byte[nonceLength];
- com.iwebpp.crypto.TweetNacl.randombytes(theNonce, nonceLength);
- String theNoncet = "";
- for (int i = 0; i < theNonce.length; i ++)
- theNoncet += " "+theNonce[i];
- Log.d(TAG, "BoxNonce: "+theNoncet);
-
-
- // keypair A
- byte [] ska = new byte[32]; for (int i = 0; i < 32; i ++) ska[i] = 0;
- TweetNacl.Box.KeyPair ka = TweetNacl.Box.keyPair_fromSecretKey(ska);
-
- String skat = "";
- for (int i = 0; i < ka.getSecretKey().length; i ++)
- skat += " "+ka.getSecretKey()[i];
- Log.d(TAG, "skat: "+skat);
-
- String pkat = "";
- for (int i = 0; i < ka.getPublicKey().length; i ++)
- pkat += " "+ka.getPublicKey()[i];
- Log.d(TAG, "pkat: "+pkat);
-
- // keypair B
- byte [] skb = new byte[32]; for (int i = 0; i < 32; i ++) skb[i] = 1;
- TweetNacl.Box.KeyPair kb = TweetNacl.Box.keyPair_fromSecretKey(skb);
-
- String skbt = "";
- for (int i = 0; i < kb.getSecretKey().length; i ++)
- skbt += " "+kb.getSecretKey()[i];
- Log.d(TAG, "skbt: "+skbt);
-
- String pkbt = "";
- for (int i = 0; i < kb.getPublicKey().length; i ++)
- pkbt += " "+kb.getPublicKey()[i];
- Log.d(TAG, "pkbt: "+pkbt);
-
- // peer A -> B
- TweetNacl.Box pab = new TweetNacl.Box(kb.getPublicKey(), ka.getSecretKey());
-
- // peer B -> A
- TweetNacl.Box pba = new TweetNacl.Box(ka.getPublicKey(), kb.getSecretKey());
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- byte [] cab = pab.box(m0.getBytes("utf-8"), theNonce);
- String cabt = "";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, "cabt: "+cabt);
-
- byte [] mba = pba.open(cab, theNonce);
- String mbat = "";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, "mbat: "+mbat);
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "box/open string success (with nonce) @" + m0);
- } else {
- Log.e(TAG, "box/open string failed @ (with nonce)" + m0 + " / " + nm0);
- }
-
- // cipher B -> A
- byte [] b0 = new byte[6];
-
- Log.d(TAG, "box@" + System.currentTimeMillis());
- byte [] cba = pba.box(b0, theNonce);
- byte [] mab = pab.open(cba, theNonce);
- Log.d(TAG, "open@" + System.currentTimeMillis());
-
- if (b0.length == mab.length) {
- int rc = 0;
-
- for (int i = 0; i < b0.length; i ++)
- if (!(b0[i] == mab[i])) {
- rc = -1;
- Log.e(TAG, "box/open binary failed (with nonce) @" + b0[i] + " / " + mab[i]);
- }
-
- if (rc == 0)
- Log.d(TAG, "box/open binary success (with nonce) @" + b0);
- } else {
- Log.e(TAG, "box/open binary failed (with nonce) @" + b0 + " / " + mab);
- }
-
- return true;
- }
-
- private boolean testSecretBox() throws UnsupportedEncodingException {
- // shared key
- byte [] shk = new byte[TweetNacl.SecretBox.keyLength];
- for (int i = 0; i < shk.length; i ++)
- shk[i] = 0x66;
-
- // peer A -> B
- TweetNacl.SecretBox pab = new TweetNacl.SecretBox(shk, 0);
-
- // peer B -> A
- TweetNacl.SecretBox pba = new TweetNacl.SecretBox(shk, 0);
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- Log.d(TAG, "stress on secret box@"+m0);
-
- for (int t = 0; t < 19; t ++, m0 += m0) {
- byte [] mb0 = m0.getBytes("utf-8");
-
- Log.d(TAG, "\n\n\tstress/"+(mb0.length/1000.0) +"kB: " + t + " times");
-
- /*String mb0t = "mb0/"+mb0.length + ": ";
- for (int i = 0; i < mb0.length; i ++)
- mb0t += " "+mb0[i];
- Log.d(TAG, mb0t);
-*/
- Log.d(TAG, "secret box ...@" + System.currentTimeMillis());
- byte [] cab = pab.box(mb0);
- Log.d(TAG, "... secret box@" + System.currentTimeMillis());
-
- /*String cabt = "cab/"+cab.length + ": ";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, cabt);
-*/
- Log.d(TAG, "\nsecret box open ...@" + System.currentTimeMillis());
- byte [] mba = pba.open(cab);
- Log.d(TAG, "... secret box open@" + System.currentTimeMillis());
-
- /*
- String mbat = "mba/"+mba.length + ": ";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, mbat);
-*/
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "\tsecret box/open succes");
- } else {
- Log.e(TAG, "\tsecret box/open failed @" + m0 + " / " + nm0);
- return false;
- }
- }
-
- return true;
- }
-
- private boolean testSecretBoxNonce() throws UnsupportedEncodingException {
- // shared key plus explicit nonce
-
- // explicit nonce
- byte [] theNonce = new byte[nonceLength];
- com.iwebpp.crypto.TweetNacl.randombytes(theNonce, nonceLength);
- String theNoncet = "";
- for (int i = 0; i < theNonce.length; i ++)
- theNoncet += " "+theNonce[i];
- Log.d(TAG, "SecretBoxNonce: "+theNoncet);
-
-
- byte [] shk = new byte[TweetNacl.SecretBox.keyLength];
- for (int i = 0; i < shk.length; i ++)
- shk[i] = 0x66;
-
- // peer A -> B
- TweetNacl.SecretBox pab = new TweetNacl.SecretBox(shk);
-
- // peer B -> A
- TweetNacl.SecretBox pba = new TweetNacl.SecretBox(shk);
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // cipher A -> B
- Log.d(TAG, "stress on secret box with explicit nonce@"+m0);
-
- for (int t = 0; t < 19; t ++, m0 += m0) {
- byte [] mb0 = m0.getBytes("utf-8");
-
- Log.d(TAG, "\n\n\tstress/"+(mb0.length/1000.0) +"kB: " + t + " times");
-
- /*String mb0t = "mb0/"+mb0.length + ": ";
- for (int i = 0; i < mb0.length; i ++)
- mb0t += " "+mb0[i];
- Log.d(TAG, mb0t);
-*/
- Log.d(TAG, "secret box ...@" + System.currentTimeMillis());
- byte [] cab = pab.box(mb0, theNonce);
- Log.d(TAG, "... secret box@" + System.currentTimeMillis());
-
- /*String cabt = "cab/"+cab.length + ": ";
- for (int i = 0; i < cab.length; i ++)
- cabt += " "+cab[i];
- Log.d(TAG, cabt);
-*/
- Log.d(TAG, "\nsecret box open ...@" + System.currentTimeMillis());
- byte [] mba = pba.open(cab, theNonce);
- Log.d(TAG, "... secret box open@" + System.currentTimeMillis());
-
- /*
- String mbat = "mba/"+mba.length + ": ";
- for (int i = 0; i < mba.length; i ++)
- mbat += " "+mba[i];
- Log.d(TAG, mbat);
-*/
-
- String nm0 = new String(mba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "\tsecret box/open success (with nonce)");
- } else {
- Log.e(TAG, "\tsecret box/open failed (with nonce) @" + m0 + " / " + nm0);
- return false;
- }
- }
-
- return true;
- }
-
-
- private boolean testSign() throws UnsupportedEncodingException {
- // keypair A
- TweetNacl.Signature.KeyPair ka = TweetNacl.Signature.keyPair();
-
- // keypair B
- TweetNacl.Signature.KeyPair kb = TweetNacl.Signature.keyPair();
-
- // peer A -> B
- TweetNacl.Signature pab = new TweetNacl.Signature(kb.getPublicKey(), ka.getSecretKey());
-
- // peer B -> A
- TweetNacl.Signature pba = new TweetNacl.Signature(ka.getPublicKey(), kb.getSecretKey());
-
- // messages
- String m0 = "Helloword, Am Tom ...";
-
- // signature A -> B
- Log.d(TAG, "\nsign...@" + System.currentTimeMillis());
- byte [] sab = pab.sign(m0.getBytes("utf-8"));
- Log.d(TAG, "...sign@" + System.currentTimeMillis());
-
- String sgt = "sign@"+m0 + ": ";
- for (int i = 0; i < TweetNacl.Signature.signatureLength; i ++)
- sgt += " "+sab[i];
- Log.d(TAG, sgt);
-
- Log.d(TAG, "verify...@" + System.currentTimeMillis());
- byte [] oba = pba.open(sab);
- Log.d(TAG, "...verify@" + System.currentTimeMillis());
-
- if (oba == null) {
- Log.e(TAG, "verify failed @" + m0);
- } else {
- String nm0 = new String(oba, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "sign success @" + m0);
- } else {
- Log.e(TAG, "sign failed @" + m0 + " / " + nm0);
- }
- }
-
- // keypair C
- byte [] seed = new byte[TweetNacl.Signature.seedLength]; for (int i = 0; i < seed.length; i ++) seed[i] = 0x66;
-
- TweetNacl.Signature.KeyPair kc = TweetNacl.Signature.keyPair_fromSeed(seed);
-
- String skct = "";
- for (int i = 0; i < kc.getSecretKey().length; i ++)
- skct += " "+kc.getSecretKey()[i];
- Log.d(TAG, "skct: "+skct);
-
- String pkct = "";
- for (int i = 0; i < kc.getPublicKey().length; i ++)
- pkct += " "+kc.getPublicKey()[i];
- Log.d(TAG, "pkct: "+pkct);
-
- // self-signed
- TweetNacl.Signature pcc = new TweetNacl.Signature(kc.getPublicKey(), kc.getSecretKey());
-
- Log.d(TAG, "\nself-sign...@" + System.currentTimeMillis());
- byte [] scc = pcc.sign(m0.getBytes("utf-8"));
- Log.d(TAG, "...self-sign@" + System.currentTimeMillis());
-
- String ssc = "self-sign@"+m0 + ": ";
- for (int i = 0; i < TweetNacl.Signature.signatureLength; i ++)
- ssc += " "+scc[i];
- Log.d(TAG, ssc);
-
- Log.d(TAG, "self-verify...@" + System.currentTimeMillis());
- byte [] occ = pcc.open(scc);
- Log.d(TAG, "...self-verify@" + System.currentTimeMillis());
-
- if (occ == null) {
- Log.e(TAG, "self-verify failed @" + m0);
- } else {
- String nm0 = new String(occ, "utf-8");
- if (nm0.equals(m0)) {
- Log.d(TAG, "self-sign success @" + m0);
- } else {
- Log.e(TAG, "self-sign failed @" + m0 + " / " + nm0);
- }
- }
-
- return true;
- }
-
- /*
- * SHA-512
- * */
- private boolean testHash() throws UnsupportedEncodingException {
- String m0 = "Helloword, Am Tom ...";
- byte [] b0 = m0.getBytes("utf-8");
-
- Log.d(TAG, "\nsha512...@" + System.currentTimeMillis());
- byte [] hash = TweetNacl.Hash.sha512(b0);
- Log.d(TAG, "...sha512@" + System.currentTimeMillis());
-
- String hst = "sha512@"+m0 + "/"+b0.length + ": ";
- for (int i = 0; i < hash.length; i ++)
- hst += " "+hash[i];
- Log.d(TAG, hst);
-
- return true;
- }
-
- /*
- * bench test using tweetnacl.c, tweetnacl.js result
- * */
- private boolean testBench() {
-
- return true;
- }
-
- public void start() {
- (new Thread(new Runnable() {
- public void run() {
- Log.d(TAG, "start test");
-
- try {
- testSecretBox();
- testSecretBoxNonce();
- testBox();
- testBoxNonce();
-
- testHash();
- testSign();
-
- ///testBench();
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- })).start();
-
- }
-
- public static void main(String[] args) {
- TweetNaclTest t = new TweetNaclTest();
- t.start();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/io/CA.java b/app/src/main/java/com/iwebpp/io/CA.java
deleted file mode 100644
index 7e7c98b..0000000
--- a/app/src/main/java/com/iwebpp/io/CA.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.iwebpp.io;
-
-public final class CA {
-
-}
diff --git a/app/src/main/java/com/iwebpp/io/IO.java b/app/src/main/java/com/iwebpp/io/IO.java
deleted file mode 100644
index 0f202a7..0000000
--- a/app/src/main/java/com/iwebpp/io/IO.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.iwebpp.io;
-
-import com.iwebpp.node.EventEmitter2;
-
-public final class IO
-extends EventEmitter2 {
-
-}
diff --git a/app/src/main/java/com/iwebpp/io/README.md b/app/src/main/java/com/iwebpp/io/README.md
deleted file mode 100644
index f677f74..0000000
--- a/app/src/main/java/com/iwebpp/io/README.md
+++ /dev/null
@@ -1 +0,0 @@
-rewrite https://github.com/InstantWebP2P/iwebpp.io in pure Java
diff --git a/app/src/main/java/com/iwebpp/io/SEP.java b/app/src/main/java/com/iwebpp/io/SEP.java
deleted file mode 100644
index 201c071..0000000
--- a/app/src/main/java/com/iwebpp/io/SEP.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.iwebpp.io;
-
-public final class SEP {
-
-}
diff --git a/app/src/main/java/com/iwebpp/io/vURL.java b/app/src/main/java/com/iwebpp/io/vURL.java
deleted file mode 100644
index b046376..0000000
--- a/app/src/main/java/com/iwebpp/io/vURL.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.iwebpp.io;
-
-public final class vURL {
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/Address.java b/app/src/main/java/com/iwebpp/libuvpp/Address.java
deleted file mode 100644
index e816ac6..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/Address.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-public class Address {
-
- private final String ip;
- private final int port;
- private final String family;
-
- public Address(final String ip,
- final int port,
- final String family) {
- this.ip = ip;
- this.port = port;
- this.family = family;
- }
-
- public String getIp() {
- return ip;
- }
-
- public int getPort() {
- return port;
- }
-
- public String getFamily() {
- return family;
- }
-
- @Override
- public String toString() {
- return "{ip: " + ip +
- ", port: " + port +
- ", family: " + family + "}";
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/ConsString.java b/app/src/main/java/com/iwebpp/libuvpp/ConsString.java
deleted file mode 100644
index 074887e..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/ConsString.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-package com.iwebpp.libuvpp;
-
-import java.io.Serializable;
-
-/**
- *
This class represents a string composed of two components, each of which
- * may be a java.lang.String or another ConsString.
- *
- *
This string representation is optimized for concatenation using the "+"
- * operator. Instead of immediately copying both components to a new character
- * array, ConsString keeps references to the original components and only
- * converts them to a String if either toString() is called or a certain depth
- * level is reached.
- *
- *
Note that instances of this class are only immutable if both parts are
- * immutable, i.e. either Strings or ConsStrings that are ultimately composed
- * of Strings.
- *
- *
Both the name and the concept are borrowed from V8.
- */
-public class ConsString implements CharSequence, Serializable {
-
- private static final long serialVersionUID = -8432806714471372570L;
-
- private CharSequence s1, s2;
- private final int length;
- private int depth;
-
- public ConsString(CharSequence str1, CharSequence str2) {
- s1 = str1;
- s2 = str2;
- length = str1.length() + str2.length();
- depth = 1;
- if (str1 instanceof ConsString) {
- depth += ((ConsString)str1).depth;
- }
- if (str2 instanceof ConsString) {
- depth += ((ConsString)str2).depth;
- }
- // Don't let it grow too deep, can cause stack overflows
- if (depth > 2000) {
- flatten();
- }
- }
-
- // Replace with string representation when serializing
- private Object writeReplace() {
- return this.toString();
- }
-
- public String toString() {
- return depth == 0 ? (String)s1 : flatten();
- }
-
- private synchronized String flatten() {
- if (depth > 0) {
- StringBuilder b = new StringBuilder(length);
- appendTo(b);
- s1 = b.toString();
- s2 = "";
- depth = 0;
- }
- return (String)s1;
- }
-
- private synchronized void appendTo(StringBuilder b) {
- appendFragment(s1, b);
- appendFragment(s2, b);
- }
-
- private static void appendFragment(CharSequence s, StringBuilder b) {
- if (s instanceof ConsString) {
- ((ConsString)s).appendTo(b);
- } else {
- b.append(s);
- }
- }
-
- public int length() {
- return length;
- }
-
- public char charAt(int index) {
- String str = depth == 0 ? (String)s1 : flatten();
- return str.charAt(index);
- }
-
- public CharSequence subSequence(int start, int end) {
- String str = depth == 0 ? (String)s1 : flatten();
- return str.substring(start, end);
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/Constants.java b/app/src/main/java/com/iwebpp/libuvpp/Constants.java
deleted file mode 100644
index f00c71f..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/Constants.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-public final class Constants {
-
- private static final Field[] FIELDS = Constants.class.getDeclaredFields();
- private static final int MASK = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
- private static final int[] FIELD_VALUES = new int[FIELDS.length];
-
- private static final Map CONSTANTS;
- private static final Map CONSTANTS_STRING;
-
- public static Map getConstants() {
- return CONSTANTS;
- }
-
- public static Map getConstantsString() {
- return CONSTANTS_STRING;
- }
-
- static {
- Constants._get_field_values(FIELD_VALUES);
- }
-
- public static final int O_RDONLY = FIELD_VALUES[0];
- public static final int O_WRONLY = FIELD_VALUES[1];
- public static final int O_RDWR = FIELD_VALUES[2];
-
- public static final int O_APPEND = FIELD_VALUES[3];
- public static final int O_CREAT = FIELD_VALUES[4];
- public static final int O_TRUNC = FIELD_VALUES[5];
- public static final int O_EXCL = FIELD_VALUES[6];
- public static final int O_SYNC = FIELD_VALUES[7];
- public static final int O_NOCTTY = FIELD_VALUES[8];
-
- public static final int S_IRUSR = FIELD_VALUES[9];
- public static final int S_IWUSR = FIELD_VALUES[10];
- public static final int S_IXUSR = FIELD_VALUES[11];
- public static final int S_IRWXU = FIELD_VALUES[12];
-
- public static final int S_IRGRP = FIELD_VALUES[13];
- public static final int S_IWGRP = FIELD_VALUES[14];
- public static final int S_IXGRP = FIELD_VALUES[15];
- public static final int S_IRWXG = FIELD_VALUES[16];
-
- public static final int S_IROTH = FIELD_VALUES[17];
- public static final int S_IWOTH = FIELD_VALUES[18];
- public static final int S_IXOTH = FIELD_VALUES[19];
- public static final int S_IRWXO = FIELD_VALUES[20];
-
- public static final int S_IFMT = FIELD_VALUES[21];
- public static final int S_IFIFO = FIELD_VALUES[22];
- public static final int S_IFCHR = FIELD_VALUES[23];
- public static final int S_IFDIR = FIELD_VALUES[24];
- public static final int S_IFBLK = FIELD_VALUES[25];
- public static final int S_IFREG = FIELD_VALUES[26];
- public static final int S_IFLNK = FIELD_VALUES[27];
- public static final int S_IFSOCK = FIELD_VALUES[28];
- public static final int S_IFWHT = FIELD_VALUES[29];
-
- public static final int S_ISUID = FIELD_VALUES[30];
- public static final int S_ISGID = FIELD_VALUES[31];
- public static final int S_ISVTX = FIELD_VALUES[32];
-
- public static final int SIGHUP = FIELD_VALUES[33];
- public static final int SIGINT = FIELD_VALUES[34];
- public static final int SIGQUIT = FIELD_VALUES[35];
- public static final int SIGILL = FIELD_VALUES[36];
- public static final int SIGTRAP = FIELD_VALUES[37];
- public static final int SIGABRT = FIELD_VALUES[38];
- public static final int SIGIOT = FIELD_VALUES[39];
- public static final int SIGBUS = FIELD_VALUES[40];
- public static final int SIGFPE = FIELD_VALUES[41];
- public static final int SIGKILL = FIELD_VALUES[42];
- public static final int SIGUSR1 = FIELD_VALUES[43];
- public static final int SIGSEGV = FIELD_VALUES[44];
- public static final int SIGUSR2 = FIELD_VALUES[45];
- public static final int SIGPIPE = FIELD_VALUES[46];
- public static final int SIGALRM = FIELD_VALUES[47];
- public static final int SIGTERM = FIELD_VALUES[48];
- public static final int SIGSTKFLT = FIELD_VALUES[49];
- public static final int SIGCHLD = FIELD_VALUES[50];
- public static final int SIGCONT = FIELD_VALUES[51];
- public static final int SIGSTOP = FIELD_VALUES[52];
- public static final int SIGTSTP = FIELD_VALUES[53];
- public static final int SIGTTIN = FIELD_VALUES[54];
- public static final int SIGTTOU = FIELD_VALUES[55];
- public static final int SIGURG = FIELD_VALUES[56];
- public static final int SIGXCPU = FIELD_VALUES[57];
- public static final int SIGXFSZ = FIELD_VALUES[58];
- public static final int SIGVTALRM = FIELD_VALUES[59];
- public static final int SIGPROF = FIELD_VALUES[60];
- public static final int SIGWINCH = FIELD_VALUES[61];
- public static final int SIGIO = FIELD_VALUES[62];
- public static final int SIGPOLL = FIELD_VALUES[63];
- public static final int SIGPWR = FIELD_VALUES[64];
- public static final int SIGSYS = FIELD_VALUES[65];
- public static final int SIGUNUSED = FIELD_VALUES[66];
-
- private static native void _get_field_values(int[] values);
-
- static {
- final Map constants = new HashMap(FIELDS.length);
- final Map constantsString = new HashMap(FIELDS.length);
- for (final Field f : FIELDS) {
- if ((f.getModifiers() & MASK) == MASK) {
- try {
- constants.put(f.getName(), (Integer) f.get(null));
- constantsString.put((Integer) f.get(null), f.getName());
- } catch (Exception ex) {
- // Should never happen, ignore with msg
- ex.printStackTrace();
- }
- }
- }
- CONSTANTS = Collections.unmodifiableMap(constants);
- CONSTANTS_STRING = Collections.unmodifiableMap(constantsString);
- }
-}
-
diff --git a/app/src/main/java/com/iwebpp/libuvpp/Files.java b/app/src/main/java/com/iwebpp/libuvpp/Files.java
deleted file mode 100644
index 26bfc56..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/Files.java
+++ /dev/null
@@ -1,887 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.cb.FileCallback;
-import com.iwebpp.libuvpp.cb.FileCloseCallback;
-import com.iwebpp.libuvpp.cb.FileOpenCallback;
-import com.iwebpp.libuvpp.cb.FileReadCallback;
-import com.iwebpp.libuvpp.cb.FileReadDirCallback;
-import com.iwebpp.libuvpp.cb.FileReadLinkCallback;
-import com.iwebpp.libuvpp.cb.FileStatsCallback;
-import com.iwebpp.libuvpp.cb.FileUTimeCallback;
-import com.iwebpp.libuvpp.cb.FileWriteCallback;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-public class Files {
-
- static {
- _static_initialize();
- }
-
- private static final Object SYNC_MODE = null;
-
- // must be equal to values in uv.h
- private static final int UV_FS_UNKNOWN = -1;
- private static final int UV_FS_CUSTOM = 0;
- private static final int UV_FS_OPEN = 1;
- private static final int UV_FS_CLOSE = 2;
- private static final int UV_FS_READ = 3;
- private static final int UV_FS_WRITE = 4;
- private static final int UV_FS_SENDFILE = 5;
- private static final int UV_FS_STAT = 6;
- private static final int UV_FS_LSTAT = 7;
- private static final int UV_FS_FSTAT = 8;
- private static final int UV_FS_FTRUNCATE = 9;
- private static final int UV_FS_UTIME = 10;
- private static final int UV_FS_FUTIME = 11;
- private static final int UV_FS_CHMOD = 12;
- private static final int UV_FS_FCHMOD = 13;
- private static final int UV_FS_FSYNC = 14;
- private static final int UV_FS_FDATASYNC = 15;
- private static final int UV_FS_UNLINK = 16;
- private static final int UV_FS_RMDIR = 17;
- private static final int UV_FS_MKDIR = 18;
- private static final int UV_FS_RENAME = 19;
- private static final int UV_FS_READDIR = 20;
- private static final int UV_FS_LINK = 21;
- private static final int UV_FS_SYMLINK = 22;
- private static final int UV_FS_READLINK = 23;
- private static final int UV_FS_CHOWN = 24;
- private static final int UV_FS_FCHOWN = 25;
-
- private FileCallback onCustom = null;
- private FileOpenCallback onOpen = null;
- private FileCloseCallback onClose = null;
- private FileReadCallback onRead = null;
- private FileWriteCallback onWrite = null;
- private FileCallback onSendfile = null;
- private FileStatsCallback onStat = null;
- private FileStatsCallback onLStat = null;
- private FileStatsCallback onFStat = null;
- private FileCallback onFTruncate = null;
- private FileUTimeCallback onUTime = null;
- private FileUTimeCallback onFUTime = null;
- private FileCallback onChmod = null;
- private FileCallback onFChmod = null;
- private FileCallback onFSync = null;
- private FileCallback onFDatasync = null;
- private FileCallback onUnlink = null;
- private FileCallback onRmDir = null;
- private FileCallback onMkDir = null;
- private FileCallback onRename = null;
- private FileReadDirCallback onReadDir = null;
- private FileCallback onLink = null;
- private FileCallback onSymLink = null;
- private FileReadLinkCallback onReadLink = null;
- private FileCallback onChown = null;
- private FileCallback onFChown = null;
-
- private final long pointer;
- private final LoopHandle loop;
- private final Map openedFiles = new HashMap();
-
- private boolean closed;
-
- // should be private but used by unit tests.
- public static final class OpenedFile {
- private final int flags;
- private final String path;
- private OpenedFile(final String path, final int flags) {
- this.path = path;
- this.flags = flags;
- }
- int getFlags() { return flags; }
- public String getPath() { return path; }
- }
-
- protected Files(final LoopHandle loop) {
- LibUVPermission.checkHandle();
- this.pointer = _new();
- assert pointer != 0;
- this.loop = loop;
- _initialize(pointer, loop.pointer());
-
- openedFiles.put(0, new OpenedFile("stdin", 0));
- openedFiles.put(1, new OpenedFile("stdout", 0));
- openedFiles.put(2, new OpenedFile("stderr", 0));
- }
-
- public void setCustomCallback(final FileCallback callback) {
- onCustom = callback;
- }
-
- public void setOpenCallback(final FileOpenCallback callback) {
- onOpen = callback;
- }
-
- public void setCloseCallback(final FileCloseCallback callback) {
- onClose = callback;
- }
-
- public void setReadCallback(final FileReadCallback callback) {
- onRead = callback;
- }
-
- public void setWriteCallback(final FileWriteCallback callback) {
- onWrite = callback;
- }
-
- public void setSendfileCallback(final FileCallback callback) {
- onSendfile = callback;
- }
-
- public void setStatCallback(final FileStatsCallback callback) {
- onStat = callback;
- }
-
- public void setLStatCallback(final FileStatsCallback callback) {
- onLStat = callback;
- }
-
- public void setFStatCallback(final FileStatsCallback callback) {
- onFStat = callback;
- }
-
- public void setFTruncateCallback(final FileCallback callback) {
- onFTruncate = callback;
- }
-
- public void setUTimeCallback(final FileUTimeCallback callback) {
- onUTime = callback;
- }
-
- public void setFUTimeCallback(final FileUTimeCallback callback) {
- onFUTime = callback;
- }
-
- public void setChmodCallback(final FileCallback callback) {
- onChmod = callback;
- }
-
- public void setFChmodCallback(final FileCallback callback) {
- onFChmod = callback;
- }
-
- public void setFSyncCallback(final FileCallback callback) {
- onFSync = callback;
- }
-
- public void setFDatasyncCallback(final FileCallback callback) {
- onFDatasync = callback;
- }
-
- public void setUnlinkCallback(final FileCallback callback) {
- onUnlink = callback;
- }
-
- public void setRmDirCallback(final FileCallback callback) {
- onRmDir = callback;
- }
-
- public void setMkDirCallback(final FileCallback callback) {
- onMkDir = callback;
- }
-
- public void setRenameCallback(final FileCallback callback) {
- onRename = callback;
- }
-
- public void setReadDirCallback(final FileReadDirCallback callback) {
- onReadDir = callback;
- }
-
- public void setLinkCallback(final FileCallback callback) {
- onLink = callback;
- }
-
- public void setSymLinkCallback(final FileCallback callback) {
- onSymLink = callback;
- }
-
- public void setReadLinkCallback(final FileReadLinkCallback callback) {
- onReadLink = callback;
- }
-
- public void setChownCallback(final FileCallback callback) {
- onChown = callback;
- }
-
- public void setFChownCallback(final FileCallback callback) {
- onFChown = callback;
- }
-
- public void close() {
- if (!closed) {
- openedFiles.clear();
- _close(pointer);
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- public int close(final int fd) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "closeSync");
- Objects.requireNonNull(file);
- LibUVPermission.checkOpenFile(file.getPath(), file.getFlags());
- final int r = _close(pointer, fd, SYNC_MODE, loop.getContext());
- if (r != -1) {
- openedFiles.remove(fd);
- }
- return r;
- }
-
- public int close(final int fd, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callClose(context, -1, newEBADF("close", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- LibUVPermission.checkOpenFile(file.getPath(), file.getFlags());
- final int r = _close(pointer, fd, context, loop.getContext());
- if (r != -1) {
- openedFiles.remove(fd);
- }
- return r;
- }
-
- public int open(final String path, final int flags, final int mode) {
- Objects.requireNonNull(path);
- LibUVPermission.checkOpenFile(path, flags);
- final int fd = _open(pointer, path, flags, mode, SYNC_MODE, loop.getContext());
- if (fd != -1) {
- openedFiles.put(fd, new OpenedFile(path, flags));
- }
- return fd;
- }
-
- public int open(final String path, final int flags, final int mode, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkOpenFile(path, flags);
- return _open(pointer, path, flags, mode, context, loop.getContext());
- }
-
- public int read(final int fd, final ByteBuffer buffer, final long offset, final long length, final long position) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "readSync");
- Objects.requireNonNull(file);
- Objects.requireNonNull(buffer);
- LibUVPermission.checkReadFile(fd, file.getPath());
- return buffer.hasArray() ?
- _read(pointer, fd, buffer, buffer.array(), length, offset, position, SYNC_MODE, loop.getContext()) :
- _read(pointer, fd, buffer, null, length, offset, position, SYNC_MODE, loop.getContext());
- }
-
- public int read(final int fd, final ByteBuffer buffer, final long offset, final long length, final long position, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callRead(context, -1, buffer, newEBADF("read", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- Objects.requireNonNull(buffer);
- LibUVPermission.checkReadFile(fd, file.getPath());
- return buffer.hasArray() ?
- _read(pointer, fd, buffer, buffer.array(), length, offset, position, context, loop.getContext()) :
- _read(pointer, fd, buffer, null, length, offset, position, context, loop.getContext());
- }
-
- public int unlink(final String path) {
- Objects.requireNonNull(path);
- LibUVPermission.checkDeleteFile(path);
- return _unlink(pointer, path, SYNC_MODE, loop.getContext());
- }
-
- public int unlink(final String path, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkDeleteFile(path);
- return _unlink(pointer, path, context, loop.getContext());
- }
-
- public int write(final int fd, final ByteBuffer buffer, final long offset, final long length, final long position) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "writeSync");
- Objects.requireNonNull(file);
- Objects.requireNonNull(buffer);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- assert(offset < buffer.limit());
- assert(offset + length <= buffer.limit());
- return buffer.hasArray() ?
- _write(pointer, fd, buffer, buffer.array(), length, offset, position, SYNC_MODE, loop.getContext()) :
- _write(pointer, fd, buffer, null, length, offset, position, SYNC_MODE, loop.getContext());
- }
-
- public int write(final int fd, final ByteBuffer buffer, final long offset, final long length, final long position, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callWrite(context, -1, newEBADF("write", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- Objects.requireNonNull(buffer);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- assert(offset < buffer.limit());
- assert(offset + length <= buffer.limit());
- return buffer.hasArray() ?
- _write(pointer, fd, buffer, buffer.array(), length, offset, position, context, loop.getContext()) :
- _write(pointer, fd, buffer, null, length, offset, position, context, loop.getContext());
- }
-
- public int mkdir(final String path, final int mode) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _mkdir(pointer, path, mode, SYNC_MODE, loop.getContext());
- }
-
- public int mkdir(final String path, final int mode, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _mkdir(pointer, path, mode, context, loop.getContext());
- }
-
- public int rmdir(final String path) {
- Objects.requireNonNull(path);
- LibUVPermission.checkDeleteFile(path);
- return _rmdir(pointer, path, SYNC_MODE, loop.getContext());
- }
-
- public int rmdir(final String path, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkDeleteFile(path);
- return _rmdir(pointer, path, context, loop.getContext());
- }
-
- public String[] readdir(final String path, final int flags) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _readdir(pointer, path, flags, SYNC_MODE, loop.getContext());
- }
-
- public String[] readdir(final String path, final int flags, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _readdir(pointer, path, flags, context, loop.getContext());
- }
-
- public Stats stat(final String path) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _stat(pointer, path, SYNC_MODE, loop.getContext());
- }
-
- public Stats stat(final String path, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _stat(pointer, path, context, loop.getContext());
- }
-
- public Stats fstat(final int fd) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "fstatSync");
- Objects.requireNonNull(file);
- LibUVPermission.checkReadFile(fd, file.getPath());
- return _fstat(pointer, fd, SYNC_MODE, loop.getContext());
- }
-
- public Stats fstat(final int fd, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callStats(UV_FS_FSTAT, context, null, newEBADF("fstat", fd), loop.getContext());
- return null;
- }
- Objects.requireNonNull(file);
- LibUVPermission.checkReadFile(fd, file.getPath());
- return _fstat(pointer, fd, context, loop.getContext());
- }
-
- public int rename(final String path, final String newPath) {
- Objects.requireNonNull(path);
- Objects.requireNonNull(newPath);
- LibUVPermission.checkWriteFile(path);
- LibUVPermission.checkWriteFile(newPath);
- return _rename(pointer, path, newPath, SYNC_MODE, loop.getContext());
- }
-
- public int rename(final String path, final String newPath, final Object context) {
- Objects.requireNonNull(path);
- Objects.requireNonNull(newPath);
- LibUVPermission.checkWriteFile(path);
- LibUVPermission.checkWriteFile(newPath);
- return _rename(pointer, path, newPath, context, loop.getContext());
- }
-
- public int fsync(final int fd) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "fsyncSync");
- Objects.requireNonNull(file);
- // If a file is open, it can be synced, no security check.
- return _fsync(pointer, fd, SYNC_MODE, loop.getContext());
- }
-
- public int fsync(final int fd, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callback(UV_FS_FSYNC, context, newEBADF("fsync", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- // If a file is open, it can be synced, no security check.
- return _fsync(pointer, fd, context, loop.getContext());
- }
-
- public int fdatasync(final int fd) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "fdatasyncSync");
- Objects.requireNonNull(file);
- // If a file is open, it can be synced, no security check.
- return _fdatasync(pointer, fd, SYNC_MODE, loop.getContext());
- }
-
- public int fdatasync(final int fd, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callback(UV_FS_FDATASYNC, context, newEBADF("fdatasync", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- // If a file is open, it can be synced, no security check.
- return _fdatasync(pointer, fd, context, loop.getContext());
- }
-
- public int ftruncate(final int fd, final long offset) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "ftruncateSync");
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _ftruncate(pointer, fd, offset, SYNC_MODE, loop.getContext());
- }
-
- public int ftruncate(final int fd, final long offset, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callback(UV_FS_FTRUNCATE, context, newEBADF("ftruncate", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _ftruncate(pointer, fd, offset, context, loop.getContext());
- }
-
- public int sendfile(final int outFd, final int inFd, final long offset, final long length) {
- Objects.requireNonNull(getOpenedFile(outFd));
- Objects.requireNonNull(getOpenedFile(inFd));
- // No security check required.
- return _sendfile(pointer, outFd, inFd, offset, length, SYNC_MODE, loop.getContext());
- }
-
- public int sendfile(final int outFd, final int inFd, final long offset, final long length, final Object context) {
- Objects.requireNonNull(getOpenedFile(outFd));
- Objects.requireNonNull(getOpenedFile(inFd));
- // No security check required.
- return _sendfile(pointer, outFd, inFd, offset, length, context, loop.getContext());
- }
-
- public int chmod(final String path, final int mode) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _chmod(pointer, path, mode, SYNC_MODE, loop.getContext());
- }
-
- public int chmod(final String path, final int mode, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _chmod(pointer, path, mode, context, loop.getContext());
- }
-
- public int utime(final String path, final double atime, final double mtime) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _utime(pointer, path, atime, mtime, SYNC_MODE, loop.getContext());
- }
-
- public int utime(final String path, final double atime, final double mtime, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _utime(pointer, path, atime, mtime, context, loop.getContext());
- }
-
- public int futime(final int fd, final double atime, final double mtime) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "futimeSync");
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _futime(pointer, fd, atime, mtime, SYNC_MODE, loop.getContext());
- }
-
- public int futime(final int fd, final double atime, final double mtime, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callUTime(UV_FS_FUTIME, context, -1, newEBADF("futime", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _futime(pointer, fd, atime, mtime, context, loop.getContext());
- }
-
- public Stats lstat(final String path) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _lstat(pointer, path, SYNC_MODE, loop.getContext());
- }
-
- public Stats lstat(final String path, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _lstat(pointer, path, context, loop.getContext());
- }
-
- public int link(final String path, final String newPath) {
- Objects.requireNonNull(path);
- Objects.requireNonNull(newPath);
- LibUVPermission.checkHardLink(path, newPath);
- return _link(pointer, path, newPath, SYNC_MODE, loop.getContext());
- }
-
- public int link(final String path, final String newPath, final Object context) {
- Objects.requireNonNull(path);
- Objects.requireNonNull(newPath);
- LibUVPermission.checkHardLink(path, newPath);
- return _link(pointer, path, newPath, context, loop.getContext());
- }
-
- public int symlink(final String path, final String newPath, final int flags) {
- Objects.requireNonNull(path);
- Objects.requireNonNull(newPath);
- LibUVPermission.checkSymbolicLink(path, newPath);
- return _symlink(pointer, path, newPath, flags, SYNC_MODE, loop.getContext());
- }
-
- public int symlink(final String path, final String newPath, final int flags, final Object context) {
- Objects.requireNonNull(path);
- Objects.requireNonNull(newPath);
- LibUVPermission.checkSymbolicLink(path, newPath);
- return _symlink(pointer, path, newPath, flags, context, loop.getContext());
- }
-
- public String readlink(final String path) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _readlink(pointer, path, SYNC_MODE, loop.getContext());
- }
-
- public String readlink(final String path, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkReadFile(path);
- return _readlink(pointer, path, context, loop.getContext());
- }
-
- public int fchmod(final int fd, final int mode) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "fchmodSync");
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _fchmod(pointer, fd, mode, SYNC_MODE, loop.getContext());
- }
-
- public int fchmod(final int fd, final int mode, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callback(UV_FS_FCHMOD, context, newEBADF("fchmod", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _fchmod(pointer, fd, mode, context, loop.getContext());
- }
-
- public int chown(final String path, final int uid, final int gid) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _chown(pointer, path, uid, gid, SYNC_MODE, loop.getContext());
- }
-
- public int chown(final String path, final int uid, final int gid, final Object context) {
- Objects.requireNonNull(path);
- LibUVPermission.checkWriteFile(path);
- return _chown(pointer, path, uid, gid, context, loop.getContext());
- }
-
- public int fchown(final int fd, final int uid, final int gid) {
- final OpenedFile file = getOpenedFileAssertNonNull(fd, "fchown");
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _fchown(pointer, fd, uid, gid, SYNC_MODE, loop.getContext());
- }
-
- public int fchown(final int fd, final int uid, final int gid, final Object context) {
- final OpenedFile file = getOpenedFile(fd);
- if (file == null) {
- callback(UV_FS_FCHOWN, context, newEBADF("fchown", fd), loop.getContext());
- return -1;
- }
- Objects.requireNonNull(file);
- LibUVPermission.checkWriteFile(fd, file.getPath());
- return _fchown(pointer, fd, uid, gid, context, loop.getContext());
- }
-
- // should be private but used by unit tests.
- public OpenedFile getOpenedFile(final int fd) {
- // No security check, can retrieve path of an opened fd.
- return openedFiles.get(fd);
- }
-
- private OpenedFile getOpenedFileAssertNonNull(final int fd, final String method) {
- final OpenedFile file = openedFiles.get(fd);
- if (file == null) {
- throw newEBADF(method, fd);
- }
- return file;
- }
-
- private NativeException newEBADF(final String method, final int fd) {
- return new NativeException(9, "EBADF", "Bad file number: " + fd, method, null, null);
- }
-
- private void callback(final int type, final Object callback, final Exception error,final Object context) {
- switch (type) {
- case UV_FS_CUSTOM:
- if (onCustom != null) {
- loop.getCallbackHandler(context).handleFileCallback(onCustom, callback, error);
- }
- break;
- case UV_FS_SENDFILE:
- if (onSendfile != null) {
- loop.getCallbackHandler(context).handleFileCallback(onSendfile, callback, error);
- }
- break;
- case UV_FS_FTRUNCATE:
- if (onFTruncate != null) {
- loop.getCallbackHandler(context).handleFileCallback(onFTruncate, callback, error);
- }
- break;
- case UV_FS_CHMOD:
- if (onChmod != null) {
- loop.getCallbackHandler(context).handleFileCallback(onChmod, callback, error);
- }
- break;
- case UV_FS_FCHMOD:
- if (onFChmod != null) {
- loop.getCallbackHandler(context).handleFileCallback(onFChmod, callback, error);
- }
- break;
- case UV_FS_FSYNC:
- if (onFSync != null) {
- loop.getCallbackHandler(context).handleFileCallback(onFSync, callback, error);
- }
- break;
- case UV_FS_FDATASYNC:
- if (onFDatasync != null) {
- loop.getCallbackHandler(context).handleFileCallback(onFDatasync, callback, error);
- }
- break;
- case UV_FS_UNLINK:
- if (onUnlink != null) {
- loop.getCallbackHandler(context).handleFileCallback(onUnlink, callback, error);
- }
- break;
- case UV_FS_RMDIR:
- if (onRmDir != null) {
- loop.getCallbackHandler(context).handleFileCallback(onRmDir, callback, error);
- }
- break;
- case UV_FS_MKDIR:
- if (onMkDir != null) {
- loop.getCallbackHandler(context).handleFileCallback(onMkDir, callback, error);
- }
- break;
- case UV_FS_RENAME:
- if (onRename != null) {
- loop.getCallbackHandler(context).handleFileCallback(onRename, callback, error);
- }
- break;
- case UV_FS_LINK:
- if (onLink != null) {
- loop.getCallbackHandler(context).handleFileCallback(onLink, callback, error);
- }
- break;
- case UV_FS_SYMLINK:
- if (onSymLink != null) {
- loop.getCallbackHandler(context).handleFileCallback(onSymLink, callback, error);
- }
- break;
- case UV_FS_CHOWN:
- if (onChown != null) {
- loop.getCallbackHandler(context).handleFileCallback(onChown, callback, error);
- }
- break;
- case UV_FS_FCHOWN:
- if (onFChown != null) {
- loop.getCallbackHandler(context).handleFileCallback(onFChown, callback, error);
- }
- break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private void callClose(final Object callback, final int fd, final Exception error, final Object context) {
- if (onClose != null) {
- loop.getCallbackHandler(context).handleFileCloseCallback(onClose, callback, fd, error);
- }
- }
-
- private void callOpen(final Object callback, final int fd, final String path, final int flags, final Exception error, final Object context) {
- if (fd != -1) {
- openedFiles.put(fd, new OpenedFile(path, flags));
- }
- if (onOpen != null) {
- loop.getCallbackHandler(context).handleFileOpenCallback(onOpen, callback, fd, error);
- }
- }
-
- private void callRead(final Object callback, final int bytesRead, final ByteBuffer data, final Exception error, final Object context) {
- if (onRead != null) {
- loop.getCallbackHandler(context).handleFileReadCallback(onRead, callback, bytesRead, data, error);
- }
- }
-
- private void callReadDir(final Object callback, final String[] names, final Exception error, final Object context) {
- if (onReadDir != null) {
- loop.getCallbackHandler(context).handleFileReadDirCallback(onReadDir, callback, names, error);
- }
- }
-
- private void callReadLink(final Object callback, final String name, final Exception error, final Object context) {
- if (onReadLink != null) {
- loop.getCallbackHandler(context).handleFileReadLinkCallback(onReadLink, callback, name, error);
- }
- }
-
- private void callStats(final int type, final Object callback, final Stats stats, final Exception error, final Object context) {
- switch(type) {
- case UV_FS_FSTAT:
- if (onFStat != null) {
- loop.getCallbackHandler(context).handleFileStatsCallback(onFStat, callback, stats, error);
- }
- break;
- case UV_FS_LSTAT:
- if (onLStat != null) {
- loop.getCallbackHandler(context).handleFileStatsCallback(onLStat, callback, stats, error);
- }
- break;
- case UV_FS_STAT:
- if (onStat != null) {
- loop.getCallbackHandler(context).handleFileStatsCallback(onStat, callback, stats, error);
- }
- break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private void callUTime(final int type, final Object callback, final long time, final Exception error, final Object context) {
- switch(type) {
- case UV_FS_UTIME:
- if (onUTime != null) {
- loop.getCallbackHandler(context).handleFileUTimeCallback(onUTime, callback, time, error);
- }
- break;
- case UV_FS_FUTIME:
- if (onFUTime != null) {
- loop.getCallbackHandler(context).handleFileUTimeCallback(onFUTime, callback, time, error);
- }
- break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private void callWrite(final Object callback, final int bytesWritten, final Exception error, final Object context) {
- if (onWrite != null) {
- loop.getCallbackHandler(context).handleFileWriteCallback(onWrite, callback, bytesWritten, error);
- }
- }
-
- private static native void _static_initialize();
-
- private static native long _new();
-
- private native void _initialize(final long ptr, final long loop);
-
- private native int _close(final long ptr);
-
- private native int _close(final long ptr, final int fd, final Object callback, final Object context);
-
- private native int _open(final long ptr, final String path, final int flags, final int mode, final Object callback, final Object context);
-
- private native int _read(final long ptr, final int fd, final ByteBuffer buffer, final byte[] data, final long length, final long offset, final long position, final Object callback, final Object context);
-
- private native int _unlink(final long ptr, final String path, final Object callback, final Object context);
-
- private native int _write(final long ptr, final int fd, final ByteBuffer buffer, final byte[] data, final long length, final long offset, final long position, final Object callback, final Object context);
-
- private native int _mkdir(final long ptr, final String path, final int mode, final Object callback, final Object context);
-
- private native int _rmdir(final long ptr, final String path, final Object callback, final Object context);
-
- private native String[] _readdir(final long ptr, final String path, final int flags, final Object callback, final Object context);
-
- private native Stats _stat(final long ptr, final String path, final Object callback, final Object context);
-
- private native Stats _fstat(final long ptr, final int fd, final Object callback, final Object context);
-
- private native int _rename(final long ptr, final String path, final String newPath, final Object callback, final Object context);
-
- private native int _fsync(final long ptr, final int fd, final Object callback, final Object context);
-
- private native int _fdatasync(final long ptr, final int fd, final Object callback, final Object context);
-
- private native int _ftruncate(final long ptr, final int fd, final long offset, final Object callback, final Object context);
-
- private native int _sendfile(final long ptr, final int outFd, final int inFd, final long offset, final long length, final Object callback, final Object context);
-
- private native int _chmod(final long ptr, final String path, final int mode, final Object callback, final Object context);
-
- private native int _utime(final long ptr, final String path, final double atime, final double mtime, final Object callback, final Object context);
-
- private native int _futime(final long ptr, final int fd, final double atime, final double mtime, final Object callback, final Object context);
-
- private native Stats _lstat(final long ptr, final String path, final Object callback, final Object context);
-
- private native int _link(final long ptr, final String path, final String newPath, final Object callback, final Object context);
-
- private native int _symlink(final long ptr, final String path, final String newPath, final int flags, final Object callback, final Object context);
-
- private native String _readlink(final long ptr, final String path, final Object callback, final Object context);
-
- private native int _fchmod(final long ptr, final int fd, final int mode, final Object callback, final Object context);
-
- private native int _chown(final long ptr, final String path, final int uid, final int gid, final Object callback, final Object context);
-
- private native int _fchown(final long ptr, final int fd, final int uid, final int gid, final Object callback, final Object context);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/LibUV.java b/app/src/main/java/com/iwebpp/libuvpp/LibUV.java
deleted file mode 100644
index 7fe58a9..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/LibUV.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-import java.util.Objects;
-
-public final class LibUV {
-
- static {
- System.loadLibrary("uvpp-jni");
- }
-
- private LibUV() {
- }
-
- // misc
-
- public static String version() {
- return _version();
- }
-
- public static void disableStdioInheritance() {
- _disable_stdio_inheritance();
- }
-
- // process
-
- public static String exePath() {
- LibUVPermission.checkPermission(LibUVPermission.PROCESS_EXE_PATH);
- return _exe_path();
- }
-
- public static String cwd() {
- LibUVPermission.checkPermission(LibUVPermission.PROCESS_CWD);
- return _cwd();
- }
-
- public static void chdir(final String dir) {
- LibUVPermission.checkPermission(LibUVPermission.PROCESS_CHDIR);
- _chdir(dir);
- }
-
- public static String getTitle() {
- LibUVPermission.checkPermission(LibUVPermission.PROCESS_GET_TITLE);
- return _getTitle();
- }
-
- public static void setTitle(final String value) {
- Objects.requireNonNull(value);
- LibUVPermission.checkPermission(LibUVPermission.PROCESS_SET_TITLE);
- _setTitle(value);
- }
-
- public static int kill(final int pid, final int signal) {
- LibUVPermission.checkPermission(LibUVPermission.PROCESS_KILL);
- return _kill(pid, signal);
- }
-
- public static int rss() {
- return _rss();
- }
-
- // os
-
- public static double getUptime() {
- return _getUptime();
- }
-
- public static double[] getLoadAvg() {
- return _getLoadAvg();
- }
-
- public static double getTotalMem() {
- return _getTotalMem();
- }
-
- public static double getFreeMem() {
- return _getFreeMem();
- }
-
- public static Object[] getCPUs() {
- return _getCPUs();
- }
-
- public static boolean isIPv6(final String ip) {
- Objects.requireNonNull(ip);
- return _isIPv6(ip);
- }
-
- public static boolean isIPv4(final String ip) {
- Objects.requireNonNull(ip);
- return _isIPv4(ip);
- }
-
- // misc
-
- private static native String _version();
-
- private static native void _disable_stdio_inheritance();
-
- // process
-
- private static native String _exe_path();
-
- private static native String _cwd();
-
- private static native void _chdir(String dir);
-
- private static native String _getTitle();
-
- private static native void _setTitle(String value);
-
- private static native int _kill(int pid, int signal);
-
- private static native int _rss();
-
- // os
-
- private static native double _getUptime();
-
- private static native double[] _getLoadAvg();
-
- private static native double _getTotalMem();
-
- private static native double _getFreeMem();
-
- private static native Object[] _getCPUs();
-
- // dns
-
- private static native boolean _isIPv6(String ip);
-
- private static native boolean _isIPv4(String ip);
-
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/LibUVPermission.java b/app/src/main/java/com/iwebpp/libuvpp/LibUVPermission.java
deleted file mode 100644
index 84e56e8..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/LibUVPermission.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-///import java.nio.file.LinkPermission;
-import java.security.BasicPermission;
-
-import com.iwebpp.libuvpp.Address;
-
-/**
- * Permissions specific to LibUV.
- * Permission examples:
- * permission net.java.libuv.LibUVPermission "libuv.process.*";
- * permission net.java.libuv.LibUVPermission "libuv.process.chdir";
- * permission net.java.libuv.LibUVPermission "libuv.pipe.*";
- * permission net.java.libuv.LibUVPermission "libuv.signal.9";
- * permission net.java.libuv.LibUVPermission "libuv.handle";
- * permission net.java.libuv.LibUVPermission "libuv.loop.multi";
- * - Child process spawning is authorized thanks to SecurityManager.checkExec.
- * libuv.spawn permission is also required.
- * - TCP/UDP are authorized thanks to calls to SecurityManager.checkConnect/checkListen/checkAccept
- * libuv.udp or libuv.tcp permission are also required.
- */
-public final class LibUVPermission extends BasicPermission {
-
- static final long serialVersionUID = 8529091307897434802L;
-
- public interface AddressResolver {
- public Address resolve();
- }
-
- private static final String LIBUV = "libuv";
- private static final String PREFIX = LIBUV + ".";
- // process
- private static final String PROCESS = PREFIX + "process.";
- public static final String PROCESS_CHDIR = PROCESS + "chdir";
- public static final String PROCESS_CWD = PROCESS + "cwd";
- public static final String PROCESS_EXE_PATH = PROCESS + "exePath";
- public static final String PROCESS_GET_TITLE = PROCESS + "getTitle";
- public static final String PROCESS_KILL = PROCESS + "kill";
- public static final String PROCESS_SET_TITLE = PROCESS + "setTitle";
- // pipe
- private static final String PIPE = PREFIX + "pipe.";
- public static final String PIPE_BIND = PIPE + "bind";
- public static final String PIPE_CONNECT = PIPE + "connect";
- public static final String PIPE_OPEN = PIPE + "open";
- public static final String PIPE_ACCEPT = PIPE + "accept";
-
- // handle
- public static final LibUVPermission HANDLE = new LibUVPermission(PREFIX + "handle");
-
- // loop
- public static final LibUVPermission MULTI_LOOP = new LibUVPermission(PREFIX + "loop.multi");
-
- // signal
- public static final String SIGNAL = PREFIX + "signal.";
-
- public LibUVPermission(final String name) {
- super(name);
- }
-
- public static void checkPermission(final String name) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (System.getSecurityManager() != null) {
- final LibUVPermission perm = new LibUVPermission(name);
- sm.checkPermission(perm);
- }*/
- }
-
- public static void checkHandle() {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (System.getSecurityManager() != null) {
- sm.checkPermission(HANDLE);
- }*/
- }
-
- public static void checkNewLoop(final int count) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (count > 1 && System.getSecurityManager() != null) {
- sm.checkPermission(MULTI_LOOP);
- }*/
- }
-
- public static void checkSpawn(final String cmd) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (System.getSecurityManager() != null) {
- sm.checkExec(cmd);
- }*/
- }
-
- public static void checkBind(final String host, final int port) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- // Side effect is to check permission to resolve host.
- new InetSocketAddress(host, port);
- }*/
- }
-
- public static void checkConnect(final String host, final int port) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkConnect(host, port);
- }*/
- }
-
- public static void checkListen(final int port) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkListen(port);
- }*/
- }
-
- public static void checkAccept(final AddressResolver resolver) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- final Address addr = resolver.resolve();
-
- sm.checkAccept(addr.getIp(), addr.getPort());
- }*/
- }
-
- public static void checkUDPBind(final String host, final int port) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- checkBind(host, port);
- sm.checkListen(port);
- }*/
- }
-
- public static void checkUDPSend(final String host, final int port) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- try {
- final InetAddress addr = InetAddress.getByName(host);
- if (addr.isMulticastAddress()) {
- sm.checkMulticast(addr);
- }
- } catch (final Exception ex) {
- throw new RuntimeException(ex);
- }
- sm.checkConnect(host, port);
- }*/
- }
-
- /*
- * Files
- */
- private static boolean isFlag(final int mask, final int flag) {
- return (mask & flag) == flag;
- }
-
- public static void checkOpenFile(final String path, final int mask) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- // write
- if (isFlag(mask, Constants.O_CREAT) ||
- isFlag(mask, Constants.O_WRONLY)||
- isFlag(mask, Constants.O_RDWR) ||
- isFlag(mask, Constants.O_TRUNC)) {
- sm.checkWrite(path);
- }
-
- // read
- if (isFlag(mask, Constants.O_RDONLY) ||
- isFlag(mask, Constants.O_RDWR)) {
- sm.checkRead(path);
- }
- }*/
- }
-
- public static void checkReadFile(final String path) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkRead(path);
- }*/
- }
-
- public static void checkWriteFile(final String path) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkWrite(path);
- }*/
- }
-
- public static void checkReadFile(final int fd, final String path) {
- /*
- // stdin, stdout, and stderr does not need to be checked as they are provided by the underlying platform.
- // Needed to support command line redirection.
- if (fd == 0 || fd == 1 || fd == 2) {
- return;
- }
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkRead(path);
- }*/
- }
-
- public static void checkWriteFile(final int fd, final String path) {
- /*
- // stdin, stdout, and stderr does not need to be checked as they are provided by the underlying platform.
- // Needed to support command line redirection.
- if (fd == 0 || fd == 1 || fd == 2) {
- return;
- }
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkWrite(path);
- }*/
- }
-
- public static void checkDeleteFile(final String path) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkDelete(path);
- }*/
- }
-
- public static void checkHardLink(final String existing, final String link) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- ///sm.checkPermission(new LinkPermission("hard"));
- sm.checkWrite(existing);
- sm.checkWrite(link);
- }*/
- }
-
- public static void checkSymbolicLink(final String existing, final String link) {
- /*
- final SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- ///sm.checkPermission(new LinkPermission("symbolic"));
- sm.checkWrite(existing);
- sm.checkWrite(link);
- }*/
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/NativeException.java b/app/src/main/java/com/iwebpp/libuvpp/NativeException.java
deleted file mode 100644
index ef620f8..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/NativeException.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-@SuppressWarnings("serial")
-public final class NativeException extends RuntimeException {
-
- private final int errno;
- private final String errnoString;
- private final String errnoMessage;
- private final String syscall;
- private final String path;
-
- public NativeException(final int errno,
- final String errnoString,
- final String errnoMessage,
- final String syscall,
- final String message,
- final String path) {
- super(message);
- this.errno = errno;
- this.errnoString = errnoString;
- this.errnoMessage = errnoMessage;
- this.syscall = syscall;
- this.path = path;
- }
-
- public NativeException(final String message) {
- super(message);
- this.errno = 0;
- this.errnoString = null;
- this.errnoMessage = null;
- this.syscall = null;
- this.path = null;
- }
-
- public NativeException(final int errno,
- final String syscall,
- final String message) {
- super(message);
- this.errno = errno;
- this.errnoString = null;
- this.errnoMessage = null;
- this.syscall = syscall;
- this.path = null;
- }
-
- public NativeException(final String syscall,
- final String message) {
- super(message);
- this.errno = 0;
- this.errnoString = null;
- this.errnoMessage = null;
- this.syscall = syscall;
- this.path = null;
- }
-
- public int errno() {
- return errno;
- }
-
- public String errnoString() {
- return errnoString;
- }
-
- public String getErrnoMessage() {
- return errnoMessage;
- }
-
- public String syscall() {
- return syscall;
- }
-
- public String path() {
- return path;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(4096);
- sb.append("errno: ");
- sb.append(errno);
- sb.append(", errnoString: ");
- sb.append(errnoString);
- sb.append(", errnoMessage: ");
- sb.append(errnoMessage);
- if (syscall != null && syscall.length() > 0) {
- sb.append(", syscall: ");
- sb.append(syscall);
- }
- if (path != null && path.length() > 0) {
- sb.append(", path: ");
- sb.append(path);
- }
- sb.append(", message: ");
- sb.append(super.getMessage());
- return sb.toString();
- }
-
- public static void static_initialize() {
- _static_initialize();
- }
-
- private static native void _static_initialize();
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/README.md b/app/src/main/java/com/iwebpp/libuvpp/README.md
deleted file mode 100644
index d77a3d6..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-libuvpp + Oracle/libuv-JNI porting to Android
-
-third-party source: Oracle libuv-JNI project
\ No newline at end of file
diff --git a/app/src/main/java/com/iwebpp/libuvpp/Stats.java b/app/src/main/java/com/iwebpp/libuvpp/Stats.java
deleted file mode 100644
index 45d2d0a..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/Stats.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-public class Stats {
-
- private int dev;
- private int ino;
- private int mode;
- private int nlink;
- private int uid;
- private int gid;
- private int rdev;
- private long size;
- private int blksize;
- private long blocks;
- private long atime;
- private long mtime;
- private long ctime;
-
- public Stats() {
- }
-
- public Stats(final int dev, final int ino, final int mode,
- final int nlink, final int uid, final int gid,
- final int rdev, final long size, final int blksize,
- final long blocks, final long atime, final long mtime,
- final long ctime) {
- set(dev, ino, mode, nlink, uid, gid, rdev, size, blksize, blocks, atime, mtime, ctime);
- }
-
- public void set(final int dev, final int ino, final int mode,
- final int nlink, final int uid, final int gid,
- final int rdev, final long size, final int blksize,
- final long blocks, final long atime, final long mtime,
- final long ctime) {
- this.dev = dev;
- this.ino = ino;
- this.mode = mode;
- this.nlink = nlink;
- this.uid = uid;
- this.gid = gid;
- this.rdev = rdev;
- this.size = size;
- this.blksize = blksize;
- this.blocks = blocks;
- this.atime = atime;
- this.mtime = mtime;
- this.ctime = ctime;
- }
-
- public int getDev() {
- return dev;
- }
-
- public int getIno() {
- return ino;
- }
-
- public int getMode() {
- return mode;
- }
-
- public int getNlink() {
- return nlink;
- }
-
- public int getUid() {
- return uid;
- }
-
- public int getGid() {
- return gid;
- }
-
- public int getRdev() {
- return rdev;
- }
-
- public long getSize() {
- return size;
- }
-
- public int getBlksize() {
- return blksize;
- }
-
- public long getBlocks() {
- return blocks;
- }
-
- public long getAtime() {
- return atime;
- }
-
- public long getMtime() {
- return mtime;
- }
-
- public long getCtime() {
- return ctime;
- }
-
- @Override
- public String toString() {
- return "{ dev: " + dev +
- " ino: " + ino +
- " mode: " + mode +
- " nlink: " + nlink +
- " uid: " + uid +
- " gid: " + gid +
- " rdev: " + rdev +
- " size: " + size +
- " blksize: " + blksize +
- " blocks: " + blocks +
- " atime: " + getAtime() +
- " mtime: " + getMtime() +
- " ctime: " + getCtime() + " }";
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/StringUtils.java b/app/src/main/java/com/iwebpp/libuvpp/StringUtils.java
deleted file mode 100644
index 73bdcb2..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/StringUtils.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayDeque;
-import java.util.Deque;
-
-
-public final class StringUtils {
-
- private static Method getComponentsMethod = null;
- static {
- try {
- getComponentsMethod = ConsString.class.getDeclaredMethod("getComponents");
- } catch (NoSuchMethodException ignore) {
- }
- }
-
- public static Deque parts(final ConsString root) {
- final Deque parts = new ArrayDeque();
- if (!consStringHasLeftRight()) {
- return fallbackParts(root, parts);
- }
-
- try {
- return reflectiveParts(parts, root);
- } catch (Exception e) {
- return fallbackParts(root, parts);
- }
- }
-
- public static boolean consStringHasLeftRight() {
- return getComponentsMethod != null;
- }
-
- private static Deque fallbackParts(final ConsString root, final Deque parts) {
- // fallback - return flattened contents as a single part
- parts.addFirst(root.toString());
- return parts;
- }
-
- public static Deque reflectiveParts(final Deque parts, final ConsString root)
- throws InvocationTargetException, IllegalAccessException {
-
- assert getComponentsMethod != null;
- final CharSequence[] rootParts = (CharSequence[]) getComponentsMethod.invoke(root);
- assert rootParts != null;
- assert rootParts.length == 2;
-
- final CharSequence left = rootParts[0];
- final CharSequence right = rootParts[1];
- final Deque stack = new ArrayDeque();
-
- stack.addFirst(left);
- CharSequence cs = right;
-
- // reuse the ConsString.flatten() algorithm, without actually flattening
- do {
- if (cs instanceof ConsString) {
- final ConsString cons = (ConsString) cs;
- final CharSequence[] consParts = (CharSequence[]) getComponentsMethod.invoke(cons);
- assert consParts != null;
- assert consParts.length == 2;
- stack.addFirst(consParts[0]); // left
- cs = consParts[1]; // right
- } else {
- final String str = (String) cs;
- if (str.length() > 0) {
- parts.offerFirst(str);
- }
- cs = stack.isEmpty() ? null : stack.pollFirst();
- }
- } while (cs != null);
-
- return parts;
- }
-
- public static boolean hasMultiByte(final String str, final String encoding) {
- /*
- switch (encoding) {
- case "base64":
- case "hex":
- case "ucs2":
- case "utf16":
- case "utf16le":
- case "utf16be":
- case "utf32":
- case "utf32le":
- case "utf32be":
- case "ucs-2":
- case "utf-16":
- case "utf-16le":
- case "utf-16be":
- case "utf-32":
- case "utf32-le":
- case "utf32-be":
- return true;
-
- case "utf8":
- case "utf-8":
- final int length = str.length();
- for (int i=0; i < length; i++) {
- if (str.charAt(i) > 0x7f) { // https://en.wikipedia.org/wiki/UTF-8
- return true;
- }
- }
- break;
-
- default:
- return true; // assume unknown encoding is multi-byte - slow but safe
- }
- */
- if (encoding == "utf32-be" || encoding == "utf32-le" || encoding == "utf-32" ||
- encoding == "utf32be" || encoding == "utf32le" || encoding == "utf32" ||
-
- encoding == "utf16-be" || encoding == "utf16-le" || encoding == "utf-16" ||
- encoding == "utf16be" || encoding == "utf16le" || encoding == "utf16" ||
-
- encoding == "ucs-2" ||
- encoding == "ucs2" ||
-
- encoding == "hex" ||
-
- encoding == "base64") {
- return true;
- } else if (encoding == "utf8" || encoding == "utf-8") {
- final int length = str.length();
- for (int i=0; i < length; i++) {
- if (str.charAt(i) > 0x7f) { // https://en.wikipedia.org/wiki/UTF-8
- return true;
- }
- }
-
- // ascii, raw, binary, iso-8859-1 are not multi-byte
- return false;
- } else {
- return true; // assume unknown encoding is multi-byte - slow but safe
- }
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/AsyncCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/AsyncCallback.java
deleted file mode 100644
index 2980448..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/AsyncCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface AsyncCallback {
-
- public void onSend(int status) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackExceptionHandler.java b/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackExceptionHandler.java
deleted file mode 100644
index 1785302..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackExceptionHandler.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface CallbackExceptionHandler {
-
- public void handle(Throwable ex);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackHandler.java b/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackHandler.java
deleted file mode 100644
index e9eaded..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackHandler.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import java.nio.ByteBuffer;
-
-import com.iwebpp.libuvpp.Address;
-import com.iwebpp.libuvpp.Stats;
-
-public interface CallbackHandler {
- public void handleAsyncCallback(AsyncCallback cb, int status);
- public void handleCheckCallback(CheckCallback cb, int status);
- public void handleIdleCallback(IdleCallback cb, int status);
- public void handlePollCallback(PollCallback cb, int status, int events);
- public void handleSignalCallback(SignalCallback cb, int signum);
- public void handleStreamReadCallback(StreamReadCallback cb, ByteBuffer data);
- public void handleStreamRead2Callback(StreamRead2Callback cb, ByteBuffer data, long handle, int type);
- public void handleStreamWriteCallback(StreamWriteCallback cb, int status, Exception error);
- public void handleFileCallback(FileCallback cb, Object context, Exception error);
- public void handleFileCloseCallback(FileCloseCallback cb, Object context, int fd, Exception error);
- public void handleFileOpenCallback(FileOpenCallback cb, Object context, int fd, Exception error);
- public void handleStreamConnectCallback(StreamConnectCallback cb, int status, Exception error);
- public void handleStreamConnectionCallback(StreamConnectionCallback cb, int status, Exception error);
- public void handleStreamCloseCallback(StreamCloseCallback cb);
- public void handleStreamShutdownCallback(StreamShutdownCallback cb, int status, Exception error);
- public void handleFileReadCallback(FileReadCallback cb, Object context, int bytesRead, ByteBuffer data, Exception error);
- public void handleFileReadDirCallback(FileReadDirCallback cb, Object context, String[] names, Exception error);
- public void handleFileReadLinkCallback(FileReadLinkCallback cb, Object context, String name, Exception error);
- public void handleFileStatsCallback(FileStatsCallback cb, Object context, Stats stats, Exception error);
- public void handleFileUTimeCallback(FileUTimeCallback cb, Object context, long time, Exception error);
- public void handleFileWriteCallback(FileWriteCallback cb, Object context, int bytesWritten, Exception error);
- public void handleFileEventCallback(FileEventCallback cb, int status, String event, String filename);
- public void handleFilePollCallback(FilePollCallback cb, int status, Stats previous, Stats current);
- public void handleFilePollStopCallback(FilePollStopCallback cb);
- public void handleProcessCloseCallback(ProcessCloseCallback cb);
- public void handleProcessExitCallback(ProcessExitCallback cb, int status, int signal, Exception error);
- public void handleTimerCallback(TimerCallback cb, int status);
- public void handleUDPRecvCallback(UDPRecvCallback cb, int nread, ByteBuffer data, Address address);
- public void handleUDPSendCallback(UDPSendCallback cb, int status, Exception error);
- public void handleUDPCloseCallback(UDPCloseCallback cb);
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackHandlerFactory.java b/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackHandlerFactory.java
deleted file mode 100644
index 5a0ea0f..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/CallbackHandlerFactory.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface CallbackHandlerFactory {
- public CallbackHandler newCallbackHandler(Object context);
- public CallbackHandler newCallbackHandler();
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/CheckCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/CheckCallback.java
deleted file mode 100644
index 40d2152..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/CheckCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface CheckCallback {
-
- public void onCheck(int status) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/ContextProvider.java b/app/src/main/java/com/iwebpp/libuvpp/cb/ContextProvider.java
deleted file mode 100644
index 5d4004b..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/ContextProvider.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface ContextProvider {
-
- public Object getContext();
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileCallback.java
deleted file mode 100644
index b4df5af..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileCallback {
-
- public void onDone(Object context, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileCloseCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileCloseCallback.java
deleted file mode 100644
index 6e0dc95..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileCloseCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileCloseCallback {
-
- public void onClose(Object context, int fd, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileEventCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileEventCallback.java
deleted file mode 100644
index 4671a58..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileEventCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileEventCallback {
-
- public void onEvent(int status, String event, String filename) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileOpenCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileOpenCallback.java
deleted file mode 100644
index 0b931c7..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileOpenCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileOpenCallback {
-
- public void onOpen(Object context, int fd, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FilePollCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FilePollCallback.java
deleted file mode 100644
index 4dad95b..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FilePollCallback.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import com.iwebpp.libuvpp.Stats;
-
-public interface FilePollCallback {
-
- public void onPoll(int status, Stats previous, Stats current) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FilePollStopCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FilePollStopCallback.java
deleted file mode 100644
index 903f5e8..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FilePollStopCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FilePollStopCallback {
-
- public void onStop() throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadCallback.java
deleted file mode 100644
index d1fa2cc..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadCallback.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import java.nio.ByteBuffer;
-
-public interface FileReadCallback {
-
- public void onRead(Object context, int bytesRead, ByteBuffer data, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadDirCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadDirCallback.java
deleted file mode 100644
index 2a2bbb4..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadDirCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileReadDirCallback {
-
- public void onReadDir(Object context, String[] names, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadLinkCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadLinkCallback.java
deleted file mode 100644
index 4b801cd..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileReadLinkCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileReadLinkCallback {
-
- public void onReadLink(Object context, String name, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileStatsCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileStatsCallback.java
deleted file mode 100644
index cdbfaa2..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileStatsCallback.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import com.iwebpp.libuvpp.Stats;
-
-public interface FileStatsCallback {
-
- public void onStats(Object context, Stats stats, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileUTimeCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileUTimeCallback.java
deleted file mode 100644
index adbee4e..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileUTimeCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileUTimeCallback {
-
- public void onUTime(Object context, long time, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/FileWriteCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/FileWriteCallback.java
deleted file mode 100644
index 6a695db..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/FileWriteCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface FileWriteCallback {
-
- public void onWrite(Object context, int bytesWritten, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/IdleCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/IdleCallback.java
deleted file mode 100644
index 36d2701..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/IdleCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface IdleCallback {
-
- public void onIdle(int status) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/PollCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/PollCallback.java
deleted file mode 100644
index 94196e3..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/PollCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface PollCallback {
-
- public void onPoll(int status, int events) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/ProcessCloseCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/ProcessCloseCallback.java
deleted file mode 100644
index e76b72b..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/ProcessCloseCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface ProcessCloseCallback {
-
- public void onClose() throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/ProcessExitCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/ProcessExitCallback.java
deleted file mode 100644
index 9789a4d..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/ProcessExitCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface ProcessExitCallback {
-
- public void onExit(int status, int signal, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/SignalCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/SignalCallback.java
deleted file mode 100644
index 8ede938..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/SignalCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface SignalCallback {
-
- public void onSignal(int signum) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamCloseCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamCloseCallback.java
deleted file mode 100644
index f0829ca..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamCloseCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface StreamCloseCallback {
-
- public void onClose() throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamConnectCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamConnectCallback.java
deleted file mode 100644
index 3084699..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamConnectCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface StreamConnectCallback {
-
- public void onConnect(int status, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamConnectionCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamConnectionCallback.java
deleted file mode 100644
index 7c04c4c..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamConnectionCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface StreamConnectionCallback {
-
- public void onConnection(int status, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamRead2Callback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamRead2Callback.java
deleted file mode 100644
index 872a96b..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamRead2Callback.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import java.nio.ByteBuffer;
-
-public interface StreamRead2Callback {
-
- public void onRead2(ByteBuffer data, long handle, int type) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamReadCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamReadCallback.java
deleted file mode 100644
index 9616e17..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamReadCallback.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import java.nio.ByteBuffer;
-
-public interface StreamReadCallback {
-
- public void onRead(ByteBuffer data) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamShutdownCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamShutdownCallback.java
deleted file mode 100644
index 2e6157f..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamShutdownCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface StreamShutdownCallback {
-
- public void onShutdown(int status, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamWriteCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/StreamWriteCallback.java
deleted file mode 100644
index 02565f0..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/StreamWriteCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface StreamWriteCallback {
-
- public void onWrite(int status, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/TimerCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/TimerCallback.java
deleted file mode 100644
index 2579417..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/TimerCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface TimerCallback {
-
- public void onTimer(int status) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/UDPCloseCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/UDPCloseCallback.java
deleted file mode 100644
index 34c1a5d..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/UDPCloseCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface UDPCloseCallback {
-
- public void onClose() throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/UDPRecvCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/UDPRecvCallback.java
deleted file mode 100644
index d4d63f9..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/UDPRecvCallback.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-import java.nio.ByteBuffer;
-
-import com.iwebpp.libuvpp.Address;
-
-public interface UDPRecvCallback {
-
- public void onRecv(int nread, ByteBuffer data, Address address) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/cb/UDPSendCallback.java b/app/src/main/java/com/iwebpp/libuvpp/cb/UDPSendCallback.java
deleted file mode 100644
index cfe5fa0..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/cb/UDPSendCallback.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.cb;
-
-public interface UDPSendCallback {
-
- public void onSend(int status, Exception error) throws Exception;
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/AsyncHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/AsyncHandle.java
deleted file mode 100644
index 59a34cb..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/AsyncHandle.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import com.iwebpp.libuvpp.cb.AsyncCallback;
-
-public class AsyncHandle extends Handle {
-
- private final AtomicBoolean closed = new AtomicBoolean(false);
-
- private AsyncCallback onSend = null;
-
- static {
- _static_initialize();
- }
-
- public void setAsyncCallback(final AsyncCallback callback) {
- onSend = callback;
- }
-
- public AsyncHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- _initialize(pointer);
- }
-
- public int send() {
- return closed.get() ? -1 : _send(pointer);
- }
-
- public void close() {
- if (closed.compareAndSet(false, true)) {
- _close(pointer);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callSend(final int status) {
- if (onSend != null) {loop.getCallbackHandler().handleAsyncCallback(onSend, status);}
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _send(final long ptr);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/CheckHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/CheckHandle.java
deleted file mode 100644
index 22261bc..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/CheckHandle.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import com.iwebpp.libuvpp.cb.CheckCallback;
-
-public class CheckHandle extends Handle {
-
- private boolean closed;
-
- private CheckCallback onCheck = null;
- private CheckCallback onClose = null;
-
- static {
- _static_initialize();
- }
-
- public void setCheckCallback(final CheckCallback callback) {
- onCheck = callback;
- }
-
- public void setCloseCallback(final CheckCallback callback) {
- onClose = callback;
- }
-
- protected CheckHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- _initialize(pointer);
- }
-
- public int start() {
- return _start(pointer);
- }
-
- public int stop() {
- return _stop(pointer);
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callback(final int type, final int status) {
- switch (type) {
- case 1: if (onCheck != null) {loop.getCallbackHandler().handleCheckCallback(onCheck, status);} break;
- case 2: if (onClose != null) {loop.getCallbackHandler().handleCheckCallback(onClose, status);} break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long ptr);
-
- private native int _stop(final long ptr);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/DefaultHandleFactory.java b/app/src/main/java/com/iwebpp/libuvpp/handles/DefaultHandleFactory.java
deleted file mode 100644
index a70b45c..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/DefaultHandleFactory.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import com.iwebpp.libuvpp.Files;
-
-public class DefaultHandleFactory implements HandleFactory {
-
- private LoopHandle loop;
-
- public static HandleFactory newFactory() { // generally only for tests
- return new DefaultHandleFactory().initialize(new LoopHandle());
- }
-
- @Override
- public HandleFactory initialize(final LoopHandle loop) {
- if (this.loop != null) throw new IllegalStateException("already initialized");
- this.loop = loop;
- return this;
- }
-
- @Override
- public LoopHandle getLoopHandle() {
- return loop;
- }
-
- @Override
- public AsyncHandle newAsyncHandle() {
- assert loop != null;
- return new AsyncHandle(loop);
- }
-
- @Override
- public CheckHandle newCheckHandle() {
- assert loop != null;
- return new CheckHandle(loop);
- }
-
- @Override
- public IdleHandle newIdleHandle() {
- assert loop != null;
- return new IdleHandle(loop);
- }
-
- @Override
- public PipeHandle newPipeHandle(final boolean ipc) {
- assert loop != null;
- return new PipeHandle(loop, ipc);
- }
-
- @Override
- public PipeHandle newPipeHandle(final long pointer,
- final boolean ipc) {
- assert loop != null;
- return new PipeHandle(loop, pointer, ipc);
- }
-
- @Override
- public PollHandle newPollHandle(final int fd) {
- assert loop != null;
- return new PollHandle(loop, fd);
- }
-
- @Override
- public PollHandle newPollHandle(final long socket) {
- assert loop != null;
- return new PollHandle(loop, socket);
- }
-
- @Override
- public ProcessHandle newProcessHandle() {
- assert loop != null;
- return new ProcessHandle(loop);
- }
-
- /*@Override
- public SignalHandle newSignalHandle() {
- assert loop != null;
- return new SignalHandle(loop);
- }*/
-
- @Override
- public TCPHandle newTCPHandle() {
- assert loop != null;
- return new TCPHandle(loop);
- }
-
- @Override
- public TCPHandle newTCPHandle(final long pointer) {
- assert loop != null;
- return new TCPHandle(loop, pointer, true);
- }
-
- /*@Override
- public TCPHandle openTCPHandle(final long socket) {
- assert loop != null;
- return new TCPHandle(loop, socket);
- }*/
-
- @Override
- public UDTHandle newUDTHandle() {
- assert loop != null;
- return new UDTHandle(loop);
- }
-
- @Override
- public UDTHandle newUDTHandle(final long pointer) {
- assert loop != null;
- return new UDTHandle(loop, pointer, true);
- }
-
- /*@Override
- public UDTHandle openUDTHandle(final long socket) {
- assert loop != null;
- return new UDTHandle(loop, socket);
- }*/
-
- @Override
- public TimerHandle newTimerHandle() {
- assert loop != null;
- return new TimerHandle(loop);
- }
-
- @Override
- public TTYHandle newTTYHandle(final int fd,
- final boolean readable) {
- assert loop != null;
- return new TTYHandle(loop, fd, readable);
- }
-
- @Override
- public UDPHandle newUDPHandle() {
- assert loop != null;
- return new UDPHandle(loop);
- }
-
- @Override
- public UDPHandle newUDPHandle(final long pointer) {
- assert loop != null;
- return new UDPHandle(loop, pointer, true);
- }
-
- @Override
- public UDPHandle openUDPHandle(final long socket) {
- assert loop != null;
- return new UDPHandle(loop, socket);
- }
-
- @Override
- public FileEventHandle newFileEventHandle() {
- assert loop != null;
- return new FileEventHandle(loop);
- }
-
- @Override
- public FilePollHandle newFilePollHandle() {
- assert loop != null;
- return new FilePollHandle(loop);
- }
-
- @Override
- public Files newFiles() {
- assert loop != null;
- return new FilesWrapper(loop);
- }
-
- private static class FilesWrapper extends Files {
- FilesWrapper(final LoopHandle loop) {
- super(loop);
- }
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/FileEventHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/FileEventHandle.java
deleted file mode 100644
index 97d65c4..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/FileEventHandle.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.cb.FileEventCallback;
-
-public class FileEventHandle extends Handle {
-
- // must be equal to values in uv.h
- private enum EventType {
- UKNOWN(0, ""),
- RENAME(1, "rename"),
- CHANGE(2, "change");
-
- final int value;
- final String string;
-
- private EventType(final int value, final String string) {
- this.value = value;
- this.string = string;
- }
- }
- private boolean closed;
-
- private FileEventCallback onEvent = null;
- private FileEventCallback onClose = null;
-
- static {
- _static_initialize();
- }
-
- public void setFileEventCallback(final FileEventCallback callback) {
- onEvent = callback;
- }
-
- public void setCloseCallback(final FileEventCallback callback) {
- onClose = callback;
- }
-
- public FileEventHandle(final LoopHandle loop) {
- super(_new(), loop);
- _initialize(pointer);
- }
-
- public int start(final String path, final boolean persistent) {
- Objects.requireNonNull(path);
- return _start(loop.pointer(), pointer, path, persistent);
- }
-
- public void stop() {
- _close(pointer);
- closed = true;
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callback(final int type, final int status, final int event, final String filename) {
- String eventStr = null;
- if (status != 0) {
- eventStr = EventType.UKNOWN.string;
- } else if ((event & EventType.RENAME.value) != 0) {
- eventStr = EventType.RENAME.string;
- } else if ((event & EventType.CHANGE.value) != 0) {
- eventStr = EventType.CHANGE.string;
- }
-
- switch (type) {
- case 1: if (onEvent != null) {loop.getCallbackHandler().handleFileEventCallback(onEvent, status, eventStr, filename);} break;
- case 2: if (onClose != null) {loop.getCallbackHandler().handleFileEventCallback(onClose, status, eventStr, filename);} break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private static native long _new();
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long loopPtr, final long ptr, final String path, final boolean persistent);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/FilePollHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/FilePollHandle.java
deleted file mode 100644
index 6de6ae9..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/FilePollHandle.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.Stats;
-import com.iwebpp.libuvpp.cb.FilePollCallback;
-import com.iwebpp.libuvpp.cb.FilePollStopCallback;
-
-public class FilePollHandle extends Handle {
-
- private boolean closed;
-
- private FilePollCallback onPoll = null;
- private FilePollStopCallback onStop = null;
- private String path = null;
-
- private final Stats previous;
- private final Stats current;
-
- static {
- _static_initialize();
- }
-
- public void setFilePollCallback(final FilePollCallback callback) {
- onPoll = callback;
- }
-
- public void setStopCallback(final FilePollStopCallback callback) {
- onStop = callback;
- }
-
- public FilePollHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- _initialize(pointer);
- previous = new Stats();
- current = new Stats();
- }
-
- public int start(final String path, final boolean persistent, final int interval) {
- Objects.requireNonNull(path);
- if (this.path != null) {
- throw new IllegalStateException("Already polling " + this.path);
- }
- this.path = path;
- return _start(pointer, path, persistent, interval, previous, current);
- }
-
- public int stop() {
- this.path = null;
- return _stop(pointer);
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callPoll(final int status) {
- if (onPoll != null) {
- loop.getCallbackHandler().handleFilePollCallback(onPoll, status, previous, current);
- }
- }
-
- private void callStop() {
- if (onStop != null) {
- loop.getCallbackHandler().handleFilePollStopCallback(onStop);
- }
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long ptr, final String path, final boolean persistent, final int interval, final Stats previous, final Stats current);
-
- private native int _stop(final long ptr);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/Handle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/Handle.java
deleted file mode 100644
index 12c8522..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/Handle.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.io.Closeable;
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.LibUVPermission;
-
-public abstract class Handle implements Closeable {
-
- protected final long pointer;
- protected final LoopHandle loop;
-
- protected Handle(final long pointer, final LoopHandle loop) {
- Objects.requireNonNull(loop);
- LibUVPermission.checkHandle();
- assert pointer != 0;
- this.pointer = pointer;
- this.loop = loop;
- }
-
- public void ref() {
- _ref(pointer);
- }
-
- public void unref() {
- _unref(pointer);
- }
-
- public boolean isClosing() {
- return _closing(pointer);
- }
-
- @Override
- public int hashCode() {
- return (int) ((pointer & 0xffffffffL) ^ ((pointer >> 32) & 0xffffffffL));
- }
-
- @Override
- public boolean equals(final Object other) {
- return other instanceof Handle && pointer == ((Handle) other).pointer;
- }
-
- @Override
- public String toString() {
- return this.getClass().getSimpleName() + "." + Long.toHexString(pointer);
- }
-
- private native void _ref(final long ptr);
-
- private native void _unref(final long ptr);
-
- private native boolean _closing(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/HandleFactory.java b/app/src/main/java/com/iwebpp/libuvpp/handles/HandleFactory.java
deleted file mode 100644
index 5a49223..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/HandleFactory.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import com.iwebpp.libuvpp.Files;
-
-public interface HandleFactory {
-
- HandleFactory initialize(final LoopHandle loop);
-
- LoopHandle getLoopHandle();
-
- AsyncHandle newAsyncHandle();
-
- CheckHandle newCheckHandle();
-
- IdleHandle newIdleHandle();
-
- PipeHandle newPipeHandle(boolean ipc);
-
- PipeHandle newPipeHandle(long pointer,
- boolean ipc);
-
- PollHandle newPollHandle(int fd);
-
- PollHandle newPollHandle(long socket);
-
- ProcessHandle newProcessHandle();
-
- ///SignalHandle newSignalHandle();
-
- TCPHandle newTCPHandle();
-
- TCPHandle newTCPHandle(long pointer);
-
- ///TCPHandle openTCPHandle(long socket);
-
- UDTHandle newUDTHandle();
-
- UDTHandle newUDTHandle(long pointer);
-
- ///UDTHandle openUDTHandle(long socket);
-
- TimerHandle newTimerHandle();
-
- TTYHandle newTTYHandle(int fd, boolean readable);
-
- UDPHandle newUDPHandle();
-
- UDPHandle newUDPHandle(long pointer);
-
- UDPHandle openUDPHandle(long socket);
-
- FileEventHandle newFileEventHandle();
-
- FilePollHandle newFilePollHandle();
-
- Files newFiles();
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/IdleHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/IdleHandle.java
deleted file mode 100644
index 7c72b24..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/IdleHandle.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import com.iwebpp.libuvpp.cb.IdleCallback;
-
-public class IdleHandle extends Handle {
-
- private boolean closed;
-
- private IdleCallback onIdle = null;
- private IdleCallback onClose = null;
-
- static {
- _static_initialize();
- }
-
- public void setIdleCallback(final IdleCallback callback) {
- onIdle = callback;
- }
-
- public void setCloseCallback(final IdleCallback callback) {
- onClose = callback;
- }
-
- protected IdleHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- _initialize(pointer);
- }
-
- public int start() {
- return _start(pointer);
- }
-
- public int stop() {
- return _stop(pointer);
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callback(final int type, final int status) {
- switch (type) {
- case 1: if (onIdle != null) {loop.getCallbackHandler().handleIdleCallback(onIdle, status);} break;
- case 2: if (onClose != null) {loop.getCallbackHandler().handleIdleCallback(onClose, status);} break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long ptr);
-
- private native int _stop(final long ptr);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/LoopCallbackHandler.java b/app/src/main/java/com/iwebpp/libuvpp/handles/LoopCallbackHandler.java
deleted file mode 100644
index 35057c7..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/LoopCallbackHandler.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.nio.ByteBuffer;
-
-import com.iwebpp.libuvpp.Address;
-import com.iwebpp.libuvpp.Stats;
-import com.iwebpp.libuvpp.cb.AsyncCallback;
-import com.iwebpp.libuvpp.cb.CallbackExceptionHandler;
-import com.iwebpp.libuvpp.cb.CallbackHandler;
-import com.iwebpp.libuvpp.cb.CheckCallback;
-import com.iwebpp.libuvpp.cb.FileCallback;
-import com.iwebpp.libuvpp.cb.FileCloseCallback;
-import com.iwebpp.libuvpp.cb.FileEventCallback;
-import com.iwebpp.libuvpp.cb.FileOpenCallback;
-import com.iwebpp.libuvpp.cb.FilePollCallback;
-import com.iwebpp.libuvpp.cb.FilePollStopCallback;
-import com.iwebpp.libuvpp.cb.FileReadCallback;
-import com.iwebpp.libuvpp.cb.FileReadDirCallback;
-import com.iwebpp.libuvpp.cb.FileReadLinkCallback;
-import com.iwebpp.libuvpp.cb.FileStatsCallback;
-import com.iwebpp.libuvpp.cb.FileUTimeCallback;
-import com.iwebpp.libuvpp.cb.FileWriteCallback;
-import com.iwebpp.libuvpp.cb.IdleCallback;
-import com.iwebpp.libuvpp.cb.PollCallback;
-import com.iwebpp.libuvpp.cb.ProcessCloseCallback;
-import com.iwebpp.libuvpp.cb.ProcessExitCallback;
-import com.iwebpp.libuvpp.cb.SignalCallback;
-import com.iwebpp.libuvpp.cb.StreamCloseCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectionCallback;
-import com.iwebpp.libuvpp.cb.StreamRead2Callback;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.cb.StreamShutdownCallback;
-import com.iwebpp.libuvpp.cb.StreamWriteCallback;
-import com.iwebpp.libuvpp.cb.TimerCallback;
-import com.iwebpp.libuvpp.cb.UDPCloseCallback;
-import com.iwebpp.libuvpp.cb.UDPRecvCallback;
-import com.iwebpp.libuvpp.cb.UDPSendCallback;
-
-public final class LoopCallbackHandler implements CallbackHandler {
-
- private final CallbackExceptionHandler exceptionHandler;
-
- public LoopCallbackHandler(final CallbackExceptionHandler exceptionHandler) {
- this.exceptionHandler = exceptionHandler;
- }
-
- @Override
- public void handleAsyncCallback(final AsyncCallback cb, final int status) {
- try {
- cb.onSend(status);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleCheckCallback(final CheckCallback cb, final int status) {
- try {
- cb.onCheck(status);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handlePollCallback(final PollCallback cb, final int status, final int events) {
- try {
- cb.onPoll(status, events);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleSignalCallback(final SignalCallback cb, final int signum) {
- try {
- cb.onSignal(signum);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamReadCallback(final StreamReadCallback cb, final ByteBuffer data) {
- try {
- cb.onRead(data);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamRead2Callback(final StreamRead2Callback cb, final ByteBuffer data, final long handle, final int type) {
- try {
- cb.onRead2(data, handle, type);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamWriteCallback(final StreamWriteCallback cb, final int status, final Exception error) {
- try {
- cb.onWrite(status, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamConnectCallback(final StreamConnectCallback cb, final int status, final Exception error) {
- try {
- cb.onConnect(status, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamConnectionCallback(final StreamConnectionCallback cb, final int status, final Exception error) {
- try {
- cb.onConnection(status, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamCloseCallback(final StreamCloseCallback cb) {
- try {
- cb.onClose();
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleStreamShutdownCallback(final StreamShutdownCallback cb, final int status, final Exception error) {
- try {
- cb.onShutdown(status, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileCallback(final FileCallback cb, final Object context, final Exception error) {
- try {
- cb.onDone(context, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileCloseCallback(final FileCloseCallback cb, final Object context, final int fd, final Exception error) {
- try {
- cb.onClose(context, fd, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileOpenCallback(final FileOpenCallback cb, final Object context, final int fd, final Exception error) {
- try {
- cb.onOpen(context, fd, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileReadCallback(final FileReadCallback cb, final Object context, final int bytesRead, final ByteBuffer data, final Exception error) {
- try {
- cb.onRead(context, bytesRead, data, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileReadDirCallback(final FileReadDirCallback cb, final Object context, final String[] names, final Exception error) {
- try {
- cb.onReadDir(context, names, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileReadLinkCallback(final FileReadLinkCallback cb, final Object context, final String name, final Exception error) {
- try {
- cb.onReadLink(context, name, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileStatsCallback(final FileStatsCallback cb, final Object context, final Stats stats, final Exception error) {
- try {
- cb.onStats(context, stats, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileUTimeCallback(final FileUTimeCallback cb, final Object context, final long time, final Exception error) {
- try {
- cb.onUTime(context, time, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileWriteCallback(final FileWriteCallback cb, final Object context, final int bytesWritten, final Exception error) {
- try {
- cb.onWrite(context, bytesWritten, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFileEventCallback(final FileEventCallback cb, final int status, final String event, final String filename) {
- try {
- cb.onEvent(status, event, filename);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFilePollCallback(FilePollCallback cb, int status, Stats previous, Stats current) {
- try {
- cb.onPoll(status, previous, current);
- } catch (Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleFilePollStopCallback(FilePollStopCallback cb) {
- try {
- cb.onStop();
- } catch (Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleProcessCloseCallback(ProcessCloseCallback cb) {
- try {
- cb.onClose();
- } catch (Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleProcessExitCallback(ProcessExitCallback cb, int status, int signal, Exception error) {
- try {
- cb.onExit(status, signal, error);
- } catch (Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleTimerCallback(final TimerCallback cb, final int status) {
- try {
- cb.onTimer(status);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleUDPRecvCallback(final UDPRecvCallback cb, final int nread, final ByteBuffer data, final Address address) {
- try {
- cb.onRecv(nread, data, address);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleUDPSendCallback(final UDPSendCallback cb, final int status, final Exception error) {
- try {
- cb.onSend(status, error);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleUDPCloseCallback(final UDPCloseCallback cb) {
- try {
- cb.onClose();
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-
- @Override
- public void handleIdleCallback(final IdleCallback cb, final int status) {
- try {
- cb.onIdle(status);
- } catch (final Exception ex) {
- exceptionHandler.handle(ex);
- }
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/LoopCallbackHandlerFactory.java b/app/src/main/java/com/iwebpp/libuvpp/handles/LoopCallbackHandlerFactory.java
deleted file mode 100644
index 54493d5..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/LoopCallbackHandlerFactory.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import com.iwebpp.libuvpp.cb.CallbackExceptionHandler;
-import com.iwebpp.libuvpp.cb.CallbackHandler;
-import com.iwebpp.libuvpp.cb.CallbackHandlerFactory;
-
-public final class LoopCallbackHandlerFactory implements CallbackHandlerFactory {
-
- private final LoopCallbackHandler defaultHandler;
-
- public LoopCallbackHandlerFactory(final CallbackExceptionHandler exceptionHandler) {
- defaultHandler = new LoopCallbackHandler(exceptionHandler);
- }
-
- @Override
- public CallbackHandler newCallbackHandler(Object context) {
- return defaultHandler;
- }
-
- @Override
- public CallbackHandler newCallbackHandler() {
- return defaultHandler;
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/LoopHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/LoopHandle.java
deleted file mode 100644
index 678df75..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/LoopHandle.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.io.Closeable;
-
-import com.iwebpp.libuvpp.LibUVPermission;
-import com.iwebpp.libuvpp.NativeException;
-
-import com.iwebpp.libuvpp.cb.CallbackExceptionHandler;
-import com.iwebpp.libuvpp.cb.ContextProvider;
-import com.iwebpp.libuvpp.cb.CallbackHandler;
-import com.iwebpp.libuvpp.cb.CallbackHandlerFactory;
-
-public class LoopHandle implements Closeable {
-
- static {
- NativeException.static_initialize();
- _static_initialize();
- }
-
- // Track the number of created LoopHandles.
- private static int createdLoopCount = 0;
-
- protected final CallbackExceptionHandler exceptionHandler;
- protected final CallbackHandlerFactory callbackHandlerFactory;
- protected final ContextProvider contextProvider;
- private final long pointer;
- private Throwable pendingException;
- private boolean closed;
-
- private enum RunMode {
-
- // must be equal to uv_run_mode values in uv.h
- DEFAULT(0),
- ONCE(1),
- NOWAIT(2);
-
- final int value;
-
- RunMode(final int value) {
- this.value = value;
- }
- }
-
- private static synchronized void newLoop() {
- LibUVPermission.checkHandle();
- createdLoopCount += 1;
- LibUVPermission.checkNewLoop(createdLoopCount);
- }
-
- public LoopHandle(final CallbackExceptionHandler exceptionHandler,
- final CallbackHandlerFactory callbackHandler,
- final ContextProvider contextProvider) {
- newLoop();
- this.pointer = _new();
- assert pointer != 0;
- assert exceptionHandler != null;
- this.exceptionHandler = exceptionHandler;
- this.callbackHandlerFactory = callbackHandler;
- this.contextProvider = contextProvider;
- closed = false;
- }
-
- public LoopHandle() {
- newLoop();
- this.pointer = _new();
- assert pointer != 0;
-
- this.exceptionHandler = new CallbackExceptionHandler() {
- @Override
- public void handle(final Throwable ex) {
- if (pendingException == null) {
- pendingException = ex;
- } else {
- pendingException.addSuppressed(ex);
- }
- }
- };
-
- this.callbackHandlerFactory = new LoopCallbackHandlerFactory(this.exceptionHandler);
-
- this.contextProvider = new ContextProvider() {
- @Override
- public Object getContext() {
- return null;
- }
- };
- }
-
- public CallbackHandler getCallbackHandler(final Object context) {
- return callbackHandlerFactory.newCallbackHandler(context);
- }
-
- public CallbackHandler getCallbackHandler() {
- return callbackHandlerFactory.newCallbackHandler();
- }
-
- public Object getContext() {
- return contextProvider.getContext();
- }
-
- public CallbackExceptionHandler getExceptionHandler() {
- return exceptionHandler;
- }
-
- public boolean runNoWait() throws Throwable {
- throwPendingException();
- return _run(pointer, RunMode.NOWAIT.value) != 0;
- }
-
- public boolean runOnce() throws Throwable {
- throwPendingException();
- return _run(pointer, RunMode.ONCE.value) != 0;
- }
-
- public boolean run() throws Throwable {
- throwPendingException();
- return _run(pointer, RunMode.DEFAULT.value) != 0;
- }
-
- public void stop() {
- _stop(pointer);
- }
-
- @Override
- public void close() {
- if (!closed) {
- closed = true;
- closeAll();
- stop();
- }
- }
-
- public void destroy() {
- _destroy(pointer);
- }
-
- public void closeAll() {
- _close_all(pointer);
- }
-
- public NativeException getLastError() {
- return _get_last_error(pointer);
- }
-
- public String[] list() {
- return _list(pointer);
- }
-
- public long pointer() {
- return pointer;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- destroy();
- super.finalize();
- }
-
- private void throwPendingException() throws Throwable {
- if (pendingException != null) {
- final Throwable pex = pendingException;
- pendingException = null;
- throw pex;
- }
- }
-
- private static native long _new();
-
- private static native void _static_initialize();
-
- private native int _run(final long ptr, final int mode);
-
- private native void _stop(final long ptr);
-
- private native void _destroy(final long ptr);
-
- private native void _close_all(final long ptr);
-
- private native String[] _list(final long ptr);
-
- private native NativeException _get_last_error(final long ptr);
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/PipeHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/PipeHandle.java
deleted file mode 100644
index 58ec787..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/PipeHandle.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.LibUVPermission;
-
-public class PipeHandle extends StreamHandle {
-
- protected PipeHandle(final LoopHandle loop,
- final boolean ipc) {
- super(_new(loop.pointer(), ipc), loop);
- }
-
- protected PipeHandle(final LoopHandle loop,
- final long pointer,
- final boolean ipc) {
- super(pointer, loop);
- }
-
- public int open(final int fd) {
- LibUVPermission.checkPermission(LibUVPermission.PIPE_OPEN);
- return _open(pointer, fd);
- }
-
- public int bind(final String name) {
- Objects.requireNonNull(name);
- LibUVPermission.checkPermission(LibUVPermission.PIPE_BIND);
- return _bind(pointer, name);
- }
-
- @Override
- public int accept(final StreamHandle client) {
- LibUVPermission.checkPermission(LibUVPermission.PIPE_ACCEPT);
- return super.accept(client);
- }
-
- public void connect(final String name) {
- Objects.requireNonNull(name);
- LibUVPermission.checkPermission(LibUVPermission.PIPE_CONNECT);
- _connect(pointer, name, loop.getContext());
- }
-
- private static native long _new(final long loop, final boolean ipc);
-
- private native int _open(final long ptr, final int fd);
-
- private native int _bind(final long ptr, final String name);
-
- private native void _connect(final long ptr, final String name, final Object context);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/PollHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/PollHandle.java
deleted file mode 100644
index e7bbcf2..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/PollHandle.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import com.iwebpp.libuvpp.cb.PollCallback;
-
-public class PollHandle extends Handle {
-
- private final AtomicBoolean closed = new AtomicBoolean(false);
-
- private PollCallback onPoll = null;
-
- static {
- _static_initialize();
- }
-
- public static final int READABLE = 1; // must match UV_READABLE in uv.h
- public static final int WRITABLE = 2; // must match UV_WRITABLE in uv.h
-
- public void setPollCallback(final PollCallback callback) {
- onPoll = callback;
- }
-
- protected PollHandle(final LoopHandle loop, final int fd) {
- super(_new(loop.pointer(), fd), loop);
- _initialize(pointer);
- }
-
- protected PollHandle(final LoopHandle loop, final long socket) {
- super(_new(loop.pointer(), socket), loop);
- _initialize(pointer);
- }
-
- public int start(int events) {
- return _start(pointer, events);
- }
-
- public int stop() {
- return _stop(pointer);
- }
-
- public void close() {
- if (closed.compareAndSet(false, true)) {
- _close(pointer);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callPoll(final int status, final int events) {
- if (onPoll != null) {loop.getCallbackHandler().handlePollCallback(onPoll, status, events);}
- }
-
- private static native long _new(final long loop, final int fd);
-
- private static native long _new(final long loop, final long socket);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long ptr, final int events);
-
- private native int _stop(final long ptr);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/ProcessHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/ProcessHandle.java
deleted file mode 100644
index 5a5305a..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/ProcessHandle.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.LibUVPermission;
-import com.iwebpp.libuvpp.cb.ProcessCloseCallback;
-import com.iwebpp.libuvpp.cb.ProcessExitCallback;
-
-public class ProcessHandle extends Handle {
-
- public enum ProcessFlags {
-
- // must be equal to values in uv.h
- NONE(0),
- SETUID(1 << 0),
- SETGID(1 << 1),
- WINDOWS_VERBATIM_ARGUMENTS(1 << 2),
- DETACHED(1 << 3),
- WINDOWS_HIDE(1 << 4);
-
- final int value;
-
- ProcessFlags(final int value) {
- this.value = value;
- }
- }
-
- private boolean closed;
-
- static {
- _static_initialize();
- }
-
- private ProcessCloseCallback onClose = null;
- private ProcessExitCallback onExit = null;
-
- protected ProcessHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- this.closed = false;
- _initialize(pointer);
- }
-
- public void setCloseCallback(final ProcessCloseCallback callback) {
- onClose = callback;
- }
-
- public void setExitCallback(final ProcessExitCallback callback) {
- onExit = callback;
- }
-
- public int spawn(final String program,
- final String[] args,
- final String[] env,
- final String dir,
- final EnumSet flags,
- final StdioOptions[] stdio,
- final int uid,
- final int gid) {
- Objects.requireNonNull(program);
- Objects.requireNonNull(args);
- assert args.length > 0;
-
- char[] cmdChars = args[0].toCharArray();
- boolean inQuote = false;
- List javaArgs = new ArrayList();
- int start = 0;
- int end = 0;
-
- for (int i = 0; i < cmdChars.length; i++) {
- switch(cmdChars[i]) {
- case '\"': {
- if (inQuote) {
- // Closing quote
- inQuote = false;
- } else {
- // Opening quote
- inQuote = true;
- }
- break;
- }
- case ' ': {
- if (!inQuote) {
- javaArgs.add(args[0].substring(start, end));
- start = ++end;
- continue;
- }
- break;
- }
- }
- end++;
- }
- javaArgs.add(args[0].substring(start, end));
-
- final String[] arguments = new String[args.length + javaArgs.size() - 1];
- System.arraycopy(javaArgs.toArray(), 0, arguments, 0, javaArgs.size());
- System.arraycopy(args, 1, arguments, javaArgs.size(), args.length - 1);
-
- int[] stdioFlags = null;
- long[] streamPointers = null;
- int[] fds = null;
- if (stdio != null && stdio.length > 0) {
- stdioFlags = new int[stdio.length];
- streamPointers = new long[stdio.length];
- fds = new int[stdio.length];
- for (int i = 0; i < stdio.length; i++) {
- stdioFlags[i] = stdio[i].type();
- streamPointers[i] = stdio[i].stream();
- fds[i] = stdio[i].fd();
- }
- } else {
- throw new IllegalArgumentException("StdioOptions cannot be null or empty");
- }
-
- int processFlags = ProcessFlags.NONE.value;
- if (flags.contains(ProcessFlags.WINDOWS_VERBATIM_ARGUMENTS)) {
- processFlags |= ProcessFlags.WINDOWS_VERBATIM_ARGUMENTS.value;
- }
- if (flags.contains(ProcessFlags.DETACHED)) {
- processFlags |= ProcessFlags.DETACHED.value;
- }
-
- LibUVPermission.checkSpawn(arguments[0]);
-
- return _spawn(pointer,
- arguments[0],
- arguments,
- env,
- dir,
- processFlags,
- stdioFlags,
- streamPointers,
- fds,
- uid,
- gid);
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- public int kill(final int signal) {
- return _kill(pointer, signal);
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callClose() {
- if (onClose != null) {
- loop.getCallbackHandler().handleProcessCloseCallback(onClose);
- }
- }
-
- private void callExit(final int status, final int signal, final Exception error) {
- if (onExit != null) {
- loop.getCallbackHandler().handleProcessExitCallback(onExit, status, signal, error);
- }
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _spawn(final long ptr,
- final String program,
- final String[] args,
- final String[] env,
- final String dir,
- final int flags,
- final int[] stdioFlags,
- final long[] streams,
- final int[] fds,
- final int uid,
- final int gid);
-
- private native void _close(final long ptr);
-
- private native int _kill(final long ptr, final int signal);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/SignalHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/SignalHandle.java
deleted file mode 100644
index ed38f0f..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/SignalHandle.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.Constants;
-import com.iwebpp.libuvpp.LibUVPermission;
-import com.iwebpp.libuvpp.cb.SignalCallback;
-
-public class SignalHandle extends Handle {
-
- private SignalCallback onSignal = null;
- private boolean closed;
-
- static {
- _static_initialize();
- }
-
- public void setSignalCallback(final SignalCallback callback) {
- onSignal = callback;
- }
-
- protected SignalHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- _initialize(pointer);
- }
-
- public void start(final String signal) {
- Objects.requireNonNull(signal);
- start(Constants.getConstants().get(signal));
- }
-
- public void start(final int signum) {
- LibUVPermission.checkPermission(LibUVPermission.SIGNAL + signum);
- _start(pointer, signum);
- }
-
- public void stop() {
- _stop(pointer);
- }
-
- public void close() {
- if (!closed) {
- stop();
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- stop();
- super.finalize();
- }
-
- private void callback(final int signum) {
- loop.getCallbackHandler().handleSignalCallback(onSignal, signum);
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long ptr, final int signum);
-
- private native int _stop(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/StdioOptions.java b/app/src/main/java/com/iwebpp/libuvpp/handles/StdioOptions.java
deleted file mode 100644
index f9eac8d..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/StdioOptions.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-public final class StdioOptions {
-
- public enum StdioType {
- IGNORE(0x00),
- CREATE_PIPE(0x01),
- INHERIT_FD(0x02),
- INHERIT_STREAM(0x04);
-
- final int value;
-
- StdioType(final int value) {
- this.value = value;
- }
- }
-
- private final StdioType type;
- private final StreamHandle stream;
- private final int fd;
-
- public StdioOptions(final StdioType type, final StreamHandle stream, final int fd) {
- this.type = type;
- this.stream = stream;
- this.fd = fd;
- }
-
- public int type() {
- if (this.type != null) {
- return this.type.value;
- }
- return StdioType.IGNORE.value;
- }
-
- public long stream() {
- if (this.stream != null) {
- return this.stream.pointer;
- }
- return 0;
- }
-
- public int fd() {
- return this.fd;
- }
-}
-
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/StreamHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/StreamHandle.java
deleted file mode 100644
index 16322f5..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/StreamHandle.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.util.Deque;
-import java.util.Objects;
-///import jdk.nashorn.internal.runtime.ConsString;
-
-import com.iwebpp.libuvpp.cb.StreamCloseCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectionCallback;
-import com.iwebpp.libuvpp.cb.StreamRead2Callback;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.cb.StreamShutdownCallback;
-import com.iwebpp.libuvpp.cb.StreamWriteCallback;
-import com.iwebpp.libuvpp.ConsString;
-import com.iwebpp.libuvpp.StringUtils;
-
-public class StreamHandle extends Handle {
-
- protected boolean closed;
- protected boolean readStarted;
-
- protected StreamReadCallback onRead = null;
- protected StreamRead2Callback onRead2 = null;
- protected StreamWriteCallback onWrite = null;
- protected StreamConnectCallback onConnect = null;
- protected StreamConnectionCallback onConnection = null;
- protected StreamCloseCallback onClose = null;
- protected StreamShutdownCallback onShutdown = null;
- public boolean reading;
-
- static {
- _static_initialize();
- }
-
- public void setReadCallback(final StreamReadCallback callback) {
- onRead = callback;
- }
-
- public void setRead2Callback(final StreamRead2Callback callback) {
- onRead2 = callback;
- }
-
- public void setWriteCallback(final StreamWriteCallback callback) {
- onWrite = callback;
- }
-
- public void setConnectCallback(final StreamConnectCallback callback) {
- onConnect = callback;
- }
-
- public void setConnectionCallback(final StreamConnectionCallback callback) {
- onConnection = callback;
- }
-
- public void setCloseCallback(final StreamCloseCallback callback) {
- onClose = callback;
- }
-
- public void setShutdownCallback(final StreamShutdownCallback callback) {
- onShutdown = callback;
- }
-
- public void readStart() {
- if (!readStarted) {
- _read_start(pointer);
- }
- readStarted = true;
- }
-
- public void read2Start() {
- if (!readStarted) {
- _read2_start(pointer);
- }
- readStarted = true;
- }
-
- public void readStop() {
- _read_stop(pointer);
- readStarted = false;
- }
-
- public int write2(final String str, final StreamHandle handle) {
- return _write2(str, handle);
- }
-
- public int write2(final String str, final UDPHandle handle) {
- return _write2(str, handle);
- }
-
- private int _write2(final String str, final Handle handle) {
- Objects.requireNonNull(str);
- assert handle != null;
- final byte[] data;
- try {
- data = str.getBytes("utf-8");
- } catch (final UnsupportedEncodingException e) {
- throw new RuntimeException(e); // "utf-8" is always supported
- }
- return _write2(pointer, ByteBuffer.wrap(data), data, 0, data.length, handle.pointer, loop.getContext());
- }
-
- public int write(final ConsString cs) {
- try {
- return write(cs, "utf-8");
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e); // "utf-8" is always supported
- }
- }
-
- @SuppressWarnings("deprecation")
- public int write(final ConsString cs, final String encoding) throws UnsupportedEncodingException {
- if (StringUtils.consStringHasLeftRight()) {
- final Deque parts = StringUtils.parts(cs);
- if (parts.size() == 1) {
- return write(parts.pollFirst(), encoding);
- }
- final String[] fragments = parts.toArray(new String[parts.size()]);
- final byte[][] buffers = new byte[fragments.length][];
- for (int i = 0; i < fragments.length; i++) {
- if (StringUtils.hasMultiByte(fragments[i], encoding)) {
- buffers[i] = fragments[i].getBytes(encoding);
- } else {
- buffers[i] = new byte[fragments[i].length()];
- // use deprecated (but fast) method to get lower bytes of str chars
- fragments[i].getBytes(0, buffers[i].length, buffers[i], 0);
- }
- }
- return _writev(pointer, buffers, buffers.length, loop.getContext());
- } else {
- return write(cs.toString(), encoding); // write after flatten
- }
- }
-
- public int write(final String str) {
- Objects.requireNonNull(str);
- try {
- return write(str, "utf-8");
- } catch (final UnsupportedEncodingException e) {
- throw new RuntimeException(e); // "utf-8" is always supported
- }
- }
-
- public int write(final String str, final String encoding) throws UnsupportedEncodingException {
- Objects.requireNonNull(str);
- Objects.requireNonNull(encoding);
-
- final byte[] data = str.getBytes(encoding);
- return write(ByteBuffer.wrap(data), 0, data.length);
- }
-
- @SuppressWarnings("deprecation")
- public int writeLowerBytes(final String str) {
- Objects.requireNonNull(str);
- final byte[] data = new byte[str.length()];
- // use deprecated (but fast) method to get lower bytes of str chars
- str.getBytes(0, data.length, data, 0);
- return write(ByteBuffer.wrap(data), 0, data.length);
- }
-
- public int write(final ByteBuffer buffer, final int offset, final int length) {
- Objects.requireNonNull(buffer);
- return buffer.hasArray() ?
- _write(pointer, buffer, buffer.array(), offset, length, loop.getContext()) :
- _write(pointer, buffer, null, offset, length, loop.getContext());
- }
-
- public int write(final ByteBuffer buffer) {
- Objects.requireNonNull(buffer);
- return write(buffer, 0, buffer.capacity());
- }
-
- public int closeWrite() {
- return _close_write(pointer, loop.getContext());
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- public void close(final StreamCloseCallback callback) {
- if (callback != null)
- setCloseCallback(callback);
- close();
- }
-
- public int listen(final int backlog) {
- return _listen(pointer, backlog);
- }
-
- public int accept(final StreamHandle client) {
- return _accept(pointer, client.pointer);
- }
-
- public boolean isReadable() {
- return _readable(pointer);
- }
-
- public boolean isWritable() {
- return _writable(pointer);
- }
-
- public long writeQueueSize() {
- return _write_queue_size(pointer);
- }
-
- protected StreamHandle(final long pointer, final LoopHandle loop) {
- super(pointer, loop);
- this.closed = false;
- this.readStarted = false;
- _initialize(pointer);
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- protected void callRead(final ByteBuffer data) {
- if (onRead != null) {
- loop.getCallbackHandler().handleStreamReadCallback(onRead, data);
- }
- }
-
- protected void callRead2(final ByteBuffer data, long handle, int type) {
- if (onRead2 != null) {
- loop.getCallbackHandler().handleStreamRead2Callback(onRead2, data, handle, type);
- }
- }
-
- protected void callWrite(final int status, final Exception error, final Object context) {
- if (onWrite != null) {
- loop.getCallbackHandler(context).handleStreamWriteCallback(onWrite, status, error);
- }
- }
-
- protected void callConnect(final int status, final Exception error, final Object context) {
- if (onConnect != null) {
- loop.getCallbackHandler(context).handleStreamConnectCallback(onConnect, status, error);
- }
- }
-
- protected void callConnection(final int status, final Exception error) {
- if (onConnection != null) {
- loop.getCallbackHandler().handleStreamConnectionCallback(onConnection, status, error);
- }
- }
-
- protected void callClose() {
- if (onClose != null) {
- loop.getCallbackHandler().handleStreamCloseCallback(onClose);
- }
- }
-
- protected void callShutdown(final int status, final Exception error, final Object context) {
- if (onShutdown != null) {
- loop.getCallbackHandler(context).handleStreamShutdownCallback(onShutdown, status, error);
- }
- }
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native void _read_start(final long ptr);
-
- private native void _read2_start(final long ptr);
-
- private native void _read_stop(final long ptr);
-
- private native boolean _readable(final long ptr);
-
- private native boolean _writable(final long ptr);
-
- private native int _write(final long ptr,
- final ByteBuffer buffer,
- final byte[] data,
- final int offset,
- final int length,
- final Object context);
-
- private native int _writev(final long ptr,
- final byte[][] buffers,
- final int bufcount,
- final Object context);
-
- private native int _write2(final long ptr,
- final ByteBuffer buffer,
- final byte[] data,
- final int offset,
- final int length,
- final long handlePointer,
- final Object context);
-
- private native long _write_queue_size(final long ptr);
-
- private native void _close(final long ptr);
-
- private native int _close_write(final long ptr, final Object context);
-
- private native int _listen(final long ptr, final int backlog);
-
- private native int _accept(final long ptr, final long client);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/TCPHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/TCPHandle.java
deleted file mode 100644
index c5f6ab9..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/TCPHandle.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.Address;
-import com.iwebpp.libuvpp.LibUVPermission;
-import com.iwebpp.libuvpp.LibUVPermission.AddressResolver;
-
-public class TCPHandle extends StreamHandle {
-
- private int bindPort = 0;
-
- public TCPHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- }
-
- public TCPHandle(final LoopHandle loop, final long socket) {
- super(_new(loop.pointer(), socket), loop);
- }
-
- public TCPHandle(final LoopHandle loop, final long pointer, boolean dummy) {
- super(pointer, loop);
- }
-
- public int bind(final String address, final int port) {
- Objects.requireNonNull(address);
- bindPort = port;
- LibUVPermission.checkBind(address, port);
- return _bind(pointer, address, port);
- }
-
- public int bind6(final String address, final int port) {
- Objects.requireNonNull(address);
- bindPort = port;
- LibUVPermission.checkBind(address, port);
- return _bind6(pointer, address, port);
- }
-
- public int connect(final String address, final int port) {
- Objects.requireNonNull(address);
- LibUVPermission.checkConnect(address, port);
- return _connect(pointer, address, port, loop.getContext());
- }
-
- public int connect6(final String address, final int port) {
- Objects.requireNonNull(address);
- LibUVPermission.checkConnect(address, port);
- return _connect6(pointer, address, port, loop.getContext());
- }
-
- @Override
- public int listen(final int backlog) {
- LibUVPermission.checkListen(bindPort);
- return super.listen(backlog);
- }
-
- @Override
- public int accept(final StreamHandle client) {
- Objects.requireNonNull(client);
- assert client instanceof TCPHandle;
- final TCPHandle tcpClient = (TCPHandle) client;
- final int accepted = super.accept(client);
- // Check once the native call has been done otherwise peerName is not available.
- // If Accept becomes asynchronous, we will have to adapt the check to be done once
- // the peerName is available.
- LibUVPermission.checkAccept(new AddressResolver() {
- @Override
- public Address resolve() {
- return tcpClient.getPeerName();
- }
- });
- return accepted;
- }
-
- public Address getSocketName() {
- return _socket_name(pointer);
- }
-
- public Address getPeerName() {
- return _peer_name(pointer);
- }
-
- public int open(final long socket) {
- return _open(pointer, socket);
- }
-
- public int setNoDelay(final boolean enable) {
- return _no_delay(pointer, enable ? 1 : 0);
- }
-
- public int setKeepAlive(final boolean enable,
- final int delay) {
- return _keep_alive(pointer, enable ? 1 : 0, delay);
- }
-
- public int setSimultaneousAccepts(final boolean enable) {
- return _simultaneous_accepts(pointer, enable ? 1 : 0);
- }
-
- private static native long _new(final long loop);
-
- private static native long _new(final long loop, final long socket);
-
- private native int _bind(final long ptr, final String address, final int port);
-
- private native int _bind6(final long ptr, final String address, final int port);
-
- private native int _connect(final long ptr, final String address, final int port, final Object context);
-
- private native int _connect6(final long ptr, final String address, final int port, final Object context);
-
- private native int _open(final long ptr, final long socket);
-
- private native Address _socket_name(final long ptr);
-
- private native Address _peer_name(final long ptr);
-
- private native int _no_delay(final long ptr, final int enable);
-
- private native int _keep_alive(final long ptr, final int enable, final int delay);
-
- private native int _simultaneous_accepts(final long ptr, final int enable);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/TTYHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/TTYHandle.java
deleted file mode 100644
index 3669e85..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/TTYHandle.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-public class TTYHandle extends StreamHandle {
-
- private final int fd;
-
- static {
- _static_initialize();
- }
-
- public enum Mode {
-
- // must be equal to values in uv.h
- NORMAL(0),
- RAW(1);
-
- final int value;
-
- Mode(final int value) {
- this.value = value;
- }
- }
-
- protected TTYHandle(final LoopHandle loop,
- final int fd,
- final boolean readable) {
- super(_new(loop.pointer(), fd, readable), loop);
- this.fd = fd;
- }
-
- public int getFd() {
- return fd;
- }
-
- public int setMode(final Mode mode) {
- return _set_mode(pointer, mode.value);
- }
-
- public void resetMode() {
- _reset_mode(pointer);
- }
-
- public int[] getWindowSize() {
- return _get_window_size(pointer);
- }
-
- public static boolean isTTY(final int fd) {
- return _is_tty(fd);
- }
-
- public static String guessHandleType(final int fd) {
- return _guess_handle_type(fd);
- }
-
- private static native void _static_initialize();
-
- private static native long _new(final long loop,
- final int fd,
- final boolean readable);
-
- private native int _set_mode(final long pointer,
- final int mode);
-
- private native void _reset_mode(final long pointer);
-
- private native int[] _get_window_size(final long pointer);
-
- private static native boolean _is_tty(final int fd);
-
- private static native String _guess_handle_type(final int fd);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/TimerHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/TimerHandle.java
deleted file mode 100644
index 81f309f..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/TimerHandle.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import com.iwebpp.libuvpp.cb.TimerCallback;
-
-public class TimerHandle extends Handle {
-
- private boolean closed;
-
- private TimerCallback onTimerFired = null;
- private TimerCallback onClose = null;
-
- static {
- _static_initialize();
- }
-
- public void setTimerFiredCallback(final TimerCallback callback) {
- onTimerFired = callback;
- }
-
- public void setCloseCallback(final TimerCallback callback) {
- onClose = callback;
- }
-
- public TimerHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- _initialize(pointer);
- }
-
- public int start(final long timeout, final long repeat) {
- return _start(pointer, timeout, repeat);
- }
-
- public int again() {
- return _again(pointer);
- }
-
- public long getRepeat() {
- return _get_repeat(pointer);
- }
-
- public void setRepeat(final long repeat) {
- _set_repeat(pointer, repeat);
- }
-
- public int stop() {
- return _stop(pointer);
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callback(final int type, final int status) {
- switch (type) {
- case 1: if (onTimerFired != null) {loop.getCallbackHandler().handleTimerCallback(onTimerFired, status);} break;
- case 2: if (onClose != null) {loop.getCallbackHandler().handleTimerCallback(onClose, status);} break;
- default: assert false : "unsupported callback type " + type;
- }
- }
-
- private static native long _new(final long loop);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native int _start(final long ptr, final long timeout, final long repeat);
-
- private native int _again(final long ptr);
-
- private native long _get_repeat(final long ptr);
-
- private native void _set_repeat(final long ptr, final long repeat);
-
- private native int _stop(final long ptr);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/UDPHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/UDPHandle.java
deleted file mode 100644
index 3b7d8d4..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/UDPHandle.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.handles;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.Address;
-import com.iwebpp.libuvpp.LibUVPermission;
-import com.iwebpp.libuvpp.cb.UDPCloseCallback;
-import com.iwebpp.libuvpp.cb.UDPRecvCallback;
-import com.iwebpp.libuvpp.cb.UDPSendCallback;
-
-public class UDPHandle extends Handle {
-
- private boolean closed;
-
- private UDPRecvCallback onRecv = null;
- private UDPSendCallback onSend = null;
- private UDPCloseCallback onClose = null;
-
- public enum Membership {
- // must be equal to uv_membership values in uv.h
- LEAVE_GROUP(0),
- JOIN_GROUP(1);
-
- final int value;
-
- Membership(final int value) {
- this.value = value;
- }
- }
-
- static {
- _static_initialize();
- }
-
- public void setRecvCallback(final UDPRecvCallback callback) {
- onRecv = callback;
- }
-
- public void setSendCallback(final UDPSendCallback callback) {
- onSend = callback;
- }
-
- public void setCloseCallback(final UDPCloseCallback callback) {
- onClose = callback;
- }
-
- public UDPHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- this.closed = false;
- _initialize(pointer);
- }
-
- public UDPHandle(final LoopHandle loop, final long socket) {
- super(_new(loop.pointer(), socket), loop);
- this.closed = false;
- _initialize(pointer);
- }
-
- public UDPHandle(final LoopHandle loop, final long pointer, boolean dummy) {
- super(pointer, loop);
- this.closed = false;
- _initialize(pointer);
- }
-
- public void close() {
- if (!closed) {
- _close(pointer);
- }
- closed = true;
- }
-
- public Address address() {
- return _address(pointer);
- }
-
- public int bind(final int port, final String address) {
- Objects.requireNonNull(address);
- LibUVPermission.checkUDPBind(address, port);
- return _bind(pointer, port, address);
- }
-
- public int bind6(final int port, final String address) {
- Objects.requireNonNull(address);
- LibUVPermission.checkUDPBind(address, port);
- return _bind6(pointer, port, address);
- }
-
- public int send(final String str,
- final int port,
- final String host) {
- Objects.requireNonNull(str);
- Objects.requireNonNull(host);
- final byte[] data;
- try {
- data = str.getBytes("utf-8");
- } catch (final UnsupportedEncodingException e) {
- throw new RuntimeException(e); // "utf-8" is always supported
- }
- return send(ByteBuffer.wrap(data), 0, data.length, port, host);
- }
-
- public int send6(final String str,
- final int port,
- final String host) {
- Objects.requireNonNull(str);
- Objects.requireNonNull(host);
- final byte[] data;
- try {
- data = str.getBytes("utf-8");
- } catch (final UnsupportedEncodingException e) {
- throw new RuntimeException(e); // "utf-8" is always supported
- }
- return send6(ByteBuffer.wrap(data), 0, data.length, port, host);
- }
-
- public int send(final String str,
- final String encoding,
- final int port,
- final String host) throws UnsupportedEncodingException {
- Objects.requireNonNull(str);
- Objects.requireNonNull(encoding);
- Objects.requireNonNull(host);
- final byte[] data = str.getBytes(encoding);
- return send(ByteBuffer.wrap(data), 0, data.length, port, host);
- }
-
- public int send6(final String str,
- final String encoding,
- final int port,
- final String host) throws UnsupportedEncodingException {
- Objects.requireNonNull(str);
- Objects.requireNonNull(encoding);
- Objects.requireNonNull(host);
- final byte[] data = str.getBytes(encoding);
- return send6(ByteBuffer.wrap(data), 0, data.length, port, host);
- }
-
- public int send(final ByteBuffer buffer,
- final int port,
- final String host) {
- Objects.requireNonNull(buffer);
- Objects.requireNonNull(host);
- LibUVPermission.checkUDPSend(host, port);
- return buffer.hasArray() ?
- _send(pointer, buffer, buffer.array(), 0, buffer.capacity(), port, host, loop.getContext()) :
- _send(pointer, buffer, null, 0, buffer.capacity(), port, host, loop.getContext());
- }
-
- public int send6(final ByteBuffer buffer,
- final int port,
- final String host) {
- Objects.requireNonNull(buffer);
- Objects.requireNonNull(host);
- LibUVPermission.checkUDPSend(host, port);
- return buffer.hasArray() ?
- _send6(pointer, buffer, buffer.array(), 0, buffer.capacity(), port, host, loop.getContext()) :
- _send6(pointer, buffer, null, 0, buffer.capacity(), port, host, loop.getContext());
- }
-
- public int send(final ByteBuffer buffer,
- final int offset,
- final int length,
- final int port,
- final String host) {
- Objects.requireNonNull(buffer);
- Objects.requireNonNull(host);
- LibUVPermission.checkUDPSend(host, port);
- return buffer.hasArray() ?
- _send(pointer, buffer, buffer.array(), offset, length, port, host, loop.getContext()) :
- _send(pointer, buffer, null, offset, length, port, host, loop.getContext());
- }
-
- public int send6(final ByteBuffer buffer,
- final int offset,
- final int length,
- final int port,
- final String host) {
- Objects.requireNonNull(buffer);
- Objects.requireNonNull(host);
- LibUVPermission.checkUDPSend(host, port);
- return buffer.hasArray() ?
- _send6(pointer, buffer, buffer.array(), offset, length, port, host, loop.getContext()) :
- _send6(pointer, buffer, null, offset, length, port, host, loop.getContext());
- }
-
- public int recvStart() {
- return _recv_start(pointer);
- }
-
- public int recvStop() {
- return _recv_stop(pointer);
- }
-
- public int setTTL(final int ttl) {
- return _set_ttl(pointer, ttl);
- }
-
- public int setMembership(final String multicastAddress,
- final String interfaceAddress,
- final Membership membership) {
- return _set_membership(pointer, multicastAddress, interfaceAddress, membership.value);
- }
-
- public int setMulticastLoop(final boolean on) {
- return _set_multicast_loop(pointer, on ? 1 : 0);
- }
-
- public int setMulticastTTL(final int ttl) {
- return _set_multicast_ttl(pointer, ttl);
- }
-
- public int setBroadcast(final boolean on) {
- return _set_broadcast(pointer, on ? 1 : 0);
- }
-
- @Override
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
- private void callRecv(final int nread, final ByteBuffer data, final Address address) {
- if (onRecv != null) {
- loop.getCallbackHandler().handleUDPRecvCallback(onRecv, nread, data, address);
- }
- }
-
- private void callSend(final int status, final Exception error, final Object context) {
- if (onSend != null) {
- loop.getCallbackHandler(context).handleUDPSendCallback(onSend, status, error);
- }
- }
-
- private void callClose() {
- if (onClose != null) {
- loop.getCallbackHandler().handleUDPCloseCallback(onClose);
- }
- }
-
- private static native long _new(final long loop);
-
- private static native long _new(final long loop, final int fd);
-
- private static native long _new(final long loop, final long socket);
-
- private static native void _static_initialize();
-
- private native void _initialize(final long ptr);
-
- private native Address _address(final long ptr);
-
- private native int _bind(final long ptr,
- final int port,
- final String host);
-
- private native int _bind6(final long ptr,
- final int port,
- final String host);
-
- private native int _send(final long ptr,
- final ByteBuffer buffer,
- final byte[] data,
- final int offset,
- final int length,
- final int port,
- final String host,
- final Object context);
-
- private native int _send6(final long ptr,
- final ByteBuffer buffer,
- final byte[] data,
- final int offset,
- final int length,
- final int port,
- final String host,
- final Object context);
-
- private native int _recv_start(final long ptr);
-
- private native int _recv_stop(final long ptr);
-
- private native int _set_ttl(long ptr,
- int ttl);
-
- private native int _set_membership(final long ptr,
- final String multicastAddress,
- final String interfaceAddress,
- final int membership);
-
- private native int _set_multicast_loop(long ptr,
- int on);
-
- private native int _set_multicast_ttl(long ptr,
- int ttl);
-
- private native int _set_broadcast(long ptr,
- int on);
-
- private native void _close(final long ptr);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/handles/UDTHandle.java b/app/src/main/java/com/iwebpp/libuvpp/handles/UDTHandle.java
deleted file mode 100644
index bf1981a..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/handles/UDTHandle.java
+++ /dev/null
@@ -1,126 +0,0 @@
-// UDT wrapper by tom zhou
-
-package com.iwebpp.libuvpp.handles;
-
-import java.util.Objects;
-
-import com.iwebpp.libuvpp.Address;
-import com.iwebpp.libuvpp.LibUVPermission;
-import com.iwebpp.libuvpp.LibUVPermission.AddressResolver;
-
-public class UDTHandle extends StreamHandle {
-
- private int bindPort = 0;
-
- public UDTHandle(final LoopHandle loop) {
- super(_new(loop.pointer()), loop);
- }
-
- public UDTHandle(final LoopHandle loop, final long socket) {
- super(_new(loop.pointer(), socket), loop);
- }
-
- public UDTHandle(final LoopHandle loop, final long pointer, boolean dummy) {
- super(pointer, loop);
- }
-
- public int bind(final String address, final int port) {
- Objects.requireNonNull(address);
- bindPort = port;
- LibUVPermission.checkBind(address, port);
- return _bind(pointer, address, port);
- }
-
- public int bind6(final String address, final int port) {
- Objects.requireNonNull(address);
- bindPort = port;
- LibUVPermission.checkBind(address, port);
- return _bind6(pointer, address, port);
- }
-
- public int connect(final String address, final int port) {
- Objects.requireNonNull(address);
- LibUVPermission.checkConnect(address, port);
- return _connect(pointer, address, port, loop.getContext());
- }
-
- public int connect6(final String address, final int port) {
- Objects.requireNonNull(address);
- LibUVPermission.checkConnect(address, port);
- return _connect6(pointer, address, port, loop.getContext());
- }
-
- @Override
- public int listen(final int backlog) {
- LibUVPermission.checkListen(bindPort);
- return super.listen(backlog);
- }
-
- @Override
- public int accept(final StreamHandle client) {
- Objects.requireNonNull(client);
- assert client instanceof UDTHandle;
- final UDTHandle udtClient = (UDTHandle) client;
- final int accepted = super.accept(client);
- // Check once the native call has been done otherwise peerName is not available.
- // If Accept becomes asynchronous, we will have to adapt the check to be done once
- // the peerName is available.
- LibUVPermission.checkAccept(new AddressResolver() {
- @Override
- public Address resolve() {
- return udtClient.getPeerName();
- }
- });
- return accepted;
- }
-
- public Address getSocketName() {
- return _socket_name(pointer);
- }
-
- public Address getPeerName() {
- return _peer_name(pointer);
- }
-
- public int open(final long socket) {
- return _open(pointer, socket);
- }
-
- public int setNoDelay(final boolean enable) {
- return _no_delay(pointer, enable ? 1 : 0);
- }
-
- public int setKeepAlive(final boolean enable,
- final int delay) {
- return _keep_alive(pointer, enable ? 1 : 0, delay);
- }
-
- public int setSimultaneousAccepts(final boolean enable) {
- return _simultaneous_accepts(pointer, enable ? 1 : 0);
- }
-
- private static native long _new(final long loop);
-
- private static native long _new(final long loop, final long socket);
-
- private native int _bind(final long ptr, final String address, final int port);
-
- private native int _bind6(final long ptr, final String address, final int port);
-
- private native int _connect(final long ptr, final String address, final int port, final Object context);
-
- private native int _connect6(final long ptr, final String address, final int port, final Object context);
-
- private native int _open(final long ptr, final long socket);
-
- private native Address _socket_name(final long ptr);
-
- private native Address _peer_name(final long ptr);
-
- private native int _no_delay(final long ptr, final int enable);
-
- private native int _keep_alive(final long ptr, final int enable, final int delay);
-
- private native int _simultaneous_accepts(final long ptr, final int enable);
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/AsyncHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/AsyncHandleTest.java
deleted file mode 100644
index 4c4c969..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/AsyncHandleTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.AsyncCallback;
-import com.iwebpp.libuvpp.handles.AsyncHandle;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class AsyncHandleTest extends TestBase {
- private static final String TAG = "AsyncHandleTest";
-
- /// @Test
- public void testAsync() throws Throwable {
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final AsyncHandle asyncHandle = handleFactory.newAsyncHandle();
- final ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(1);
-
- asyncHandle.setAsyncCallback(new AsyncCallback() {
- @Override
- public void onSend(final int status) throws Exception {
- gotCallback.set(true);
- System.out.println("onSend!");
- times.incrementAndGet();
- asyncHandle.close();
- }
- });
-
- timer.schedule(new Runnable() {
- @Override
- public void run() {
- System.out.println("calling asyncHandle.send...");
- asyncHandle.send();
- }
- }, 100, TimeUnit.MILLISECONDS);
-
- loop.run();
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertEquals(times.get(), 1);
- }
-
- static class Holder {
- AsyncHandle asyncHandle;
- volatile boolean initialized = false;
- final int id;
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
- final LoopHandle loop = new LoopHandle();
- final Throwable[] errors = new Throwable[1];
- final Thread thread = new Thread() {
- @Override
- public void run() {
- try {
- asyncHandle = new AsyncHandle(loop);
- asyncHandle.setAsyncCallback(new AsyncCallback() {
- @Override
- public void onSend(final int status) throws Exception {
- gotCallback.set(true);
- System.out.println(id + " onSend!");
- times.incrementAndGet();
- asyncHandle.close();
- }
- });
- synchronized (loop) {
- initialized = true;
- loop.notifyAll();
- }
- loop.run();
- } catch (Throwable throwable) {
- errors[0] = throwable;
- }
- }
- };
- Holder(int id) {this.id = id;}
- }
-
- /// @Test
- public void testAsyncMulti() throws Throwable {
- final int CONCURRENCY = 256;
- final ScheduledExecutorService timer = new ScheduledThreadPoolExecutor(1);
-
- final Holder[] holders = new Holder[CONCURRENCY];
- for (int i=0; i < holders.length; i++) {
- final Holder holder = holders[i] = new Holder(i);
- holder.thread.start();
- synchronized (holder.loop) {
- while (!holder.initialized) {
- holder.loop.wait();
- }
- }
- final int fi = i;
- timer.schedule(new Runnable() {
- @Override
- public void run() {
- System.out.println(fi + " calling asyncHandle.send...");
- holder.asyncHandle.send();
- }
- }, (int) (Math.random() * 1000), TimeUnit.MILLISECONDS);
- }
-
- for (int i=0; i < holders.length; i++) {
- final Holder holder = holders[i];
- holder.thread.join();
- if (holder.errors[0] != null) {
- throw holder.errors[0];
- }
-
- ///Assert.assertTrue(holder.gotCallback.get());
- ///Assert.assertEquals(holder.times.get(), 1);
- }
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final AsyncHandleTest test = new AsyncHandleTest();
- try {
- test.testAsync();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- try {
- test.testAsyncMulti();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/CWDTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/CWDTest.java
deleted file mode 100644
index 03e00e6..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/CWDTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.LibUV;
-
-
-public class CWDTest extends TestBase {
- private static final String TAG = "CWDTest";
-
- private String cwd;
-
-
- ///@Test
- public void testCWD() {
- System.out.println("user.dir is " + cwd);
- ///Assert.assertEquals(System.getProperty("user.dir"), cwd);
-
- final String home = System.getProperty("user.home");
- System.out.println("user.home is " + home);
- LibUV.chdir(home);
- ///Assert.assertEquals(home, LibUV.cwd());
-
- final String java = System.getProperty("java.home");
- System.out.println("java.home is " + java);
- LibUV.chdir(java);
- ///Assert.assertEquals(java, LibUV.cwd());
- }
-
- public void run() {
- Log.d(TAG, "start test");
-
- testCWD();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/CheckHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/CheckHandleTest.java
deleted file mode 100644
index 36b5556..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/CheckHandleTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.CheckCallback;
-import com.iwebpp.libuvpp.handles.CheckHandle;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class CheckHandleTest extends TestBase {
- private static final String TAG = "CheckHandleTest";
-
- /// @Test
- public void testCheck() throws Throwable {
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotClose = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final CheckHandle checkHandle = handleFactory.newCheckHandle();
-
- checkHandle.setCloseCallback(new CheckCallback() {
- @Override
- public void onCheck(final int i) throws Exception {
- System.out.println("check closed");
- gotClose.set(true);
- }
- });
-
- checkHandle.setCheckCallback(new CheckCallback() {
- @Override
- public void onCheck(final int status) throws Exception {
- gotCallback.set(true);
- System.out.println("check!");
- times.incrementAndGet();
- checkHandle.close();
- }
- });
-
- checkHandle.start();
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotClose.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout waiting for check");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotClose.get());
- ///Assert.assertEquals(times.get(), 1);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final CheckHandleTest test = new CheckHandleTest();
- try {
- test.testCheck();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/FileEventHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/FileEventHandleTest.java
deleted file mode 100644
index ba142ee..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/FileEventHandleTest.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.Constants;
-import com.iwebpp.libuvpp.Files;
-import com.iwebpp.libuvpp.cb.FileEventCallback;
-import com.iwebpp.libuvpp.handles.FileEventHandle;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class FileEventHandleTest extends TestBase {
-
- private static final String TAG = "FileEventHandleTest";
-
- private String testName;
-
- private boolean shouldSkip() {
- if (System.getProperty("os.name").toLowerCase().contains("mac")) {
- System.out.println("WARNING: skipping " + testName + "() since test does not work on Mac ");
- return true;
- }
- return false;
- }
-
- ///@BeforeMethod
- public void startSession(final Method method) throws Exception {
- testName = (TestBase.TMPDIR.endsWith(File.separator) ? TestBase.TMPDIR : TestBase.TMPDIR + File.separator) + method.getName();
- }
-
- /// @Test
- public void testFileChangeEvent() throws Throwable {
- if (shouldSkip()) return;
-
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotClose = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final FileEventHandle eventHandle = new FileEventHandle(loop);
-
- eventHandle.setCloseCallback(new FileEventCallback() {
- @Override
- public void onEvent(final int status, final String event, final String filename) throws Exception {
- System.out.println("file event closed");
- handle.unlink(testName);
- gotClose.set(true);
- }
- });
-
- eventHandle.setFileEventCallback(new FileEventCallback() {
- @Override
- public void onEvent(final int status, final String event, final String filename) throws Exception {
- ///Assert.assertEquals(status, 0);
- ///Assert.assertEquals(event, "change");
- ///Assert.assertTrue(testName.endsWith(filename));
- gotCallback.set(true);
- System.out.println("file event");
- times.incrementAndGet();
- eventHandle.close();
- }
- });
-
- final int fd = handle.open(testName, Constants.O_WRONLY | Constants.O_CREAT, Constants.S_IRWXU);
- eventHandle.start(testName, true);
- handle.ftruncate(fd, 1000);
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotClose.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout waiting for file event");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotClose.get());
- ///Assert.assertEquals(times.get(), 1);
- }
-
- /// @Test
- public void testFileRenameEvent() throws Throwable {
- if (shouldSkip()) return;
- final String newName = testName + "_new";
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotClose = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final FileEventHandle eventHandle = new FileEventHandle(loop);
-
- eventHandle.setCloseCallback(new FileEventCallback() {
- @Override
- public void onEvent(final int status, final String event, final String filename) throws Exception {
- System.out.println("file event closed");
- handle.unlink(newName);
- gotClose.set(true);
- }
- });
-
- eventHandle.setFileEventCallback(new FileEventCallback() {
- @Override
- public void onEvent(final int status, final String event, final String filename) throws Exception {
- ///Assert.assertEquals(status, 0);
- ///Assert.assertEquals(event, "rename");
- ///Assert.assertTrue(testName.endsWith(filename));
- gotCallback.set(true);
- System.out.println("file event");
- times.incrementAndGet();
- eventHandle.close();
- }
- });
-
- @SuppressWarnings("unused")
- final int fd = handle.open(testName, Constants.O_WRONLY | Constants.O_CREAT, Constants.S_IRWXU);
-
- eventHandle.start(testName, true);
- handle.rename(testName, newName);
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotClose.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout waiting for file event");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotClose.get());
- ///Assert.assertEquals(times.get(), 1);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final FileEventHandleTest test = new FileEventHandleTest();
- try {
- test.startSession(test.getClass().getMethod("testFileChangeEvent"));
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- try {
- test.testFileChangeEvent();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- try {
- test.startSession(test.getClass().getMethod("testFileRenameEvent"));
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- try {
- test.testFileRenameEvent();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/FilePollHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/FilePollHandleTest.java
deleted file mode 100644
index 3e6a90b..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/FilePollHandleTest.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package com.iwebpp.libuvpp.tests;
-
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.Constants;
-import com.iwebpp.libuvpp.Files;
-import com.iwebpp.libuvpp.Stats;
-import com.iwebpp.libuvpp.cb.FileOpenCallback;
-import com.iwebpp.libuvpp.cb.FilePollCallback;
-import com.iwebpp.libuvpp.cb.FilePollStopCallback;
-import com.iwebpp.libuvpp.handles.FilePollHandle;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class FilePollHandleTest extends TestBase {
-
- private static final String TAG = "FilePollHandleTest";
-
- private String testName;
-
- ///@BeforeMethod
- public void startSession(final Method method) throws Exception {
- testName = (TestBase.TMPDIR.endsWith(File.separator) ? TestBase.TMPDIR : TestBase.TMPDIR + File.separator) + method.getName();
- }
-
- /// @Test
- public void testFilePoll() throws Throwable {
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotStop = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final FilePollHandle pollHandle = new FilePollHandle(loop);
-
- handle.setOpenCallback(new FileOpenCallback() {
- @Override
- public void onOpen(final Object context, final int fd, final Exception error) throws Exception {
- handle.ftruncate(fd, 1000);
- handle.close(fd);
- }
- });
-
- pollHandle.setStopCallback(new FilePollStopCallback() {
- @Override
- public void onStop() throws Exception {
- System.out.println("poll stop");
- handle.unlink(testName);
- gotStop.set(true);
- }
- });
-
- pollHandle.setFilePollCallback(new FilePollCallback() {
- @Override
- public void onPoll(int status, Stats prev, Stats curr) throws Exception {
- ///Assert.assertEquals(status, 0);
- ///Assert.assertEquals(prev.getSize(), 0);
- ///Assert.assertEquals(curr.getSize(), 1000);
- gotCallback.set(true);
- System.out.println("poll");
- times.incrementAndGet();
- pollHandle.close();
- }
- });
-
- final int fd = handle.open(testName, Constants.O_WRONLY | Constants.O_CREAT, Constants.S_IRWXU);
- handle.close(fd);
-
- pollHandle.start(testName, true, 1);
-
- handle.open(testName, Constants.O_WRONLY | Constants.O_CREAT, Constants.S_IRWXU, this);
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotStop.get()) {
- if (System.currentTimeMillis() - start > TIMEOUT) {
- ///Assert.fail("timeout waiting for file poll");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotStop.get());
- ///Assert.assertEquals(times.get(), 1);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final FilePollHandleTest test = new FilePollHandleTest();
- try {
- test.testFilePoll();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-}
-
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/FilesTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/FilesTest.java
deleted file mode 100644
index 7ece02e..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/FilesTest.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.io.File;
-import java.lang.reflect.Method;
-import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import com.iwebpp.libuvpp.Constants;
-import com.iwebpp.libuvpp.Files;
-import com.iwebpp.libuvpp.Files.OpenedFile;
-import com.iwebpp.libuvpp.Stats;
-import com.iwebpp.libuvpp.cb.FileCallback;
-import com.iwebpp.libuvpp.cb.FileCloseCallback;
-import com.iwebpp.libuvpp.cb.FileOpenCallback;
-import com.iwebpp.libuvpp.cb.FileReadCallback;
-import com.iwebpp.libuvpp.cb.FileReadDirCallback;
-import com.iwebpp.libuvpp.cb.FileWriteCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class FilesTest extends TestBase {
-
- private final HandleFactory handleFactory = newFactory();
-
- private String testName;
-
- public void startSession(final Method method) throws Exception {
- testName = (TMPDIR.endsWith(File.separator) ? TMPDIR : TMPDIR + File.separator) + method.getName();
- }
-
- public void endSession(final Method method) {
- final Files handle = handleFactory.newFiles();
-
- cleanupFiles(handle, testName);
- cleanupFiles(handle, testName + ".txt");
- cleanupFiles(handle, testName + "-new.txt");
- cleanupFiles(handle, testName + "2.txt");
- }
-
- ///@Test
- public void testGetPath() {
- final String filename = testName + ".txt";
- final Files handle = handleFactory.newFiles();
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- final OpenedFile openedFile = handle.getOpenedFile(fd);
- ///Assert.assertEquals(openedFile.getPath(), filename);
- cleanupFiles(handle, filename);
- }
-
- ///@Test
- public void testOpenWriteReadAndCloseSync() {
- final String filename = testName + ".txt";
- final ByteBuffer b = ByteBuffer.wrap("some data".getBytes());
- final Files handle = handleFactory.newFiles();
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- ///Assert.assertTrue(fd >= 0);
- handle.write(fd, b, 0, b.limit(), 0);
- final ByteBuffer bb = ByteBuffer.allocateDirect(b.capacity());
- handle.read(fd, bb, 0, bb.limit(), 0);
- final int status = handle.close(fd);
- ///Assert.assertTrue(status == 0);
- ///Assert.assertEquals(b, bb);
- cleanupFiles(handle, filename);
- }
-
- ///@Test
- public void testOpenWriteReadAndCloseAsync() throws Throwable {
- final String filename = testName + ".txt";
- final String data = "some data";
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final ByteBuffer writeBuffer = ByteBuffer.wrap(data.getBytes());
- final ByteBuffer readBuffer = ByteBuffer.allocateDirect(writeBuffer.capacity());
- final AtomicInteger fd = new AtomicInteger();
- final AtomicBoolean openCallbackCalled = new AtomicBoolean(false);
- final AtomicBoolean writeCallbackCalled = new AtomicBoolean(false);
- final AtomicBoolean readCallbackCalled = new AtomicBoolean(false);
- final AtomicBoolean closeCallbackCalled = new AtomicBoolean(false);
-
- handle.setOpenCallback(new FileOpenCallback() {
- @Override
- public void onOpen(final Object context, final int file, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- openCallbackCalled.set(true);
- checkException(error);
- fd.set(file);
- ///Assert.assertTrue(fd.get() > 0);
- handle.write(fd.get(), writeBuffer, 0, writeBuffer.limit(), 0, FilesTest.this);
- }
- });
-
- handle.setWriteCallback(new FileWriteCallback() {
- @Override
- public void onWrite(Object context, int bytesWritten, Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- writeCallbackCalled.set(true);
- ///Assert.assertNull(error);
- ///Assert.assertEquals(bytesWritten, data.getBytes().length);
- handle.read(fd.get(), readBuffer, 0, readBuffer.limit(), 0, FilesTest.this);
- }
- });
-
- handle.setReadCallback(new FileReadCallback() {
- @Override
- public void onRead(Object context, int bytesRead, ByteBuffer data, Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- readCallbackCalled.set(true);
- ///Assert.assertNull(error);
- ///Assert.assertEquals(bytesRead, writeBuffer.limit());
- ///Assert.assertEquals(data, writeBuffer);
- handle.close(fd.get(), FilesTest.this);
- }
- });
-
- handle.setCloseCallback(new FileCloseCallback() {
- @Override
- public void onClose(final Object context, final int file, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- closeCallbackCalled.set(true);
- checkException(error);
- ///Assert.assertEquals(file, fd.get());
- cleanupFiles(handle, filename);
- }
- });
-
- handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO, FilesTest.this);
- loop.run();
- ///Assert.assertTrue(openCallbackCalled.get());
- ///Assert.assertTrue(writeCallbackCalled.get());
- ///Assert.assertTrue(readCallbackCalled.get());
- ///Assert.assertTrue(closeCallbackCalled.get());
- }
-
- ///@Test
- public void testUnlinkSync() {
- final String filename = testName + ".txt";
- final Files handle = handleFactory.newFiles();
-
- @SuppressWarnings("unused")
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- final int status = handle.unlink(filename);
- ///Assert.assertTrue(status == 0);
- }
-
- ///@Test
- public void testUnlinkAsync() throws Throwable {
- final String filename = testName + ".txt";
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final AtomicBoolean unlinkCallbackCalled = new AtomicBoolean(false);
-
- handle.setUnlinkCallback(new FileCallback() {
- @Override
- public void onDone(final Object context, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- unlinkCallbackCalled.set(true);
- checkException(error);
- }
- });
-
- handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- handle.unlink(filename, FilesTest.this);
- loop.run();
- ///Assert.assertTrue(unlinkCallbackCalled.get());
- }
-
- ///@Test
- public void testMkdirRmdirSync() {
- final String dirname = testName;
- final Files handle = handleFactory.newFiles();
-
- int status = handle.mkdir(dirname, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- ///Assert.assertTrue(status == 0);
- status = handle.rmdir(dirname);
- ///Assert.assertTrue(status == 0);
- }
-
- ///@Test
- public void testMkdirRmdirAsync() throws Throwable {
- final String dirname = testName;
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final AtomicBoolean mkdirCallbackCalled = new AtomicBoolean(false);
- final AtomicBoolean rmdirCallbackCalled = new AtomicBoolean(false);
-
- handle.setMkDirCallback( new FileCallback() {
- @Override
- public void onDone(final Object context, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- mkdirCallbackCalled.set(true);
- checkException(error);
- handle.rmdir(dirname, FilesTest.this);
- }
- });
-
- handle.setRmDirCallback(new FileCallback() {
- @Override
- public void onDone(final Object context, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- rmdirCallbackCalled.set(true);
- checkException(error);
- }
- });
-
- final int status = handle.mkdir(dirname, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO, FilesTest.this);
- ///Assert.assertTrue(status == 0);
- loop.run();
- ///Assert.assertTrue(mkdirCallbackCalled.get());
- ///Assert.assertTrue(rmdirCallbackCalled.get());
-
- }
-
- ///@Test
- public void testReaddirSync() {
- final Files handle = handleFactory.newFiles();
- final String filename = "src";
- final String[] names = handle.readdir(filename, Constants.O_RDONLY);
- ///Assert.assertEquals(names.length, 2);
- }
-
- ///@Test
- public void testReaddirAsync() throws Throwable {
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final String filename = "src";
- final AtomicBoolean readdirCallbackCalled = new AtomicBoolean(false);
-
- handle.setReadDirCallback(new FileReadDirCallback() {
- @Override
- public void onReadDir(Object context, String[] names, Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- readdirCallbackCalled.set(true);
- ///Assert.assertEquals(names.length, 2);
- }
- });
-
- final String[] names = handle.readdir(filename, Constants.O_RDONLY, FilesTest.this);
- ///Assert.assertEquals(names, null);
- loop.run();
- ///Assert.assertTrue(readdirCallbackCalled.get());
- }
-
- ///@Test
- public void testRenameSync() {
- final String filename = testName + ".txt";
- final String newName = testName + "-new" + ".txt";
- final Files handle = handleFactory.newFiles();
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- handle.close(fd);
- handle.rename(filename, newName);
- ///Assert.assertTrue (handle.open(newName, Constants.O_RDONLY, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO) > 0);
- cleanupFiles(handle, newName);
- }
-
-
- ///@Test
- public void testRenameAsync() throws Throwable {
- final String filename = testName + ".txt";
- final String newName = testName + "-new" + ".txt";
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final AtomicBoolean renameCallbackCalled = new AtomicBoolean(false);
-
- handle.setRenameCallback(new FileCallback() {
- @Override
- public void onDone(final Object context, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- renameCallbackCalled.set(true);
- checkException(error);
- ///Assert.assertTrue (handle.open(newName, Constants.O_RDONLY, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO) > 0);
- cleanupFiles(handle, newName);
- }
- });
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- handle.close(fd);
- handle.rename(filename, newName, FilesTest.this);
- loop.run();
- ///Assert.assertTrue(renameCallbackCalled.get());
- }
-
- ///@Test
- public void testFtruncateSync() {
- final String filename = testName + ".txt";
- final Files handle = handleFactory.newFiles();
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- handle.ftruncate(fd, 1000);
- final Stats stats = handle.fstat(fd);
- ///Assert.assertEquals(stats.getSize(), 1000);
- cleanupFiles(handle, filename);
- }
-
- ///@Test
- public void testFtruncateAsync() throws Throwable {
- final String filename = testName + ".txt";
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final AtomicInteger fd = new AtomicInteger();
- final AtomicBoolean ftruncateCallbackCalled = new AtomicBoolean(false);
-
- handle.setFTruncateCallback(new FileCallback() {
- @Override
- public void onDone(final Object context, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- ftruncateCallbackCalled.set(true);
- checkException(error);
- final Stats stats = handle.fstat(fd.get());
- ///Assert.assertEquals(stats.getSize(), 1000);
- cleanupFiles(handle, filename);
- }
- });
-
- fd.set(handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO));
- handle.ftruncate(fd.get(), 1000, FilesTest.this);
- loop.run();
- ///Assert.assertTrue(ftruncateCallbackCalled.get());
- }
-
- ///@Test
- public void testLinkSync() {
- final String filename = testName + ".txt";
- final String filename2 = testName + "2.txt";
- final Files handle = handleFactory.newFiles();
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- final ByteBuffer b = ByteBuffer.wrap("some data".getBytes());
- handle.write(fd, b, 0, b.limit(), 0);
- handle.close(fd);
- handle.link(filename, filename2);
- final Stats stats = handle.stat(filename2);
- ///Assert.assertEquals(stats.getSize(), b.limit());
- cleanupFiles(handle, filename, filename2);
- }
-
- ///@Test
- public void testLinkAsync() throws Throwable {
- final String filename = testName + ".txt";
- final String filename2 = testName + "2.txt";
- final LoopHandle loop = handleFactory.getLoopHandle();
- final Files handle = handleFactory.newFiles();
- final AtomicBoolean linkCallbackCalled = new AtomicBoolean();
- final ByteBuffer b = ByteBuffer.wrap("some data".getBytes());
-
- handle.setLinkCallback(new FileCallback() {
- @Override
- public void onDone(final Object context, final Exception error) throws Exception {
- ///Assert.assertEquals(context, FilesTest.this);
- linkCallbackCalled.set(true);
- final Stats stats = handle.stat(filename2);
- ///Assert.assertEquals(stats.getSize(), b.limit());
- cleanupFiles(handle, filename, filename2);
- }
- });
-
- final int fd = handle.open(filename, Constants.O_RDWR | Constants.O_CREAT, Constants.S_IRWXU | Constants.S_IRWXG | Constants.S_IRWXO);
- handle.write(fd, b, 0, b.limit(), 0);
- handle.close(fd);
- handle.link(filename, filename2, FilesTest.this);
- loop.run();
- ///Assert.assertTrue(linkCallbackCalled.get());
- }
-
- private void cleanupFiles(final Files handle, final String... files) {
- for (int i = 0; i < files.length; i++) {
- try {
- final String test = files[i];
- final Stats stat = handle.stat(test);
- if ((stat.getMode() & Constants.S_IFMT) == Constants.S_IFDIR) {
- handle.rmdir(test);
- } else if ((stat.getMode() & Constants.S_IFMT) == Constants.S_IFREG) {
- handle.unlink(test);
- }
- } catch (final Exception ignore) {
- }
- }
- }
-
- private void checkException(final Exception error) {
- if (error != null) {
- throw new RuntimeException(error);
- }
- }
-
- public static void main(String[] args) throws Exception {
- final String[] classes = {FilesTest.class.getName()};
- ///TestRunner.main(classes);
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/IdleHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/IdleHandleTest.java
deleted file mode 100644
index ef2c50e..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/IdleHandleTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.IdleCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.IdleHandle;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class IdleHandleTest extends TestBase {
- private static final String TAG = "IdleHandleTest";
-
- /// @Test
- public void testIdle() throws Throwable {
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotClose = new AtomicBoolean(false);
- final AtomicInteger times = new AtomicInteger(0);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final IdleHandle idleHandle = handleFactory.newIdleHandle();
-
- idleHandle.setCloseCallback(new IdleCallback() {
- @Override
- public void onIdle(final int i) throws Exception {
- System.out.println("idle closed");
- gotClose.set(true);
- }
- });
-
- idleHandle.setIdleCallback(new IdleCallback() {
- @Override
- public void onIdle(final int status) throws Exception {
- gotCallback.set(true);
- System.out.println("idle!");
- times.incrementAndGet();
- idleHandle.close();
- }
- });
-
- idleHandle.start();
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotClose.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout waiting for idle");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotClose.get());
- ///Assert.assertEquals(times.get(), 1);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final IdleHandleTest test = new IdleHandleTest();
- try {
- test.testIdle();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/Logger.java b/app/src/main/java/com/iwebpp/libuvpp/tests/Logger.java
deleted file mode 100644
index a54f7eb..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/Logger.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-
-public final class Logger {
-
- private final String prefix;
-
- public Logger() {
- this.prefix = null;
- }
-
- public Logger(final String prefix) {
- this.prefix = prefix;
- }
-
- public byte[] array(final ByteBuffer byteBuffer) {
- if (byteBuffer.hasArray()) {
- return byteBuffer.array();
- } else {
- final ByteBuffer dup = byteBuffer.duplicate();
- final byte[] data = new byte[dup.capacity()];
- dup.clear();
- dup.get(data);
- return data;
- }
- }
-
- public void log(final Object... args) throws Exception {
- System.out.print(prefix == null ? "" : prefix);
- if (args != null) {
- for (final Object arg : args) {
- if (arg instanceof ByteBuffer) {
- final byte[] bytes = array(((ByteBuffer) arg));
- System.out.print(new String(bytes, "utf-8"));
- } else {
- System.out.print(arg);
- }
- System.out.print(" ");
- }
- }
- System.out.println();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/LoopHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/LoopHandleTest.java
deleted file mode 100644
index a323bb0..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/LoopHandleTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.handles.AsyncHandle;
-import com.iwebpp.libuvpp.handles.CheckHandle;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.IdleHandle;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.PipeHandle;
-import com.iwebpp.libuvpp.handles.TCPHandle;
-import com.iwebpp.libuvpp.handles.UDPHandle;
-import com.iwebpp.libuvpp.handles.UDTHandle;
-
-///import org.testng.Assert;
-///import org.testng.annotations.Test;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class LoopHandleTest extends TestBase {
- private static final String TAG = "LoopHandleTest";
-
- private static final String DOT_SPLIT_REGEX = "\\.";
-
- /// @Test
- public void testList() throws Throwable {
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final String[] handles = loop.list();
- ///Assert.assertNotNull(handles);
- ///Assert.assertEquals(handles.length, 0);
-
- final AsyncHandle async= handleFactory.newAsyncHandle();
- final CheckHandle check= handleFactory.newCheckHandle();
- final IdleHandle idle= handleFactory.newIdleHandle();
- ///final SignalHandle signal= handleFactory.newSignalHandle();
- final PipeHandle pipe= handleFactory.newPipeHandle(false);
- final TCPHandle tcp= handleFactory.newTCPHandle();
- final UDPHandle udp= handleFactory.newUDPHandle();
- final UDTHandle udt= handleFactory.newUDTHandle();
-
- System.out.println(async);
- System.out.println(check);
- System.out.println(idle);
- ///System.out.println(signal);
- System.out.println(pipe);
- System.out.println(tcp);
- System.out.println(udp);
- System.out.println(udt);
-
- final Set pointers = new HashSet();
- pointers.add(async.toString().split(DOT_SPLIT_REGEX)[1]);
- pointers.add(check.toString().split(DOT_SPLIT_REGEX)[1]);
- pointers.add(idle.toString().split(DOT_SPLIT_REGEX)[1]);
- ///pointers.add(signal.toString().split(DOT_SPLIT_REGEX)[1]);
- pointers.add(pipe.toString().split(DOT_SPLIT_REGEX)[1]);
- pointers.add(tcp.toString().split(DOT_SPLIT_REGEX)[1]);
- pointers.add(udp.toString().split(DOT_SPLIT_REGEX)[1]);
- pointers.add(udt.toString().split(DOT_SPLIT_REGEX)[1]);
-
- final String[] handles1 = loop.list();
- ///Assert.assertNotNull(handles1);
- ///Assert.assertEquals(handles1.length, 7);
- for (final String handle : handles1) {
- System.out.println(handle);
- ///Assert.assertNotNull(handle);
- final String pointer = handle.toString().split(DOT_SPLIT_REGEX)[1];
- ///Assert.assertTrue(pointers.remove(pointer));
- }
- ///Assert.assertTrue(pointers.isEmpty());
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final LoopHandleTest test = new LoopHandleTest();
- try {
- test.testList();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/PipeHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/PipeHandleTest.java
deleted file mode 100644
index 3112ccc..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/PipeHandleTest.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.StreamCloseCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectionCallback;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.PipeHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class PipeHandleTest extends TestBase {
- private static final String TAG = "PipeHandleTest";
-
- private static final String OS = System.getProperty("os.name");
- private static final int TIMES = 10;
-
- ///@Test
- public void testConnection() throws Throwable {
- final String PIPE_NAME;
- if (OS.startsWith("Windows")) {
- PIPE_NAME = "\\\\.\\pipe\\libuv-java-pipe-handle-test-pipe";
- } else {
- PIPE_NAME = "/tmp/libuv-java-pipe-handle-test-pipe";
- ///Files.deleteIfExists(FileSystems.getDefault().getPath(PIPE_NAME));
- }
-
- final AtomicInteger serverSendCount = new AtomicInteger(0);
- final AtomicInteger clientSendCount = new AtomicInteger(0);
-
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
- final AtomicInteger clientRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final Logger serverLoggingCallback = new Logger("S: ");
- final Logger clientLoggingCallback = new Logger("C: ");
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final PipeHandle server = handleFactory.newPipeHandle(false);
- final PipeHandle peer = handleFactory.newPipeHandle(false);
- final PipeHandle client = handleFactory.newPipeHandle(false);
-
- peer.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- serverRecvCount.incrementAndGet();
- if (data == null) {
- peer.close();
- } else {
- final Object[] args = {data};
- serverLoggingCallback.log(args);
- if (serverSendCount.get() < TIMES) {
- peer.write("PING " + serverSendCount.incrementAndGet());
- } else {
- peer.close();
- }
- }
- }
- });
-
- peer.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception {
- serverDone.set(true);
- }
- });
-
- server.setConnectionCallback(new StreamConnectionCallback() {
- @Override
- public void onConnection(int status, Exception error) throws Exception {
- serverLoggingCallback.log(status, error);
- server.accept(peer);
- peer.readStart();
- peer.write("INIT " + serverSendCount.incrementAndGet());
- server.close(); // not expecting any more connections
- }
- });
-
- client.setConnectCallback(new StreamConnectCallback() {
- @Override
- public void onConnect(int status, Exception error) throws Exception {
- clientLoggingCallback.log(status, error);
- client.readStart();
- }
- });
-
- client.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- clientRecvCount.incrementAndGet();
- if (data == null) {
- client.close();
- } else {
- final Object[] args = {data};
- clientLoggingCallback.log(args);
- if (clientSendCount.incrementAndGet() < TIMES) {
- client.write("PONG " + clientSendCount.get());
- } else {
- client.close();
- }
- }
- }
- });
-
- client.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception {
- clientDone.set(true);
- }
- });
-
- server.bind(PIPE_NAME);
- server.listen(0);
-
- client.connect(PIPE_NAME);
-
- while (!serverDone.get() && !clientDone.get()) {
- loop.run();
- }
-
- client.close();
- server.close();
-
- ///Assert.assertEquals(serverSendCount.get(), TIMES);
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- ///Assert.assertEquals(clientRecvCount.get(), TIMES);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- try {
- new PipeHandleTest().testConnection();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/ProcessHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/ProcessHandleTest.java
deleted file mode 100644
index cfcb477..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/ProcessHandleTest.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-import java.util.EnumSet;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.ProcessCloseCallback;
-import com.iwebpp.libuvpp.cb.ProcessExitCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectionCallback;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.PipeHandle;
-import com.iwebpp.libuvpp.handles.ProcessHandle;
-import com.iwebpp.libuvpp.handles.StdioOptions;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class ProcessHandleTest extends TestBase {
- private static final String TAG = "CheckHandleTest";
-
- private static final String OS = System.getProperty("os.name");
-
- ///@Test
- public void testExitCode() throws Throwable {
- final String MESSAGE = "TEST";
- final String PIPE_NAME;
- if (OS.startsWith("Windows")) {
- PIPE_NAME = "\\\\.\\pipe\\libuv-java-process-handle-test-pipe";
- } else {
- PIPE_NAME = "/tmp/libuv-java-process-handle-test-pipe";
- ///Files.deleteIfExists(FileSystems.getDefault().getPath(PIPE_NAME));
- }
-
- final AtomicBoolean exitCalled = new AtomicBoolean(false);
- final AtomicBoolean closeCalled = new AtomicBoolean(false);
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final ProcessHandle process = handleFactory.newProcessHandle();
- final PipeHandle parent = handleFactory.newPipeHandle(false);
- final PipeHandle peer = handleFactory.newPipeHandle(false);
- final PipeHandle child = handleFactory.newPipeHandle(false);
-
- peer.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- final byte[] bytes = data.array();
- final String s = new String(bytes, "utf-8");
- ///Assert.assertEquals(s, MESSAGE);
- peer.close();
- process.close();
- }
- });
-
- parent.setConnectionCallback(new StreamConnectionCallback() {
- @Override
- public void onConnection(int status, Exception error) throws Exception {
- parent.accept(peer);
- peer.readStart();
- parent.close();
- }
- });
-
- child.setConnectCallback(new StreamConnectCallback() {
- @Override
- public void onConnect(int status, Exception error) throws Exception {
- child.write(MESSAGE);
- child.close();
- }
- });
-
- process.setExitCallback(new ProcessExitCallback() {
- @Override
- public void onExit(final int status, final int signal, final Exception error) throws Exception {
- System.out.println("status " + status + ", signal " + signal);
- child.connect(PIPE_NAME);
- exitCalled.set(true);
- }
- });
-
- process.setCloseCallback(new ProcessCloseCallback() {
- @Override
- public void onClose() throws Exception {
- closeCalled.set(true);
- }
- });
-
- final String[] args = new String[2];
- args[0] = "java";
- args[1] = "-version";
-
- final EnumSet processFlags = EnumSet.noneOf(ProcessHandle.ProcessFlags.class);
- processFlags.add(ProcessHandle.ProcessFlags.NONE);
-
- final StdioOptions[] stdio = new StdioOptions[3];
- stdio[0] = new StdioOptions(StdioOptions.StdioType.INHERIT_FD, null, 0);
- stdio[1] = new StdioOptions(StdioOptions.StdioType.INHERIT_FD, null, 1);
- stdio[2] = new StdioOptions(StdioOptions.StdioType.INHERIT_FD, null, 2);
-
- parent.bind(PIPE_NAME);
- parent.listen(0);
-
- process.spawn(args[0], args, null, ".", processFlags, stdio, -1, -1);
-
- while (!exitCalled.get() && !closeCalled.get()) {
- loop.run();
- }
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final ProcessHandleTest test = new ProcessHandleTest();
- try {
- test.testExitCode();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/TCPHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/TCPHandleTest.java
deleted file mode 100644
index f4c52fb..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/TCPHandleTest.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-import java.util.Random;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.StreamCloseCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectionCallback;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.TCPHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class TCPHandleTest extends TestBase {
- private static final String TAG = "TCPHandleTest";
-
- private static final String ADDRESS = "127.0.0.1";
- private static final String ADDRESS6 = "::1";
- private static final int PORT = 23456;
- private static final int PORT6 = 34567;
- private static final int TIMES = 10;
-
- public void testConnection() throws Throwable {
- final AtomicInteger serverSendCount = new AtomicInteger(0);
- final AtomicInteger clientSendCount = new AtomicInteger(0);
-
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
- final AtomicInteger clientRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final TCPHandle server = handleFactory.newTCPHandle();
- final TCPHandle peer = handleFactory.newTCPHandle();
- final TCPHandle client = handleFactory.newTCPHandle();
-
- final Logger serverLoggingCallback = new Logger("s: ");
- final Logger clientLoggingCallback = new Logger("c: ");
-
- final Random random = new Random();
-
- server.setConnectionCallback(new StreamConnectionCallback() {
- @Override
- public void onConnection(int status, Exception error) throws Exception {
- serverLoggingCallback.log(status, error);
- server.accept(peer);
- peer.readStart();
- Log.d(TAG, "s: " + server.getSocketName() + " connected to " + peer.getPeerName());
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- server.close(); // not expecting any more connections
- }
- });
-
- peer.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- serverRecvCount.incrementAndGet();
- if (data == null) {
- peer.close();
- } else {
- final Object[] args = {data};
- serverLoggingCallback.log(args);
- if (serverRecvCount.get() == TIMES) {
- peer.close();
- } else {
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- }
- }
- }
- });
-
- peer.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- serverDone.set(true);
- }
- });
-
- client.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- clientRecvCount.incrementAndGet();
- if (data == null) {
- client.close();
- } else {
- final Object[] args = {data};
- clientLoggingCallback.log(args);
- if (clientRecvCount.get() == TIMES) {
- client.close();
- } else {
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- }
- }
- });
-
- client.setConnectCallback(new StreamConnectCallback() {
- @Override
- public void onConnect(int status, Exception error) throws Exception { // connect
- clientLoggingCallback.log(status, error);
- Log.d(TAG, "c: " + client.getSocketName() + " connected to " + client.getPeerName());
- client.readStart();
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- });
-
- client.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- clientDone.set(true);
- }
- });
-
- server.bind(ADDRESS, PORT);
- server.listen(1);
-
- Thread.sleep((long) (random.nextDouble() * 100));
- client.connect(ADDRESS, PORT);
-
- while (!serverDone.get() || !clientDone.get()) {
- loop.run();
- }
-
- ///Assert.assertEquals(serverSendCount.get(), TIMES);
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- ///Assert.assertEquals(clientRecvCount.get(), TIMES);
- }
-
- public void testConnection6() throws Throwable {
- final LoopHandle loop = new LoopHandle();
- if (!UDPHandleTest.isIPv6Enabled(loop)) {
- return;
- }
-
- final AtomicInteger serverSendCount = new AtomicInteger(0);
- final AtomicInteger clientSendCount = new AtomicInteger(0);
-
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
- final AtomicInteger clientRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final TCPHandle server = new TCPHandle(loop);
- final TCPHandle peer = new TCPHandle(loop);
- final TCPHandle client = new TCPHandle(loop);
-
- final Logger serverLoggingCallback = new Logger("s: ");
- final Logger clientLoggingCallback = new Logger("c: ");
-
- final Random random = new Random();
-
- server.setConnectionCallback(new StreamConnectionCallback() {
- @Override
- public void onConnection(int status, Exception error) throws Exception {
- serverLoggingCallback.log(status, error);
- server.accept(peer);
- peer.readStart();
- Log.d(TAG, "s: " + server.getSocketName() + " connected to " + peer.getPeerName());
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- server.close(); // not expecting any more connections
- }
- });
-
- peer.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- serverRecvCount.incrementAndGet();
- if (data == null) {
- peer.close();
- } else {
- final Object[] args = {data};
- serverLoggingCallback.log(args);
- if (serverRecvCount.get() == TIMES) {
- peer.close();
- } else {
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- }
- }
- }
- });
-
- peer.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- serverDone.set(true);
- }
- });
-
- client.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- clientRecvCount.incrementAndGet();
- if (data == null) {
- client.close();
- } else {
- final Object[] args = {data};
- clientLoggingCallback.log(args);
- if (clientRecvCount.get() == TIMES) {
- client.close();
- } else {
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- }
- }
- });
-
- client.setConnectCallback(new StreamConnectCallback() {
- @Override
- public void onConnect(int status, Exception error) throws Exception {
- clientLoggingCallback.log(status, error);
- Log.d(TAG, "c: " + client.getSocketName() + " connected to " + client.getPeerName());
- client.readStart();
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- });
-
- client.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- clientDone.set(true);
- }
- });
-
- server.bind6(ADDRESS6, PORT6);
- server.listen(1);
-
- Thread.sleep((long) (random.nextDouble() * 100));
- client.connect6(ADDRESS6, PORT6);
-
- while (!serverDone.get() || !clientDone.get()) {
- loop.run();
- }
-
- ///Assert.assertEquals(serverSendCount.get(), TIMES);
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- ///Assert.assertEquals(clientRecvCount.get(), TIMES);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- try {
- testConnection();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- try {
- testConnection6();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/TTYHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/TTYHandleTest.java
deleted file mode 100644
index 002211b..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/TTYHandleTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.NativeException;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.cb.StreamWriteCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.TTYHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class TTYHandleTest extends TestBase {
- private static final String TAG = "TTYHandleTest";
-
- private TTYHandle newTTY(final HandleFactory factory, final int fd, final boolean readable) {
- final TTYHandle tty;
- try {
- tty = factory.newTTYHandle(fd, readable);
- } catch (final NativeException nx) {
- if ("EBADF".equals(nx.errnoString())) {
- // running under a test runner or ant
- System.out.println("EBADF error creating tty " + fd);
- return null;
- }
- throw nx; // any other error fails the test
- }
- if (!TTYHandle.isTTY(fd)) {
- System.out.println("not a tty " + fd);
- return null;
- }
- return tty;
- }
-
- /// @Test
- public void testStdOutErrWindowSize() {
- testStdOutErrWindowSize("stdout", 1);
- testStdOutErrWindowSize("stderr", 2);
- }
-
- private void testStdOutErrWindowSize(final String name, final int fd) {
- final HandleFactory handleFactory = newFactory();
- final TTYHandle tty = newTTY(handleFactory, fd, false);
- if (tty == null) {
- return;
- }
- testWindowSize(name, tty);
- }
-
- /// @Test
- public void testStdinWindowSize() {
- final HandleFactory handleFactory = newFactory();
- final TTYHandle tty = newTTY(handleFactory, 0, true);
- if (tty == null) {
- return;
- }
- testWindowSize("stdin", tty);
- }
-
- private void testWindowSize(final String name, final TTYHandle tty) {
- final int[] windowSize = tty.getWindowSize();
- ///Assert.assertNotNull(windowSize);
- ///Assert.assertEquals(windowSize.length, 2);
- ///Assert.assertNotNull(windowSize[0]);
- ///Assert.assertNotNull(windowSize[1]);
- ///Assert.assertTrue(windowSize[0] > 10);
- ///Assert.assertTrue(windowSize[1] > 10);
- System.out.println("tty " + name + " window size: " + windowSize[0] + " : " + windowSize[1]);
- }
-
- /// @Test
- public void testWrite() throws Throwable {
- testWrite("stdout", 1);
- testWrite("stderr", 2);
- }
-
- private void testWrite(final String name, final int fd) throws Throwable {
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final TTYHandle tty = newTTY(handleFactory, fd, false);
- if (tty == null) {
- return;
- }
- tty.setWriteCallback(new StreamWriteCallback() {
- @Override
- public void onWrite(int status, Exception error) throws Exception {
- System.out.println(status);
- ///Assert.assertEquals(status, 0);
- ///Assert.assertNotNull(error);
- }
- });
- tty.write("written to " + name + "\n");
- loop.run();
- }
-
- /// @Test
- public void testRead() throws Throwable {
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final TTYHandle tty = newTTY(handleFactory, 0, true);
- if (tty == null) {
- return;
- }
- final String prompt = "\ntype something (^D to exit) > ";
- tty.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- if (data != null) {
- System.out.print(new String(data.array()));
- System.out.print(prompt);
- } else {
- System.out.print("\n");
- }
- }
- });
- System.out.print(prompt);
- tty.readStart();
- loop.run();
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final TTYHandleTest test = new TTYHandleTest();
- try {
- test.testWrite();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- test.testStdOutErrWindowSize();
-
- try {
- test.testRead();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- test.testStdinWindowSize();
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/TestBase.java b/app/src/main/java/com/iwebpp/libuvpp/tests/TestBase.java
deleted file mode 100644
index d58a773..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/TestBase.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-import com.iwebpp.libuvpp.*;
-import java.util.Arrays;
-
-public class TestBase extends Thread {
-
- static {
- // call an idempotent LibUV method just to ensure that the native lib is loaded
- LibUV.cwd();
- }
-
- protected static final String TMPDIR = System.getProperty("java.io.tmpdir");
- protected static final int TIMEOUT = 5000;
- protected static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows");
-
- protected static void fill(final ByteBuffer buffer, byte b) {
- if (buffer.hasArray()) {
- Arrays.fill(buffer.array(), b);
- } else {
- final byte[] data = new byte[buffer.capacity()];
- Arrays.fill(data, b);
- buffer.clear();
- buffer.put(data);
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/TimerHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/TimerHandleTest.java
deleted file mode 100644
index 1bed39d..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/TimerHandleTest.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.TimerCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.TimerHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class TimerHandleTest extends TestBase {
- private static final String TAG = "TimerHandleTest";
-
- private static final int TIMES = 100;
-
- /// @Test
- public void testOnce() throws Throwable {
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotClose = new AtomicBoolean(false);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final TimerHandle timer = handleFactory.newTimerHandle();
-
- timer.setCloseCallback(new TimerCallback() {
- @Override
- public void onTimer(final int i) throws Exception {
- System.out.println("timer closed");
- gotClose.set(true);
- }
- });
-
- timer.setTimerFiredCallback(new TimerCallback() {
- @Override
- public void onTimer(final int status) throws Exception {
- gotCallback.set(true);
- System.out.println("timer fired once");
- timer.close();
- }
- });
-
- timer.start(100, 0);
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotClose.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout waiting for timer");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotClose.get());
- }
-
- /// @Test
- public void testRepeat() throws Throwable {
- final AtomicBoolean gotCallback = new AtomicBoolean(false);
- final AtomicBoolean gotClose = new AtomicBoolean(false);
- final AtomicInteger callbackCount = new AtomicInteger(0);
-
- final LoopHandle loop = new LoopHandle();
- final TimerHandle timer = new TimerHandle(loop);
-
- timer.setCloseCallback(new TimerCallback() {
- @Override
- public void onTimer(final int i) throws Exception {
- System.out.println("repeat timer closed");
- gotClose.set(true);
- }
- });
-
- timer.setTimerFiredCallback(new TimerCallback() {
- @Override
- public void onTimer(final int status) throws Exception {
- gotCallback.set(true);
- if (callbackCount.incrementAndGet() == TIMES) {
- System.out.println("closing repeat timer");
- gotClose.set(true);
- }
- System.out.println("timer fired " + callbackCount.get());
- }
- });
-
- timer.start(50, 5);
-
- final long start = System.currentTimeMillis();
- while (!gotCallback.get() || !gotClose.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout waiting for timer");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertTrue(gotCallback.get());
- ///Assert.assertTrue(gotClose.get());
- ///Assert.assertTrue(callbackCount.get() == TIMES);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final TimerHandleTest test = new TimerHandleTest();
- try {
- test.testOnce();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- /*try {
- test.testRepeat();
- } catch (Throwable e) {
- e.printStackTrace();
- }*/
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/UDPHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/UDPHandleTest.java
deleted file mode 100644
index 8281343..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/UDPHandleTest.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.Address;
-import com.iwebpp.libuvpp.cb.UDPRecvCallback;
-import com.iwebpp.libuvpp.cb.UDPSendCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.UDPHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class UDPHandleTest extends TestBase {
- private static final String TAG = "UDPHandleTest";
-
- private static final String HOST = "127.0.0.1";
- private static final String HOST6 = "::1";
- private static final int PORT = 34567;
- private static final int PORT6 = 45678;
- private static final int TIMES = 10;
-
- ///@Test
- public void testConnection() throws Throwable {
- final AtomicInteger clientSendCount = new AtomicInteger(0);
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final UDPHandle server = handleFactory.newUDPHandle();
- final UDPHandle client = handleFactory.newUDPHandle();
-
- server.setRecvCallback(new UDPRecvCallback() {
- @Override
- public void onRecv(int nread, ByteBuffer data, Address address) throws Exception {
- if (serverRecvCount.incrementAndGet() < TIMES) {
- } else {
- server.close();
- serverDone.set(true);
- }
- }
- });
-
- client.setSendCallback(new UDPSendCallback() {
- @Override
- public void onSend(int status, Exception error) throws Exception {
- if (clientSendCount.incrementAndGet() < TIMES) {
- } else {
- client.close();
- clientDone.set(true);
- }
- }
- });
-
- server.bind(PORT, HOST);
- server.recvStart();
-
- for (int i=0; i < TIMES; i++) {
- client.send("PING." + i, PORT, HOST);
- }
-
- final long start = System.currentTimeMillis();
- while (!serverDone.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- }
-
- ///@Test
- public void testConnection6() throws Throwable {
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- if (!isIPv6Enabled(loop)) {
- return;
- }
- final AtomicInteger clientSendCount = new AtomicInteger(0);
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final UDPHandle server = handleFactory.newUDPHandle();
- final UDPHandle client = handleFactory.newUDPHandle();
-
- server.setRecvCallback(new UDPRecvCallback() {
- @Override
- public void onRecv(int nread, ByteBuffer data, Address address) throws Exception {
- if (serverRecvCount.incrementAndGet() < TIMES) {
- System.out.printf(TAG+",server6.onRecv nread: %d, data: %s, addr: %s\n", nread, new String(data.array()), address);
- } else {
- server.close();
- serverDone.set(true);
- }
- }
- });
-
- client.setSendCallback(new UDPSendCallback() {
- @Override
- public void onSend(int status, Exception error) throws Exception {
- if (clientSendCount.incrementAndGet() < TIMES) {
- } else {
- client.close();
- clientDone.set(true);
- }
- }
- });
-
- server.bind6(PORT6, HOST6);
- server.recvStart();
-
- for (int i=0; i < TIMES; i++) {
- client.send6("PING." + i, PORT6, HOST6);
- }
-
- final long start = System.currentTimeMillis();
- while (!serverDone.get()) {
- if (System.currentTimeMillis() - start > TestBase.TIMEOUT) {
- ///Assert.fail("timeout");
- }
- loop.runNoWait();
- }
-
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final UDPHandleTest test = new UDPHandleTest();
- try {
- test.testConnection();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- try {
- test.testConnection6();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
- public static boolean isIPv6Enabled(final LoopHandle loop) {
- UDPHandle socket = null;
- try {
- socket = new UDPHandle(loop);
- socket.recvStart();
- socket.send6("", PORT6, HOST6);
- } catch(final com.iwebpp.libuvpp.NativeException e) {
- if ("EAFNOSUPPORT".equals(e.errnoString())) {
- return false;
- }
- } finally {
- if (socket != null) {
- socket.close();
- }
- }
- return true;
- }
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/UDTHandleTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/UDTHandleTest.java
deleted file mode 100644
index 33d2a54..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/UDTHandleTest.java
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import java.nio.ByteBuffer;
-import java.util.Random;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import android.util.Log;
-
-import com.iwebpp.libuvpp.cb.StreamCloseCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectCallback;
-import com.iwebpp.libuvpp.cb.StreamConnectionCallback;
-import com.iwebpp.libuvpp.cb.StreamReadCallback;
-import com.iwebpp.libuvpp.handles.HandleFactory;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.UDTHandle;
-
-import static com.iwebpp.libuvpp.handles.DefaultHandleFactory.newFactory;
-
-public class UDTHandleTest extends TestBase {
- private static final String TAG = "UDTHandleTest";
-
- private static final String ADDRESS = "127.0.0.1";
- private static final String ADDRESS6 = "::1";
- private static final int PORT = 23456;
- private static final int PORT6 = 34567;
- private static final int TIMES = 10;
-
- public void testConnection() throws Throwable {
- final AtomicInteger serverSendCount = new AtomicInteger(0);
- final AtomicInteger clientSendCount = new AtomicInteger(0);
-
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
- final AtomicInteger clientRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final HandleFactory handleFactory = newFactory();
- final LoopHandle loop = handleFactory.getLoopHandle();
- final UDTHandle server = handleFactory.newUDTHandle();
- final UDTHandle peer = handleFactory.newUDTHandle();
- final UDTHandle client = handleFactory.newUDTHandle();
-
- final Logger serverLoggingCallback = new Logger("s: ");
- final Logger clientLoggingCallback = new Logger("c: ");
-
- final Random random = new Random();
-
- server.setConnectionCallback(new StreamConnectionCallback() {
- @Override
- public void onConnection(int status, Exception error) throws Exception {
- serverLoggingCallback.log(status, error);
- server.accept(peer);
- peer.readStart();
- Log.d(TAG, "s: " + server.getSocketName() + " connected to " + peer.getPeerName());
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- server.close(); // not expecting any more connections
- }
- });
-
- peer.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- serverRecvCount.incrementAndGet();
- if (data == null) {
- peer.close();
- } else {
- final Object[] args = {data};
- serverLoggingCallback.log(args);
- if (serverRecvCount.get() == TIMES) {
- peer.close();
- } else {
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- }
- }
- }
- });
-
- peer.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- serverDone.set(true);
- }
- });
-
- client.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- clientRecvCount.incrementAndGet();
- if (data == null) {
- client.close();
- } else {
- final Object[] args = {data};
- clientLoggingCallback.log(args);
- if (clientRecvCount.get() == TIMES) {
- client.close();
- } else {
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- }
- }
- });
-
- client.setConnectCallback(new StreamConnectCallback() {
- @Override
- public void onConnect(int status, Exception error) throws Exception { // connect
- clientLoggingCallback.log(status, error);
- Log.d(TAG, "c: " + client.getSocketName() + " connected to " + client.getPeerName());
- client.readStart();
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- });
-
- client.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- clientDone.set(true);
- }
- });
-
- server.bind(ADDRESS, PORT);
- server.listen(1);
-
- Thread.sleep((long) (random.nextDouble() * 100));
- client.connect(ADDRESS, PORT);
-
- while (!serverDone.get() || !clientDone.get()) {
- loop.run();
- }
-
- ///Assert.assertEquals(serverSendCount.get(), TIMES);
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- ///Assert.assertEquals(clientRecvCount.get(), TIMES);
- }
-
- public void testConnection6() throws Throwable {
- final LoopHandle loop = new LoopHandle();
- if (!UDPHandleTest.isIPv6Enabled(loop)) {
- return;
- }
-
- final AtomicInteger serverSendCount = new AtomicInteger(0);
- final AtomicInteger clientSendCount = new AtomicInteger(0);
-
- final AtomicInteger serverRecvCount = new AtomicInteger(0);
- final AtomicInteger clientRecvCount = new AtomicInteger(0);
-
- final AtomicBoolean serverDone = new AtomicBoolean(false);
- final AtomicBoolean clientDone = new AtomicBoolean(false);
-
- final UDTHandle server = new UDTHandle(loop);
- final UDTHandle peer = new UDTHandle(loop);
- final UDTHandle client = new UDTHandle(loop);
-
- final Logger serverLoggingCallback = new Logger("s: ");
- final Logger clientLoggingCallback = new Logger("c: ");
-
- final Random random = new Random();
-
- server.setConnectionCallback(new StreamConnectionCallback() {
- @Override
- public void onConnection(int status, Exception error) throws Exception {
- serverLoggingCallback.log(status, error);
- server.accept(peer);
- peer.readStart();
- Log.d(TAG, "s: " + server.getSocketName() + " connected to " + peer.getPeerName());
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- server.close(); // not expecting any more connections
- }
- });
-
- peer.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- serverRecvCount.incrementAndGet();
- if (data == null) {
- peer.close();
- } else {
- final Object[] args = {data};
- serverLoggingCallback.log(args);
- if (serverRecvCount.get() == TIMES) {
- peer.close();
- } else {
- peer.write("message " + serverSendCount.getAndIncrement() + " from server");
- }
- }
- }
- });
-
- peer.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- serverDone.set(true);
- }
- });
-
- client.setReadCallback(new StreamReadCallback() {
- @Override
- public void onRead(final ByteBuffer data) throws Exception {
- clientRecvCount.incrementAndGet();
- if (data == null) {
- client.close();
- } else {
- final Object[] args = {data};
- clientLoggingCallback.log(args);
- if (clientRecvCount.get() == TIMES) {
- client.close();
- } else {
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- }
- }
- });
-
- client.setConnectCallback(new StreamConnectCallback() {
- @Override
- public void onConnect(int status, Exception error) throws Exception {
- clientLoggingCallback.log(status, error);
- Log.d(TAG, "c: " + client.getSocketName() + " connected to " + client.getPeerName());
- client.readStart();
- client.write("message " + clientSendCount.getAndIncrement() + " from client");
- }
- });
-
- client.setCloseCallback(new StreamCloseCallback() {
- @Override
- public void onClose() throws Exception { // close
- clientDone.set(true);
- }
- });
-
- server.bind6(ADDRESS6, PORT6);
- server.listen(1);
-
- Thread.sleep((long) (random.nextDouble() * 100));
- client.connect6(ADDRESS6, PORT6);
-
- while (!serverDone.get() || !clientDone.get()) {
- loop.run();
- }
-
- ///Assert.assertEquals(serverSendCount.get(), TIMES);
- ///Assert.assertEquals(clientSendCount.get(), TIMES);
- ///Assert.assertEquals(serverRecvCount.get(), TIMES);
- ///Assert.assertEquals(clientRecvCount.get(), TIMES);
- }
-
- ///public static void main(final String[] args) throws Throwable {
- public void run() {
- Log.d(TAG, "start test");
-
- final UDTHandleTest test = new UDTHandleTest();
- try {
- test.testConnection();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- try {
- test.testConnection6();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/libuvpp/tests/VersionTest.java b/app/src/main/java/com/iwebpp/libuvpp/tests/VersionTest.java
deleted file mode 100644
index 8fa2865..0000000
--- a/app/src/main/java/com/iwebpp/libuvpp/tests/VersionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code 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
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package com.iwebpp.libuvpp.tests;
-
-import com.iwebpp.libuvpp.LibUV;
-import android.util.Log;
-
-public class VersionTest extends TestBase {
-
- private static final String TAG = "VersionTest";
-
- ///@Test
- public void testVersion() {
- final String version = LibUV.version();
- Log.d(TAG, "libuv version is " + version);
-
- System.out.println("libuv version is " + version);
- ///junit.framework.///Assert.assertEquals(version, "0.10.27");
- }
-
- ///@Test
- public void testExePath() {
- final String exe = LibUV.exePath();
- Log.d(TAG, "exe is " + exe);
-
- System.out.println("exe is " + exe);
- ///junit.framework.///Assert.assertNotNull(exe);
- }
-
- public void run() {
- Log.d(TAG, "start test");
-
- testVersion();
- testExePath();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/middleware/Connect.java b/app/src/main/java/com/iwebpp/middleware/Connect.java
deleted file mode 100644
index 65b7a81..0000000
--- a/app/src/main/java/com/iwebpp/middleware/Connect.java
+++ /dev/null
@@ -1,202 +0,0 @@
-package com.iwebpp.middleware;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import com.iwebpp.node.EventEmitter2;
-import com.iwebpp.node.http.HttpServer.requestListener;
-import com.iwebpp.node.http.IncomingMessage;
-import com.iwebpp.node.http.ServerResponse;
-
-public class Connect
-extends EventEmitter2
-implements requestListener {
-
- private static final String TAG = "Connect";
-
- private String parent;
-
- private class stack_b {
- private String path;
- private requestListener cb;
-
- protected stack_b(String path, requestListener cb) {
- this.path = path;
- this.cb = cb;
- }
- }
-
- private List stack;
-
- public Connect() {
- parent = null;
- stack = new LinkedList();
- }
-
- public Connect(String path) {
- parent = path;
- stack = new LinkedList();
- }
-
- public Connect setParent(String path) {
- parent = path;
- return this;
- }
- public String getParent() {
- return parent!=null? parent : "";
- }
-
- /*
- * @description
- * append callback on default path /
- * */
- public Connect use(requestListener cb) throws Exception {
- return use("/", cb);
- }
-
- /*
- * @description
- * append callback on path
- * */
- public Connect use(String path, requestListener cb) throws Exception {
- debug(TAG, "added request cb:"+cb+" on "+path);
-
- // normalize
- if (path == null)
- path = "/";
- else if (path.charAt(0) != '/')
- path = "/" + path;
-
- // queue request handler
- stack.add(new stack_b(path, cb));
-
- this.emit("add:"+path, cb);
-
- return this;
- }
-
- /*
- * @description
- * take out callback on default path /
- * */
- public Connect unuse(requestListener cb) throws Exception {
- return unuse("/", cb);
- }
-
- /*
- * @description
- * take out callback on path
- * */
- public Connect unuse(String path, requestListener cb) throws Exception {
- debug(TAG, "removed request cb:"+cb+" on "+path);
-
- // normalize
- if (path == null)
- path = "/";
- else if (path.charAt(0) != '/')
- path = "/" + path;
-
- // cost operation
- for (stack_b b : stack)
- if (b.path.equalsIgnoreCase(path) && b.cb == cb)
- stack.remove(b);
-
- this.emit("del:"+path, cb);
-
- return this;
- }
-
- /*
- * @description
- * take out all callback on path
- * */
- public Connect unuse(String path) throws Exception {
- debug(TAG, "removed request on "+path);
-
- // normalize
- if (path == null)
- path = "/";
- else if (path.charAt(0) != '/')
- path = "/" + path;
-
- // cost operation
- for (stack_b b : stack)
- if (b.path.equalsIgnoreCase(path))
- stack.remove(b);
-
- this.emit("del:"+path+":all");
-
- return this;
- }
-
- /*
- * @description
- * take out all callback on all path
- * */
- public Connect unuse() throws Exception {
- debug(TAG, "removed all requests");
-
- stack.clear();
-
- this.emit("del:/any:all");
-
- return this;
- }
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- String path = req.url();
-
- debug(TAG, "request on "+path);
-
- // check if embedded stack
- if (parent != null && !parent.equals("/")) {
- if (path.startsWith(parent)) {
- path = path.substring(parent.length());
- debug(TAG, "child path: "+path);
- } else
- return;
- }
-
- // run stack until response header sent out
- for (stack_b b : stack) {
- // check embedded path
- if (b.cb instanceof Connect) {
- debug(TAG, "embedded path handle");
-
- Connect embedded = (Connect)b.cb;
- // set parent path
- String ppath = null;
- if (!b.path.equals("/")) ppath = b.path;
- if (parent!=null && !parent.equals("/")) ppath = ppath!=null ? parent+ppath : parent;
- embedded.setParent(ppath);
-
- embedded.onRequest(req, res);
-
- // check if res.sent
- if (res.headersSent()) {
- debug(TAG, "embedded response sent done, stop stack");
- break;
- }
- } else {
- // check absolute path
- if (path.startsWith(b.path)) {
- debug(TAG, "absolute path handle");
- // override req.url ???
- String temp = req.url(); req.url(path);
- b.cb.onRequest(req, res);
- // restore req.url ???
- req.url(temp);
-
- // check if res.sent
- if (res.headersSent()) {
- debug(TAG, "absolute response sent done, stop stack");
- break;
- }
- }
- }
- }
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/middleware/Static.java b/app/src/main/java/com/iwebpp/middleware/Static.java
deleted file mode 100644
index 82bdb60..0000000
--- a/app/src/main/java/com/iwebpp/middleware/Static.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.iwebpp.middleware;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import android.content.Context;
-import android.content.res.AssetManager;
-
-import com.iwebpp.SimpleDebug;
-import com.iwebpp.node.http.HttpServer.requestListener;
-import com.iwebpp.node.http.IncomingMessage;
-import com.iwebpp.node.http.ServerResponse;
-
-/**
- * @description Static file server from android Assert directory
- * */
-public class Static extends SimpleDebug
-implements requestListener {
-
- private Context ctx;
-
- private String rootPath;
-
- private AssetManager assertManager;
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- String filePath = rootPath + req.url();
-
- // check file existence
-
-
- // check file type
-
-
- // get file from assert
- String tContents = "";
- try {
- InputStream stream = assertManager.open(filePath);
-
- int size = stream.available();
- byte[] buffer = new byte[size];
- stream.read(buffer);
- stream.close();
- tContents = new String(buffer, "utf-8");
- } catch (IOException e) {
- // Handle exceptions here
- }
-
- // return response
- }
-
- public Static(Context ctx, String root) {
- this.ctx = ctx;
- this.rootPath = root.charAt(root.length()-1) == '/' ? root : root + "/";
- this.assertManager = ctx.getAssets();
- }
- public Static(Context ctx) {
- this(ctx, "/www/");
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/middleware/test/ConnectTest.java b/app/src/main/java/com/iwebpp/middleware/test/ConnectTest.java
deleted file mode 100644
index e636eb4..0000000
--- a/app/src/main/java/com/iwebpp/middleware/test/ConnectTest.java
+++ /dev/null
@@ -1,253 +0,0 @@
-package com.iwebpp.middleware.test;
-
-
-import android.util.Log;
-
-import com.iwebpp.middleware.Connect;
-import com.iwebpp.node.NodeContext;
-import com.iwebpp.node.NodeContext.TimeoutListener;
-import com.iwebpp.node.http.ClientRequest.responseListener;
-import com.iwebpp.node.http.HttpServer;
-import com.iwebpp.node.http.HttpServer.requestListener;
-import com.iwebpp.node.http.HttppServer;
-import com.iwebpp.node.http.IncomingMessage;
-import com.iwebpp.node.http.ServerResponse;
-import com.iwebpp.node.http.http;
-import com.iwebpp.node.http.httpp;
-
-import junit.framework.TestCase;
-
-public final class ConnectTest extends TestCase {
- private static final String TAG = "ConnectTest";
-
- private NodeContext ctx;
-
- // TODO are these supposed to communicate with each other?
- public void testStack() throws Exception {
- Connect stack = new Connect();
-
- // append timestamp header
- stack.use(new requestListener(){
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- res.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));
- }
-
- });
-
- // set status code
- stack.use(new requestListener(){
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- res.writeHead(200);
- res.end(null, null, null);
- }
-
- });
-
- // set un-reachable header
- stack.use(new requestListener(){
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- res.setHeader("unreachable", "yes");
- }
-
- });
-
- // route on path
- stack.use("/route", new requestListener(){
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- res.setHeader("route", req.url());
- res.end("route", "utf-8", null);
- }
-
- });
-
- HttpServer srv = http.createServer(ctx, stack);
- HttppServer srvpp = httpp.createServer(ctx, stack);
-
- int port = 5188;
- srv.listen(port, "0.0.0.0"); Log.d(TAG, "http server listen on "+port);
- srvpp.listen(port, "0.0.0.0"); Log.d(TAG, "httpp server listen on "+port);
-
- // request on /, /route
- ctx.setTimeout(new TimeoutListener(){
-
- @Override
- public void onTimeout() throws Exception {
- http.get(ctx, "http://localhost:5188/", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, "got http response on " + res.getPath() +", headers:"+res.headers());
- }
-
- });
- httpp.get(ctx, "http://localhost:5188/", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, "got httpp response on " + res.getPath() +", headers:"+res.headers());
- }
-
- });
-
- http.get(ctx, "http://localhost:5188/route", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, "got http response on " + res.getPath() +", headers:"+res.headers());
- }
-
- });
- httpp.get(ctx, "http://localhost:5188/route", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, "got httpp response on " + res.getPath() +", headers:"+res.headers());
- }
-
- });
- }
-
- }, 2000);
- }
-
- public void testNest() throws Exception {
- final Connect stack = new Connect();
- final Connect stack1 = new Connect();
-
- // append timestamp header
- stack1.use("/nest", new requestListener(){
-
- @Override
- public void onRequest(IncomingMessage req, ServerResponse res)
- throws Exception {
- res.setHeader("timestamp2", ""+System.currentTimeMillis());
- res.setHeader("ppath", stack1.getParent());
- res.end("nest", "utf-8", null);
- }
-
- });
-
- stack.use("/nest/nest", stack1);
- stack.use("/nest", stack1);
- stack.use(stack1);
-
- HttpServer srv = http.createServer(ctx, stack);
- HttppServer srvpp = httpp.createServer(ctx, stack);
-
- int port = 5189;
- srv.listen(port, "0.0.0.0"); Log.d(TAG, "http server listen on "+port);
- srvpp.listen(port, "0.0.0.0"); Log.d(TAG, "httpp server listen on "+port);
-
- // request on /, /route
- ctx.setTimeout(new TimeoutListener(){
-
- @Override
- public void onTimeout() throws Exception {
- http.get(ctx, "http://localhost:5189/", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got http response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
- httpp.get(ctx, "http://localhost:5189/", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got httpp response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
-
- http.get(ctx, "http://localhost:5189/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got http response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
- httpp.get(ctx, "http://localhost:5189/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got httpp response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
-
- http.get(ctx, "http://localhost:5189/nest/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got http response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
- httpp.get(ctx, "http://localhost:5189/nest/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got httpp response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
-
- http.get(ctx, "http://localhost:5189/nest/nest/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got http response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
- httpp.get(ctx, "http://localhost:5189/nest/nest/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got httpp response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
-
- http.get(ctx, "http://localhost:5189/nest/nest/nest/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got http response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
- httpp.get(ctx, "http://localhost:5189/nest/nest/nest/nest", new responseListener(){
-
- @Override
- public void onResponse(IncomingMessage res) throws Exception {
- Log.d(TAG, String.format("got httpp response on %s, headers: %s", res.getPath(), res.headers()));
- }
-
- });
- }
-
- }, 2000);
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- this.ctx = new NodeContext();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/node/Dns.java b/app/src/main/java/com/iwebpp/node/Dns.java
deleted file mode 100644
index cfb482d..0000000
--- a/app/src/main/java/com/iwebpp/node/Dns.java
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-
-public final class Dns
-extends EventEmitter2 {
- private static final String TAG = "Dns";
-
- private static final Map _errdesc;
- static {
- _errdesc = new Hashtable();
-
- _errdesc.put("NODATA", "DNS server returned answer with no data.");
- _errdesc.put("FORMERR", "DNS server claims query was misformatted.");
- _errdesc.put("SERVFAIL", "DNS server returned general failure.");
- _errdesc.put("NOTFOUND", "Domain name not found.");
- _errdesc.put("NOTIMP", "DNS server does not implement requested operation.");
- _errdesc.put("REFUSED", "DNS server refused query.");
- _errdesc.put("BADQUERY", "Misformatted DNS query.");
- _errdesc.put("BADNAME", "Misformatted domain name.");
- _errdesc.put("BADFAMILY", "Misformatted domain name.");
- _errdesc.put("BADRESP", "Misformatted DNS reply.");
- _errdesc.put("CONNREFUSED", "Could not contact DNS servers.");
- _errdesc.put("TIMEOUT", "Timeout while contacting DNS servers.");
- _errdesc.put("EOF", "End of file.");
- _errdesc.put("FILE", "Error reading file.");
- _errdesc.put("NOMEM", "Out of memory.");
- _errdesc.put("DESTRUCTION", "Channel is being destroyed.");
- _errdesc.put("BADSTR", "Misformatted string.");
- _errdesc.put("BADFLAGS", "Illegal flags specified.");
- _errdesc.put("NONAME", "Given hostname is not numeric.");
- _errdesc.put("BADHINTS", "Illegal hints flags specified.");
- _errdesc.put("NOTINITIALIZED", "c-ares library initialization not yet performed.");
- _errdesc.put("LOADIPHLPAPI", "Error loading iphlpapi.dll.");
- _errdesc.put("ADDRGETNETWORKPARAMS", "Could not find GetNetworkParams function.");
- _errdesc.put("CANCELLED", "DNS query cancelled.");
- }
-
- // return first matched IP
- public static String lookup(String domain) {
-
- try {
- InetAddress ipaddr = InetAddress.getByName(domain);
- String ip = ipaddr.getHostAddress();
-
- debug(TAG, "domain:"+domain+",ip:"+ip);
-
- return ip;
- } catch (UnknownHostException e) {
- ///e.printStackTrace();
- }
-
- return null;
- }
-
- public static String lookup(String domain, int family) {
-
- try {
- InetAddress[] ipaddrs = InetAddress.getAllByName(domain);
- String ip = null;
-
- // return first matched IP
- for (int i = 0; i < ipaddrs.length; i ++) {
- String addr = ipaddrs[i].getHostAddress();
-
- if (family == 4 && Util.isIPv4(addr)) {
- ip = addr; break;
- } else
-
- if (family == 6 && Util.isIPv6(addr)) {
- ip = addr; break;
- }
- }
-
- debug(TAG, "domain:"+domain+",ip:"+ip);
-
- return ip;
- } catch (UnknownHostException e) {
- ///e.printStackTrace();
- }
-
- return null;
- }
-
- public static void lookup(String domain, int family, lookupCallback callback) {
-
- }
- public interface lookupCallback {
- public void onLookup(NodeError err, String ip, int family) throws Exception;
- }
-
- public static List reverse(String ip) {
-
- try {
- InetAddress[] ipaddrs = InetAddress.getAllByName(ip);
-
- List domains = new ArrayList();
-
- for (int i = 0; i < ipaddrs.length; i ++)
- domains.add(ipaddrs[i].getHostName());
-
- return domains;
- } catch (UnknownHostException e) {
- ///e.printStackTrace();
- }
-
- return null;
- }
-
- public static void reverse(String ip, reverseCallback callback) {
-
- }
- public interface reverseCallback {
- public void onReverse(NodeError err, String [] domains) throws Exception;
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/node/EventEmitter.java b/app/src/main/java/com/iwebpp/node/EventEmitter.java
deleted file mode 100644
index e1ecc82..0000000
--- a/app/src/main/java/com/iwebpp/node/EventEmitter.java
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-import java.util.List;
-
-public interface EventEmitter {
- public boolean emit(final String event) throws Exception;
- public boolean emit(final String event, final Object data) throws Exception;
-
- public interface Listener {
- public void onEvent(final Object data) throws Exception;
- };
-
- public EventEmitter on(final String event, final Listener cb) throws Exception;
- public EventEmitter once(final String event, final Listener cb) throws Exception;
-
- public EventEmitter addListener(final String event, final Listener cb);
- public EventEmitter addListener(final String event, final Listener cb, int priority);
-
- public EventEmitter removeListener(final String event, final Listener cb);
- public EventEmitter removeListener(final String event);
- public EventEmitter removeListener();
- public EventEmitter removeAllListeners();
- public EventEmitter setMaxListeners(final String event, final int n);
- public List listeners(final String event);
- public int listenerCount(final String event);
-}
diff --git a/app/src/main/java/com/iwebpp/node/EventEmitter2.java b/app/src/main/java/com/iwebpp/node/EventEmitter2.java
deleted file mode 100644
index fbd830a..0000000
--- a/app/src/main/java/com/iwebpp/node/EventEmitter2.java
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-import java.nio.ByteBuffer;
-import java.util.Hashtable;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import com.iwebpp.SimpleDebug;
-
-
-public class EventEmitter2
-extends SimpleDebug
-implements EventEmitter {
- private final static String TAG = "EventEmitter2";
- private Map> events;
- private Map maxEvents;
-
- public EventEmitter2() {
- this.events = new Hashtable>();
- this.maxEvents = new Hashtable();
- }
-
- @Override
- public boolean emit(final String event) throws Exception {
- if (events.containsKey(event)) {
- debug(TAG, "emit "+event+" at="+this);
- for (Listener cb : events.get(event))
- cb.onEvent(null);
- } else {
- debug(TAG, "unknown event "+event+" at="+this);
- return false;
- }
- return true;
- }
-
- @Override
- public boolean emit(final String event, final Object data) throws Exception {
- if (events.containsKey(event)) {
- debug(TAG, "emit "+event+" data="+data+" at="+this);
-
- for (Listener cb : events.get(event))
- // always create new one to share in case ByteBuffer, etc
- if (data instanceof ByteBuffer) {
- ByteBuffer bb = ((ByteBuffer)data).slice();
- cb.onEvent(bb);
- } else
- cb.onEvent(data);
- } else {
- debug(TAG, "unknown event "+event+" data "+data+" at="+this);
- return false;
- }
- return true;
- }
-
- @Override
- public EventEmitter addListener(final String event, final Listener cb) {
- // check maxListens
- if (maxEvents.containsKey(event) &&
- maxEvents.get(event) < listenerCount(event)) {
- warn(TAG, "exceed maxListeners@"+event+" at="+this);
-
- ///return this;
- }
-
- if (!events.containsKey(event)) {
- events.put(event, new LinkedList());
- }
-
- debug(TAG, "addListener "+event+" cb="+cb+" at="+this);
-
- events.get(event).add(cb);
-
- return this;
- }
-
- @Override
- public EventEmitter addListener(final String event, final Listener cb, final int priority) {
- // check maxListens
- if (maxEvents.containsKey(event) &&
- maxEvents.get(event) < listenerCount(event)) {
- warn(TAG, "exceed maxListeners@"+event+" at="+this);
-
- ///return this;
- }
-
- if (!events.containsKey(event)) {
- events.put(event, new LinkedList());
- }
-
- if (priority < listenerCount(event))
- events.get(event).add(priority, cb);
- else
- events.get(event).add(cb);
-
- return this;
- }
-
- @Override
- public EventEmitter on(final String event, final Listener cb) throws Exception {
- return addListener(event, cb);
- }
-
- @Override
- public EventEmitter once(final String event, final Listener ocb) {
- return addListener(event, new Listener(){
-
- @Override
- public void onEvent(final Object data) throws Exception {
- ocb.onEvent(data);
-
- // remove listener
- removeListener(event, this);
- }
-
- });
- }
-
- @Override
- public EventEmitter removeListener(final String event, final Listener cb) {
- if (events.containsKey(event) && events.get(event).contains(cb))
- events.get(event).remove(cb);
-
- return this;
- }
-
- @Override
- public EventEmitter removeListener(final String event) {
- if (events.containsKey(event))
- events.remove(event);
-
- return this;
- }
-
- @Override
- public EventEmitter removeListener() {
- events.clear();
- return this;
- }
-
- @Override
- public EventEmitter removeAllListeners() {
- events.clear();
- return this;
- }
-
- @Override
- public EventEmitter setMaxListeners(final String event, final int n) {
- this.maxEvents.put(event, n);
- return this;
- }
-
- @Override
- public List listeners(final String event) {
- return events.containsKey(event) ? events.get(event) : null;
- }
-
- @Override
- public int listenerCount(final String event) {
- return events.containsKey(event) ? events.get(event).size() : 0;
- }
-}
diff --git a/app/src/main/java/com/iwebpp/node/HttpParser.java b/app/src/main/java/com/iwebpp/node/HttpParser.java
deleted file mode 100644
index 51a1048..0000000
--- a/app/src/main/java/com/iwebpp/node/HttpParser.java
+++ /dev/null
@@ -1,3919 +0,0 @@
-// Copyright (c) 2014-present Tom Zhou
-
-
-package com.iwebpp.node;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-
-import com.iwebpp.SimpleDebug;
-
-
-public abstract class HttpParser extends SimpleDebug {
- private final static String TAG = "HttpParser";
-
- protected HttpParser(http_parser_type type, Object data) {
- this.data = data;
-
- reset(type);
- }
- @SuppressWarnings("unused")
- private HttpParser() {this.data = null;}
-
- public static enum http_parser_type {
- HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH;
- }
-
- private enum State {
- s_unknown (0)
-
- , s_dead (1) /* important that this is > 0 */
-
- , s_start_req_or_res (2)
- , s_res_or_resp_H (3)
- , s_start_res (4)
- , s_res_H (5)
- , s_res_HT (6)
- , s_res_HTT (7)
- , s_res_HTTP (8)
- , s_res_first_http_major (9)
- , s_res_http_major (10)
- , s_res_first_http_minor (11)
- , s_res_http_minor (12)
- , s_res_first_status_code (13)
- , s_res_status_code (14)
- , s_res_status_start (15)
- , s_res_status (16)
- , s_res_line_almost_done (17)
-
- , s_start_req (18)
-
- , s_req_method (19)
- , s_req_spaces_before_url (20)
- , s_req_schema (21)
- , s_req_schema_slash (22)
- , s_req_schema_slash_slash (23)
- , s_req_server_start (24)
- , s_req_server (25)
- , s_req_server_with_at (26)
- , s_req_path (27)
- , s_req_query_string_start (28)
- , s_req_query_string (29)
- , s_req_fragment_start (30)
- , s_req_fragment (31)
- , s_req_http_start (32)
- , s_req_http_H (33)
- , s_req_http_HT (34)
- , s_req_http_HTT (35)
- , s_req_http_HTTP (36)
- , s_req_first_http_major (37)
- , s_req_http_major (38)
- , s_req_first_http_minor (39)
- , s_req_http_minor (40)
- , s_req_line_almost_done (41)
-
- , s_header_field_start (42)
- , s_header_field (43)
- , s_header_value_discard_ws (44)
- , s_header_value_discard_ws_almost_done (45)
- , s_header_value_discard_lws (46)
- , s_header_value_start (47)
- , s_header_value (48)
- , s_header_value_lws (49)
-
- , s_header_almost_done (50)
-
- , s_chunk_size_start (51)
- , s_chunk_size (52)
- , s_chunk_parameters (53)
- , s_chunk_size_almost_done (54)
-
- , s_headers_almost_done (55)
- , s_headers_done (56)
-
- /* Important: 's_headers_done' must be the last 'header' State. All
- * states beyond this must be 'body' states. It is used for overflow
- * checking. See the PARSING_HEADER() macro.
- */
-
- , s_chunk_data (57)
- , s_chunk_data_almost_done (58)
- , s_chunk_data_done (59)
-
- , s_body_identity (60)
- , s_body_identity_eof (61)
-
- , s_message_done (62);
-
- private final int state;
- private State(int state) {
- this.state = state;
- }
- }
-
- private enum header_states {
- h_general (0)
- , h_C (1)
- , h_CO (2)
- , h_CON (3)
-
- , h_matching_connection (4)
- , h_matching_proxy_connection (5)
- , h_matching_content_length (6)
- , h_matching_transfer_encoding (7)
- , h_matching_upgrade (8)
-
- , h_connection (9)
- , h_content_length (10)
- , h_transfer_encoding (11)
- , h_upgrade (12)
-
- , h_matching_transfer_encoding_chunked (13)
- , h_matching_connection_keep_alive (14)
- , h_matching_connection_close (15)
-
- , h_transfer_encoding_chunked (16)
- , h_connection_keep_alive (17)
- , h_connection_close (18);
-
- private header_states(int state){ }
- };
-
- private enum http_host_state {
- s_http_host_dead (1)
- , s_http_userinfo_start (2)
- , s_http_userinfo (3)
- , s_http_host_start (4)
- , s_http_host_v6_start (5)
- , s_http_host (6)
- , s_http_host_v6 (7)
- , s_http_host_v6_end (8)
- , s_http_host_port_start (9)
- , s_http_host_port (10);
-
- private http_host_state(int state){ }
- }
-
- /* Request Methods */
- public static enum http_method {
- HTTP_DELETE ("DELETE\0"),
- HTTP_GET ("GET\0"),
- HTTP_HEAD ("HEAD\0"),
- HTTP_POST ("POST\0"),
- HTTP_PUT ("PUT\0"),
-
- /* pathological */
- HTTP_CONNECT ("CONNECT\0"),
- HTTP_OPTIONS ("OPTIONS\0"),
- HTTP_TRACE ("TRACE\0"),
-
- /* webdav */
- HTTP_COPY ("COPY\0"),
- HTTP_LOCK ("LOCK\0"),
- HTTP_MKCOL ("MKCOL\0"),
- HTTP_MOVE ("MOVE\0"),
- HTTP_PROPFIND ("PROPFIND\0"),
- HTTP_PROPPATCH ("PROPPATCH\0"),
- HTTP_SEARCH ("SEARCH\0"),
- HTTP_UNLOCK ("UNLOCK\0"),
-
- /* subversion */
- HTTP_REPORT ("REPORT\0"),
- HTTP_MKACTIVITY ("MKACTIVITY\0"),
- HTTP_CHECKOUT ("CHECKOUT\0"),
- HTTP_MERGE ("MERGE\0"),
-
- /* upnp */
- HTTP_MSEARCH ("M-SEARCH\0"),
- HTTP_NOTIFY ("NOTIFY\0"),
- HTTP_SUBSCRIBE ("SUBSCRIBE\0"),
- HTTP_UNSUBSCRIBE ("UNSUBSCRIBE\0"),
-
- /* RFC-5789 */
- HTTP_PATCH ("PATCH\0"),
- HTTP_PURGE ("PURGE\0"),
-
- // invalid
- HTTP_INVALID ("INVALID\0");
-
-
- private final String desc;
- private http_method(String desc) {
- this.desc = desc;
- }
-
- public String desc() {
- return desc.substring(0, desc.length()-1);
- }
- }
-
- /* Define HPE_* values for each errno value above */
- public static enum http_errno {
- /* No error */
- ///XX(OK, "success")
- HPE_OK("success"),
-
- /* Callback-related errors */
- ///XX(CB_message_begin, "the on_message_begin callback failed")
- ///XX(CB_url, "the on_url callback failed")
- ///XX(CB_header_field, "the on_header_field callback failed")
- ///XX(CB_header_value, "the on_header_value callback failed")
- ///XX(CB_headers_complete, "the on_headers_complete callback failed")
- ///XX(CB_body, "the on_body callback failed")
- ///XX(CB_message_complete, "the on_message_complete callback failed")
- ///XX(CB_status, "the on_status callback failed")
- HPE_CB_message_begin("the on_message_begin callback failed"),
- HPE_CB_url("the on_url callback failed"),
- HPE_CB_header_field("the on_header_field callback failed" ),
- HPE_CB_header_value("the on_header_value callback failed"),
- HPE_CB_headers_complete("the on_headers_complete callback failed"),
- HPE_CB_body("the on_body callback failed"),
- HPE_CB_message_complete("the on_message_complete callback failed"),
- HPE_CB_status("the on_status callback failed"),
-
- /* Parsing-related errors */
- ///XX(INVALID_EOF_STATE, "stream ended at an unexpected time")
- ///XX(HEADER_OVERFLOW,
- /// "too many header bytes seen; overflow detected")
- ///XX(CLOSED_CONNECTION,
- /// "data received after completed connection: close message")
- ///XX(INVALID_VERSION, "invalid http version")
- ///XX(INVALID_STATUS, "invalid http status code")
- ///XX(INVALID_METHOD, "invalid http method")
- ///XX(INVALID_URL, "invalid URL")
- HPE_INVALID_EOF_STATE("stream ended at an unexpected time"),
- HPE_HEADER_OVERFLOW("too many header bytes seen; overflow detected"),
- HPE_CLOSED_CONNECTION("data received after completed connection: close message"),
- HPE_INVALID_VERSION("invalid http version"),
- HPE_INVALID_STATUS("invalid http status code"),
- HPE_INVALID_METHOD("invalid http method"),
- HPE_INVALID_URL("invalid URL"),
-
- ///XX(INVALID_HOST, "invalid host")
- ///XX(INVALID_PORT, "invalid port")
- ///XX(INVALID_PATH, "invalid path")
- ///XX(INVALID_QUERY_STRING, "invalid query string")
- ///XX(INVALID_FRAGMENT, "invalid fragment")
- ///XX(LF_EXPECTED, "LF character expected")
- ///XX(INVALID_HEADER_TOKEN, "invalid character in header")
- ///XX(INVALID_CONTENT_LENGTH,
- /// "invalid character in content-length header")
- ///XX(INVALID_CHUNK_SIZE,
- /// "invalid character in chunk size header")
- ///XX(INVALID_CONSTANT, "invalid constant string")
- ///XX(INVALID_INTERNAL_STATE, "encountered unexpected internal State")
- ///XX(STRICT, "strict mode assertion failed")
- ///XX(PAUSED, "parser is paused")
- ///XX(MAYBE, "an unknown error occurred")
- HPE_INVALID_HOST("invalid host"),
- HPE_INVALID_PORT("invalid port"),
- HPE_INVALID_PATH("invalid path"),
- HPE_INVALID_QUERY_STRING("invalid query string"),
- HPE_INVALID_FRAGMENT("invalid fragment"),
- HPE_LF_EXPECTED("LF character expected"),
- HPE_INVALID_HEADER_TOKEN("invalid character in header"),
- HPE_INVALID_CONTENT_LENGTH("invalid character in content-length header"),
- HPE_INVALID_CHUNK_SIZE("invalid character in chunk size header"),
- HPE_INVALID_CONSTANT("invalid constant string"),
- HPE_INVALID_INTERNAL_STATE("encountered unexpected internal State"),
- HPE_STRICT("strict mode assertion failed"),
- HPE_PAUSED("parser is paused"),
- HPE_UNKNOWN("an unknown error occurred");
-
- private final String desc;
- private http_errno(String desc) {
- this.desc = desc;
- }
-
- public String desc() {
- return this.desc;
- }
- }
-
- /* Get an http_errno value from an http_parser */
- protected http_errno HTTP_PARSER_ERRNO() {
- return this.http_errno;
- }
-
- /* Flag values for http_parser.flags field */
- private enum Flags {
- F_CHUNKED (1 << 0),
- F_CONNECTION_KEEP_ALIVE (1 << 1),
- F_CONNECTION_CLOSE (1 << 2),
- F_TRAILING (1 << 3),
- F_UPGRADE (1 << 4),
- F_SKIPBODY (1 << 5);
-
- private final int flag;
- private Flags(int flag) {
- this.flag= flag;
- }
- }
-
- private enum http_parser_url_fields {
- UF_SCHEMA (0),
- UF_HOST (1),
- UF_PORT (2),
- UF_PATH (3),
- UF_QUERY (4),
- UF_FRAGMENT (5),
- UF_USERINFO (6),
- UF_MAX (7);
-
- private final int field;
-
- private http_parser_url_fields(int field) {
- this.field = field;
- }
- }
-
- private final static String PROXY_CONNECTION = "proxy-connection\0";
- private final static String CONNECTION = "connection\0";
- private final static String CONTENT_LENGTH = "content-length\0";
- private final static String TRANSFER_ENCODING = "transfer-encoding\0";
- private final static String UPGRADE = "upgrade\0";
- private final static String CHUNKED = "chunked\0";
- private final static String KEEP_ALIVE = "keep-alive\0";
- private final static String CLOSE = "close\0";
-
- private static long ULLONG_MAX() {
- return Long.MAX_VALUE;
- }
-
- private static long MIN(long a, long b) {
- return ((a) < (b) ? (a) : (b));
- }
-
- private static boolean BIT_AT(int [] a, int i) {
- i &= 0xff;
-
- return (0 != (a[i >> 3] &
- (1 << (i & 7))));
- }
-
- private void SET_ERRNO(http_errno e) {
- this.http_errno = e;
- }
-
- /* Tokens as defined by rfc 2616. Also lowercases them.
- * token = 1*
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- */
- private final static char tokens[] = {
- /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
- 0, 0, 0, 0, 0, 0, 0, 0,
- /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
- 0, 0, 0, 0, 0, 0, 0, 0,
- /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
- 0, 0, 0, 0, 0, 0, 0, 0,
- /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
- 0, 0, 0, 0, 0, 0, 0, 0,
- /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
- 0, '!', 0, '#', '$', '%', '&', '\'',
- /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
- 0, 0, '*', '+', 0, '-', '.', 0,
- /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
- '0', '1', '2', '3', '4', '5', '6', '7',
- /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
- '8', '9', 0, 0, 0, 0, 0, 0,
- /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
- 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
- /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
- 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
- /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
- 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
- /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
- 'x', 'y', 'z', 0, 0, 0, '^', '_',
- /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
- '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
- /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
- 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
- /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
- 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
- /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
- 'x', 'y', 'z', 0, '|', 0, '~', 0
- };
-
- private final static char ASCII[] = {
- /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
- 0, 0, 0, 0, 0, 0, 0, 0,
- /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
- 0, '\t', '\n', 0, '\f', '\r', 0, 0,
- /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
- 0, 0, 0, 0, 0, 0, 0, 0,
- /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
- 0, 0, 0, 0, 0, 0, 0, 0,
-
- /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
- ' ', '!', '"', '#', '$', '%', '&', '\'',
- /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
- '(', ')', '*', '+', ',', '-', '.', '/',
- /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
- '0', '1', '2', '3', '4', '5', '6', '7',
- /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
- '8', '9', ':', ';', '<', '=', '>', '?',
- /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
- '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
- /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
- /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
- /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
- 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
- /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
- '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
- /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
- 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
- /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
- 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
- /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
- 'x', 'y', 'z', '{', '|', '}', '~', 0
- };
-
- private final static byte unhex[] = {
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
- ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
- ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
- , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
- ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
- ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
- ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
- ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
- };
-
- // strict parse mode
- private final static int normal_url_char[] = {
- /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
- 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
- /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
- 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
- /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
- 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
- /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
- 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
- /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
- 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128,
- /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,
- /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
- /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
- 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,
- };
-
- private boolean PARSING_HEADER() {
- return (this.state.state <= State.s_headers_done.state);
- }
-
- /* Does the parser need to see an EOF to find the end of the message? */
- private boolean http_message_needs_eof () {
- if (type == http_parser_type.HTTP_REQUEST) {
- return false;
- }
-
- /* See RFC 2616 section 4.4 */
- if (status_code / 100 == 1 || /* 1xx e.g. Continue */
- status_code == 204 || /* No Content */
- status_code == 304 || /* Not Modified */
- (flags & Flags.F_SKIPBODY.flag)!=0) { /* response to a HEAD request */
- return false;
- }
-
- if ((flags & Flags.F_CHUNKED.flag)!=0 || content_length != ULLONG_MAX()) {
- return false;
- }
-
- return true;
- }
-
- /* Macros for character classes; depends on strict-mode */
- /*#define CR '\r'
- #define LF '\n'
- #define LOWER(c) (unsigned char)(c | 0x20)
- #define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z')
- #define IS_NUM(c) ((c) >= '0' && (c) <= '9')
- #define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c))
- #define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
- #define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \
- (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
- (c) == ')')
- #define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
- (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
- (c) == '$' || (c) == ',')
-
- #if HTTP_PARSER_STRICT
- #define TOKEN(c) (tokens[(unsigned char)c])
- #define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c))
- #define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
- #else
- #define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c])
- #define IS_URL_CHAR(c) \
- (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
- #define IS_HOST_CHAR(c) \
- (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
- #endif
-
-
- #define start_state (type == HTTP_REQUEST ? s_start_req : s_start_res)
- */
-
- private static char LOWER(char c) {
- return Character.toLowerCase(c);
- }
- private static boolean IS_ALPHA(char c) {
- boolean yes = (LOWER(c) >= 'a' && LOWER(c) <= 'z');
-
- if (!yes) debug(TAG, "\n\n\nNot alpha: "+c);
-
- return yes;
- }
- private static boolean IS_NUM(char c) {
- boolean yes = ((c) >= '0' && (c) <= '9');
-
- if (!yes) debug(TAG, "\n\n\nNot num: "+c);
-
- return yes;
- }
- private static boolean IS_ALPHANUM(char c) {
- return (IS_ALPHA(c) || IS_NUM(c));
- }
- private static boolean IS_HEX(char c) {
- boolean yes = (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'));
-
- if (!yes) debug(TAG, "\n\n\nNot HEX: "+c);
-
- return yes;
- }
- private static boolean IS_MARK(char c) {
- return ((c) == '-' || (c) == '_' || (c) == '.' ||
- (c) == '!' || (c) == '~' || (c) == '*' ||
- (c) == '\'' || (c) == '(' || (c) == ')');
- }
- private static boolean IS_USERINFO_CHAR(char c) {
- return (IS_ALPHANUM(c) || IS_MARK(c) ||
- (c) == '%' || (c) == ';' || (c) == ':' ||
- (c) == '&' || (c) == '=' || (c) == '+' ||
- (c) == '$' || (c) == ',');
- }
-
- private static char TOKEN(int uc) {
- uc &= 0xff;
-
- debug(TAG, "TOKEN uc: "+uc);
-
- return (tokens[uc]);
- }
-
- private static boolean IS_URL_CHAR(char c)
- throws UnsupportedEncodingException {
- // convert to ASICII / UTF-8 char
- String cstr = "" + c;
- int uc = cstr.getBytes("utf-8")[0] & 0xff;
-
- debug(TAG, "IS_URL_CHAR cstr: "+cstr+", uc: "+uc);
-
- return (BIT_AT(normal_url_char, uc));
- }
-
- private static boolean IS_HOST_CHAR(char c) {
- return (IS_ALPHANUM(c) || (c) == '.' || (c) == '-');
- }
-
- private State start_state() {
- return (type == http_parser_type.HTTP_REQUEST ? State.s_start_req : State.s_start_res);
- }
-
- private State NEW_MESSAGE() {
- return http_should_keep_alive() ? start_state() : State.s_dead;
- }
-
- /* Our URL parser.
- *
- * This is designed to be shared by http_parser_execute() for URL validation,
- * hence it has a State transition + byte-for-byte interface. In addition, it
- * is meant to be embedded in http_parser_parse_url(), which does the dirty
- * work of turning State transitions URL components for its API.
- *
- * This function should only be invoked with non-space characters. It is
- * assumed that the caller cares about (and can detect) the transition between
- * URL and non-URL states by looking for these.
- */
- private static State parse_url_char(State s, final char ch)
- throws UnsupportedEncodingException
- {
- if (ch == ' ' || ch == '\r' || ch == '\n') {
- return State.s_dead;
- }
-
- ///#if HTTP_PARSER_STRICT
- if (ch == '\t' || ch == '\f') {
- return State.s_dead;
- }
- ///#endif
-
- switch (s) {
- case s_req_spaces_before_url:
- /* Proxied requests are followed by scheme of an absolute URI (alpha).
- * All methods except CONNECT are followed by '/' or '*'.
- */
-
- if (ch == '/' || ch == '*') {
- return State.s_req_path;
- }
-
- if (IS_ALPHA(ch)) {
- return State.s_req_schema;
- }
-
- break;
-
- case s_req_schema:
- if (IS_ALPHA(ch)) {
- return s;
- }
-
- if (ch == ':') {
- return State.s_req_schema_slash;
- }
-
- break;
-
- case s_req_schema_slash:
- if (ch == '/') {
- return State.s_req_schema_slash_slash;
- }
-
- break;
-
- case s_req_schema_slash_slash:
- if (ch == '/') {
- return State.s_req_server_start;
- }
-
- break;
-
- case s_req_server_with_at:
- if (ch == '@') {
- return State.s_dead;
- }
-
- /* FALLTHROUGH */
- case s_req_server_start:
- case s_req_server:
- if (ch == '/') {
- return State.s_req_path;
- }
-
- if (ch == '?') {
- return State.s_req_query_string_start;
- }
-
- if (ch == '@') {
- return State.s_req_server_with_at;
- }
-
- if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
- return State.s_req_server;
- }
-
- break;
-
- case s_req_path:
- if (IS_URL_CHAR(ch)) {
- return s;
- }
-
- switch (ch) {
- case '?':
- return State.s_req_query_string_start;
-
- case '#':
- return State.s_req_fragment_start;
- }
-
- break;
-
- case s_req_query_string_start:
- case s_req_query_string:
- if (IS_URL_CHAR(ch)) {
- return State.s_req_query_string;
- }
-
- switch (ch) {
- case '?':
- /* allow extra '?' in query string */
- return State.s_req_query_string;
-
- case '#':
- return State.s_req_fragment_start;
- }
-
- break;
-
- case s_req_fragment_start:
- if (IS_URL_CHAR(ch)) {
- return State.s_req_fragment;
- }
-
- switch (ch) {
- case '?':
- return State.s_req_fragment;
-
- case '#':
- return s;
- }
-
- break;
-
- case s_req_fragment:
- if (IS_URL_CHAR(ch)) {
- return s;
- }
-
- switch (ch) {
- case '?':
- case '#':
- return s;
- }
-
- break;
-
- default:
- break;
- }
-
- /* We should never fall out of the switch above unless there's an error */
- return State.s_dead;
- }
-
-
- /* Result structure for http_parser_parse_url().
- *
- * Callers should index into field_data[] with UF_* values if field_set
- * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
- * because we probably have padding left over), we convert any port to
- * a uint16_t.
- */
- protected static class http_parser_url {
- protected int field_set; /* Bitmask of (1 << UF_*) values */
- protected int port; /* Converted UF_PORT string */
-
- protected class field_data_t {
- int off; /* Offset into buffer in which field starts */
- int len; /* Length of run in buffer */
- }
-
- protected field_data_t field_data[];
-
- protected http_parser_url() {
- field_data = new field_data_t[http_parser_url_fields.UF_MAX.field];
- }
- }
-
- /*
- *
-struct http_parser_settings {
- http_cb on_message_begin;
- http_data_cb on_url;
- http_data_cb on_status;
- http_data_cb on_header_field;
- http_data_cb on_header_value;
- http_cb on_headers_complete;
- http_data_cb on_body;
- http_cb on_message_complete;
-};
- * */
- protected abstract int on_message_begin() throws Exception;
- protected abstract int on_url(ByteBuffer url) throws Exception;
- protected abstract int on_status(ByteBuffer status) throws Exception;
- protected abstract int on_header_field(ByteBuffer field) throws Exception;
- protected abstract int on_header_value(ByteBuffer vaule) throws Exception;
- protected abstract int on_headers_complete() throws Exception;
- protected abstract int on_body(ByteBuffer body) throws Exception;
- protected abstract int on_message_complete() throws Exception;
-
- /* Returns the library version. Bits 16-23 contain the major version number,
- * bits 8-15 the minor version number and bits 0-7 the patch level.
- * Usage example:
- *
- * unsigned long version = http_parser_version();
- * unsigned major = (version >> 16) & 255;
- * unsigned minor = (version >> 8) & 255;
- * unsigned patch = version & 255;
- * printf("http_parser v%u.%u.%u\n", major, minor, version);
- */
- private final static long HTTP_PARSER_VERSION_MAJOR = 2;
- private final static long HTTP_PARSER_VERSION_MINOR = 3;
- private final static long HTTP_PARSER_VERSION_PATCH = 0;
-
- public long version() {
- return HTTP_PARSER_VERSION_MAJOR * 0x10000 |
- HTTP_PARSER_VERSION_MINOR * 0x00100 |
- HTTP_PARSER_VERSION_PATCH * 0x00001;
- }
-
- /* Maximium header size allowed */
- private final static int HTTP_MAX_HEADER_SIZE = (80*1024);
-
- ///void http_parser_init(http_parser *parser, enum http_parser_type type);
-
- @SuppressWarnings("static-access")
- public void reset(http_parser_type type) {
- this.type = type;
- this.http_errno = http_errno.HPE_OK;
- this.state = (type == http_parser_type.HTTP_REQUEST ? State.s_start_req :
- (type == http_parser_type.HTTP_RESPONSE ? State.s_start_res : State.s_start_req_or_res));
-
- // zero fields
- this.content_length = 0;
- this.flags = 0;
- this.http_major = this.http_minor = 0;
- this.index = 0;
- this.nread = 0;
- this.status_code = 0;
- this.upgrade = false;
- this.header_state = header_state.h_general;
- this.method = http_method.HTTP_INVALID;
- }
-
- @SuppressWarnings("static-access")
- public int execute(ByteBuffer data) throws Exception {
- char c, ch;
- int uc;
-
- /*int8_t unhex_val;
- const char *p = data;
- const char *header_field_mark = 0;
- const char *header_value_mark = 0;
- const char *url_mark = 0;
- const char *body_mark = 0;
- const char *status_mark = 0;
- */
- byte unhex_val;
- int p = 0;
- int header_field_mark = -1;
- int header_value_mark = -1;
- int url_mark = -1;
- int body_mark = -1;
- int status_mark = -1;
- int len = (data == null) ? 0 : data.capacity();
- int reexecute_byte = 0;
-
- debug(TAG, "http_parser_execute .");
-
- /* We're in an error state. Don't bother doing anything. */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- return 0;
- }
-
- debug(TAG, "http_parser_execute ..");
-
- if (len == 0) {
- switch (state) {
- case s_body_identity_eof:
- /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if
- * we got paused.
- */
- ///CALLBACK_NOTIFY_NOADVANCE(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- }
- return 0;
-
- case s_dead:
- case s_start_req_or_res:
- case s_start_res:
- case s_start_req:
- return 0;
-
- default:
- SET_ERRNO(http_errno.HPE_INVALID_EOF_STATE);
- return 1;
- }
- }
-
-
- if (state == State.s_header_field)
- header_field_mark = 0;///data;
-
- if (state == State.s_header_value)
- header_value_mark = 0;///data;
-
- switch (state) {
- case s_req_path:
- case s_req_schema:
- case s_req_schema_slash:
- case s_req_schema_slash_slash:
- case s_req_server_start:
- case s_req_server:
- case s_req_server_with_at:
- case s_req_query_string_start:
- case s_req_query_string:
- case s_req_fragment_start:
- case s_req_fragment:
- url_mark = 0;///data;
- break;
- case s_res_status:
- status_mark = 0;///data;
- break;
- default:
- break;
- }
-
- debug(TAG, "http_parser_execute ... state:"+state.state);
-
- ///for (p=data; p != data + len; p++) {
- for (p = 0; p < len; p ++) {
- ///ch = *p;
- uc = data.get(p) & 0xff;
- ch = ASCII[uc];
-
- debug(TAG, "uc: "+uc+", ch: "+ch);
-
- ///if (PARSING_HEADER(state)) {
- if (PARSING_HEADER()) {
- debug(TAG, "PARSING_HEADER");
-
- ///++nread;
- nread++;
-
- /* Don't allow the total size of the http headers (including the status
- * line) to exceed HTTP_MAX_HEADER_SIZE. This check is here to protect
- * embedders against denial-of-service attacks where the attacker feeds
- * us a never-ending header that the embedder keeps buffering.
- *
- * This check is arguably the responsibility of embedders but we're doing
- * it on the embedder's behalf because most won't bother and this way we
- * make the web a little safer. HTTP_MAX_HEADER_SIZE is still far bigger
- * than any reasonable request or response so this should never affect
- * day-to-day operation.
- */
- ///if (nread > HTTP_MAX_HEADER_SIZE) {
- if (nread > HTTP_MAX_HEADER_SIZE) {
- SET_ERRNO(http_errno.HPE_HEADER_OVERFLOW);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- }
-
- ///reexecute_byte:
- while (true) {
- debug(TAG, "reexecute_byte "+(reexecute_byte++)+",err:"+HTTP_PARSER_ERRNO().desc()+",state:"+state.state);
-
- switch (state) {
-
- case s_dead:
- /* this state is used after a 'Connection: close' message
- * the parser will error out if it reads another message
- */
- if (ch == '\r' || ch == '\n')
- break;
-
- SET_ERRNO(http_errno.HPE_CLOSED_CONNECTION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- case s_start_req_or_res:
- {
- if (ch == '\r' || ch == '\n')
- break;
-
- flags = 0;
- content_length = ULLONG_MAX();
-
- if (ch == 'H') {
- state = State.s_res_or_resp_H;
-
- ///CALLBACK_NOTIFY(message_begin);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_begin()) {
- SET_ERRNO(http_errno.HPE_CB_message_begin);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
-
- } else {
- type = http_parser_type.HTTP_REQUEST;
- state = State.s_start_req;
- ///goto reexecute_byte;
- continue;
- }
-
- break;
- }
-
- case s_res_or_resp_H:
- if (ch == 'T') {
- type = http_parser_type.HTTP_RESPONSE;
- state = State.s_res_HT;
- } else {
- if (ch != 'E') {
- SET_ERRNO(http_errno.HPE_INVALID_CONSTANT);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- type = http_parser_type.HTTP_REQUEST;
- method = http_method.HTTP_HEAD;
- index = 2;
- state = State.s_req_method;
- }
- break;
-
- case s_start_res:
- {
- flags = 0;
- content_length = ULLONG_MAX();
-
- switch (ch) {
- case 'H':
- state = State.s_res_H;
- break;
-
- case '\r':
- case '\n':
- break;
-
- default:
- SET_ERRNO(http_errno.HPE_INVALID_CONSTANT);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- ///CALLBACK_NOTIFY(message_begin);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_begin()) {
- SET_ERRNO(http_errno.HPE_CB_message_begin);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- break;
- }
-
- case s_res_H:
- ///STRICT_CHECK(ch != 'T');
- if (ch != 'T') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_res_HT;
- break;
-
- case s_res_HT:
- ///STRICT_CHECK(ch != 'T');
- if (ch != 'T') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_res_HTT;
- break;
-
- case s_res_HTT:
- ///STRICT_CHECK(ch != 'P');
- if (ch != 'P') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_res_HTTP;
- break;
-
- case s_res_HTTP:
- ///STRICT_CHECK(ch != '/');
- if (ch != '/') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_res_first_http_major;
- break;
-
- case s_res_first_http_major:
- if (ch < '0' || ch > '9') {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_major = ch - '0';
- state = State.s_res_http_major;
- break;
-
- /* major http version or dot */
- case s_res_http_major:
- {
- if (ch == '.') {
- state = State.s_res_first_http_minor;
- break;
- }
-
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_major *= 10;
- http_major += ch - '0';
-
- if (http_major > 999) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- break;
- }
-
- /* first digit of minor http version */
- case s_res_first_http_minor:
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_minor = ch - '0';
- state = State.s_res_http_minor;
- break;
-
- /* minor http version or end of request line */
- case s_res_http_minor:
- {
- if (ch == ' ') {
- state = State.s_res_first_status_code;
- break;
- }
-
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_minor *= 10;
- http_minor += ch - '0';
-
- if (http_minor > 999) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- break;
- }
-
- case s_res_first_status_code:
- {
- if (!IS_NUM(ch)) {
- if (ch == ' ') {
- break;
- }
-
- SET_ERRNO(http_errno.HPE_INVALID_STATUS);
- ////goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- status_code = ch - '0';
- state = State.s_res_status_code;
- break;
- }
-
- case s_res_status_code:
- {
- if (!IS_NUM(ch)) {
- switch (ch) {
- case ' ':
- state = State.s_res_status_start;
- break;
- case '\r':
- state = State.s_res_line_almost_done;
- break;
- case '\n':
- state = State.s_header_field_start;
- break;
- default:
- SET_ERRNO(http_errno.HPE_INVALID_STATUS);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- break;
- }
-
- status_code *= 10;
- status_code += ch - '0';
-
- if (status_code > 999) {
- SET_ERRNO(http_errno.HPE_INVALID_STATUS);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- break;
- }
-
- case s_res_status_start:
- {
- if (ch == '\r') {
- state = State.s_res_line_almost_done;
- break;
- }
-
- if (ch == '\n') {
- state = State.s_header_field_start;
- break;
- }
-
- ///MARK(status);
- if (status_mark == -1) status_mark = p;
-
- state = State.s_res_status;
- index = 0;
- break;
- }
-
- case s_res_status:
- if (ch == '\r') {
- state = State.s_res_line_almost_done;
- ///CALLBACK_DATA(status);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (status_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(status_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_status(FOR##_mark, (LEN))) {
- if (0 != on_status(rb)) {
- SET_ERRNO(http_errno.HPE_CB_status);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- status_mark = -1;
- }
- }
- break;
- }
-
- if (ch == '\n') {
- state = State.s_header_field_start;
- ///CALLBACK_DATA(status);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (status_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(status_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_status(FOR##_mark, (LEN))) {
- if (0 != on_status(rb)) {
- SET_ERRNO(http_errno.HPE_CB_status);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- status_mark = -1;
- }
- }
- break;
- }
-
- break;
-
- case s_res_line_almost_done:
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_header_field_start;
- break;
-
- case s_start_req:
- {
- if (ch == '\r' || ch == '\n')
- break;
- flags = 0;
- content_length = ULLONG_MAX();
-
- if (!IS_ALPHA(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- method = http_method.HTTP_INVALID;
- index = 1;
- switch (ch) {
- case 'C': method = http_method.HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
- case 'D': method = http_method.HTTP_DELETE; break;
- case 'G': method = http_method.HTTP_GET; break;
- case 'H': method = http_method.HTTP_HEAD; break;
- case 'L': method = http_method.HTTP_LOCK; break;
- case 'M': method = http_method.HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH */ break;
- case 'N': method = http_method.HTTP_NOTIFY; break;
- case 'O': method = http_method.HTTP_OPTIONS; break;
- case 'P': method = http_method.HTTP_POST;
- /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
- break;
- case 'R': method = http_method.HTTP_REPORT; break;
- case 'S': method = http_method.HTTP_SUBSCRIBE; /* or SEARCH */ break;
- case 'T': method = http_method.HTTP_TRACE; break;
- case 'U': method = http_method.HTTP_UNLOCK; /* or UNSUBSCRIBE */ break;
- default:
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- state = State.s_req_method;
-
- ///CALLBACK_NOTIFY(message_begin);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_begin()) {
- SET_ERRNO(http_errno.HPE_CB_message_begin);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
-
- break;
- }
-
- case s_req_method:
- {
- char [] matcher;
- if (ch == '\0') {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- matcher = method.desc.toCharArray();
- if (ch == ' ' && matcher[index] == '\0') {
- state = State.s_req_spaces_before_url;
- } else if (ch == matcher[index]) {
- ; /* nada */
- } else if (method == http_method.HTTP_CONNECT) {
- if (index == 1 && ch == 'H') {
- method = http_method.HTTP_CHECKOUT;
- } else if (index == 2 && ch == 'P') {
- method = http_method.HTTP_COPY;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else if (method == http_method.HTTP_MKCOL) {
- if (index == 1 && ch == 'O') {
- method = http_method.HTTP_MOVE;
- } else if (index == 1 && ch == 'E') {
- method = http_method.HTTP_MERGE;
- } else if (index == 1 && ch == '-') {
- method = http_method.HTTP_MSEARCH;
- } else if (index == 2 && ch == 'A') {
- method = http_method.HTTP_MKACTIVITY;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else if (method == http_method.HTTP_SUBSCRIBE) {
- if (index == 1 && ch == 'E') {
- method = http_method.HTTP_SEARCH;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else if (index == 1 && method == http_method.HTTP_POST) {
- if (ch == 'R') {
- method = http_method.HTTP_PROPFIND; /* or HTTP_PROPPATCH */
- } else if (ch == 'U') {
- method = http_method.HTTP_PUT; /* or HTTP_PURGE */
- } else if (ch == 'A') {
- method = http_method.HTTP_PATCH;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else if (index == 2) {
- if (method == http_method.HTTP_PUT) {
- if (ch == 'R') {
- method = http_method.HTTP_PURGE;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else if (method == http_method.HTTP_UNLOCK) {
- if (ch == 'S') {
- method = http_method.HTTP_UNSUBSCRIBE;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- } else if (index == 4 && method == http_method.HTTP_PROPFIND && ch == 'P') {
- method = http_method.HTTP_PROPPATCH;
- } else {
- SET_ERRNO(http_errno.HPE_INVALID_METHOD);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- ++index;
- break;
- }
-
- case s_req_spaces_before_url:
- {
- if (ch == ' ') break;
-
- ///MARK(url);
- if (url_mark == -1) url_mark = p;
-
- if (method == http_method.HTTP_CONNECT) {
- state = State.s_req_server_start;
- }
-
- state = parse_url_char(state, ch);
- if (state == State.s_dead) {
- SET_ERRNO(http_errno.HPE_INVALID_URL);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- break;
- }
-
- case s_req_schema:
- case s_req_schema_slash:
- case s_req_schema_slash_slash:
- case s_req_server_start:
- {
- switch (ch) {
- /* No whitespace allowed here */
- case ' ':
- case '\r':
- case '\n':
- SET_ERRNO(http_errno.HPE_INVALID_URL);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- default:
- state = parse_url_char(state, ch);
- if (state == State.s_dead) {
- SET_ERRNO(http_errno.HPE_INVALID_URL);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- }
-
- break;
- }
-
- case s_req_server:
- case s_req_server_with_at:
- case s_req_path:
- case s_req_query_string_start:
- case s_req_query_string:
- case s_req_fragment_start:
- case s_req_fragment:
- {
- switch (ch) {
- case ' ':
- state = State.s_req_http_start;
- ///CALLBACK_DATA(url);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (url_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(url_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_url(FOR##_mark, (LEN))) {
- if (0 != on_url(rb)) {
- SET_ERRNO(http_errno.HPE_CB_url);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- url_mark = -1;
- }
- }
- break;
- case '\r':
- case '\n':
- http_major = 0;
- http_minor = 9;
- state = (ch == '\r') ?
- State.s_req_line_almost_done :
- State.s_header_field_start;
- ///CALLBACK_DATA(url);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (url_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(url_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_url(rb)) {
- SET_ERRNO(http_errno.HPE_CB_url);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- url_mark = -1;
- }
- }
- break;
- default:
- state = parse_url_char(state, ch);
- if (state == State.s_dead) {
- SET_ERRNO(http_errno.HPE_INVALID_URL);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- }
- break;
- }
-
- case s_req_http_start:
- switch (ch) {
- case 'H':
- state = State.s_req_http_H;
- break;
- case ' ':
- break;
- default:
- SET_ERRNO(http_errno.HPE_INVALID_CONSTANT);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
- break;
-
- case s_req_http_H:
- ///STRICT_CHECK(ch != 'T');
- if (ch != 'T') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_req_http_HT;
- break;
-
- case s_req_http_HT:
- ///STRICT_CHECK(ch != 'T');
- if (ch != 'T') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_req_http_HTT;
- break;
-
- case s_req_http_HTT:
- ///STRICT_CHECK(ch != 'P');
- if (ch != 'P') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_req_http_HTTP;
- break;
-
- case s_req_http_HTTP:
- ///STRICT_CHECK(ch != '/');
- if (ch != '/') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_req_first_http_major;
- break;
-
- /* first digit of major http version */
- case s_req_first_http_major:
- if (ch < '1' || ch > '9') {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_major = ch - '0';
- state = State.s_req_http_major;
- break;
-
- /* major http version or dot */
- case s_req_http_major:
- {
- if (ch == '.') {
- state = State.s_req_first_http_minor;
- break;
- }
-
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_major *= 10;
- http_major += ch - '0';
-
- if (http_major > 999) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- break;
- }
-
- /* first digit of minor http version */
- case s_req_first_http_minor:
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_minor = ch - '0';
- state = State.s_req_http_minor;
- break;
-
- /* minor http version or end of request line */
- case s_req_http_minor:
- {
- if (ch == '\r') {
- state = State.s_req_line_almost_done;
- break;
- }
-
- if (ch == '\n') {
- state = State.s_header_field_start;
- break;
- }
-
- /* XXX allow spaces after digit? */
-
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- http_minor *= 10;
- http_minor += ch - '0';
-
- if (http_minor > 999) {
- SET_ERRNO(http_errno.HPE_INVALID_VERSION);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- break;
- }
-
- /* end of request line */
- case s_req_line_almost_done:
- {
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_LF_EXPECTED);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- state = State.s_header_field_start;
- break;
- }
-
- case s_header_field_start:
- {
- if (ch == '\r') {
- state = State.s_headers_almost_done;
- break;
- }
-
- if (ch == '\n') {
- /* they might be just sending \n instead of \r\n so this would be
- * the second \n to denote the end of headers*/
- state = State.s_headers_almost_done;
- ///goto reexecute_byte;
- continue;
- }
-
- // Java char is 16bits, not ASCII/UTF-8 char
- ///c = TOKEN(ch);
- c = TOKEN(uc);
-
- if (0==c) {
- SET_ERRNO(http_errno.HPE_INVALID_HEADER_TOKEN);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- ///MARK(header_field);
- if (header_field_mark == -1) header_field_mark = p;
-
- index = 0;
- state = State.s_header_field;
-
- switch (c) {
- case 'c':
- header_state = header_states.h_C;
- break;
-
- case 'p':
- header_state = header_states.h_matching_proxy_connection;
- break;
-
- case 't':
- header_state = header_states.h_matching_transfer_encoding;
- break;
-
- case 'u':
- header_state = header_states.h_matching_upgrade;
- break;
-
- default:
- header_state = header_states.h_general;
- break;
- }
- break;
- }
-
- case s_header_field:
- {
- // Java char is 16bits, not ASCII/UTF-8 char
- ///c = TOKEN(ch);
- c = TOKEN(uc);
-
- if (c != 0) {
- switch (header_state) {
- case h_general:
- break;
-
- case h_C:
- index++;
- header_state = (c == 'o' ? header_states.h_CO : header_states.h_general);
- break;
-
- case h_CO:
- index++;
- header_state = (c == 'n' ? header_states.h_CON : header_states.h_general);
- break;
-
- case h_CON:
- index++;
- switch (c) {
- case 'n':
- header_state = header_states.h_matching_connection;
- break;
- case 't':
- header_state = header_states.h_matching_content_length;
- break;
- default:
- header_state = header_states.h_general;
- break;
- }
- break;
-
- /* connection */
-
- case h_matching_connection:
- index++;
- ///if (index > sizeof(CONNECTION)-1
- if (index > CONNECTION.length()-1
- || c != CONNECTION.toCharArray()[index]) {
- header_state = header_states.h_general;
- ///} else if (index == sizeof(CONNECTION)-2) {
- } else if (index == CONNECTION.length()-2) {
- header_state = header_states.h_connection;
- }
- break;
-
- /* proxy-connection */
-
- case h_matching_proxy_connection:
- index++;
- ///if (index > sizeof(PROXY_CONNECTION)-1
- if (index > PROXY_CONNECTION.length()-1
- || c != PROXY_CONNECTION.toCharArray()[index]) {
- header_state = header_states.h_general;
- ///} else if (index == sizeof(PROXY_CONNECTION)-2) {
- } else if (index == (PROXY_CONNECTION).length()-2) {
- header_state = header_states.h_connection;
- }
- break;
-
- /* content-length */
-
- case h_matching_content_length:
- index++;
- if (index > (CONTENT_LENGTH).length()-1
- || c != CONTENT_LENGTH.toCharArray()[index]) {
- header_state = header_states.h_general;
- } else if (index == (CONTENT_LENGTH).length()-2) {
- header_state = header_states.h_content_length;
- }
- break;
-
- /* transfer-encoding */
-
- case h_matching_transfer_encoding:
- index++;
- if (index > (TRANSFER_ENCODING).length()-1
- || c != TRANSFER_ENCODING.toCharArray()[index]) {
- header_state = header_states.h_general;
- } else if (index == (TRANSFER_ENCODING).length()-2) {
- header_state = header_states.h_transfer_encoding;
- }
- break;
-
- /* upgrade */
-
- case h_matching_upgrade:
- index++;
- if (index > (UPGRADE).length()-1
- || c != UPGRADE.toCharArray()[index]) {
- header_state = header_states.h_general;
- } else if (index == (UPGRADE).length()-2) {
- header_state = header_states.h_upgrade;
- }
- break;
-
- case h_connection:
- case h_content_length:
- case h_transfer_encoding:
- case h_upgrade:
- if (ch != ' ') header_state = header_states.h_general;
- break;
-
- default:
- ///assert(0 && "Unknown header_state");
- assert("Unknown header_state"==null);
- break;
- }
- break;
- }
-
- if (ch == ':') {
- state = State.s_header_value_discard_ws;
- ///CALLBACK_DATA(header_field);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_field_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_field_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_field(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_field);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- header_field_mark = -1;
- }
- }
- break;
- }
-
- if (ch == '\r') {
- state = State.s_header_almost_done;
- ///CALLBACK_DATA(header_field);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_field_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_field_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_field(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_field);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- header_field_mark = -1;
- }
- }
- break;
- }
-
- if (ch == '\n') {
- state = State.s_header_field_start;
- ///CALLBACK_DATA(header_field);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_field_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_field_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_field(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_field);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- header_field_mark = -1;
- }
- }
- break;
- }
-
- SET_ERRNO(http_errno.HPE_INVALID_HEADER_TOKEN);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- case s_header_value_discard_ws:
- if (ch == ' ' || ch == '\t') break;
-
- if (ch == '\r') {
- state = State.s_header_value_discard_ws_almost_done;
- break;
- }
-
- if (ch == '\n') {
- state = State.s_header_value_discard_lws;
- break;
- }
-
- /* FALLTHROUGH */
-
- case s_header_value_start:
- {
- ///MARK(header_value);
- if (header_value_mark == -1) header_value_mark = p;
-
- state = State.s_header_value;
- index = 0;
-
- c = LOWER(ch);
-
- switch (header_state) {
- case h_upgrade:
- flags |= Flags.F_UPGRADE.flag;
- header_state = header_states.h_general;
- break;
-
- case h_transfer_encoding:
- /* looking for 'Transfer-Encoding: chunked' */
- if ('c' == c) {
- header_state = header_states.h_matching_transfer_encoding_chunked;
- } else {
- header_state = header_states.h_general;
- }
- break;
-
- case h_content_length:
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_CONTENT_LENGTH);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- content_length = ch - '0';
- break;
-
- case h_connection:
- /* looking for 'Connection: keep-alive' */
- if (c == 'k') {
- header_state = header_states.h_matching_connection_keep_alive;
- /* looking for 'Connection: close' */
- } else if (c == 'c') {
- header_state = header_states.h_matching_connection_close;
- } else {
- header_state = header_states.h_general;
- }
- break;
-
- default:
- header_state = header_states.h_general;
- break;
- }
- break;
- }
-
- case s_header_value:
- {
-
- if (ch == '\r') {
- state = State.s_header_almost_done;
- ///CALLBACK_DATA(header_value);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_value_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_value_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_value(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_value);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- header_value_mark = -1;
- }
- }
- break;
- }
-
- if (ch == '\n') {
- state = State.s_header_almost_done;
-
- ///CALLBACK_DATA_NOADVANCE(header_value);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_value_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_value_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_value(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_value);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- header_value_mark = -1;
- }
- }
-
- ///goto reexecute_byte;
- continue;
- }
-
- c = LOWER(ch);
-
- switch (header_state) {
- case h_general:
- break;
-
- case h_connection:
- case h_transfer_encoding:
- ///assert(0 && "Shouldn't get here.");
- assert("Shouldn't get here."==null);
- break;
-
- case h_content_length:
- {
- long t;
-
- if (ch == ' ') break;
-
- if (!IS_NUM(ch)) {
- SET_ERRNO(http_errno.HPE_INVALID_CONTENT_LENGTH);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- t = content_length;
- t *= 10;
- t += ch - '0';
-
- /* Overflow? Test against a conservative limit for simplicity. */
- if ((ULLONG_MAX() - 10) / 10 < content_length) {
- SET_ERRNO(http_errno.HPE_INVALID_CONTENT_LENGTH);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- content_length = t;
- break;
- }
-
- /* Transfer-Encoding: chunked */
- case h_matching_transfer_encoding_chunked:
- index++;
- if (index > (CHUNKED).length()-1
- || c != CHUNKED.toCharArray()[index]) {
- header_state = header_states.h_general;
- } else if (index == (CHUNKED).length()-2) {
- header_state = header_states.h_transfer_encoding_chunked;
- }
- break;
-
- /* looking for 'Connection: keep-alive' */
- case h_matching_connection_keep_alive:
- index++;
- if (index > (KEEP_ALIVE).length()-1
- || c != KEEP_ALIVE.toCharArray()[index]) {
- header_state = header_states.h_general;
- } else if (index == (KEEP_ALIVE).length()-2) {
- header_state = header_states.h_connection_keep_alive;
- }
- break;
-
- /* looking for 'Connection: close' */
- case h_matching_connection_close:
- index++;
- if (index > (CLOSE).length()-1
- || c != CLOSE.toCharArray()[index]) {
- header_state = header_states.h_general;
- } else if (index == (CLOSE).length()-2) {
- header_state = header_states.h_connection_close;
- }
- break;
-
- case h_transfer_encoding_chunked:
- case h_connection_keep_alive:
- case h_connection_close:
- if (ch != ' ') header_state = header_states.h_general;
- break;
-
- default:
- state = State.s_header_value;
- header_state = header_states.h_general;
- break;
- }
- break;
- }
-
- case s_header_almost_done:
- {
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_header_value_lws;
- break;
- }
-
- case s_header_value_lws:
- {
- if (ch == ' ' || ch == '\t') {
- state = State.s_header_value_start;
- ///goto reexecute_byte;
- continue;
- }
-
- /* finished the header */
- switch (header_state) {
- case h_connection_keep_alive:
- flags |= Flags.F_CONNECTION_KEEP_ALIVE.flag;
- break;
- case h_connection_close:
- flags |= Flags.F_CONNECTION_CLOSE.flag;
- break;
- case h_transfer_encoding_chunked:
- flags |= Flags.F_CHUNKED.flag;
- break;
- default:
- break;
- }
-
- state = State.s_header_field_start;
- ///goto reexecute_byte;
- continue;
- }
-
- case s_header_value_discard_ws_almost_done:
- {
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_header_value_discard_lws;
- break;
- }
-
- case s_header_value_discard_lws:
- {
- if (ch == ' ' || ch == '\t') {
- state = State.s_header_value_discard_ws;
- break;
- } else {
- /* header value was empty */
- ///MARK(header_value);
- if (header_value_mark == -1) header_value_mark = p;
-
- state = State.s_header_field_start;
-
- ///CALLBACK_DATA_NOADVANCE(header_value);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_value_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_value_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_value(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_value);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- header_value_mark = -1;
- }
- }
-
- ///goto reexecute_byte;
- continue;
- }
- }
-
- case s_headers_almost_done:
- {
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- if (0!=(flags & Flags.F_TRAILING.flag)) {
- /* End of a chunked request */
- state = NEW_MESSAGE();
-
- ///CALLBACK_NOTIFY(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- break;
- }
-
- state = State.s_headers_done;
-
- /* Set this here so that on_headers_complete() callbacks can see it */
- upgrade =
- ((flags & Flags.F_UPGRADE.flag)!=0 || method == http_method.HTTP_CONNECT);
-
- /* Here we call the headers_complete callback. This is somewhat
- * different than other callbacks because if the user returns 1, we
- * will interpret that as saying that this message has no body. This
- * is needed for the annoying case of recieving a response to a HEAD
- * request.
- *
- * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so
- * we have to simulate it by handling a change in errno below.
- */
- // TBD...
- ///if (settings->on_headers_complete)
- {
- ///switch (settings->on_headers_complete(parser)) {
- switch (on_headers_complete()) {
- case 0:
- break;
-
- case 1:
- flags |= Flags.F_SKIPBODY.flag;
- break;
-
- default:
- SET_ERRNO(http_errno.HPE_CB_headers_complete);
- ///return p - data; /* Error */
- return p;
- }
- }
-
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return p - data;
- return p;
- }
-
- ///goto reexecute_byte;
- continue;
- }
-
- case s_headers_done:
- {
- ///debug(TAG, "STRICT_CHECK ch:"+ch+",state:"+state.state);
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- nread = 0;
-
- /* Exit, the rest of the connect is in a different protocol. */
- if (upgrade) {
- state = NEW_MESSAGE();
-
- ///CALLBACK_NOTIFY(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- ///return (p - data) + 1;
- return p + 1;
- }
-
- if ((flags & Flags.F_SKIPBODY.flag)!=0) {
- state = NEW_MESSAGE();
-
- ///CALLBACK_NOTIFY(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- } else if ((flags & Flags.F_CHUNKED.flag)!=0) {
- /* chunked encoding - ignore Content-Length header */
- state = State.s_chunk_size_start;
- } else {
- if (content_length == 0) {
- /* Content-Length header given but zero: Content-Length: 0\r\n */
- state = NEW_MESSAGE();
-
- ///CALLBACK_NOTIFY(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- } else if (content_length != ULLONG_MAX()) {
- /* Content-Length header given and non-zero */
- state = State.s_body_identity;
- } else {
- if (type == http_parser_type.HTTP_REQUEST ||
- !http_message_needs_eof()) {
- /* Assume content-length 0 - read the next */
- state = NEW_MESSAGE();
-
- ///CALLBACK_NOTIFY(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- } else {
- /* Read body until EOF */
- state = State.s_body_identity_eof;
- }
- }
- }
-
- break;
- }
-
- case s_body_identity:
- {
- ///long to_read = MIN(content_length,
- /// (long) ((data + len) - p));
- long to_read = MIN(content_length, len - p);
-
- assert(content_length != 0
- && content_length != ULLONG_MAX());
-
- /* The difference between advancing content_length and p is because
- * the latter will automaticaly advance on the next loop iteration.
- * Further, if content_length ends up at 0, we want to see the last
- * byte again for our message complete callback.
- */
- ///MARK(body);
- if (body_mark == -1) body_mark = p;
-
- content_length -= to_read;
- p += to_read - 1;
-
- if (content_length == 0) {
- state = State.s_message_done;
-
- /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte.
- *
- * The alternative to doing this is to wait for the next byte to
- * trigger the data callback, just as in every other case. The
- * problem with this is that this makes it difficult for the test
- * harness to distinguish between complete-on-EOF and
- * complete-on-length. It's not clear that this distinction is
- * important for applications, but let's keep it for now.
- */
- ///CALLBACK_DATA_(body, p - body_mark + 1, p - data);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (body_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(body_mark);
- int olmt = bb.limit(); bb.limit(p+1);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_body(rb)) {
- SET_ERRNO(http_errno.HPE_CB_body);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- body_mark = -1;
- }
- }
-
- ///goto reexecute_byte;
- continue;
- }
-
- break;
- }
-
- /* read until EOF */
- case s_body_identity_eof:
- ///MARK(body);
- if (body_mark == -1) body_mark = p;
-
- ///p = data + len - 1;
- p = len - 1;
-
- break;
-
- case s_message_done:
- state = NEW_MESSAGE();
-
- ///CALLBACK_NOTIFY(message_complete);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- ///if (settings->on_##FOR)
- {
- if (0 != on_message_complete()) {
- SET_ERRNO(http_errno.HPE_CB_message_complete);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- }
- break;
-
- case s_chunk_size_start:
- {
- assert(nread == 1);
- assert(0!=(flags & Flags.F_CHUNKED.flag));
-
- ///unhex_val = unhex[ch & 0xffff];
- unhex_val = unhex[uc];
-
- if (unhex_val == -1) {
- SET_ERRNO(http_errno.HPE_INVALID_CHUNK_SIZE);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- content_length = unhex_val;
- state = State.s_chunk_size;
- break;
- }
-
- case s_chunk_size:
- {
- long t;
-
- assert(0!=(flags & Flags.F_CHUNKED.flag));
-
- if (ch == '\r') {
- state = State.s_chunk_size_almost_done;
- break;
- }
-
- ///unhex_val = unhex[ch & 0xffff];
- unhex_val = unhex[uc];
-
- if (unhex_val == -1) {
- if (ch == ';' || ch == ' ') {
- state = State.s_chunk_parameters;
- break;
- }
-
- SET_ERRNO(http_errno.HPE_INVALID_CHUNK_SIZE);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- t = content_length;
- t *= 16;
- t += unhex_val;
-
- /* Overflow? Test against a conservative limit for simplicity. */
- if ((ULLONG_MAX() - 16) / 16 < content_length) {
- SET_ERRNO(http_errno.HPE_INVALID_CONTENT_LENGTH);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- content_length = t;
- break;
- }
-
- case s_chunk_parameters:
- {
- assert(0!=(flags & Flags.F_CHUNKED.flag));
- /* just ignore this shit. TODO check for overflow */
- if (ch == '\r') {
- state = State.s_chunk_size_almost_done;
- break;
- }
- break;
- }
-
- case s_chunk_size_almost_done:
- {
- assert(0!=(flags & Flags.F_CHUNKED.flag));
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- nread = 0;
-
- if (content_length == 0) {
- flags |= Flags.F_TRAILING.flag;
- state = State.s_header_field_start;
- } else {
- state = State.s_chunk_data;
- }
- break;
- }
-
- case s_chunk_data:
- {
- ///long to_read = MIN(content_length,
- /// (long) ((data + len) - p));
- long to_read = MIN(content_length, len - p);
-
- assert(0!=(flags & Flags.F_CHUNKED.flag));
- assert(content_length != 0
- && content_length != ULLONG_MAX());
-
- /* See the explanation in s_body_identity for why the content
- * length and data pointers are managed this way.
- */
- ///MARK(body);
- if (body_mark == -1) body_mark = p;
-
- content_length -= to_read;
- p += to_read - 1;
-
- if (content_length == 0) {
- state = State.s_chunk_data_almost_done;
- }
-
- break;
- }
-
- case s_chunk_data_almost_done:
- assert(0!=(flags & Flags.F_CHUNKED.flag));
- assert(content_length == 0);
-
- ///STRICT_CHECK(ch != '\r');
- if (ch != '\r') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- state = State.s_chunk_data_done;
-
- ///CALLBACK_DATA(body);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (body_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(body_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_body(rb)) {
- SET_ERRNO(http_errno.HPE_CB_body);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p + 1);
- }
- }
- ///FOR##_mark = NULL;
- body_mark = -1;
- }
- }
-
- break;
-
- case s_chunk_data_done:
- assert(0!=(flags & Flags.F_CHUNKED.flag));
- ///STRICT_CHECK(ch != '\n');
- if (ch != '\n') {
- SET_ERRNO(http_errno.HPE_STRICT);
-
- ///goto error;
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
-
- nread = 0;
- state = State.s_chunk_size_start;
- break;
-
- default:
- ///assert(0 && "unhandled state");
- assert("unhandled state"==null);
- SET_ERRNO(http_errno.HPE_INVALID_INTERNAL_STATE);
- ///goto error;
- {
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- ///return (p - data);
- return p;
- }
- }
-
- // break while loop
- debug(TAG, "break while loop, reexecute_byte:"+reexecute_byte+",err:"+HTTP_PARSER_ERRNO().desc());
-
- break;
- }
- }
-
- /* Run callbacks for any marks that we have leftover after we ran our of
- * bytes. There should be at most one of these set, so it's OK to invoke
- * them in series (unset marks will not result in callbacks).
- *
- * We use the NOADVANCE() variety of callbacks here because 'p' has already
- * overflowed 'data' and this allows us to correct for the off-by-one that
- * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p'
- * value that's in-bounds).
- */
-
- assert(((header_field_mark!=-1 ? 1 : 0) +
- (header_value_mark!=-1 ? 1 : 0) +
- (url_mark!=-1 ? 1 : 0) +
- (body_mark!=-1 ? 1 : 0) +
- (status_mark!=-1 ? 1 : 0)) <= 1);
-
- ///CALLBACK_DATA_NOADVANCE(header_field);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_field_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_field_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_field(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_field);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- header_field_mark = -1;
- }
- }
-
- ///CALLBACK_DATA_NOADVANCE(header_value);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (header_value_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(header_value_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_header_value(rb)) {
- SET_ERRNO(http_errno.HPE_CB_header_value);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- header_value_mark = -1;
- }
- }
-
- ///CALLBACK_DATA_NOADVANCE(url);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (url_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(url_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_url(rb)) {
- SET_ERRNO(http_errno.HPE_CB_url);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- url_mark = -1;
- }
- }
-
- ///CALLBACK_DATA_NOADVANCE(body);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (body_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(body_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_body(rb)) {
- SET_ERRNO(http_errno.HPE_CB_body);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- body_mark = -1;
- }
- }
-
- ///CALLBACK_DATA_NOADVANCE(status);
- {
- assert(HTTP_PARSER_ERRNO() == http_errno.HPE_OK);
-
- if (status_mark != -1) {
- ///if (settings->on_##FOR)
- {
- // slice data ByteBuffer
- ByteBuffer bb = data;
- int opos = bb.position(); bb.position(status_mark);
- int olmt = bb.limit(); bb.limit(p);
-
- ByteBuffer rb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///if (0 != on_##FOR(FOR##_mark, (LEN))) {
- if (0 != on_status(rb)) {
- SET_ERRNO(http_errno.HPE_CB_status);
- }
-
- /* We either errored above or got paused; get out */
- if (HTTP_PARSER_ERRNO() != http_errno.HPE_OK) {
- ///return (ER);
- return (p);
- }
- }
- ///FOR##_mark = NULL;
- status_mark = -1;
- }
- }
-
- return len;
-
- /*error:
- if (HTTP_PARSER_ERRNO(parser) == HPE_OK) {
- SET_ERRNO(http_errno.HPE_UNKNOWN);
- }
-
- return (p - data);*/
- }
-
- /* If http_should_keep_alive() in the on_headers_complete or
- * on_message_complete callback returns 0, then this should be
- * the last message on the connection.
- * If you are the server, respond with the "Connection: close" header.
- * If you are the client, close the connection.
- */
- ///int http_should_keep_alive(const http_parser *parser);
- protected boolean http_should_keep_alive() {
- if (http_major > 0 && http_minor > 0) {
- /* HTTP/1.1 */
- if ((flags & Flags.F_CONNECTION_CLOSE.flag)!=0) {
- return false;
- }
- } else {
- /* HTTP/1.0 or earlier */
- if (0==(flags & Flags.F_CONNECTION_KEEP_ALIVE.flag)) {
- return false;
- }
- }
-
- return !http_message_needs_eof();
- }
-
- /* Returns a string version of the http method. */
- ///const char *http_method_str(enum http_method m);
- protected static String http_method_str(http_method m) {
- return m.desc;
- }
-
- /* Return a string name of the given error */
- ///const char *http_errno_name(enum http_errno err);
- protected static String http_errno_name(http_errno err) {
- return err.name();
- }
-
- /* Return a string description of the given error */
- ///const char *http_errno_description(enum http_errno err);
- protected static String http_errno_description(http_errno err) {
- return err.desc;
- }
-
- /* Parse a URL; return nonzero on failure */
- ///int http_parser_parse_url(const char *buf, size_t buflen,
- /// int is_connect,
- /// struct http_parser_url *u);
- public static int parse_url(char [] buf, boolean is_connect, http_parser_url u)
- throws UnsupportedEncodingException {
- State s;
- ///const char *p;
- int p = 0;
- http_parser_url_fields uf, old_uf;
- boolean found_at = false;
- int buflen = buf != null ? buf.length : 0;
-
- u.port = u.field_set = 0;
- s = is_connect ? State.s_req_server_start : State.s_req_spaces_before_url;
- uf = old_uf = http_parser_url_fields.UF_MAX;
-
- ///for (p = buf; p < buf + buflen; p++) {
- for (p = 0; p < buflen; p++) {
- s = parse_url_char(s, buf[p]);
-
- /* Figure out the next field that we're operating on */
- switch (s) {
- case s_dead:
- return 1;
-
- /* Skip delimeters */
- case s_req_schema_slash:
- case s_req_schema_slash_slash:
- case s_req_server_start:
- case s_req_query_string_start:
- case s_req_fragment_start:
- continue;
-
- case s_req_schema:
- uf = http_parser_url_fields.UF_SCHEMA;
- break;
-
- case s_req_server_with_at:
- found_at = true;
-
- /* FALLTROUGH */
- case s_req_server:
- uf = http_parser_url_fields.UF_HOST;
- break;
-
- case s_req_path:
- uf = http_parser_url_fields.UF_PATH;
- break;
-
- case s_req_query_string:
- uf = http_parser_url_fields.UF_QUERY;
- break;
-
- case s_req_fragment:
- uf = http_parser_url_fields.UF_FRAGMENT;
- break;
-
- default:
- assert(null=="Unexpected state");
- return 1;
- }
-
- /* Nothing's changed; soldier on */
- if (uf == old_uf) {
- u.field_data[uf.field].len++;
- continue;
- }
-
- u.field_data[uf.field].off = p; ///p - buf;
- u.field_data[uf.field].len = 1;
-
- u.field_set |= (1 << uf.field);
- old_uf = uf;
- }
-
- /* host must be present if there is a schema */
- /* parsing http:///toto will fail */
- if ((u.field_set &
- ((1 << http_parser_url_fields.UF_SCHEMA.field) |
- (1 << http_parser_url_fields.UF_HOST.field))) != 0) {
- if (http_parse_host(buf, u, found_at) != 0) {
- return 1;
- }
- }
-
- /* CONNECT requests can only contain "hostname:port" */
- if (is_connect && u.field_set !=
- ((1 << http_parser_url_fields.UF_HOST.field) |
- (1 << http_parser_url_fields.UF_PORT.field))) {
- return 1;
- }
-
- if (0!=(u.field_set & (1 << http_parser_url_fields.UF_PORT.field))) {
- /* Don't bother with endp; we've already validated the string */
- ///unsigned long v = strtoul(buf + u.field_data[UF_PORT].off, NULL, 10);
- String pstr = new String(buf).
- substring(u.field_data[http_parser_url_fields.UF_PORT.field].off,
- u.field_data[http_parser_url_fields.UF_PORT.field].len);
-
- int v = Integer.parseInt(pstr, 10);
-
- debug(TAG, "port str: "+pstr+", port: "+v);
-
- /* Ports have a max value of 2^16 */
- if (v > 0xffff) {
- return 1;
- }
-
- u.port = v;
- }
-
- return 0;
- }
-
- private static http_host_state
- http_parse_host_char(http_host_state s, final char ch) {
- switch(s) {
- case s_http_userinfo:
- case s_http_userinfo_start:
- if (ch == '@') {
- return http_host_state.s_http_host_start;
- }
-
- if (IS_USERINFO_CHAR(ch)) {
- return http_host_state.s_http_userinfo;
- }
- break;
-
- case s_http_host_start:
- if (ch == '[') {
- return http_host_state.s_http_host_v6_start;
- }
-
- if (IS_HOST_CHAR(ch)) {
- return http_host_state.s_http_host;
- }
-
- break;
-
- case s_http_host:
- if (IS_HOST_CHAR(ch)) {
- return http_host_state.s_http_host;
- }
-
- /* FALLTHROUGH */
- case s_http_host_v6_end:
- if (ch == ':') {
- return http_host_state.s_http_host_port_start;
- }
-
- break;
-
- case s_http_host_v6:
- if (ch == ']') {
- return http_host_state.s_http_host_v6_end;
- }
-
- /* FALLTHROUGH */
- case s_http_host_v6_start:
- if (IS_HEX(ch) || ch == ':' || ch == '.') {
- return http_host_state.s_http_host_v6;
- }
-
- break;
-
- case s_http_host_port:
- case s_http_host_port_start:
- if (IS_NUM(ch)) {
- return http_host_state.s_http_host_port;
- }
-
- break;
-
- default:
- break;
- }
- return http_host_state.s_http_host_dead;
- }
-
- private static int
- http_parse_host(final char [] buf, http_parser_url u, boolean found_at) {
- http_host_state s;
-
- ///const char *p;
- int p = 0;
- ///size_t buflen = u.field_data[UF_HOST].off + u.field_data[UF_HOST].len;
- int buflen = u.field_data[http_parser_url_fields.UF_HOST.field].off +
- u.field_data[http_parser_url_fields.UF_HOST.field].len;
-
- u.field_data[http_parser_url_fields.UF_HOST.field].len = 0;
-
- s = found_at ? http_host_state.s_http_userinfo_start :
- http_host_state.s_http_host_start;
-
- ///for (p = buf + u.field_data[UF_HOST].off; p < buf + buflen; p++) {
- for (p = u.field_data[http_parser_url_fields.UF_HOST.field].off;
- p < buflen; p++) {
- http_host_state new_s = http_parse_host_char(s, buf[p]);
-
- if (new_s == http_host_state.s_http_host_dead) {
- return 1;
- }
-
- switch(new_s) {
- case s_http_host:
- if (s != http_host_state.s_http_host) {
- u.field_data[http_parser_url_fields.UF_HOST.field].off = p;///p - buf;
- }
- u.field_data[http_parser_url_fields.UF_HOST.field].len++;
- break;
-
- case s_http_host_v6:
- if (s != http_host_state.s_http_host_v6) {
- u.field_data[http_parser_url_fields.UF_HOST.field].off = p;///p - buf;
- }
- u.field_data[http_parser_url_fields.UF_HOST.field].len++;
- break;
-
- case s_http_host_port:
- if (s != http_host_state.s_http_host_port) {
- u.field_data[http_parser_url_fields.UF_PORT.field].off = p;///p - buf;
- u.field_data[http_parser_url_fields.UF_PORT.field].len = 0;
- u.field_set |= (1 << http_parser_url_fields.UF_PORT.field);
- }
- u.field_data[http_parser_url_fields.UF_PORT.field].len++;
- break;
-
- case s_http_userinfo:
- if (s != http_host_state.s_http_userinfo) {
- u.field_data[http_parser_url_fields.UF_USERINFO.field].off = p;///p - buf ;
- u.field_data[http_parser_url_fields.UF_USERINFO.field].len = 0;
- u.field_set |= (1 << http_parser_url_fields.UF_USERINFO.field);
- }
- u.field_data[http_parser_url_fields.UF_USERINFO.field].len++;
- break;
-
- default:
- break;
- }
- s = new_s;
- }
-
- /* Make sure we don't end somewhere unexpected */
- switch (s) {
- case s_http_host_start:
- case s_http_host_v6_start:
- case s_http_host_v6:
- case s_http_host_port_start:
- case s_http_userinfo:
- case s_http_userinfo_start:
- return 1;
- default:
- break;
- }
-
- return 0;
- }
-
- /* Pause or un-pause the parser; a nonzero value pauses */
- ///void http_parser_pause(http_parser *parser, int paused);
- @SuppressWarnings("static-access")
- protected void pause(boolean paused) {
- /* Users should only be pausing/unpausing a parser that is not in an error
- * state. In non-debug builds, there's not much that we can do about this
- * other than ignore it.
- */
- if (HTTP_PARSER_ERRNO() == http_errno.HPE_OK ||
- HTTP_PARSER_ERRNO() == http_errno.HPE_PAUSED) {
- SET_ERRNO((paused) ? http_errno.HPE_PAUSED : http_errno.HPE_OK);
- } else {
- assert(null == "Attempting to pause parser in error state");
- }
- }
-
- /* Checks if this is the final chunk of the body. */
- ///int http_body_is_final(const http_parser *parser);
- protected boolean http_body_is_final() {
- return state == State.s_message_done;
- }
-
- ///struct http_parser {
- /** PRIVATE **/
- private http_parser_type type; /* enum http_parser_type */
- /**
- * @return the type
- */
- public http_parser_type getType() {
- return type;
- }
- /**
- * @return the nread
- */
- public int getNread() {
- return nread;
- }
-
- private int flags = 0; /* F_* values from 'flags' enum; semi-protected */
- private State state; /* enum State from http_parser.c */
- private header_states header_state; /* enum header_state from http_parser.c */
- private int index = 0; /* index into current matcher */
-
- private int nread = 0; /* # bytes read in various scenarios */
- private long content_length = 0; /* # bytes in body (0 if no Content-Length header) */
-
- /** READ-ONLY **/
- private int http_major;
- /**
- * @return the http_major
- */
- public int getHttp_major() {
- return http_major;
- }
- /**
- * @return the http_minor
- */
- public int getHttp_minor() {
- return http_minor;
- }
- /**
- * @return the status_code
- */
- public int getStatus_code() {
- return status_code;
- }
- /**
- * @return the method
- */
- public http_method getMethod() {
- return method;
- }
- /**
- * @return the http_errno
- */
- public http_errno getHttp_errno() {
- return http_errno;
- }
- /**
- * @return the upgrade
- */
- public boolean isUpgrade() {
- return upgrade;
- }
-
- /**
- * @return the data
- */
- public Object getData() {
- return data;
- }
-
- private int http_minor = 0;
- private int status_code = 0; /* responses only */
- private http_method method; /* requests only */
- private http_errno http_errno;
-
- /* 1 = Upgrade header was present and the parser has exited because of that.
- * 0 = No upgrade header present.
- * Should be checked when http_parser_execute() returns in addition to
- * error checking.
- */
- private boolean upgrade = false;
-
- /** PUBLIC **/
- private final Object data; /* A pointer to get hook to the "connection" or "socket" object */
- ///};
-
-}
diff --git a/app/src/main/java/com/iwebpp/node/NodeContext.java b/app/src/main/java/com/iwebpp/node/NodeContext.java
deleted file mode 100644
index babd4aa..0000000
--- a/app/src/main/java/com/iwebpp/node/NodeContext.java
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-import java.util.Date;
-
-
-import com.iwebpp.SimpleDebug;
-import com.iwebpp.libuvpp.LibUV;
-import com.iwebpp.libuvpp.cb.TimerCallback;
-import com.iwebpp.libuvpp.handles.LoopHandle;
-import com.iwebpp.libuvpp.handles.TimerHandle;
-
-// Node.android libUV loop context
-public final class NodeContext extends SimpleDebug {
- private static final String TAG = "NodeContext";
-
- static {
- // call an idempotent LibUV method just to ensure that the native lib is loaded
- LibUV.cwd();
- }
-
- private LoopHandle loop;
-
- /**
- * @return the loop
- */
- public LoopHandle getLoop() {
- return loop;
- }
-
- public NodeContext() {
- this.loop = new LoopHandle();
- }
-
- public void execute() throws Throwable {
- this.loop.run();
- }
-
- public void destroy() {
- this.loop.destroy();
- }
-
- /*
- * DOM-style timers
- */
- // setTimeout/clearTimeout
- public interface TimeoutListener{
- public void onTimeout() throws Exception;
- }
- // after: ms
- public TimerHandle setTimeout(final TimeoutListener callback, int after) {
- final TimerHandle timer = new TimerHandle(loop);
-
- timer.setCloseCallback(new TimerCallback() {
- @Override
- public void onTimer(final int i) throws Exception {
- debug(TAG, "setTimeout timer closed");
- }
- });
-
- timer.setTimerFiredCallback(new TimerCallback() {
- @Override
- public void onTimer(final int status) throws Exception {
- debug(TAG, "setTimeout timer fired");
-
- callback.onTimeout();
-
- timer.close();
- }
- });
-
- timer.start(after, 0);
-
- return timer;
- }
- public void clearTimeout(TimerHandle timer) {
- timer.close();
- }
-
- // setInterval/clearInterval
- public interface IntervalListener{
- public void onInterval() throws Exception;
- }
- // repeat: ms
- public TimerHandle setInterval(final IntervalListener callback, int repeat) {
- final TimerHandle timer = new TimerHandle(loop);
-
- timer.setCloseCallback(new TimerCallback() {
- @Override
- public void onTimer(final int i) throws Exception {
- debug(TAG, "setInterval timer closed");
- }
- });
-
- timer.setTimerFiredCallback(new TimerCallback() {
- @Override
- public void onTimer(final int status) throws Exception {
- debug(TAG, "setInterval timer fired");
-
- callback.onInterval();
- }
- });
-
- timer.start(repeat, repeat);
-
- return timer;
- }
- public void clearInterval(TimerHandle timer) {
- timer.close();
- }
-
- // fire on next tick
- public void nextTick(final nextTickListener next) {
- final TimerHandle timer = new TimerHandle(loop);
-
- timer.setCloseCallback(new TimerCallback() {
- @Override
- public void onTimer(final int i) throws Exception {
- debug(TAG, "nextTick timer closed");
- }
- });
-
- timer.setTimerFiredCallback(new TimerCallback() {
- @Override
- public void onTimer(final int status) throws Exception {
- debug(TAG, "nextTick timer fired");
-
- next.onNextTick();
-
- timer.close();
- }
- });
-
- timer.start(0, 0);
- }
- public interface nextTickListener {
- void onNextTick() throws Exception;
- }
-
- //
- private volatile String dateCached = null;
- public String utcDate() {
- if (null == dateCached) {
- Date d = new Date();
- // TBD... GTC
- dateCached = d.toString();
-
- setTimeout(new TimeoutListener() {
-
- @Override
- public void onTimeout() throws Exception {
- dateCached = null;
- }
-
- }, 1000);
- }
-
- return dateCached;
- }
-
-}
-
diff --git a/app/src/main/java/com/iwebpp/node/NodeError.java b/app/src/main/java/com/iwebpp/node/NodeError.java
deleted file mode 100644
index 5a81b3c..0000000
--- a/app/src/main/java/com/iwebpp/node/NodeError.java
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-@SuppressWarnings("serial")
-public final class NodeError
-extends RuntimeException {
- private String code;
-
- /**
- * @return the code
- */
- public String getCode() {
- return code;
- }
-
- public NodeError(String code, String message) {
- super(message);
- this.code = code;
- }
-
- public NodeError(String message) {
- super(message);
- this.code = "";
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(4096);
- sb.append("code: ");
- sb.append(code);
- sb.append(", message: ");
- sb.append(super.getMessage());
- return sb.toString();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/node/Timers.java b/app/src/main/java/com/iwebpp/node/Timers.java
deleted file mode 100644
index ac90290..0000000
--- a/app/src/main/java/com/iwebpp/node/Timers.java
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-public final class Timers extends EventEmitter2 {
- private NodeContext context;
-
- /**
- * @return the context
- */
- public NodeContext getContext() {
- return context;
- }
-
- public static void _unrefActive(Object item) {
-
- }
-
- public static void unenroll(Object item) {
-
- }
-
- public static void enroll(Object item, int msecs) {
-
- }
-
- public Timers(final NodeContext ctx) {
- this.context = ctx;
- }
- @SuppressWarnings("unused")
- private Timers(){}
-
-}
diff --git a/app/src/main/java/com/iwebpp/node/Url.java b/app/src/main/java/com/iwebpp/node/Url.java
deleted file mode 100644
index 881007a..0000000
--- a/app/src/main/java/com/iwebpp/node/Url.java
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-import java.util.Hashtable;
-import java.util.Map;
-
-import android.net.Uri;
-
-
-public final class Url
-extends EventEmitter2 {
-
- public static class UrlObj {
- public String href = null;
- public String protocol = null;
- public boolean slashes = false;
- public String host = null;
- public String auth = null;
- public String hostname = null;
- public int port = -1;
- public String pathname = null;
- public String search = null;
- public String path = null;
- public String query = null;
- public String hash = null;
-
- public Map queryParams;
-
- public boolean parseQueryString = false;
- public boolean slashesDenoteHost = false;
-
- UrlObj() {
- this.queryParams = new Hashtable();
- }
-
- public String toString() {
- try {
- return Url.format(this);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- }
-
- public static UrlObj parse(
- String urlStr,
- boolean parseQueryString,
- boolean slashesDenoteHost) throws Exception {
- UrlObj obj = new UrlObj();
-
- Uri url = Uri.parse(urlStr).normalizeScheme();
-
- obj.parseQueryString = parseQueryString;
- obj.slashesDenoteHost = slashesDenoteHost;
-
- obj.href = urlStr.toLowerCase();
-
- obj.protocol = url.getScheme()!=null ? url.getScheme()+":" : null;
- obj.slashes = slashesDenoteHost;
- obj.hostname = url.getHost();
- obj.port = url.getPort();
- obj.auth = url.getUserInfo();
- obj.pathname = url.getPath();
- obj.query = url.getQuery();
- obj.hash = url.getFragment()!=null ? "#"+url.getFragment() : null;
-
- obj.search = obj.query!=null ? "?"+obj.query : null;
- obj.host = obj.hostname!=null ? obj.hostname + (obj.port>0 ? ":"+obj.port : "") : null;
- obj.path = obj.pathname!=null ? obj.pathname + (obj.search!=null ? obj.search : "") : null;
-
- // only find first matched key
- if (obj.parseQueryString && obj.query!=null)
- for (String k : url.getQueryParameterNames())
- obj.queryParams.put(k, url.getQueryParameter(k));
-
- return obj;
- }
-
- public static UrlObj parse(String urlStr) throws Exception {
- return parse(urlStr, true, true);
- }
-
- public static String format(UrlObj obj) throws Exception {
- String str = "";
-
- str += obj.protocol!=null ? obj.protocol : "http:";
-
- str += obj.slashes ? "//" : "";
-
- str += obj.auth!=null ? obj.auth+"@" : "";
-
- if (obj.host != null) {
- str += obj.host;
- } else if (obj.hostname!=null) {
- str += obj.hostname;
- str += obj.port>0 ? ":"+obj.port : "";
- } else {
- throw new Exception("Miss URL hostname");
- }
-
- if (obj.path != null) {
- str += obj.path;
- } else if (obj.pathname != null) {
- str += obj.pathname;
-
- if (obj.search != null) {
- str += obj.search;
- } else if (obj.query != null) {
- str += "?" + obj.query;
- }
- } else {
- // TBD...
- ///str += "/";
-
- if (obj.search != null) {
- str += obj.search;
- } else if (obj.query != null) {
- str += "?" + obj.query;
- }
- }
-
- str += obj.hash!=null ? obj.hash : "";
-
- return str;
- }
-
- public static String resolve(String from, String to) {
- return Uri.withAppendedPath(Uri.parse(from), to).toString();
- }
-
-}
diff --git a/app/src/main/java/com/iwebpp/node/Util.java b/app/src/main/java/com/iwebpp/node/Util.java
deleted file mode 100644
index c03e0b9..0000000
--- a/app/src/main/java/com/iwebpp/node/Util.java
+++ /dev/null
@@ -1,220 +0,0 @@
-// Copyright (c) 2014 Tom Zhou
-
-
-package com.iwebpp.node;
-
-import android.text.TextUtils;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.util.List;
-
-import com.iwebpp.libuvpp.LibUV;
-
-public final class Util {
- @SuppressWarnings("unused")
- private static final String TAG = "Util";
-
- // Buffer
- public static boolean isBuffer(Object chunk) {
- return chunk instanceof ByteBuffer;
- }
-
- public static boolean isString(Object chunk) {
- return chunk instanceof String;
- }
-
- public static boolean isNullOrUndefined(Object obj) {
- return obj == null;
- }
-
- public static boolean isUndefined(Object obj) {
- return obj == null;
- }
-
- public static boolean isNull(Object obj) {
- return obj == null;
- }
-
- public static int chunkLength(Object chunk) {
- if (isBuffer(chunk)) {
- ByteBuffer bb = (ByteBuffer)chunk;
- return bb.capacity();
- }
-
- if (isString(chunk)) {
- String s = (String)chunk;
- return s.length();
- }
-
- return 0;
- }
-
- public static int stringByteLength(String chunk, String encoding) throws UnsupportedEncodingException {
- if (isString(chunk))
- return chunk.getBytes(encoding).length;
-
- return 0;
- }
-
- public static int chunkByteLength(Object chunk, String encoding) throws UnsupportedEncodingException {
- if (isBuffer(chunk)) {
- ByteBuffer bb = (ByteBuffer)chunk;
- return bb.capacity();
- }
-
- if (isString(chunk)) {
- return stringByteLength((String) chunk, encoding);
- }
-
- return 0;
- }
-
- public static Object chunkSlice(Object chunk, int start, int end) {
- if (isBuffer(chunk)) {
- ByteBuffer bb = (ByteBuffer)chunk;
- int opos = bb.position(); bb.position(start);
- int olmt = bb.limit(); bb.limit(end);
-
- ByteBuffer mb = bb.slice();
- bb.limit(olmt); bb.position(opos);
-
- ///ByteBuffer rb = ByteBuffer.allocate(mb.capacity());
- ///rb.put(mb); rb.flip();
-
- return mb;
- }
-
- if (isString(chunk)) {
- String s = (String)chunk;
-
- return s.substring(start, end);
- }
-
- return null;
- }
-
- public static Object chunkSlice(Object chunk, int start) {
- if (isBuffer(chunk)) {
- ByteBuffer bb = (ByteBuffer)chunk;
- int opos = bb.position(); bb.position(start);
-
- ByteBuffer mb = bb.slice();
- bb.position(opos);
-
- ///ByteBuffer rb = ByteBuffer.allocate(mb.capacity());
- ///rb.put(mb); rb.flip();
-
- return mb;
- }
-
- if (isString(chunk)) {
- String s = (String)chunk;
-
- return s.substring(start, s.length());
- }
-
- return null;
- }
-
- public static boolean zeroString(String s) {
- return TextUtils.isEmpty(s);
- }
-
- public static ByteBuffer concatByteBuffer(List