21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

msg.msg_iov->iov_base = (void *)&sync;<br />

msg.msg_iov->iov_len = sizeof(sync);<br />

return (sendmsg(sd, &msg, 0) != -1);<br />

}<br />

On all platforms, it is possible to obtain credentials from a peer at any point during<br />

the connection; however, it often makes the most sense to get the information immediately<br />

after the connection is established. For example, if your server needs to get<br />

the credentials of each client that connects, the server code might look something<br />

like this:<br />

typedef void (*spc_client_fn)(spc_socket_t *, spc_credentials *, void *);<br />

void spc_unix_server(spc_client_fn callback, void *arg) {<br />

spc_socket_t *client, *listener;<br />

spc_credentials *credentials;<br />

listener = spc_socket_listen(SOCK_STREAM, 0, "127.0.0.1", 2222);<br />

while ((client = spc_socket_accept(listener)) != 0) {<br />

if (!(credentials = spc_get_credentials(client->sd))) {<br />

printf("Unable to get credentials from connecting client!\n");<br />

spc_socket_close(client);<br />

} else {<br />

printf("Client credentials:\n\tuid: %d\n\tgid: %d\n",<br />

SPC_PEER_UID(credentials), SPC_PEER_GID(credentials));<br />

/* do something with the credentials and the connection ... */<br />

callback(client, credentials, arg);<br />

}<br />

}<br />

}<br />

The corresponding client code might look something like this:<br />

spc_socket_t *spc_unix_connect(void) {<br />

spc_socket_t *conn;<br />

if (!(conn = spc_socket_connect("127.0.0.1", 2222))) {<br />

printf("Unable to connect to the server!\n");<br />

return 0;<br />

}<br />

if (!spc_send_credentials(conn->sd)) {<br />

printf("Unable to send credentials to the server!\n");<br />

spc_socket_close(conn);<br />

return 0;<br />

}<br />

printf("Credentials were successfully sent to the server.\n");<br />

return conn;<br />

}<br />

Note finally that while it is possible to obtain credentials from a peer at any point<br />

during the connection, many implementations will send the credentials only once. If<br />

you need the credential information at more than one point during a conversation,<br />

you should make sure to save the information that was obtained the first time it was<br />

needed.<br />

Performing Authentication with Unix Domain Sockets | 485<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!