Why is JavaScript unable to fetch JSON data from C when the uint32 value is a multiple of 256 plus 10?

After receiving some helpful feedback, I decided to make some changes to this question that I posted yesterday. The title and content have been edited for clarity based on the new information I've learned.

Recently, I've been utilizing C code to transmit JSON strings from C to a Firefox extension using the native-messaging API. This setup has been functioning smoothly for a few months now, as I continue to add more code to both programs.

The variable response points to the JSON string generated in C. As shown, the string is prefixed with a unint32 value representing the number of bytes in the string.

Oddly enough, JSON strings with a byte length equal to a multiple of 256 plus 10 seem to be successfully transmitted from C to the extension but are not being processed by the extension. I have tested values like 266 and 522.

Typically, if an invalid string is transmitted, the background script would throw an error related to malformed JSON or exceeding size limits, resulting in the closure of the C program. However, no errors are triggered when dealing with these specific sizes of JSON strings; the C program remains open.

Furthermore, running the same JSON strings in the C executable command line results in the correct JSON output displayed on the screen/stdout. Interestingly, altering the length of the strings by adding or removing a byte allows the extension to receive and parse them, unlike the mentioned sizes.

To aid in identifying issues, I also write the JSON to a local disk file. Upon inspection, everything appears normal except for one observation. These specific strings contain a smiley face after the uint32 size, causing the remaining bytes and JSON data to move to the next line. In contrast, all other strings retain their original formatting with non-typeable characters on the same line.

Any insights on why the extension fails to pick up these strings?

Thank you.

int send_response( const char *response )
{
    int rc;
    FILE *fp_out;
    fp_out = fopen( "test.txt", "w" );

    // Write response ( JSON prefixed with its UTF-8 length ).
    const uint32_t len = strlen( response );

    if ( ( rc = fwrite( &len, sizeof len, 1, fp_out ) ) != 1 ||
         ( rc = fwrite( response, len, 1, fp_out ) ) != 1 )
    {}

    if ( ( rc = fwrite( &len, sizeof len, 1, stdout ) ) != 1 ||
         ( rc = fwrite( response, sizeof *response, len, stdout ) ) != len )
    {
        perror( "fwrite" );
        return EXIT_FAILURE;
    }

    fclose( fp_out );
    return 0;

} // close send_response

Answer №1

There seems to be an issue with Windows OS using /r/n instead of /n for new line characters. This helpful resource from the Chrome Developer's site discusses native messaging and provides a link to a Windows page detailing how to use _setmode() to set stdout to _O_BINARY in C code.

To resolve, simply implement

result = _setmode( _fileno( stdout ), _O_BINARY );
, which will return -1 if unsuccessful.

For further clarification, this response on the SQLite forum dives deeper into the root cause.

I opted to post this as an answer rather than appending it to my original question due to past experiences of having added information removed before closing the question. Likely, this paragraph will also be stripped out.

A big thank you to @user3386109 for steering me towards the solution when I was lost!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

A Beginner's Guide to Understanding Elasticsearch, Logstash, and Kibana without Technical Jargon

I am confused. I understand that Logstash allows us to input csv/log files and apply filters using separators and columns. The output is then sent to elasticsearch for use with Kibana. However, I'm unsure about whether or not we need to specify an ind ...

Converting ed25519 private key into OpenSSH Format using JavaScript

After generating an ed25519 key pair using the javascript crypto library, I am now faced with the challenge of saving the private key in openssh format. Despite attempting to use the sshpk library for this task, I encountered an issue where the exported k ...

Unable to convert the current JSON object (for example, {"title":"content"}) into the specified type 'System.Collections.Generic.List`1`

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Facebook; using Newtonsoft.Json; namespace facebook { class Program { static void Main(string[] args) { var client = new Facebo ...

Can multiple objects be grouped together and easily dragged in Leaflet?

Is there a way to group a set of objects together so they can be dragged simultaneously? I want to make multiple objects draggable on a map and have them behave as a single marker when moved. Currently, I have a geojson file containing several objects that ...

The nested directive link function failed to execute and the controller was not recognized

Apologies in advance for adding to the sea of 'mah directive link function isn't called!' posts on Stack Overflow, but none of the solutions seem to work for me. I have a directive named sgMapHeader nested inside another directive called sg ...

Choosing between exclusive choices across multiple selection elements in Vue 3

In my Vue component, there are 5 distinct values stored in the options variable. I want users to select only one value from each of the 5 select options I provide. This means that once a user selects a value in one input select component, that same value c ...

The design problem arises from using jQuery to dynamically prepare the table body at runtime

The table row and data are not appearing in the correct format. Here is a link to the problem on Fiddle: http://jsfiddle.net/otc056L9/ Below is the HTML code: <table border="1" style="width: 100%" class="eventtable"> <thead style="color: b ...

Transform Yaml into Json data that has been sorted using Terraform

Is there a way to transform a YAML datasource into a sorted JSON file using Terraform? Here is an example of the YAML data: users: - key: 'user[0].name' value: Roku - key: 'user[0].age' value: '55' - key: ' ...

Retrieving game information from the Hearthstone API

I'm currently working on developing a random Hearthstone card generator, but I've run into some issues with extracting JSON data from the API and converting it into a JavaScript object for use in my HTML. While I've confirmed that the API re ...

Incorporate JSON data using jQuery's AJAX in MVC3

I need assistance with parsing the JSON data retrieved from a webservice through my controller. Currently, I am displaying the entire JSON string in a div as text. However, I only want to extract specific values such as "color" and "size". I am unsure of ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Encountering issues with tesseract callbacks in nodejs due to validation errors

I encountered the following error: fs.js:132 throw new ERR_INVALID_CALLBACK(); ^ TypeError [ERR_INVALID_CALLBACK]: Callback must be a function at makeCallback (fs.js:132:11) at Object.fs.unlink (fs.js:1002:14) at /home/bakedpanda/Documents/BTP/ ...

When I include scroll-snap-type: y; in the body tag, the scroll-snapping feature does not function properly

Hey there! I've been trying to implement scroll-snapping on my project but unfortunately, I couldn't get it to work. I tested it out on both Chrome and Firefox, but no luck so far. Here's the code snippet I've been working with, would a ...

Capture sound from web browser and display live audio visualization

I'm searching for a package that can capture audio input from the browser's microphone and display it in real time. Are there any JavaScript packages available for this purpose? I've looked at various audio visualizer options, but they all r ...

Encountering an Ajax Issue with Laravel 5.4

I encountered the following error: "{"status":"error","msg":"Category was not created"}" Below is my Controller Function where I execute the action : function create_category(Request $request){ if($request->ajax()){ $c ...

What causes the Access-Control-Allow-Origin error to appear with AJAX requests but not with Rails?

After attempting to retrieve a response from the API of Career Builder using AJAX (trying xml, json, and jsonp), I consistently encountered the "Access-Control-Allow-Origin" error. However, when I followed icodeya's tutorial and retrieved a response f ...

Challenges encountered when combining freeRTOS and LwIP for TCP communication with threading and tasks

Encountering difficulties with FreeRTOS+LwIP on a Zedboard, where the board crashes and requires a power reset. Suspecting network connection issues as I have two connections; one for incoming and one for outgoing traffic. Both connect successfully, but th ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...