-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnm_c_cr.c
More file actions
88 lines (76 loc) · 1.97 KB
/
nm_c_cr.c
File metadata and controls
88 lines (76 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// https://codereview.stackexchange.com/a/298284
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const uint32_t max_message_size = 64 * 1024 * 1024;
/**
* Get a message in Chrome's native messaging format
*
* @return A pointer to the message if succesful, `NULL` otherwise.
* The caller is responsible for freeing the message using
* free().
*/
char* getMessage(void) {
// Read the size of the message
uint32_t size;
size_t result = fread(&size, sizeof size, 1, stdin);
if (result != 1) {
return NULL;
}
// Check if the size is valid
if (size > max_message_size) {
return NULL;
}
// Allocate memory for the message and the terminating NUL-byte
char *message = malloc(size + 1);
if (!message) {
return NULL;
}
// Read the message itself
result = fread(message, size, 1, stdin);
if (result != 1) {
free(message);
return NULL;
}
// Ensure the message is NUL-terminated
message[size] = '\0';
return message;
}
/**
* Send a message in Chrome's native messaging format
*
* @param message A pointer to the message.
It must be a NUL-terminated string.
* @return `true` if the message was sent succesfully,
`false` otherwise.
*/
bool sendMessage(const char* message) {
// Write the size of the message
const uint32_t size = strlen(message);
if (fwrite(&size, sizeof size, 1, stdout) != 1) {
return false;
}
// Write the message itself
if (fwrite(message, size, 1, stdout) != 1) {
return false;
}
// Flush the output to ensure the message is sent completely
return fflush(stdout) == 0;
}
int main(void) {
while (true) {
char* message = getMessage();
if (!message) {
perror("Could not read message");
return EXIT_FAILURE;
}
bool sent = sendMessage(message);
free(message);
if (!sent) {
perror("Could not send message");
return EXIT_FAILURE;
}
}
}