SSL_do_handshake() get stuck - c

in my code i call SSL_do_handshake() function.
Everything works fine if the server gets the "right" messages.
BUT, for security issues I tried sending a dummy message. just "hello" to the right port and the right ip address.
in this case, SSL_do_handshake() gets stuck forever.
I want the function to return in that case, so that my server will not get stuck.
What are the options ?
I read about setting bio to non-blocking..
I added to my code :
BIO_set_nbio(bio, 1); before the connection is established..
but it didn't do thew work...
What can I do ?

BIO_set_nbio sets only the flag, that the bio should be considered non-blocking. You have to actually make the socket itself non-blocking.

Related

EVFILT_WRITE returning twice

I'm trying to send a buffer to my socket client when the file descriptor is available for writing.
EV_SET is set to: EVFILT_WRITE, EV_ADD | EV_DISABLE | EV_CLEAR
then when changed to EVFILT_WRITE, EV_ENABLE then EVFILT_WRITE get triggered once which is great!
but if i use the function write or send when i get EVFILT_WRITE like this:
if (e->filter == EVFILT_WRITE)
send(socket, buff, strlen(buff), 0);
then i get again another EVFILT_WRITE event. It seems like the send function trigger another EVFILT_WRITE event. is that expected behaviour? I thought EVFILT_WRITE triggers only when the file descriptor is available for writing.
I searched for the issue, but it looks like nobody mention that. Can someone please confirm if that is expected behaviour and why?
This is how I understand it:
Since you used EV_CLEAR, the kevent facility starts to return state transitions, not the current state. So, whenever you touch the socket descriptor with kevent() or send() calls, you get an EVFILT_WRITE event back.
Another way to look at this:
When send() is called the descriptor becomes unavailable for writing for a moment and then again becomes available, which is why you get an event.
I'll try to loop in some knowledgeable people to this question.

send() before recv()

i have two projects: one is a client and one is a server.
lets say the server as to send 2 messages one after the other to the client.
the client code is like this:
while(1)
{
recv(acceptedStr, socket);
printf("%s\n, acceptedStr);
*other code lines*
}
while the server code is like this:
while(1)
{
send(socket, "First String");
send(socket, "Second String");
*other code lines*
}
if there is no TIME_OUT for the second send, will the recv of the client get "Second String"? or does he have to make sure that he is in a recv before the server send?
No, the receiving end does not need to have an recv active for the send to work.
Once a connection is established, the data is buffered by the OS network stack. And recv will succeed once data has arrived and send will succeed if the data was delivered to the network stack of the receiver.
Answer to your question
Yes, That is enough and your code will work. But if you want to extend it more, or if the server and the client need to be at sync at all times, do continue reading.
Sync of server and client
Do read this if you want synchronous operations of server and client.
I have previously worked with send and recv and one thing that I would suggest you is that you always alternate the recv and send in complementary ways. As an example
Server:
send()
recv()
send()
.
.
.
Client:
recv()
send()
recv()
.
.
.
This usually gets tiring to keep track of. (I think the return send from a entity on recv is called ack).
But, at some point you would like to turn the flow of events. For this, you can just send and recv some random data.
I had previously written a wrapper around send and recv for a project of mine. Feel free to check it out: https://github.com/ArenaGrenade/Simple-FTP-Server/blob/main/utils.cpp. (Its pretty well documented, so even if you did not understand my explanation you would understand the one in code.)
Let me know if you understood by marking mine as an answer. Happy to help! If you have doubts just comment below. :)
The client does receive the Second String, but it does not work as you think it should.
I created the client and server through the two official samples:Complete Winsock Client Code and Complete Winsock Server Code
I modified the sample so that the server only sends data and the client only receives data.
When I try to send data twice in a row, the client will receive the following content:
You can see that the client does receive Second String, but because you keep sending these two data, it will cause problems in the picture.
Because the data is being sent continuously, the client will also receive the data sent multiple times at one time, and save them to the same buffer, although only part of it is displayed (because it is truncated by'\0'), but It can be seen from the size of the buffer that the data sent multiple times is received at one time.And the content received later will be unpredictable

How does socketIO handle the functions I give to him?

It's a project including angularJs, nodeJs and mongoDb.
I have this client side code :
webSocket.emit('createNode', node, function(node){
/* ^ */
/* Where does this goes ? */
$scope.nodes.push(node);
});
And this server side code :
socket.on('createNode', function(node, callback) {
/* ^ */
/* Where does this comes from ? */
mongo.connect("mongodb://localhost:27017/test", function(err, db) {
db.collection('nodes').insertOne(node, function(error, data){
callback(node);
});
});
});
I want to know how does socketIo do to run the function I gave him and how can I execute a piece of code after an emit success without calling it explicitly server-side.
It's the so called acknowledgement. You can check the docs here: http://socket.io/docs/#sending-and-getting-data-(acknowledgements).
It's very simple idea - when you emit something from the client, the client saves your acknowledgment callback and maps it to your specific emit call. "emit createNode - function() {}". Then it sends the info to the server and marks that this emit needs callback. When the server calls it, it's not actually calling the function on the client, it's just internally saying to socket "okay send back the acknowledgment".
Socket.IO actually makes another emit back from the server and because it's marked as acknowledgment, the client treats it like so. It browses the map it has created and calls the function that was stored previously.
It's all done internally so that you don't write logic for waiting for that callback - it's all under the hood for you.
Back to your last question - "how can I execute a piece of code after an emit success". There is no such a thing as "emit success". The client does not know if the emit reached the server or what has happened there. Sockets are simply a channel that sends information - they do not care what's going on next. That's the way it's built.
If you need to know if server got your command, you must send back that information to the client. Which means, in terms of Socket.IO, that you should use those acknowledgments and explicitly notify about success.
But don't be afraid of that - explicitly does NOT mean you are calling client side function, it's just notifying client that all went well and command was received. This approach is very powerful as you can pass params about the result of the command, stating if it was valid or not, if the result is success or not. So go ahead, give it a try :)

Help with Select?

So i'm trying to make a server that listens on multiple ports.
I'm having trouble getting my head around select.
Could someone give me a little bit of pseudo code around the order I do things and why.
I get that i bind two separate sockets to different ports. Sure. But then can I just call listen on both ports?
On my client(s), do i just call connect, and listen will notice the connection attempt? How do i choose to accept it?
Sorry for the novice questions. I've tried beejs guide and a few others, but they don't really cover multiple ports very well (they all seem to use the same example).
Thanks!
After calling bind and listen on the server, the fd for the socket is just another fd that you can use with the select call. When select returns and indicates data on that fd, you can call accept on the fd to begin receiving data.
Edit: Also, the fd you receive when you accept the connection is another fd that can be passed to the select call.
Client Side:
you need only to call the connect.
Server side the steps are more or less the following:
create the socket
Bind the socket
Start listening
Add file descriptor of the listening socket to the select
When the select return on the listening socket then call the accept function upon it. It will return another file descriptor(remember to add this new file descriptor to the list of the FD for which the select has to return through FD_SET)

Can I Send to Socket and receive from it in the same place in C

I have a dll written in C.
I would like to send data to a socket and receive the answer in the same function.
e.g.:
BOOL SendToSocketAndRecv(...)
{
// ...
send(...);
retval = recv(...);
// ...
}
In another word, my dll should not follow Client Server pattren.
Is this possible ?
any help ?
Thank you - Khayralla
Yes
You may work in either blocking (synchronous) or non-blocking (asynchronous) mode. Depending on this you may or may not send more data before you receive something from the peer.
"Stream" sockets (like TCP) are "tunnels". If the peer sends several packets you may receive them in a single call to recv, and vice-versa - a sinle "message" from the peer may take several calls to recv. Hence you should read the message in a loop.
You have a lot to learn about network programming.
I am sending a commands to Robot and then wait to get answer
Yes, what you have will work.
But things start to get interesting when you factor in the chance that the robot will not respond for whatever reason. Then you need to provide for a timeout on the response. Soon other things start to creep in. For example, you may not want to be stuck in the read for the duration of the wait, because you may need to service other events (user input or other sources) as they comes in.
A common architecture to handle this is to use select() and make it the hub of all your incoming events. Then you drive a state machine (or machines) off these events. You end up with an event driven architecture. It would look something like this:
while(true)
{
select(fds for event sources, timeout);
if (timeout)
{
call robot state machine(timeout);
continue;
}
iterate through fds
{
if (fd has data)
{
read data into buf
if (fd is for robot)
{
call robot state machine(buf)
}
else if (fd is for source1)
{
call source1 state machine(buf)
}
...
}
}
}
In this model, sends can be done from anywhere in the code. But you wind up sitting in the select() after, waiting for events. Also, you will have to figure out the details of doing the correct timeout and select in general, but there is enough of that out there.
Yes this is both possible and legal. The API itself isn't concerned about being used from the same function.
not only is this possible, it is a classic coding idiom for a client in a client server system. Usually the function is called something like ExecuteRequest

Resources