How does one use mutually defined Streams in Idris? - idris

The issue I'm having may be more general than stated in the question. I'm trying to get the following program to work:
module Main
main: IO ()
process: Int -> Int
process req = req+1
server: Stream Int -> Stream Int
client: Int -> Stream Int -> Stream Int
server (req :: reqs) = process req :: server reqs
client initreq (resp :: resps) = initreq :: client resp resps
mutual
reqsOut: Stream Int
respsOut: Stream Int
-- This fixes the segfault:
-- reqsOut = cycle [1, 2, 3, 4]
reqsOut = client 0 respsOut
respsOut = server reqsOut
main = do
printLn(take 5 reqsOut)
It will run if I swap out the definition of reqsOut with the commented version, but generates a segmentation fault as is. My guess is I'm using mutual incorrectly, but I'm not sure how.

Note that in function call the arguments gets evaluated beforehand, in particular case splits. Here in client the stream gets case splitted with client initreq (req :: reqs), so respsOut in client 0 respsOut gets evaluated before the delayed tail:
reqsOut =
client 0 respsOut =
client 0 (case respsOut of (req :: reqs) => ...) =
client 0 (case (server regsOut) of (req :: regs) => ...) =
...
You can delay the split with
client initreq stream = initreq :: client (head stream) (tail stream)
But then you'd still have the infinite loop through server:
reqsOut =
client 0 respsOut =
client 0 (server regsOut) =
client 0 (case regsOut of (req :: reqs) => ...) =
...
You can delay the computation of respsOut by making the argument Lazy:
client : Int -> Lazy (Stream Int) -> Stream Int
client initreq stream = initreq :: client (head stream) (tail stream)
And now client can finally construct a Stream Int without evaluating its arguments:
client 0 respsOut =
0 :: Delay (client (head (Force respsOut)) (tail (Force respsOut))) : Stream int

Related

Winsock2, BitCoin Select() returns data to read, Recv() returns 0 bytes

I made a connection to BitCoin node via WinSock2. I sent the proper "getaddr" message and then the server responds, the replied data are ready to read, because Select() notifies this, but when I call Recv() there are 0 bytes read.
My code is working OK on localhost test server. The incomplete "getaddr" message (less than 24 bytes) is NOT replied by BitCoin node, only proper message, but I can't read the reply with Recv(). After returning 0 bytes, the Select() still returns there are data to read.
My code is divided into DLL which uses Winsock2 and the main() function.
Here are key fragments:
struct CMessageHeader
{
uint32_t magic;
char command[12];
uint32_t payload;
uint32_t checksum;
};
CSocket *sock = new CSocket();
int actual; /* Actually read/written bytes */
sock->connect("109.173.41.43", 8333);
CMessageHeader msg = { 0xf9beb4d9, "getaddr\0\0\0\0", 0, 0x5df6e0e2 }, rcv = { 0 };
actual = sock->send((const char *)&msg, sizeof(msg));
actual = sock->select(2, 0); /* Select read with 2 seconds waiting time */
actual = sock->receive((char *)&rcv, sizeof(rcv));
The key fragment of DLL code:
int CSocket::receive(char *buf, int len)
{
int actual;
if ((actual = ::recv(sock, buf, len, 0)) == SOCKET_ERROR) {
std::ostringstream s;
s << "Nie mozna odebrac " << len << " bajtow.";
throw(CError(s));
}
return(actual);
}
If select() reports the socket is readable, and then recv() returns 0 afterwards, that means the peer gracefully closed the connection on their end (ie, sent a FIN packet to you), so you need to close your socket.
On a side note, recv() can return fewer bytes than requested, so your receive() function should call recv() in a loop until all of the expected bytes have actually been received, or an error occurs (same with send(), too).

How get session key from ssl session

I created client and server program to exchange the data.
Client and server uses tls to pass the message securely.
Used openssl to make the connection between server and client.
Now i have the ssl handle.
Is there any way to extract server write key, server random, client random,client write key, master key.
in the below code sample Servlet method will connect to the client do the handshake get the session keys.
i am trying to read the tls packet from the port after tls handshake completed and pass the packet to another module.
To check the for malformed or invalid packets i need to decrypt the packet to inspect the payload where i required the session keys.
Is there any way to extract server write key, server random, client random,client write key, master key.
code snippet:
main(){
// Initialize the SSL library
SSL_library_init();
portnum = Argc[1];
ctx = InitServerCTX(); /* initialize SSL */
LoadCertificates(ctx, "mycert.pem", "mycert.pem"); /* load certs */
server = OpenListener(atoi(portnum)); /* create server socket */
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
Servlet()
{
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
unsigned char key[100];
//SSL_SESSION_get_master_key(ssl,key,100);
//printf("masterkey:%s", key);
ShowCerts(ssl); /* get any certificates */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
buf[bytes] = '\0';
printf("Client msg: \"%s\"\n", buf);
if ( bytes > 0 )
{
if(strcmp(cpValidMessage,buf) == 0)
{
SSL_write(ssl, ServerResponse, strlen(ServerResponse)); /*
send reply */
}

How to read client certificate in polarssl?

How to read client certificate from server side using mbedtls(polarssl)?
I had a server that was coded using mbedtls(polarssl). I want to read the client certificate and fetch some information from that certificate. Can anyone know what function will be used to read client certificate?
I think you could use mbedtls_x509_crt_info which returns an informational string about the certificate.
You can get the peer certificate from the ssl session when the client connects and then print the info out.
mbedtls_ssl_context ssl;
...
mbedtls_x509_crt *crt = ssl.session->peer_cert;
unsigned char buf[1024];
int ret = mbedtls_x509_crt_info((char *) buf, sizeof( buf ) - 1, "", crt);
if( ret != -1 )
{
mbedtls_printf( "%s\n", buf );
}
I didn't test this, just checked the examples.

Does netlink use 'broadcast' for passing messages?

I am following netlink example on this question and answer.
But, I don't see a sort of connection identifier in source codes. Say:
Kernel
my_nl_sock = netlink_kernel_create(&init_net, NETLINK_USERSOCK, 0,
my_nl_rcv_msg, NULL, THIS_MODULE);
User space
nls = nl_socket_alloc();
ret = nl_connect(nls, NETLINK_USERSOCK);
ret = nl_send_simple(nls, MY_MSG_TYPE, 0, msg, sizeof(msg));
where NETLINK_USERSOCK and MY_MSG_TYPE don't seem to be a connection identifier.
In such a case, how does netlink know which data comes from which user space app or kernel module and which user space app or kernel module the data should go?
In my guess, netlink receives data from user space app or kernel module and broadcasts it. And every netlink-connected app or module checks message type if data is destined to 'me'
Is what I think right?
Firstly, I recommend to read some doc, for example http://www.linuxfoundation.org/collaborate/workgroups/networking/generic_netlink_howto
To communicate you have to register a family with supported operations. It can be done with the following functions
int genl_register_family( struct genl_family *family)
int genl_register_ops( struct genl_family * family, struct genl_ops *ops)
An example of a family definition:
/*
* Attributes (variables): the index in this enum is used as a reference for the type,
* userspace application has to indicate the corresponding type
*/
enum {
CTRL_ATT_R_UNSPEC = 0,
CTRL_ATT_CNT_SESSIONS,
__CTRL_ATT_R_MAX
};
#define CTRL_ATT_R_MAX ( __CTRL_ATT_R_MAX - 1 )
#define CTRL_FAMILY "your-family"
#define CTRL_PROTO_VERSION 1
/* Family definition */
static struct genl_family ctrl_bin_gnl_family = {
.id = GENL_ID_GENERATE, // genetlink should generate an id
.hdrsize = 0,
.name = CTRL_FAMILY, // the name of this family, used by userspace application
.version = CTRL_PROTO_VERSION, // version number
.maxattr = CTRL_ATT_R_MAX, // max number of attr
};
An example of an operation definition:
struct genl_ops ctrl_info = {
.cmd = CTRL_CMD_INFO,
.flags = 0,
.policy = 0, // you can use policy if you need
.doit = 0, // set this callback if this op does some interval stuff
.dumpit = __info, // set this callback if this op dump data
};
After that you can use in your userspace app your family and operations to communicate. Make a connection:
struct nl_sock * _nl = nl_socket_alloc();
int ret = genl_connect(nl);
// test if fail
int gid = genl_ctrl_resolve( nl, CTRL_FAMILY );
// test if fail
Send info operation
struct nl_msg * msg = msg_alloc(
CTRL_CMD_INFO,
NLM_F_DUMP
);
int ret = nl_send_auto(_nl, msg );
// test if fail
// wait for the ack
// read a reply

How to receive message from 'any' channel in PROMELA/SPIN

I'm modeling an algorithm in Spin.
I have a process that has several channels and at some point, I know a message is going to come but don't know from which channel. So want to wait (block) the process until it a message comes from any of the channels. how can I do that?
I think you need Promela's if construct (see http://spinroot.com/spin/Man/if.html).
In the process you're referring to, you probably need the following:
byte var;
if
:: ch1?var -> skip
:: ch2?var -> skip
:: ch3?var -> skip
fi
If none of the channels have anything on them, then "the selection construct as a whole blocks" (quoting the manual), which is exactly the behaviour you want.
To quote the relevant part of the manual more fully:
"An option [each of the :: lines] can be selected for execution only when its guard statement is executable [the guard statement is the part before the ->]. If more than one guard statement is executable, one of them will be selected non-deterministically. If none of the guards are executable, the selection construct as a whole blocks."
By the way, I haven't syntax checked or simulated the above in Spin. Hopefully it's right. I'm quite new to Promela and Spin myself.
If you want to have your number of channels variable without having to change the implementation of the send and receive parts, you might use the approach of the following producer-consumer example:
#define NUMCHAN 4
chan channels[NUMCHAN];
init {
chan ch1 = [1] of { byte };
chan ch2 = [1] of { byte };
chan ch3 = [1] of { byte };
chan ch4 = [1] of { byte };
channels[0] = ch1;
channels[1] = ch2;
channels[2] = ch3;
channels[3] = ch4;
// Add further channels above, in
// accordance with NUMCHAN
// First let the producer write
// something, then start the consumer
run producer();
atomic { _nr_pr == 1 ->
run consumer();
}
}
proctype consumer() {
byte var, i;
chan theChan;
i = 0;
do
:: i == NUMCHAN -> break
:: else ->
theChan = channels[i];
if
:: skip // non-deterministic skip
:: nempty(theChan) ->
theChan ? var;
printf("Read value %d from channel %d\n", var, i+1)
fi;
i++
od
}
proctype producer() {
byte var, i;
chan theChan;
i = 0;
do
:: i == NUMCHAN -> break
:: else ->
theChan = channels[i];
if
:: skip;
:: theChan ! 1;
printf("Write value 1 to channel %d\n", i+1)
fi;
i++
od
}
The do loop in the consumer process non-deterministically chooses an index between 0 and NUMCHAN-1 and reads from the respective channel, if there is something to read, else this channel is always skipped. Naturally, during a simulation with Spin the probability to read from channel NUMCHAN is much smaller than that of channel 0, but this does not make any difference in model checking, where any possible path is explored.