Erlang C node related question - erlang

In the tutorial provided at:
http://www.erlang.org/doc/tutorial/cnode.html
There is the following example:
/* cnode_s.c */
#include
#include
#include
#include
#include "erl_interface.h"
#include "ei.h"
#define BUFSIZE 1000
int main(int argc, char **argv) {
int port; /* Listen port number */
int listen; /* Listen socket */
int fd; /* fd to Erlang node */
ErlConnect conn; /* Connection data */
int loop = 1; /* Loop flag */
int got; /* Result of receive */
unsigned char buf[BUFSIZE]; /* Buffer for incoming message */
ErlMessage emsg; /* Incoming message */
ETERM *fromp, *tuplep, *fnp, *argp, *resp;
int res;
port = atoi(argv[1]);
erl_init(NULL, 0);
if (erl_connect_init(1, "secretcookie", 0) == -1)
erl_err_quit("erl_connect_init");
/* Make a listen socket */
if ((listen = my_listen(port))
I suspect that erl_receive_msg is a blocking call, and I don't know how to overcome this. In C network programming there is the "select" statement but in the Erlang EI API I don't know whether there is such a statement.
Basically I want to build a C node, that continuously sends messages to Erlang nodes. For simplicity suppose there is only one Erlang node.
The Erlang node has to process the messages it receives from the C node. The Erlang node is not supposed to ensure that it has received the message, not does it have to reply with the result of processing. Therefore once the message is sent I don't care about it faith.
One might think that one could modify the code as:
...
if (emsg.type == ERL_REG_SEND) {
...
while(1) {
//generate tuple
erl_send(fd, fromp, tuple);
//free alloc resources
}
...
}
This will produce an infinite loop in which we produce and consume (send) messages.
But there is an important problem: if I do this, then the C node might send too many messages to the Erlang node (so there should be a way to send a message from the Erlang node to the C node to slow down), or the Erlang node might think that the C node is down.
I know that the questions must be short an suite (this is long and ugly), but summing up:
What mechanism (procedure call, algorithm) one might use to develop an eager producer in C for a lazy consumer in Erlang, such that both parties are aware of the underlying context ?

I use Port Drivers myself for the case you are describing (haven't touched the C nodes because I'd rather have more decoupling).
Have a look at the Port Driver library for Erlang: EPAPI. There is a project that leverages this library: Erland DBus.

Did you check the ei_receive_msg_tmo function? I suppose it works similar to the receive after construct of Erlang, so if you set timeout to 0, it will be non-blocking.
I believe erl_interface is deprecated, and ei should be used instead. This might be a complete misinformation though...

you need to take a closer look at the tutorial link that you posted. (search for "And finally we have the code for the C node client.") You will see that the author provided a client cnode implementation. It looks rational.

Related

How to work with the output of another ECU

I am new in CAPL (CANoe). I have 2 Nodes here; CAN_Portscanner that scans a vehicle and returns 47 ECUs and their services and a Diagnostic Tester that i want to develop. it has to recognize only a few ECUs from the Portscanner. When I find the service, I need to send a service request to an ECU and extend the ECU function with a response in CANoe to know that my request was successful.
I need to read a message from another .can file and work with it.
I tried something like this:
includes
{
#include "CAN_Portscanner.can"
}
variables
{
int counter;
}
void MainTest()
{
while(diagnose_request_msg.ID <= 0x7E1)
{
counter++;
}
write("Number of ECUs in the Tester: %d",counter);
}
I don't know if the #include is correct and why do i obtain a warning about MainTest.
Warning 2033 at (12,1): Use of function 'MainTest' seems to indicate that this file should be a test module or test unit. Diagnostic Tester.can

Communicating between subnets with ESP8266 wifi extender

I have a local (household 192.168.0.X) network provided by my router/modem which assigns local IP addresses by the usual Dynamic DNS. I have added an ESP8266 runnning in the WiFi Nat (natp) mode to act as an extender. So it connected to the router as a station and then provides an access point that other devices can connect to. Currently, its subnet is 172...X).
This works in the sense that devices on the extended subnet can see the "world" like google.com etc...
The problem is devices on the 192. network can't see any devices on the extended network.
The source of the problem is pretty obvious: the 192 network devices are all connected by the router which has no clue about any devices connnected to the extender access point.
Is this possible and is there a good ESP 82666 example for this?
If not example, I'm unsure what I'm not understanding-- I'm unsure of what to call this configuration so googling it isn't working.
I feel like there ought to be a way to make the extender just a transparent replicator/relay so the Router is seeing every device and is doing the DHCPS job itself rather than the ESP8266 access point. But I'm stuck.
What sort of configuration approach I can use to expose the devices on the extended network to the computers on the 192 network?
There's a myriad of possible settings but I can't seem to find a permutation that works. (e.g. the Gateway setting or turning off DHCP on the extender access point.) I've tried making the extender network be the same 192.168.0.X rather than 172. But that didn't help.
Detail:
What I have here is a sensor network out in my barn that lives on the access point. I want to be able to access the sensors from inside the house. I've goofed around with workarounds of having the barn devices send their data to a server out in the world. But I want direct access so I can query the devices or do over the air programming directly to the devices from my home computer. I can only do this right now by connecting the home computer to the (slower) extended network access point rather than the high speed home router.
Here's an example of the code I'm modifying (basically one of the ESPWIFI example sketches.)
// NAPT example released to public domain
#if LWIP_FEATURES && !LWIP_IPV6
#define HAVE_NETDUMP 0
#ifndef STASSID
#define STASSID "HouseModem"
#define STAPSK "HouseModemPassword"
#endif
#include <ESP8266WiFi.h>
#include <lwip/napt.h>
#include <lwip/dns.h>
#include <dhcpserver.h>
#define NAPT 1000
#define NAPT_PORT 10
#if HAVE_NETDUMP
#include <NetDump.h>
void dump(int netif_idx, const char* data, size_t len, int out, int success) {
(void)success; // What does this do?
Serial.print(out ? F("out ") : F(" in "));
Serial.printf("%d ", netif_idx);
// optional filter example: if (netDump_is_ARP(data))
{
netDump(Serial, data, len);
//netDumpHex(Serial, data, len);
}
}
#endif
void setup() {
Serial.begin(115200);
Serial.printf("\n\nNAPT Range extender\n");
Serial.printf("Heap on start: %d\n", ESP.getFreeHeap());
#if HAVE_NETDUMP
phy_capture = dump;
#endif
// first, connect to STA so we can get a proper local DNS server
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(500);
}
Serial.printf("\nSTA: %s (dns: %s / %s)\n",
WiFi.localIP().toString().c_str(),
WiFi.dnsIP(0).toString().c_str(),
WiFi.dnsIP(1).toString().c_str());
// give DNS servers to AP side
dhcps_set_dns(0, WiFi.dnsIP(0));
dhcps_set_dns(1, WiFi.dnsIP(1));
WiFi.softAPConfig( // enable AP, with android-compatible google domain
// IPAddress(172, 217, 28, 254),
// IPAddress(172, 217, 28, 254),
// IPAddress(255, 255, 255, 0));
WiFi.localIP(),IPAddress(192,168,0,1),IPAddress(255, 255, 255, 0));
WiFi.softAP(STASSID "extender", STAPSK); // odd way to concat strings
Serial.printf("AP: %s\n", WiFi.softAPIP().toString().c_str());
Serial.printf("Heap before: %d\n", ESP.getFreeHeap());
err_t ret = ip_napt_init(NAPT, NAPT_PORT);
Serial.printf("ip_napt_init(%d,%d): ret=%d (OK=%d)\n", NAPT, NAPT_PORT, (int)ret, (int)ERR_OK);
if (ret == ERR_OK) {
ret = ip_napt_enable_no(SOFTAP_IF, 1);
Serial.printf("ip_napt_enable_no(SOFTAP_IF): ret=%d (OK=%d)\n", (int)ret, (int)ERR_OK);
if (ret == ERR_OK) {
Serial.printf("WiFi Network '%s' with same password is now NATed behind '%s'\n", STASSID "extender", STASSID);
}
}
Serial.printf("Heap after napt init: %d\n", ESP.getFreeHeap());
if (ret != ERR_OK) {
Serial.printf("NAPT initialization failed\n");
}
}
#else
void setup() {
Serial.begin(115200);
Serial.printf("\n\nNAPT not supported in this configuration\n");
}
#endif
void loop() {
}
You can subnetting the routers network from nat devices onwords. So tree like network structure may form.
Let say your router is assigning 192.168.0.x/24 ip to your first hop devices then those devices could modify their access points network with 192.168.1.x/24 and so on upto the possible last hop.
To make it form dynamically on their own you may need to assign common ssid and password to all devices in that structure.
If you could able to achieve this then their may be chances of accessing individual devices from router.
Also you may get the idea of to what hop level individual device seats in network tree by their subnet ip.

FastCGI Handling multiple requests without a library

I would like to know how should I handle multiple requests with one instance of a program, by that I mean, a fcgi program is supposed to continue running after one request has been answered, the problem is, how do I know that the current request data inside the environment variables is not the one from the last request.
My idea is to use setenv to set the environment variables to NULL after parsing them so when they are not NULL it means that the server has set them to the values of the new request but I'm not sure if this is the way it is supposed to be done.
I know that there are libraries that handle this stuff and that it is safer to use those, but right now my objective is just to learn how fcgi works behind the libraries
It's not clear what do you mean by 'multiple requests' in your question.
Based on your description I assume that you expect that your FastCgi app is still alive after processing the first request and can handle another request.
But that's the nature of FastCgi: a single program/service is running in an 'infinite loop' and handle all incoming requests. It's guaranteed by the FastCGI design that the Request object (including all environment variables) are properly set.
The old CGI works in an opposite way: a new process (i.e. instance) of the CGI program is spawned on each request.
It's highly likely that you keen on concurrent requests. But that's still possible.
Unfortunately you haven't mentioned neither server type nor programming language nor OS which you work with.
It's really easy to find examples for handling concurrent requests on Unix systems in C/C++.
You've mentioned that you wouldn't like to use any libraries but I believe you have to use at least one which implements the FastCGI interface. The most commonly used is fcgiapp by Open Market.
Handling concurrent requests is achieved by the multi-threading technique which is called Locks.
I'm a 'Windows guy' so this is my example for WINAPI and C:
#define THREAD_COUNT 20
#define FAST_CGI_SOCKET ":9345"
#include <locale.h>
#include "fcgiapp.h"
CRITICAL_SECTION accept_mutex;
DWORD WINAPI requestHandler()
{
int code;
FCGX_Request request;
FCGX_InitRequest(&request, 0, 0);
for (;;)
{
EnterCriticalSection(&accept_mutex);
code = FCGX_Accept_r(&request);
LeaveCriticalSection(&accept_mutex);
if (code < 0) break;
// TODO handle request
FCGX_Finish_r(&request);
}
return 0;
}
void initFastCgi() {
FCGX_Init();
FCGX_OpenSocket(FAST_CGI_SOCKET, SOMAXCONN);
}
void startThreadsAndWait() {
int i;
HANDLE threads[THREAD_COUNT];
InitializeCriticalSection(&accept_mutex);
for (i = 0; i < THREAD_COUNT; i++) {
threads[i] = CreateThread(NULL, 0, &requestHandler, NULL, 0, NULL);
}
for (i = 0; i < THREAD_COUNT; i++) {
WaitForSingleObject(threads[i], INFINITE);
}
for (i = 0; i < THREAD_COUNT; i++) {
CloseHandle(threads[i]);
}
}
void appStart() {
setlocale(LC_ALL, "en_US.utf8");
initFastCgi();
}
void freeResources() {
}
void appFinish() {
freeResources();
}
int main(void)
{
appStart();
startThreadsAndWait();
appFinish();
return 0;
}
All the magic is around accept_mutex.
Hope that will help even if you use a different OS or a programming language

starting a process with exactly the same address structure as previous openning

Is it possible to start a process in windows with exactly the same address structure as the previous opening of the process?
To clarify the goal of this question I should mention that I use cheatengine (http://www.cheatengine.org/) to cheat some games! It includes several iterations to find a parameter (e.g. ammunition) and freeze it. However, each time I restart the game, since the memory structure of the game changes, I need to go through the time-consuming iterations again. So, if there were a method bring up the game exactly with the same memory structure as before, I wouldn't need going through iterations.
Not to say it's impossible, but this is essentially too much work due to the dynamic memory allocation routines the process will be using including the new operator and malloc(). Additionally when the DLL's imported by the executable are loaded into memory they have a preferred imagebase but if that address is already used, the OS will load it into a different memory location. Additionally Address Space Layout Randomization (ASLR) can be enabled on the process which is a security measure that randomizes the memory address of code sections.
The solution to your problem is much easier then what you're asking. To defeat the dynamic memory allocation described above you can still resolve the correct address of a variable by utilizing:
Relative offsets from module bases
Multi-level pointers
Pattern Scanning
Cheat Engine has all 3 of these built into it. When you save an address to your table is often saves it as a module + relative offset. You can pointer scan for the address and save it as a multilevel pointer or reverse the pointer yourself and manually place it in the table. Pattern scanning is achieved by using a CE Script, which you can put right in the Cheat Table.
In this case the ammo variable, may be a "static address" which means it's relative to the base address of the module. you may see it listed in Cheat Engine as "client.dll + 0xDEADCODE". You simply get the base address of the module at runtime and add the relative offset.
If you're looking to make an external hack in C++ you can get started like this.
In an external hack you do this by walking a ToolHelp32Snapshot:
uintptr_t GetModuleBase(const wchar_t * ModuleName, DWORD ProcessId) {
// This structure contains lots of goodies about a module
MODULEENTRY32 ModuleEntry = { 0 };
// Grab a snapshot of all the modules in the specified process
HANDLE SnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessId);
if (!SnapShot)
return NULL;
// You have to initialize the size, otherwise it will not work
ModuleEntry.dwSize = sizeof(ModuleEntry);
// Get the first module in the process
if (!Module32First(SnapShot, &ModuleEntry))
return NULL;
do {
// Check if the module name matches the one we're looking for
if (!wcscmp(ModuleEntry.szModule, ModuleName)) {
// If it does, close the snapshot handle and return the base address
CloseHandle(SnapShot);
return (DWORD)ModuleEntry.modBaseAddr;
}
// Grab the next module in the snapshot
} while (Module32Next(SnapShot, &ModuleEntry));
// We couldn't find the specified module, so return NULL
CloseHandle(SnapShot);
return NULL;
}
To get the Process ID you would do:
bool GetPid(const wchar_t* targetProcess, DWORD* procID)
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap && snap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First(snap, &pe))
{
do
{
if (!wcscmp(pe.szExeFile, targetProcess))
{
CloseHandle(snap);
*procID = pe.th32ProcessID;
return true;
}
} while (Process32Next(snap, &pe));
}
}
return false;
}
Using my example you would combine these functions and do:
DWORD procId;
GetPid(L"game.exe", &procId);
uintptr_t modBaseAddr = GetModuleBase(L"client.dll", procId);
uintptr_t ammoAddr = modBaseAddr + 0xDEADCODE;
If the address is not "static" you can find a pointer to it, the base address of the pointer must be static and then you just follow the above guide, and dereference each level of the pointer and add an offset.
Of course I have a function for that too :)
uintptr_t FindDmaAddy(HANDLE hProcHandle, uintptr_t BaseAddress, uintptr_t Offsets[], int PointerLevel)
{
uintptr_t pointer = BaseAddress;
uintptr_t pTemp;
uintptr_t pointerAddr;
for (int i = 0; i < PointerLevel; i++)
{
if (i == 0)
{
ReadProcessMemory(hProcHandle, (LPCVOID)pointer, &pTemp, sizeof(pTemp), NULL);
}
pointerAddr = pTemp + Offsets[i];
ReadProcessMemory(hProcHandle, (LPCVOID)pointerAddr, &pTemp, sizeof(pTemp), NULL);
}
return pointerAddr;
}
I would highly recommend watching some Youtube tutorials to see how it's done, much better explained in video format.

Reading memory protection

I would like to know if there is for linux a way of retrieving the protection of the memory. Like, I want to restore the protection that existed after changing it with mprotect.
Based on the answer by davidg, here's the function unsigned int read_mprotection(void* addr):
re_mprot.c, re_mprot.h from the reDroid project at github (the code works on Android, it should be portable to other linuxes).
The file /proc/self/maps on Linux contains information about the current layout of virtual memory, what each segment is and the memory protection of that segment. Changes made using mprotect will cause the file to be updated appropriately.
By parsing /proc/self/maps before you start modifying it with mprotect, you should have enough information to restore the previous layout.
The following example shows the contents of /proc/self/maps in three scenarios:
Prior to any operation being performed;
After a mmap (which shows one additional entry in the file); and finally
After a mprotect (which shows the permission bits changing in the file).
(Tested with 32-bit Linux 2.6).
#include <sys/mman.h>
#include <stdio.h>
#include <errno.h>
#define PAGE_SIZE 4096
void show_mappings(void)
{
int a;
FILE *f = fopen("/proc/self/maps", "r");
while ((a = fgetc(f)) >= 0)
putchar(a);
fclose(f);
printf("-----------------------------------------------\n");
}
int main(void)
{
void *mapping;
/* Show initial mappings. */
show_mappings();
/* Map in some pages. */
mapping = mmap(NULL, 16 * PAGE_SIZE, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
printf("*** Returned mapping: %p\n", mapping);
show_mappings();
/* Change the mapping. */
mprotect(mapping, PAGE_SIZE, PROT_READ | PROT_WRITE);
show_mappings();
return 0;
}
As far as I know, there is not mechanism other than the /proc/ interface that Linux provides to allow you to determine the layout of your virtual memory. Thus, parsing this file is about the best you can do.

Resources