edits
[iotcloud.git] / version2 / src / C / CloudComm.cc
index 452317f42335854743b9e95cb3d1f81bc62e8858..9a15732711360236be62ab804f7a695ed88106b3 100644 (file)
@@ -53,11 +53,11 @@ CloudComm::CloudComm(Table *_table,  IoTString *_baseurl, IoTString *_password,
  */
 SecretKeySpec *CloudComm::initKey() {
        try {
-               PBEKeySpec keyspec = new PBEKeySpec(password->internalBytes(),
-                                                                                                                                                               salt,
-                                                                                                                                                               65536,
-                                                                                                                                                               128);
-               SecretKey tmpkey = SecretKeyFactory_getInstance("PBKDF2WithHmacSHA256")->generateSecret(keyspec);
+               PBEKeySpec *keyspec = new PBEKeySpec(password->internalBytes(),
+                                                                                                                                                                salt,
+                                                                                                                                                                65536,
+                                                                                                                                                                128);
+               SecretKey *tmpkey = SecretKeyFactory_getInstance("PBKDF2WithHmacSHA256")->generateSecret(keyspec);
                return new SecretKeySpec(tmpkey->getEncoded(), "AES");
        } catch (Exception *e) {
                throw new Error("Failed generating key.");
@@ -82,7 +82,6 @@ void CloudComm::initSecurity() {
  * Inits the HMAC generator.
  */
 void CloudComm::initCrypt() {
-
        if (password == NULL) {
                return;
        }
@@ -123,19 +122,15 @@ void CloudComm::setSalt() {
                        printf("%d\n", (int)saltTmp->get(i) & 255);
                }
 
-
                URL *url = new URL(baseurl + "?req=setsalt");
-
                timer->startTime();
-               URLConnection con = url->openConnection();
-               HttpURLConnection http = (HttpURLConnection) con;
+               URLConnection *con = url->openConnection();
+               HttpURLConnection *http = (HttpURLConnection *) con;
 
                http->setRequestMethod("POST");
                http->setFixedLengthStreamingMode(saltTmp->length());
                http->setDoOutput(true);
                http->setConnectTimeout(CloudComm_TIMEOUT_MILLIS);
-
-
                http->connect();
 
                OutputStream *os = http->getOutputStream();
@@ -143,18 +138,17 @@ void CloudComm::setSalt() {
                os->flush();
 
                int responsecode = http->getResponseCode();
-               if (responsecode != HttpURLConnection.HTTP_OK) {
+               if (responsecode != HttpURLConnection_HTTP_OK) {
                        // TODO: Remove this print
-                       System.out.println(responsecode);
+                       printf("%d\n", responsecode);
                        throw new Error("Invalid response");
                }
 
                timer->endTime();
-
                salt = saltTmp;
        } catch (Exception *e) {
                timer->endTime();
-               throw new ServerException("Failed setting salt", ServerException.TypeConnectTimeout);
+               throw new ServerException("Failed setting salt", ServerException_TypeConnectTimeout);
        }
 }
 
@@ -169,36 +163,28 @@ bool CloudComm::getSalt() {
                throw new Error("getSlot failed");
        }
        try {
-
                timer->startTime();
                con = url->openConnection();
-               http = (HttpURLConnection) con;
+               http = (HttpURLConnection *) con;
                http->setRequestMethod("POST");
                http->setConnectTimeout(CloudComm_TIMEOUT_MILLIS);
                http->setReadTimeout(CloudComm_TIMEOUT_MILLIS);
-
-
                http->connect();
                timer->endTime();
        } catch (SocketTimeoutException *e) {
                timer->endTime();
-               throw new ServerException("getSalt failed", ServerException.TypeConnectTimeout);
+               throw new ServerException("getSalt failed", ServerException_TypeConnectTimeout);
        } catch (Exception *e) {
                throw new Error("getSlot failed");
        }
 
        try {
-
                timer->startTime();
-
-               int responsecode = http.getResponseCode();
-               if (responsecode != HttpURLConnection.HTTP_OK) {
-                       // TODO: Remove this print
-                       // System.out.println(responsecode);
+               int responsecode = http->getResponseCode();
+               if (responsecode != HttpURLConnection_HTTP_OK) {
                        throw new Error("Invalid response");
                }
-
-               InputStream is = http->getInputStream();
+               InputStream *is = http->getInputStream();
                if (is->available() > 0) {
                        DataInputStream *dis = new DataInputStream(is);
                        int salt_length = dis->readInt();
@@ -206,24 +192,21 @@ bool CloudComm::getSalt() {
                        dis->readFully(tmp);
                        salt = tmp;
                        timer->endTime();
-
                        return true;
                } else {
                        timer->endTime();
-
                        return false;
                }
        } catch (SocketTimeoutException *e) {
                timer->endTime();
-
-               throw new ServerException("getSalt failed", ServerException.TypeInputTimeout);
+               throw new ServerException("getSalt failed", ServerException_TypeInputTimeout);
        } catch (Exception *e) {
                throw new Error("getSlot failed");
        }
 }
 
 Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber) {
-       ByteBuffer buffer = ByteBuffer.allocate(CloudComm_IV_SIZE);
+       ByteBuffer *buffer = ByteBuffer_allocate(CloudComm_IV_SIZE);
        buffer->putLong(machineId);
        int64_t localSequenceNumberShifted = localSequenceNumber << 16;
        buffer->putLong(localSequenceNumberShifted);
@@ -232,24 +215,22 @@ Array<char> *CloudComm::createIV(int64_t machineId, int64_t localSequenceNumber)
 
 Array<char> *CloudComm::encryptSlotAndPrependIV(Array<char> *rawData, Array<char> *ivBytes) {
        try {
-               IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
-               Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
-               cipher->init(Cipher.ENCRYPT_MODE, key, ivSpec);
+               IvParameterSpec *ivSpec = new IvParameterSpec(ivBytes);
+               Cipher *cipher = Cipher_getInstance("AES/CTR/NoPadding");
+               cipher->init(Cipher_ENCRYPT_MODE, key, ivSpec);
 
                Array<char> *encryptedBytes = cipher->doFinal(rawData);
 
                Array<char> *chars = new Array<char>(encryptedBytes->length() + CloudComm_IV_SIZE);
-               System_arraycopy(ivBytes, 0, chars, 0, ivBytes.length());
-               System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes.length);
+               System_arraycopy(ivBytes, 0, chars, 0, ivBytes->length());
+               System_arraycopy(encryptedBytes, 0, chars, CloudComm_IV_SIZE, encryptedBytes->length());
 
                return chars;
-
        } catch (Exception *e) {
                throw new Error("Failed To Encrypt");
        }
 }
 
-
 Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
        try {
                Array<char> *ivBytes = new Array<char>(CloudComm_IV_SIZE);
@@ -258,17 +239,14 @@ Array<char> *CloudComm::stripIVAndDecryptSlot(Array<char> *rawData) {
                System_arraycopy(rawData, CloudComm_IV_SIZE, encryptedBytes, 0, encryptedBytes->length);
 
                IvParameterSpec *ivSpec = new IvParameterSpec(ivBytes);
-
                Cipher *cipher = Cipher_getInstance("AES/CTR/NoPadding");
                cipher->init(Cipher_DECRYPT_MODE, key, ivSpec);
                return cipher->doFinal(encryptedBytes);
-
        } catch (Exception *e) {
                throw new Error("Failed To Decrypt");
        }
 }
 
-
 /*
  * API for putting a slot into the queue.  Returns NULL on success.
  * On failure, the server will send slots with newer sequence
@@ -278,53 +256,41 @@ Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
        try {
                if (salt == NULL) {
                        if (!getSalt()) {
-                               throw new ServerException("putSlot failed", ServerException.TypeSalt);
+                               throw new ServerException("putSlot failed", ServerException_TypeSalt);
                        }
                        initCrypt();
                }
 
                int64_t sequencenumber = slot->getSequenceNumber();
                Array<char> *slotBytes = slot->encode(mac);
-
                Array<char> *chars = encryptSlotAndPrependIV(slotBytes, slot->getSlotCryptIV());
-
                URL *url = buildRequest(true, sequencenumber, max);
-
                timer->startTime();
                URLConnection *con = url->openConnection();
                HttpURLConnection *http = (HttpURLConnection *) con;
-
                http->setRequestMethod("POST");
                http->setFixedLengthStreamingMode(chars->length);
                http->setDoOutput(true);
                http->setConnectTimeout(CloudComm_TIMEOUT_MILLIS);
                http->setReadTimeout(CloudComm_TIMEOUT_MILLIS);
                http->connect();
-
                OutputStream *os = http->getOutputStream();
                os->write(chars);
                os->flush();
-
                timer->endTime();
-
-
        } catch (ServerException *e) {
                timer->endTime();
-
                throw e;
        } catch (SocketTimeoutException *e) {
                timer->endTime();
-
-               throw new ServerException("putSlot failed", ServerException.TypeConnectTimeout);
+               throw new ServerException("putSlot failed", ServerException_TypeConnectTimeout);
        } catch (Exception *e) {
                throw new Error("putSlot failed");
        }
 
-
-
        try {
                timer->startTime();
-               InputStream is = http->getInputStream();
+               InputStream *is = http->getInputStream();
                DataInputStream *dis = new DataInputStream(is);
                Array<char> *resptype = new Array<char>(7);
                dis->readFully(resptype);
@@ -336,7 +302,6 @@ Array<Slot *> *CloudComm::putSlot(Slot *slot, int max) {
                        return NULL;
                } else
                        throw new Error("Bad response to putslot");
-
        } catch (SocketTimeoutException *e) {
                timer->endTime();
                throw new ServerException("putSlot failed", ServerException->TypeInputTimeout);
@@ -353,7 +318,7 @@ Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
        try {
                if (salt == NULL) {
                        if (!getSalt()) {
-                               throw new ServerException("getSlots failed", ServerException.TypeSalt);
+                               throw new ServerException("getSlots failed", ServerException_TypeSalt);
                        }
                        initCrypt();
                }
@@ -361,20 +326,15 @@ Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
                URL *url = buildRequest(false, sequencenumber, 0);
                timer->startTime();
                URLConnection *con = url->openConnection();
-               HttpURLConnection *http = (HttpURLConnection) con;
+               HttpURLConnection *http = (HttpURLConnection *) con;
                http->setRequestMethod("POST");
                http->setConnectTimeout(CloudComm_TIMEOUT_MILLIS);
                http->setReadTimeout(CloudComm_TIMEOUT_MILLIS);
-
-
-
                http->connect();
                timer->endTime();
-
        } catch (SocketTimeoutException *e) {
                timer->endTime();
-
-               throw new ServerException("getSlots failed", ServerException.TypeConnectTimeout);
+               throw new ServerException("getSlots failed", ServerException_TypeConnectTimeout);
        } catch (ServerException *e) {
                timer->endTime();
 
@@ -384,23 +344,19 @@ Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
        }
 
        try {
-
                timer->startTime();
                InputStream *is = http->getInputStream();
                DataInputStream *dis = new DataInputStream(is);
                Array<char> *resptype = new Array<char>(7);
-
                dis->readFully(resptype);
                timer->endTime();
-
-               if (!resptype->equals("getslot".getBytes()))
+               if (!resptype->equals("getslot"->getBytes()))
                        throw new Error("Bad Response: " + new String(resptype));
 
                return processSlots(dis);
        } catch (SocketTimeoutException *e) {
                timer->endTime();
-
-               throw new ServerException("getSlots failed", ServerException.TypeInputTimeout);
+               throw new ServerException("getSlots failed", ServerException_TypeInputTimeout);
        } catch (Exception *e) {
                throw new Error("getSlots failed");
        }
@@ -413,15 +369,13 @@ Array<Slot *> *CloudComm::getSlots(int64_t sequencenumber) {
 Array<Slot *> *CloudComm::processSlots(DataInputStream *dis) {
        int numberofslots = dis->readInt();
        Array<int> *sizesofslots = new Array<int>(numberofslots);
-
        Array<Slot *> *slots = new Array<Slot *>(numberofslots);
+
        for (int i = 0; i < numberofslots; i++)
                sizesofslots->set(i, dis->readInt());
-
        for (int i = 0; i < numberofslots; i++) {
                Array<char> *rawData = new Array<char>(sizesofslots->get(i));
                dis->readFully(rawData);
-
                Array<char> *data = stripIVAndDecryptSlot(rawData);
                slots->set(i, Slot_decode(table, data, mac));
        }
@@ -430,17 +384,15 @@ Array<Slot *> *CloudComm::processSlots(DataInputStream *dis) {
 }
 
 Array<char> *sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, String host, int port) {
-       if (salt == NULL) {
+       if (salt == NULL)
                return NULL;
-       }
        try {
                printf("Passing Locally\n");
-
                mac->update(sendData);
                Array<char> *genmac = mac->doFinal();
                Array<char> *totalData = new Array<char>(sendData->length() + genmac->length());
-               System_arraycopy(sendData, 0, totalData, 0, sendData.length());
-               System - arraycopy(genmac, 0, totalData, sendData.length, genmac->length());
+               System_arraycopy(sendData, 0, totalData, 0, sendData->length());
+               System_arraycopy(genmac, 0, totalData, sendData->length(), genmac->length());
 
                // Encrypt the data for sending
                Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
@@ -461,20 +413,17 @@ Array<char> *sendLocalData(Array<char> *sendData, int64_t localSequenceNumber, S
                int lengthOfReturnData = input->readInt();
                Array<char> *returnData = new Array<char>(lengthOfReturnData);
                input->readFully(returnData);
-
                timer->endTime();
-
                returnData = stripIVAndDecryptSlot(returnData);
 
                // We are done with this socket
                socket->close();
-
                mac->update(returnData, 0, returnData->length - HMAC_SIZE);
                Array<char> *realmac = mac->doFinal();
                Array<char> *recmac = new Array<char>(HMAC_SIZE);
                System_arraycopy(returnData, returnData->length - realmac->length, recmac, 0, realmac->length);
 
-               if (!Arrays->equals(recmac, realmac))
+               if (!recmac->equals(realmac))
                        throw new Error("Local Error: Invalid HMAC!  Potential Attack!");
 
                Array<char> *returnData2 = new Array<char>(lengthOfReturnData - recmac->length());
@@ -504,7 +453,6 @@ void CloudComm::localServerWorkerFunction() {
                try {
                        // Accept incoming socket
                        Socket *socket = inputSocket->accept();
-
                        DataInputStream *input = new DataInputStream(socket->getInputStream());
                        DataOutputStream *output = new DataOutputStream(socket->getOutputStream());
 
@@ -512,12 +460,10 @@ void CloudComm::localServerWorkerFunction() {
                        int dataSize = input->readInt();
                        Array<char> *readData = new Array<char>(dataSize);
                        input->readFully(readData);
-
                        timer->endTime();
 
                        // Decrypt the data
                        readData = stripIVAndDecryptSlot(readData);
-
                        mac->update(readData, 0, readData->length - HMAC_SIZE);
                        Array<char> *genmac = mac->doFinal();
                        Array<char> *recmac = new Array<char>(HMAC_SIZE);
@@ -531,8 +477,6 @@ void CloudComm::localServerWorkerFunction() {
 
                        // Process the data
                        Array<char> *sendData = table->acceptDataFromLocal(returnData);
-
-
                        mac->update(sendData);
                        Array<char> *realmac = mac->doFinal();
                        Array<char> *totalData = new Array<char>(sendData->length() + realmac->length());
@@ -543,7 +487,6 @@ void CloudComm::localServerWorkerFunction() {
                        Array<char> *iv = createIV(table->getMachineId(), table->getLocalSequenceNumber());
                        Array<char> *encryptedData = encryptSlotAndPrependIV(totalData, iv);
 
-
                        timer->startTime();
                        // Send data to output (length of data, the data)
                        output->writeInt(encryptedData->length());
@@ -576,4 +519,3 @@ void CloudComm::close() {
                }
        }
 }
-