Last active
March 8, 2023 03:16
-
-
Save ericlaw1979/8774f001a030c2019619e99ecd41a380 to your computer and use it in GitHub Desktop.
A simple Native Message Host for Chromium that echoes received messages.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This is a simple Native Message Host application. It echoes any messages | |
* it receives. After receiving and echoing a `{"quit":1}` message, the app | |
* will exit. | |
*/ | |
#include <fcntl.h> | |
#include <io.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef union { | |
unsigned long as_ulong; | |
unsigned char as_bytes[4]; | |
} MessageLength; | |
int main(int argc, char argv[]) | |
{ | |
// Set stdio streams to unbuffered binary mode to avoid | |
// corrupting messages. | |
_setmode(_fileno(stdin), _O_BINARY); | |
setvbuf(stdin, NULL, _IONBF, 0); | |
_setmode(_fileno(stdout), _O_BINARY); | |
setvbuf(stdout, NULL, _IONBF, 0); | |
size_t bytes_read = 0; | |
MessageLength message_length; | |
message_length.as_ulong = 0; | |
char* message_body = nullptr; | |
// Read the size from stdin. | |
bytes_read = fread(message_length.as_bytes, 1, 4, stdin); | |
// Read messages in a loop. | |
while (bytes_read == 4) | |
{ | |
bool got_exit_signal = false; | |
int iLen = (int)message_length.as_ulong; | |
if (iLen > 0) { | |
// Read the message body. | |
message_body = (char*)malloc(iLen); | |
bytes_read = fread(message_body, 1, iLen, stdin); | |
// Check for the exit signal. | |
got_exit_signal = !_strnicmp(message_body, "{\"quit\":1}", iLen); | |
// Reply by echo'ing the message. | |
fwrite(message_length.as_bytes, 1, 4, stdout); | |
fwrite(message_body, 1, iLen, stdout); | |
fflush(stdout); | |
} | |
else { | |
break; | |
} | |
if (message_body != nullptr) free(message_body); | |
// If we were asked to exit, do that now. | |
if (got_exit_signal) break; | |
// Otherwise, read the next message. | |
bytes_read = fread(message_length.as_bytes, 1, 4, stdin); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment