21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Instead, you should use this code from a thread, or use the traditional Unix model,<br />

where you fork( ) off a new process for each client connection. Or you can simply<br />

rearrange the code so that you incrementally read data without blocking.<br />

unsigned char *spc_server_read(spc_ssock_t *ctx, size_t *len, size_t *end) {<br />

unsigned char nonce[SPC_CWC_NONCE_LEN], status;<br />

/* If it's the server's turn to speak, abort. We know it's the server's turn<br />

* to speak if the first byte of the nonce is the CLIENT distinguisher.<br />

*/<br />

if (ctx->nonce[0] != SPC_SERVER_DISTINGUISHER &&<br />

ctx->nonce[0] != SPC_SERVER_LACKS_NONCE) abort();<br />

spc_get_status_and_nonce(ctx->fd, &status, nonce);<br />

*end = status;<br />

/* If we need to do so, copy over the random bytes of the nonce. */<br />

if (ctx->nonce[0] == SPC_SERVER_LACKS_NONCE)<br />

memcpy(ctx->nonce + SPC_IV_IX, nonce + SPC_IV_IX, SPC_IV_LEN);<br />

/* Now, set the distinguisher field to client, and increment our copy of<br />

* the nonce.<br />

*/<br />

ctx->nonce[0] = SPC_CLIENT_DISTINGUISHER;<br />

spc_increment_counter(ctx->nonce + SPC_CTR_IX, SPC_CTR_LEN);<br />

return spc_finish_decryption(ctx, status, nonce, len);<br />

}<br />

Now we just need to handle the server-side sending of messages, which requires only<br />

a little bit of work:<br />

void spc_ssock_server_send(spc_ssock_t *ctx, unsigned char *msg, size_t mlen) {<br />

/* If it's not our turn to speak, abort. We know it's our turn if the client<br />

* spoke last.<br />

*/<br />

if (ctx->nonce[0] != SPC_CLIENT_DISTINGUISHER) abort();<br />

/* Set the distinguisher, but don't bump the counter, because we already did<br />

* when we received the message from the client.<br />

*/<br />

ctx->nonce[0] = SPC_SERVER_DISTINGUISHER;<br />

spc_base_send(ctx, msg, mlen);<br />

}<br />

There is one more potential issue that we should note. In some situations in which<br />

you’re going to be dealing with incredibly long messages, it does not make sense to<br />

have to know how much data is going to be in a message before you start to send it.<br />

Doing so will require buffering up large amounts of data, which might not always be<br />

possible, particularly in an embedded device.<br />

500 | Chapter 9: Networking<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!