The native messaging host could not receive any message when the size of message sent to NativeApp is 282B,538B,794B,1050B - firefox-addon-webextensions

Recently, I am testing a extension with Native messaging protocol on the chrome,firefox and opera.There is a problem that would always crash the NativeApp on the specially appointed of our platform.
On debugging I find that the app would be crash and log: "error: only 0 could be read." in the special size of a message from the extension.
Through the loop test demo, the native app would fail to receive message when the size of the json message sent to the application is 282B,538B,794B,1050B,1306B,1562B,1818B,2074B...
Here is the function that reading a 32-bit value containing the message length to precede a message.
int InputParser::readMessageLengthFromStream() {
int result = 0;
char size[sizeof (int)];
CString str = "";
inputStream.read(size, sizeof (int));
//check the input
if (inputStream){
Dlog("All characters read successfully!");
}
else{
Dlog("error: only %d could be read.",inputStream.gcount());
return -1;
}
for (int n = sizeof (int) - 1; n >= 0; n--) {
result = (result << 8) + (unsigned char)size[n];
}
return result;
}
Do you have the same question?
Is there any solution to fix it ?

Related

JNI function returning illegal UTF characters at android

Im trying to return string from JNI to android but its returning illegal UTF characters like this:
JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8:
illegal start byte 0x80
04-12 16:08:09.899 18210-18372 A/art:art/runtime/runtime.cc:427]
string: '���� ���!��"��,"���"���#���$��%���
%��`&��'��H(���)��D*���*��X+��,���,���-��4.��|.��P/��t/���/��01��x1��
2��D2���2���3���4���5��06���6��9���9��;���;��H<��=��0=���=���>��8?��
Here is the code which I am using:
JNIEXPORT jbyteArray Java_pakdata_com_qurantextc_MainActivity_get(
JNIEnv *pEnv,
jobject this,
jint pageNo, jint lang) {
char* buffer=(char*)malloc(10000); // this buffer contains the ayat
register unsigned int pageNumber = pageNo - 1;
char * header=(char*)malloc(1000);
sprintf(header,"[{\"OFFSET\":%d,\"DATA\":\"",pageNumber+1);
strcpy(buffer,header);
// to get the last ayat of the page
// this loop will fetch all ayats of the page
for (int i = start_ayat; i <= end_ayat; i++) {
sprintf(buffer+strlen(buffer),"<div class=\\\"qr0\\\" data-ayat=\\\"%d\\\" id=\"%d\\\"><span>",i+1,i+1);
get(lang, i, buffer + strlen(buffer)); // len is equal to length of buffer ( strlen() )
strcpy(buffer+strlen(buffer),"<\\/span><\\/div>");
}
// char* footer;
sprintf(buffer+strlen(buffer),"<div class=\\\"pagebreak\">%d<a id=\\\"%d\\\"next\\\"href=\\\"\\/page\\/%d\\\"></a><\\/div <\\/div>\"}]",pageNumber+1,pageNumber+1,pageNumber+1);
__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG","string: '%s'" , buffer);
int l = strlen(buffer);
char c[l];
strcpy(c,replace(buffer,"\r","<br>"));
jbyteArray ret = (*pEnv)->NewByteArray(pEnv,l);
(*pEnv)->SetByteArrayRegion (pEnv,ret, 0, l, c);
const char * errorKind = NULL;
uint8_t utf8 = checkUtfytes(c, &errorKind);
if (errorKind != NULL) {
free(buffer);
return ret;
} else {
free(buffer);
return ret;
}
I have tried using this too:
return = (*pEnv)->NewStringUTF(pEnv,buffer)
but it still contain illegal UTF characters..
Here is my android side code
byte[] ss = get(a, pos);
s= new String(ss,"UTF-8");
Still getting illegal UTF character error.
I have tried encoding on java side but its no help either,
I am posting here because all other methods that are written here i have already tried but it didn't worked.
PLEASE HELP!!!
May be I am late but your code seems to be correct but according to JNI documentation they doesn't support these characters. You have to handle it from server side. Hope it helps.

InternetReadFile's output to string gives a "ÌÌÌÌÌÌ" sequence in C

I am trying to read the text content of a HTTP Post Response body using InternetReadFile. However, all it contains is a string of "Ì" (-52 when converted to int).
Could this be encoding related? Is it that what is being returned is not a string at all?
Am I missing a step required to read the output?
Please note that I know for a fact that this message body contains plain text (based on logs).
Here is the code:
Ptr = (char *)OutBuffer;
while(TRUE)
{
// read the server response
//
if(!InternetReadFile(RequestHandle,Ptr,Length ,&BytesRead))
{
Rc = GetLastError();
InternetCloseHandle(RequestHandle );
SetLastError(Rc);
return(ACE_HTTP_ERROR);
}
if(BytesRead == 0) // end of data
break;
TotalLength += BytesRead;
Ptr += BytesRead;
if(TotalLength >= *OutBufferLength)
{
InternetCloseHandle(RequestHandle );
SetLastError(ERROR_INSUFFICIENT_BUFFER);
*OutBufferLength = TotalLength;
return(ACE_HTTP_NO_ENOUGH_SPACE);
}
}
*OutBufferLength = TotalLength;
At this point, Ptr, when read as a char array, contains nothing but a sequence of 'Ì'.

Arduino Variable size Array Declaration

I get an error while trying to run the following code:
int SizeOfReadArray = 10;
int PacketLength = 5;
unsigned char rmessage[SizeOfReadArray];
unsigned long flag = 0;
unsigned char DataPacket[PacketLength];
int alternate = 1;
int remaining;
int Index;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
PacketExtraction();
}
void PacketExtraction(){
// Read Serial Buffer store in array
Serial.readBytes(rmessage,SizeOfReadArray);
// onetime execution for getting exact message from serial buffer
if (flag == 0){
for (int j=0;j<SizeOfReadArray;j++){
// check for start of packets through header bytes
if (rmessage[j+0] == 65 && rmessage[j+1] == 65){
// store the Index for extracting packet from message array
Index = j;
remaining = SizeOfReadArray-Index+PacketLength;
flag = 1;
}
}
}
// actual packet extraction
/* take PacketLength of data from serial burffr and store the rest
for remaining bytes for next data packet construction */
if (alternate == 1){
for (int k=0;k<5;k++){
DataPacket[k]=rmessage[k+Index];
}
// storing remaining bytes form next execution
unsigned char previouspacket[remaining];
for (int k=0;k<remaining;k++){
previouspacket[k] = rmessage[k+Index+PacketLength];
}
alternate = 0;
}
/* now this time take the previously saved remaining bytes of packet
and merge them with the current packet data */
else{
for (int k=0;k<remaining;k++){
DataPacket[k] = previouspacket[k];
}
for (int k=0;k<(remaining+1);k++){
DataPacket[k+remaining] = rmessage[k];
}
alternate = 1;
}
}
Error Message:
Arduino: 1.6.1 (Windows 7), Board: "Arduino Mega or Mega 2560,
ATmega2560 (Mega 2560)"
sketch_apr04b.ino: In function 'void PacketExtraction()':
sketch_apr04b.ino:52:23: error: 'previouspacket' was not declared in
this scope
Error compiling.
This report would have more information with "Show verbose output
during compilation" enabled in File > Preferences.
previouspacket is only declared in the first branch of the if…then blocks.
You should move unsigned char previouspacket[remaining]; before the if statement

Parsing a "String"( char array) in C for string ,int and int

I have a UDP socket server and client set up where the client asks for some information from the server, sending a request in the form of a char array that holds the [ID, " ",choice, " ", request] which are a string, int, and int respectively. I need to be able to parse these three parameters out of the array to access my database to send the correct information back. So far I have tried using a while loop to parse through these, but unfortunately This is not working.any suggestions to a better solution that works? The first int will be one digit long, the second however can be however long.
char *idToCheck;
int k = 0;
while(strcmp(messBuffer[k]," ") == 1){
idToCheck += messBuffer[k];
}
int choice = messBuffer[k++];
int request;
while(strcmp(messBuffer[k],"\0") == 1){
????
}
A few things:
You need to have idToCheck point to or be defined to have some storage.
Don't use strcmp to compare characters - just use ==
How about this to start you out - assumes the Id won't be longer than MAX_ID_LEN.
#define MAX_ID_LEN 80
char idToCheck[MAX_ID_LEN]
int i;
for (i = 0; i < MAX_ID_LEN; i++) {
if (messBuffer[i] != ' ') {
idToCheck[i] = messBUffer[i];
}
else {
break;
}
}

Shared library function does working correctly after first dlopen

I am creating a websocket server in C. Since taking a server down, recompiling it, and running it again is counterproductive to what a server app should do, I am looking for ways to dynamically load in my functions so that I can keep the main server app running while being able to alter / create new functions that will be used in it. I created a function that allows me to call a function by name with correct arguments like you would a normal function call, but when I go to call it the second time it does not do the same thing the second time I call it dynamically. To lay out my problem by steps, consider the following situations:
Situation 1
Start server application without calling sendMessage dynamically.
Connect to the websocket server via browser.
After successful connection send a message to the server (I use Hello World)
Server will echo the message the client sent.
Send the same message to the server again.
Server will echo message again. (this is when the server sendMessage function is not loaded dynamically
Repeating steps 5 and 6 will not cause the client to disconnect.
Now for the situation using a dynamic version of the servers sendMessage function to echo the client message.
Situation 2
Start server application while allowing sendMessage to be called using loadFunction.
Connect to the websocket server via browser.
After successful connection send a message to the server (again I use Hello World)
Server will echo the message the client sent like it should.
Send the same message to the server again.
This time the server does not echo the message the client sent.
Sending more messages after the first will eventually cause the connection to end (This is where I am having a problem
Situation 1 is when my function sendMessage is called normally (not through loadFunction) while situation 2 is where I replace sendMessage with my loadFunction call that loads the library holding sendMessage, assigns it to a location function variable (see code) and call the function like it would normally.
I am thinking that the problem lies with the write function in sendMessage when I dynamically load it. But the function works perfectly when I don't load it dynamically which is odd to me.
My question is why is why would my sendMessage function operate differently from when I call it normally and when I call it dynamically? Below is some code and output from both situations
sendMessage.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include "include/structs.h"
//#include "include/functions.h"
/*
* sendMessage: this function is used then we want to send message (s)
* of length (len) from the server to a client (sock)
*
* ARGUMENTS
* sock: the socket where we want the message to go
* s: A string containing the message we want to send
* len: the length of the string s
*/
void *sendMessage(int sock, char *s, int len) {
int frameCount;
uint16_t len16;
char frame[10];
char *reply = malloc(sizeof(char) * (len + 8));
frame[0] = '\x81';
if (len <= 125) {
frame[1] = len;
frameCount = 2;
} else if (len >= 126 && len <= 65535) {
frame[1] = 126;
len16 = htons(len);
memcpy(frame + 2, &len16, 2);
frameCount = 4;
} else {
frame[1] = 127;
//NOTE: HAVE NOT FULLY CONFIGURED A MESSAGE OF THIS LENGTH (TODO)
//frame[2] = (char)( ((char)len >> 56) & (char)255 );
//frame[3] = (char)( ((char)len >> 48) & (char)255 );
//frame[4] = (char)( ((char)len >> 40) & (char)255 );
//frame[5] = (char)( ((char)len >> 32) & (char)255 );
//frame[6] = (char)( ((char)len >> 24) & (char)255 );
frame[7] = (char)( ((char)len >> 16) & (char)255 );
frame[8] = (char)( ((char)len >> 8) & (char)255 );
frame[9] = (char)( ((char)len) & (char)255 );
frameCount = 10;
}//END IF
memcpy(reply, frame, frameCount);
memcpy(reply + frameCount, s, len);
//printf("sock: %d\ts: %s\tlen: %d\n", sock, s, len);
if (write(sock, reply, strlen(reply)) <= 0) {
printf("\n\nWE ARE NOT WRITING!!\n\n");
} else {
//printf("we did write\n");
}//END IF
free(reply);
reply = NULL;
return NULL;
}//END FUNCTION
loadFunction.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include "include/functions.h"
int checkForError(char *error) {
if (error != NULL) {
printf("ERROR: %s\n", error);
exit(EXIT_FAILURE);
}//END IF
return 0;
}//END IF
void * loadFunction(char *func, void ** args) {
void *handle;
//void * (*alterStruct)(int sock, char *action);
int filenameLength;
char * filename;
//void *(*funcPtr);
filenameLength = strlen("lib/lib") + strlen(func) + strlen(".dll");
filename = malloc(sizeof(char) * (filenameLength + 1));
strcpy(filename, "lib/lib");
strcat(filename, func);
strcat(filename, ".dll");
handle = dlopen(filename, RTLD_LAZY);
free(filename);
if (!handle) {
checkForError(dlerror());
}//END IF
dlerror();
if (strncmp(func, "sendMessage", strlen(func)) == 0) {
void * (*funcPtr)(int, char *, int);
//*(void **) (&funcPtr) = dlsym(handle, func);
funcPtr = (void *)dlsym(handle, func);
checkForError(dlerror());
(*funcPtr)((int)args[0], (char *)args[1], (int)args[2]);
//free(*(void **)(&funcPtr));
//*(void **) (&funcPtr) = NULL;
}// else if (strncmp(func, "alterStruct", strlen(func)) == 0) {
//void * (*funcPtr)(int sock, char *action);
//} else if (strncmp(func, "execute", strlen(func)) == 0) {
//void * (*funcPtr)(const char *command, clientStruct s, FILE **in, FILE **out, FILE **err);
//} else {
//void * (*funcPtr)(int sock, char *s, int len);
//}//END IF
dlclose(handle);
handle = NULL;
return NULL;
return NULL;
}//END loadFunction
If you need more code to solve this problem I have it accessable on GitHub here (the dynamic branch is where the problem can be found)
Also, I am using Cygwins' GNU gcc compiler (which I have never have a problem compiling on) to compile my application and libraries so I may not have access to certain Linux commands (for example dlmopen). That said, please do not say use a different compiler because I've had no other problems thus far and I do not intend on changing how I compile my code.
I did not document the command I use to compile just the libsendMessage.dll used in loadFunction. you can obtain it using the following
gcc -c -fPIC sendMessage.c
mv sendMessage.o objects/sendMessage.o
gcc -shared -o lib/libsendMessage.dll objects/sendMessage.o libfunctions.c
Thank you in advance.
I have figured out my problem and it is quite an odd one.
When i was testing the sendMessage function using my dynamic method i printf exactly what was being sent through the socket and apparently it was sending the correct message. However, it was also sending the characters from my filename variable in the loadFunction function which to me is strange that the memory address was accessable to sendMessage when it was malloced, freed and set to NULL way before the function call to the dynamic sendMessage was called.
Solution
After I opened my library with dlopen(filename, RTLD_LAZY) I used memset(filename, '\0', filenameLength) to write null characters to the memory address of filename making the string contain all null characters which when accessed as a character counts as a end of string.
I'm not sure why I am having to use memset so much in this application but i know that it has fixed string bugs for me multiple times.

Resources