-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathipc_shm.cpp
More file actions
106 lines (83 loc) · 2.44 KB
/
Copy pathipc_shm.cpp
File metadata and controls
106 lines (83 loc) · 2.44 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Revision 4: Shared memory module updated
#include "ipc_shm.h"
#include "security.h"
#include "logger.h"
#include <windows.h>
#include <iostream>
#include <string>
#include <cstring>
#define SHM_NAME L"MySharedMemory" // Same for read + write
#define SHM_SIZE 1024 // Bigger size = safer
// ======================
// SHARED MEMORY WRITE
// ======================
void shmWrite() {
HANDLE hMap = CreateFileMappingW(
INVALID_HANDLE_VALUE, // Use RAM, not a file
NULL,
PAGE_READWRITE,
0,
SHM_SIZE,
SHM_NAME // Must match in reader
);
if (hMap == NULL) {
std::cout << "Failed to create shared memory. ERROR = " << GetLastError() << "\n";
return;
}
void* mem = MapViewOfFile(
hMap,
FILE_MAP_ALL_ACCESS,
0, 0,
SHM_SIZE
);
if (mem == NULL) {
std::cout << "Failed to map shared memory. ERROR = " << GetLastError() << "\n";
CloseHandle(hMap);
return;
}
std::string msg;
std::cout << "Enter message: ";
std::cin.ignore();
std::getline(std::cin, msg);
// Encrypt message
msg = encryptData(msg);
// Clear block and copy data
memset(mem, 0, SHM_SIZE);
memcpy(mem, msg.c_str(), msg.size());
std::cout << "Message written to shared memory.\n";
logEvent("[SHM] Wrote encrypted message.");
UnmapViewOfFile(mem);
CloseHandle(hMap);
}
// ======================
// SHARED MEMORY READ
// ======================
void shmRead() {
HANDLE hMap = OpenFileMappingW(
FILE_MAP_ALL_ACCESS,
FALSE,
SHM_NAME
);
if (hMap == NULL) {
std::cout << "No shared memory segment found. ERROR = " << GetLastError() << "\n";
return;
}
void* mem = MapViewOfFile(
hMap,
FILE_MAP_ALL_ACCESS,
0, 0,
SHM_SIZE
);
if (mem == NULL) {
std::cout << "Failed to map shared memory (Read). ERROR = " << GetLastError() << "\n";
CloseHandle(hMap);
return;
}
// Convert memory buffer to string
std::string encrypted((char*)mem);
std::string decrypted = decryptData(encrypted);
std::cout << "Shared Memory Contains: " << decrypted << "\n";
logEvent("[SHM] Read & decrypted message.");
UnmapViewOfFile(mem);
CloseHandle(hMap);
}