Can't get redis connector to work with g-wan - c

Did all the hiredis installation
defaulting to make make install etc
Result running g-wan:
Linking hellox.c: undefined symbol: redisConnect
online says linking lib is wrong? how to fix this?

Read how to link libraries with G-WAN. Even with GCC you need to tell the linker what library is in use. G-WAN is not different.

Here my script working on my server :
#include "gwan.h" // G-WAN API
#pragma link "hiredis"
#include "hiredis/hiredis.h"
typedef struct
{
redisContext *rCont;
redisReply *rReply;
} data_t;
int main(int argc, char *argv[])
{
data_t **d = (data_t**)get_env(argv, US_SERVER_DATA);
xbuf_t *reply = get_reply(argv);
u64 start = getus();
const char *hostname = "127.0.0.1";
int port = 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
if(!d[0]) // first time: persistent pointer is uninitialized
{
d[0] = (data_t*)calloc(1, sizeof(data_t));
if(!d[0])
return 500; // out of memory
d[0]->rCont = redisConnectWithTimeout(hostname, port, timeout);
}
d[0]->rReply = redisCommand(d[0]->rCont,"PING");
xbuf_xcat(get_reply(argv), "PING %s<br>", d[0]->rReply->str);
freeReplyObject(d[0]->rReply);
xbuf_xcat(get_reply(argv), "<hr>%llu µs<hr>", getus() - start);
return 200;
}
You have to get hiredis compiled and copied into your lib directory.

Related

Raspberry Pi serdev driver never reaches probe function

I want to write a minimal serdev Linux driver on a Raspberry Pi. Therefore I have to enable the kernel option SERIAL_DEV_CTRL_TTYPORT, but I don't know how. I have tried various options, but my Kernel Module never reaches the Probe function...
Here is what I got already:
I tried to enable the option by changing the /boot/cmdline.txt to:
SERIAL_DEV_CTRL_TTYPORT SERIAL_DEV_CTRL_TTYPORT=y SERIAL_DEV_CTRL_TTYPORT=yes root=PARTUUID=8d696e29-02 rootfstype=ext4 fsck.repair=yes rootwait modules-load=dwc2,g_ether
The device tree overlay:
/dts-v1/;
/plugin/;
/ {
compatible = "brcm,bcm2835";
fragment#0 {
target = <&uart0>;
status = "okay";
__overlay__ {
my_device {
compatible = "brightlight,echodev";
status = "okay";
};
};
};
};
The Kernel Module:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/serdev.h>
#include <linux/mod_devicetable.h>
#include <linux/property.h>
#include <linux/platform_device.h>
#include <linux/of_device.h>
/* Meta Information */
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Johannes 4 GNU/Linux");
MODULE_DESCRIPTION("A simple serdev example");
/* Declate the probe and remove functions */
static int dt_probe(struct serdev_device *serdev);
static void dt_remove(struct serdev_device *serdev);
static struct of_device_id my_driver_ids[] = {
{
.compatible = "brightlight,echodev",
}, { /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, my_driver_ids);
static struct serdev_device_driver my_driver = {
.probe = dt_probe,
.remove = dt_remove,
.driver = {
.name = "echodev",
.of_match_table = my_driver_ids,
},
};
/**
* #brief This function is called on loading the driver
*/
static int dt_probe(struct serdev_device *serdev) {
printk("my_serdev - Now I am in the probe function!");
return 0;
}
/**
* #brief This function is called on unloading the driver
*/
static void dt_remove(struct serdev_device *serdev) {
printk("my_serdev - Now I am in the remove function\n");
}
module_serdev_device_driver(my_driver);
Do you have any tips?
UPDATE 1:
I checked my Kernel .config file and found out, that CONFIG_SERIAL_DEV_CTRL_TTYPORT is already set and enabled. I double checked it with
pi#raspberrypi:~ $ sudo modprobe configs
pi#raspberrypi:~ $ gzip -d /proc/config.gz --stdout | grep SERIAL_DEV
CONFIG_SERIAL_DEV_BUS=y
CONFIG_SERIAL_DEV_CTRL_TTYPORT=y
But then, why does my module never reaches the probe function???
Best regards,
Johannes
Ok, I got it, but I don't know exactly why it is working know.
When posting this example, I used dtoverlay to load the device tree overlay:
sudo dtoverlay testoverlay.dtbo
When doing so, I couldn't reach the probe function. Then I copied my overlay to /boot/overlays and added it to /boot/config.txt:
dtoverlay=testoverlay
And after a reboot, I inserted my kernel module and it reached the probe function. Does anyone know why this works now but not before?

How to intercept storage size query commands

I am developing a file system using libfuse and need to find a way to intercept calls for storage size querying, i.e. du and df.
But I have been unable to identify how to this and unable to find an example that showcase this.
Looking at the debug output from my filesystem, doesn't give much information either, as I am unsure which call I should intercept.
For the df you can implement the statfs() operation, something like this:
static int do_statfs(const char *path, struct statvfs *st)
{
int rv;
rv = statvfs("/", st);
st->f_bavail = 15717083;
return rv;
}
In the example above, just to simplify, I query the root filesystem, than modify blocks available, but you can (and should) feel the complete statvfs structure with the information regarding your filesystem.
Now for the du, the man says: "Summarize disk usage of each FILE, recursively for directories", so every file will be queried. For this you need to implement the stat() operation.
static int do_getattr(const char *path, struct stat *st)
{
st->st_uid = getuid();
st->st_gid = getgid();
st->st_atime = time(NULL);
st->st_mtime = time(NULL);
// fill the rest of the stat structure
return 0;
}
Once those are implemented you have to add them do fuse_operations structure:
static struct fuse_operations operations = {
.open = do_open,
.getattr = do_getattr,
.readdir = do_readdir,
.read = do_read,
.statfs = do_statfs,
.release = do_release,
};
and pass it as a parameter to the fuse_main()
int main(int argc, char *argv[])
{
return fuse_main(argc, argv, &operations, NULL);
}

SGX Enclave: Where the actual function that does the procession goes and how it gets compiled

After reading lots of documentation i did the first simple enclave function:
enclave {
//Include files
//Import other edl files
//Data structure declarations to be used as parameters of the
//function prototypes in edl
trusted {
public function myFirstMethod([in] int *a, [in] int *b,[out] int *sum);
};
untrusted {
};
};
Then over bash I run the edger8r:
sgx_edger8r enclave.edl
Then it generated the following files as you can see over the schema:
So I assume somewhere over the enclave_t.c the only reference I found is in this function:
static sgx_status_t SGX_CDECL sgx_myFirstMethod(void* pms)
{
CHECK_REF_POINTER(pms, sizeof(ms_myFirstMethod_t));
ms_myFirstMethod_t* ms = SGX_CAST(ms_myFirstMethod_t*, pms);
sgx_status_t status = SGX_SUCCESS;
int* _tmp_a = ms->ms_a;
size_t _len_a = sizeof(*_tmp_a);
int* _in_a = NULL;
int* _tmp_b = ms->ms_b;
size_t _len_b = sizeof(*_tmp_b);
int* _in_b = NULL;
CHECK_UNIQUE_POINTER(_tmp_a, _len_a);
CHECK_UNIQUE_POINTER(_tmp_b, _len_b);
if (_tmp_a != NULL) {
_in_a = (int*)malloc(_len_a);
if (_in_a == NULL) {
status = SGX_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(_in_a, _tmp_a, _len_a);
}
if (_tmp_b != NULL) {
_in_b = (int*)malloc(_len_b);
if (_in_b == NULL) {
status = SGX_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(_in_b, _tmp_b, _len_b);
}
ms->ms_retval = myFirstMethod(_in_a, _in_b);
err:
if (_in_a) free(_in_a);
if (_in_b) free(_in_b);
return status;
}
Especially in
ms->ms_retval = myFirstMethod(_in_a, _in_b);
But where to put the myFirstMethod? Also how I will compile my enclave as a part of an application as a static library.
As fas as I searched is the tutorial in theese links:
https://software.intel.com/en-us/articles/intel-software-guard-extensions-developing-a-sample-enclave-application
https://software.intel.com/en-us/sgx/code-samples
All mention Visual Studio that does not natively run over GNU/Linux so are a bit hard for me to follow.
Edit 1:
Further looking I have seen on https://github.com/01org/linux-sgx that I can compile over simulation mode as the link mentions:
make SGX_MODE=SIM
And I successfully I have installed the driver and the sdk. I want to compile over SIMULATION mode and not real one.
The autogenerated outputs of edger8r are only to provide interface between the enclave and the untrusted outside world. They are not supposed to contain your implementations.
You should define myFirstMethod in another source file, say enclave.c or enclave.cpp and link it with the rest of your project. The signature of the function being exactly what you declared in your edl, except for the pointer qualifiers, which are for edger8r to consume.
It will go like this:
enclave.cpp:
void myFirstMethod(int *a, int *b, int *sum)
{
*sum = *a + *b;
}
Dimitris first check if you have compatible hardware from this list
https://github.com/ayeks/SGX-hardware
Then try to clone an run this repo
https://github.com/digawp/hello-enclave
That will help you understand how it works

Segmentation fault 11 in following code. How to avoid overflow?

void main(int argc, char* argv[]) {
char* hostname = (char*)malloc(sizeof(char)*1024);
hostname = getClientHostName("122.205.26.34");
printf("%s\n", hostname);
free(hostname);
}
char* getClientHostName(char* client_ip) {
char hostnames[5][2];
hostnames[0][0] = "122.205.26.34";
hostnames[0][1] = "aaaaa";
hostnames[1][0] = "120.205.36.30";
hostnames[1][1] = "bbbbb";
hostnames[2][0] = "120.205.16.36";
hostnames[2][1] = "ccccc";
hostnames[3][0] = "149.205.36.46";
hostnames[3][1] = "dddddd";
hostnames[4][0] = "169.205.36.33";
hostnames[4][1] = "eeeeee";
for(int i = 0; i<5; i++) {
if(!strcmp(hostnames[i][0], client_ip))
return (char*)hostnames[i][1];
}
return NULL;
}
Beginner in C.
I am not sure if there would be a better way to implement what I am trying to implement. The code is self-explanatory. Is there any way that I can predefine the size of hostname, using some general size of IP addresses, to avoid seg fault? Is there a even better way where I don't have to hardcode the size?
After fixing the compiler errors and warnings you get:
const char* getClientHostName(const char* client_ip) {
const char * hostnames[5][2];
hostnames[0][0] = "122.205.26.34";
hostnames[0][1] = "aaaaa";
hostnames[1][0] = "120.205.36.30";
hostnames[1][1] = "bbbbb";
hostnames[2][0] = "120.205.16.36";
hostnames[2][1] = "ccccc";
hostnames[3][0] = "149.205.36.46";
hostnames[3][1] = "dddddd";
hostnames[4][0] = "169.205.36.33";
hostnames[4][1] = "eeeeee";
for(int i = 0; i<5; i++) {
if(!strcmp(hostnames[i][0], client_ip))
return hostnames[i][1];
}
return NULL;
}
int main(int argc, char* argv[]) {
const char * hostname = getClientHostName("128.205.36.34");
printf("%s\n", hostname);
}
Is there a even better way where I don't have to hardcode the size?
Take the habit to compile with all warnings and debug info: gcc -Wall -Wextra -g with GCC. Improve the code to get no warnings at all.
If you want to get genuine IP addresses, this is operating system specific (since standard C11 don't know about IP addresses; check by reading n1570). On Linux you would use name service routines such as getaddrinfo(3) & getnameinfo(3) or the obsolete gethostbyname(3).
If this is just an exercise without actual relationship to TCP/IP sockets (see tcp(7), ip(7), socket(7)) you could store the table in some global array:
struct myipentry_st {
const char* myip_hostname;
const char* myip_address;
};
then define a global array containing them, with the convention of terminating it by some {NULL, NULL} entry:
const struct myipentry_st mytable[] = {
{"aaaaa", "122.205.26.34"},
{"bbbb", "120.205.36.30"},
/// etc
{NULL, NULL} // end marker
};
You'll better have a global or static variable (not an automatic one sitting on the call stack) because you don't want to fill it on every call to your getClientHostName.
Then your lookup routine (inefficient, since in linear time) would be:
const char* getClientHostName(char* client_ip) {
for (const struct myipentry_st* ent = mytable;
ent->myip_hostname != NULL;
ent++)
// the if below is the only statement of the body of `for` loop
if (!strcmp(ent->myip_address, client_ip))
return ent->myip_hostname;
// this happens after the `for` when nothing was found
return NULL;
}
You could even declare that table as a heap allocated pointer:
const struct myipentry_st**mytable;
then use calloc to allocate it and read its data from some text file.
Read the documentation of every standard or external function that you are using. Don't forget to check against failure (e.g. of calloc, like here). Avoid memory leaks by appropriate calls to free. Use the debugger gdb and valgrind. Beware of undefined behavior.
In the real world, you would have perhaps thousands of entries and you would perform the lookup many times (perhaps millions of times, e.g. once per every HTTP request in a web server or client). Then choose a better data structure (hash table or red-black tree perhaps). Read some Introduction to Algorithms.
Add * to type definition char * hostnames[5][2]. This must be array of pointers, not simple chars. Another necessary change is strcpy instead of = in strcpy( hostname, getClientHostName("122.205.26.34") );.
PS: Always try to compile with 0 compiler warnings, not only 0 errors!

Compile Lua script to unsigned char buffer

Im working on a server in C that dynamically generating Lua commands on the fly and send them by socket to the clients. Right now the server is using plain text, but I would like the server to pre-compile the script before sending it to the clients.
I check luac.c but couldn't find how to be able to do something like this:
char lua_commands[ 1024 ] = { "a = 123; b = 456; c = a + b;" };
int socket
unsigned int send_buffer_size
unsigned char *send_buffer
/* Compile lua_commands and store the binary script into send_buffer without
having to write first the .out on disk then read it again in order store the content
into send_buffer */
send( socket, send_buffer, send_buffer_size, 0 );
Anybody can help me to achieve this?
[ Update ]
Ok, I think I figure it out:
#include "lua.h"
#include "lauxlib.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lstring.h"
#include "lundump.h"
#define toproto(L,i) (clvalue(L->top+(i))->l.p)
static int writer( lua_State *L, const void *p, size_t size, void *u ){
unsigned int i = 0;
unsigned char *d = ( unsigned char * )p;
// Print all the bytes on the console.
while( i != size ) {
printf("%d ", d[ i ] );
++i;
}
return 0;
}
void compile( lua_State *L, char *command ){
const Proto* f;
if (luaL_loadstring( L, command ) !=0 ) {
printf( "%s\n", lua_tostring( L, -1 ) );
}
f = toproto( L,-1 );
lua_lock( L );
luaU_dump( L, f, writer, NULL, 1 );
lua_unlock( L );
}
int main (int argc, const char * argv[]) {
lua_State *L = lua_open();
compile( L, "a = 123; b = 456; c = a + b; print( c );" );
lua_close( L );
return 0;
}
However that leads me to another question, do I have to close and reopen (lua_open, lua_close) the Lua state every time I'm calling my compile() function with other Lua commands or the output will only be the result of the latest luaL_loadstring?
Im not sure but look to me from the toproto macro definition that the top most stack will be returned am I correct?
You should use lua_dump() instead of internal toproto() + luaU_dump() functions. As an added bonus, this way your code will support LuaJIT 2.
It is not necessary to recreate the state each time you get the dump.
BUT. I would avoid executing Lua bytecode that came from the untrusted source (and server often is untrusted to the client). It is not safe, and may lead to severe security issues. (No such problems with source code — but you still have to sandbox it, of course.)
In general, always make sure that you check that the code you load from untrusted source is not bytecode (it is, if first byte is 27 decimal). Always execute such code in a sandbox.
If all that you need is to pass data in Lua-friendly way, pick some proper data serialization library instead. Aside of sandboxing and portability problems, loadstring() is rather slow.
For example, we're using using my luatexts library for similar purposes (make sure to pore through this list for alternatives). Luatexts supports tuples, which plays nicely with function calls. For example (in pseudocode):
Server:
my_send(luatexts.lua.save("myMethod", { param = true }, 42))
Client:
local actions = { }
function actions.myMethod(params, number)
print(params.param, number) --> true, 42
end
local function handle_action(ok, name, ...)
assert(ok, name) -- name would contain error message if not OK
local handler = assert(actions[name], "unknown action")
return handler(...)
end
local str = my_receive()
handle_action(luatexts.load(str))
Open a ticket if you want luatexts.save or streaming support implemented in C.

Resources