Update writev
[m6w6/libmemcached] / libmemcached / sasl.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * Libmemcached library
4 *
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 * Copyright (C) 2006-2009 Brian Aker All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following disclaimer
17 * in the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * The names of its contributors may not be used to endorse or
21 * promote products derived from this software without specific prior
22 * written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 *
36 */
37
38 #include <libmemcached/common.h>
39 #include <cassert>
40
41 #if defined(LIBMEMCACHED_WITH_SASL_SUPPORT) && LIBMEMCACHED_WITH_SASL_SUPPORT
42
43 #if defined(HAVE_LIBSASL) && HAVE_LIBSASL
44 #include <sasl/sasl.h>
45 #endif
46
47 #include <pthread.h>
48
49 void memcached_set_sasl_callbacks(memcached_st *ptr,
50 const sasl_callback_t *callbacks)
51 {
52 ptr->sasl.callbacks= const_cast<sasl_callback_t *>(callbacks);
53 ptr->sasl.is_allocated= false;
54 }
55
56 sasl_callback_t *memcached_get_sasl_callbacks(memcached_st *ptr)
57 {
58 return ptr->sasl.callbacks;
59 }
60
61 /**
62 * Resolve the names for both ends of a connection
63 * @param fd socket to check
64 * @param laddr local address (out)
65 * @param raddr remote address (out)
66 * @return true on success false otherwise (errno contains more info)
67 */
68 static memcached_return_t resolve_names(memcached_server_st& server, char *laddr, size_t laddr_length, char *raddr, size_t raddr_length)
69 {
70 char host[NI_MAXHOST];
71 char port[NI_MAXSERV];
72 struct sockaddr_storage saddr;
73 socklen_t salen= sizeof(saddr);
74
75 if (getsockname(server.fd, (struct sockaddr *)&saddr, &salen) < 0)
76 {
77 return memcached_set_errno(server, MEMCACHED_ERRNO, MEMCACHED_AT);
78 }
79
80 if (getnameinfo((struct sockaddr *)&saddr, salen, host, sizeof(host), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
81 {
82 return MEMCACHED_HOST_LOOKUP_FAILURE;
83 }
84
85 (void)snprintf(laddr, laddr_length, "%s;%s", host, port);
86 salen= sizeof(saddr);
87
88 if (getpeername(server.fd, (struct sockaddr *)&saddr, &salen) < 0)
89 {
90 return memcached_set_errno(server, MEMCACHED_ERRNO, MEMCACHED_AT);
91 }
92
93 if (getnameinfo((struct sockaddr *)&saddr, salen, host, sizeof(host),
94 port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
95 {
96 return memcached_set_error(server, MEMCACHED_HOST_LOOKUP_FAILURE, MEMCACHED_AT);
97 }
98
99 (void)snprintf(raddr, raddr_length, "%s;%s", host, port);
100
101 return MEMCACHED_SUCCESS;
102 }
103
104 extern "C" {
105
106 static void sasl_shutdown_function()
107 {
108 sasl_done();
109 }
110
111 static volatile int sasl_startup_state= SASL_OK;
112 pthread_mutex_t sasl_startup_state_LOCK= PTHREAD_MUTEX_INITIALIZER;
113 static pthread_once_t sasl_startup_once= PTHREAD_ONCE_INIT;
114 static void sasl_startup_function(void)
115 {
116 sasl_startup_state= sasl_client_init(NULL);
117
118 if (sasl_startup_state == SASL_OK)
119 {
120 (void)atexit(sasl_shutdown_function);
121 }
122 }
123
124 } // extern "C"
125
126 memcached_return_t memcached_sasl_authenticate_connection(memcached_server_st *server)
127 {
128 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
129 {
130 return MEMCACHED_NOT_SUPPORTED;
131 }
132
133 if (server == NULL)
134 {
135 return MEMCACHED_INVALID_ARGUMENTS;
136 }
137
138 /* SANITY CHECK: SASL can only be used with the binary protocol */
139 if (memcached_is_binary(server->root) == false)
140 {
141 return memcached_set_error(*server, MEMCACHED_INVALID_ARGUMENTS, MEMCACHED_AT,
142 memcached_literal_param("memcached_sasl_authenticate_connection() is not supported via the ASCII protocol"));
143 }
144
145 /* Try to get the supported mech from the server. Servers without SASL
146 * support will return UNKNOWN COMMAND, so we can just treat that
147 * as authenticated
148 */
149 protocol_binary_request_no_extras request= { };
150 request.message.header.request.magic= PROTOCOL_BINARY_REQ;
151 request.message.header.request.opcode= PROTOCOL_BINARY_CMD_SASL_LIST_MECHS;
152
153 if (memcached_io_write(server, request.bytes,
154 sizeof(request.bytes), 1) != sizeof(request.bytes))
155 {
156 return MEMCACHED_WRITE_FAILURE;
157 }
158
159 memcached_server_response_increment(server);
160
161 char mech[MEMCACHED_MAX_BUFFER];
162 memcached_return_t rc= memcached_response(server, mech, sizeof(mech), NULL);
163 if (memcached_failed(rc))
164 {
165 if (rc == MEMCACHED_PROTOCOL_ERROR)
166 {
167 /* If the server doesn't support SASL it will return PROTOCOL_ERROR.
168 * This error may also be returned for other errors, but let's assume
169 * that the server don't support SASL and treat it as success and
170 * let the client fail with the next operation if the error was
171 * caused by another problem....
172 */
173 rc= MEMCACHED_SUCCESS;
174 }
175
176 return rc;
177 }
178
179 /* set ip addresses */
180 char laddr[NI_MAXHOST + NI_MAXSERV];
181 char raddr[NI_MAXHOST + NI_MAXSERV];
182
183 if (memcached_failed(rc= resolve_names(*server, laddr, sizeof(laddr), raddr, sizeof(raddr))))
184 {
185 return rc;
186 }
187
188 int pthread_error;
189 if ((pthread_error= pthread_once(&sasl_startup_once, sasl_startup_function)) != 0)
190 {
191 return memcached_set_errno(*server, pthread_error, MEMCACHED_AT);
192 }
193
194 (void)pthread_mutex_lock(&sasl_startup_state_LOCK);
195 if (sasl_startup_state != SASL_OK)
196 {
197 const char *sasl_error_msg= sasl_errstring(sasl_startup_state, NULL, NULL);
198 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
199 memcached_string_make_from_cstr(sasl_error_msg));
200 }
201 (void)pthread_mutex_unlock(&sasl_startup_state_LOCK);
202
203 sasl_conn_t *conn;
204 int ret;
205 if ((ret= sasl_client_new("memcached", server->hostname, laddr, raddr, server->root->sasl.callbacks, 0, &conn) ) != SASL_OK)
206 {
207 const char *sasl_error_msg= sasl_errstring(ret, NULL, NULL);
208
209 sasl_dispose(&conn);
210
211 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
212 memcached_string_make_from_cstr(sasl_error_msg));
213 }
214
215 const char *data;
216 const char *chosenmech;
217 unsigned int len;
218 ret= sasl_client_start(conn, mech, NULL, &data, &len, &chosenmech);
219 if (ret != SASL_OK and ret != SASL_CONTINUE)
220 {
221 const char *sasl_error_msg= sasl_errstring(ret, NULL, NULL);
222
223 sasl_dispose(&conn);
224
225 return memcached_set_error(*server, MEMCACHED_AUTH_PROBLEM, MEMCACHED_AT,
226 memcached_string_make_from_cstr(sasl_error_msg));
227 }
228 uint16_t keylen= (uint16_t)strlen(chosenmech);
229 request.message.header.request.opcode= PROTOCOL_BINARY_CMD_SASL_AUTH;
230 request.message.header.request.keylen= htons(keylen);
231 request.message.header.request.bodylen= htonl(len + keylen);
232
233 do {
234 /* send the packet */
235
236 libmemcached_io_vector_st vector[]=
237 {
238 { request.bytes, sizeof(request.bytes) },
239 { chosenmech, keylen },
240 { data, len }
241 };
242
243 if (memcached_io_writev(server, vector, 3, true) == false)
244 {
245 rc= MEMCACHED_WRITE_FAILURE;
246 break;
247 }
248 memcached_server_response_increment(server);
249
250 /* read the response */
251 rc= memcached_response(server, NULL, 0, NULL);
252 if (rc != MEMCACHED_AUTH_CONTINUE)
253 {
254 break;
255 }
256
257 ret= sasl_client_step(conn, memcached_result_value(&server->root->result),
258 (unsigned int)memcached_result_length(&server->root->result),
259 NULL, &data, &len);
260
261 if (ret != SASL_OK && ret != SASL_CONTINUE)
262 {
263 rc= MEMCACHED_AUTH_PROBLEM;
264 break;
265 }
266
267 request.message.header.request.opcode= PROTOCOL_BINARY_CMD_SASL_STEP;
268 request.message.header.request.bodylen= htonl(len + keylen);
269 } while (true);
270
271 /* Release resources */
272 sasl_dispose(&conn);
273
274 return memcached_set_error(*server, rc, MEMCACHED_AT);
275 }
276
277 static int get_username(void *context, int id, const char **result, unsigned int *len)
278 {
279 if (!context || !result || (id != SASL_CB_USER && id != SASL_CB_AUTHNAME))
280 {
281 return SASL_BADPARAM;
282 }
283
284 *result= (char *)context;
285 if (len)
286 {
287 *len= (unsigned int)strlen(*result);
288 }
289
290 return SASL_OK;
291 }
292
293 static int get_password(sasl_conn_t *conn, void *context, int id,
294 sasl_secret_t **psecret)
295 {
296 if (!conn || ! psecret || id != SASL_CB_PASS)
297 {
298 return SASL_BADPARAM;
299 }
300
301 *psecret= (sasl_secret_t *)context;
302
303 return SASL_OK;
304 }
305
306 memcached_return_t memcached_set_sasl_auth_data(memcached_st *ptr,
307 const char *username,
308 const char *password)
309 {
310 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
311 {
312 return MEMCACHED_NOT_SUPPORTED;
313 }
314
315 if (ptr == NULL or username == NULL or password == NULL)
316 {
317 return MEMCACHED_INVALID_ARGUMENTS;
318 }
319
320 memcached_return_t ret;
321 if (memcached_failed(ret= memcached_behavior_set(ptr, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1)))
322 {
323 return memcached_set_error(*ptr, ret, MEMCACHED_AT, memcached_literal_param("Unable change to binary protocol which is required for SASL."));
324 }
325
326 memcached_destroy_sasl_auth_data(ptr);
327
328 sasl_callback_t *callbacks= libmemcached_xcalloc(ptr, 4, sasl_callback_t);
329 size_t password_length= strlen(password);
330 size_t username_length= strlen(username);
331 char *name= (char *)libmemcached_malloc(ptr, username_length +1);
332 sasl_secret_t *secret= (sasl_secret_t*)libmemcached_malloc(ptr, password_length +1 + sizeof(sasl_secret_t));
333
334 if (callbacks == NULL or name == NULL or secret == NULL)
335 {
336 libmemcached_free(ptr, callbacks);
337 libmemcached_free(ptr, name);
338 libmemcached_free(ptr, secret);
339 return memcached_set_error(*ptr, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT);
340 }
341
342 secret->len= password_length;
343 memcpy(secret->data, password, password_length);
344 secret->data[password_length]= 0;
345
346 callbacks[0].id= SASL_CB_USER;
347 callbacks[0].proc= (int (*)())get_username;
348 callbacks[0].context= strncpy(name, username, username_length +1);
349 callbacks[1].id= SASL_CB_AUTHNAME;
350 callbacks[1].proc= (int (*)())get_username;
351 callbacks[1].context= name;
352 callbacks[2].id= SASL_CB_PASS;
353 callbacks[2].proc= (int (*)())get_password;
354 callbacks[2].context= secret;
355 callbacks[3].id= SASL_CB_LIST_END;
356
357 ptr->sasl.callbacks= callbacks;
358 ptr->sasl.is_allocated= true;
359
360 return MEMCACHED_SUCCESS;
361 }
362
363 memcached_return_t memcached_destroy_sasl_auth_data(memcached_st *ptr)
364 {
365 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
366 {
367 return MEMCACHED_NOT_SUPPORTED;
368 }
369
370 if (ptr == NULL)
371 {
372 return MEMCACHED_INVALID_ARGUMENTS;
373 }
374
375 if (ptr->sasl.callbacks == NULL)
376 {
377 return MEMCACHED_SUCCESS;
378 }
379
380 if (ptr->sasl.is_allocated)
381 {
382 libmemcached_free(ptr, ptr->sasl.callbacks[0].context);
383 libmemcached_free(ptr, ptr->sasl.callbacks[2].context);
384 libmemcached_free(ptr, (void*)ptr->sasl.callbacks);
385 ptr->sasl.is_allocated= false;
386 }
387
388 ptr->sasl.callbacks= NULL;
389
390 return MEMCACHED_SUCCESS;
391 }
392
393 memcached_return_t memcached_clone_sasl(memcached_st *clone, const memcached_st *source)
394 {
395 if (LIBMEMCACHED_WITH_SASL_SUPPORT == 0)
396 {
397 return MEMCACHED_NOT_SUPPORTED;
398 }
399
400 if (clone == NULL or source == NULL)
401 {
402 return MEMCACHED_INVALID_ARGUMENTS;
403 }
404
405 if (source->sasl.callbacks == NULL)
406 {
407 return MEMCACHED_SUCCESS;
408 }
409
410 /* Hopefully we are using our own callback mechanisms.. */
411 if (source->sasl.callbacks[0].id == SASL_CB_USER &&
412 source->sasl.callbacks[0].proc == (int (*)())get_username &&
413 source->sasl.callbacks[1].id == SASL_CB_AUTHNAME &&
414 source->sasl.callbacks[1].proc == (int (*)())get_username &&
415 source->sasl.callbacks[2].id == SASL_CB_PASS &&
416 source->sasl.callbacks[2].proc == (int (*)())get_password &&
417 source->sasl.callbacks[3].id == SASL_CB_LIST_END)
418 {
419 sasl_secret_t *secret= (sasl_secret_t *)source->sasl.callbacks[2].context;
420 return memcached_set_sasl_auth_data(clone,
421 (const char*)source->sasl.callbacks[0].context,
422 (const char*)secret->data);
423 }
424
425 /*
426 * But we're not. It may work if we know what the user tries to pass
427 * into the list, but if we don't know the ID we don't know how to handle
428 * the context...
429 */
430 ptrdiff_t total= 0;
431
432 while (source->sasl.callbacks[total].id != SASL_CB_LIST_END)
433 {
434 switch (source->sasl.callbacks[total].id)
435 {
436 case SASL_CB_USER:
437 case SASL_CB_AUTHNAME:
438 case SASL_CB_PASS:
439 break;
440 default:
441 /* I don't know how to deal with this... */
442 return MEMCACHED_NOT_SUPPORTED;
443 }
444
445 ++total;
446 }
447
448 sasl_callback_t *callbacks= libmemcached_xcalloc(clone, total +1, sasl_callback_t);
449 if (callbacks == NULL)
450 {
451 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
452 }
453 memcpy(callbacks, source->sasl.callbacks, (total + 1) * sizeof(sasl_callback_t));
454
455 /* Now update the context... */
456 for (ptrdiff_t x= 0; x < total; ++x)
457 {
458 if (callbacks[x].id == SASL_CB_USER || callbacks[x].id == SASL_CB_AUTHNAME)
459 {
460 callbacks[x].context= (sasl_callback_t*)libmemcached_malloc(clone, strlen((const char*)source->sasl.callbacks[x].context));
461
462 if (callbacks[x].context == NULL)
463 {
464 /* Failed to allocate memory, clean up previously allocated memory */
465 for (ptrdiff_t y= 0; y < x; ++y)
466 {
467 libmemcached_free(clone, clone->sasl.callbacks[y].context);
468 }
469
470 libmemcached_free(clone, callbacks);
471 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
472 }
473 strncpy((char*)callbacks[x].context, (const char*)source->sasl.callbacks[x].context, sizeof(callbacks[x].context));
474 }
475 else
476 {
477 sasl_secret_t *src= (sasl_secret_t *)source->sasl.callbacks[x].context;
478 sasl_secret_t *n= (sasl_secret_t*)libmemcached_malloc(clone, src->len + 1 + sizeof(*n));
479 if (n == NULL)
480 {
481 /* Failed to allocate memory, clean up previously allocated memory */
482 for (ptrdiff_t y= 0; y < x; ++y)
483 {
484 libmemcached_free(clone, clone->sasl.callbacks[y].context);
485 }
486
487 libmemcached_free(clone, callbacks);
488 return MEMCACHED_MEMORY_ALLOCATION_FAILURE;
489 }
490 memcpy(n, src, src->len + 1 + sizeof(*n));
491 callbacks[x].context= n;
492 }
493 }
494
495 clone->sasl.callbacks= callbacks;
496 clone->sasl.is_allocated= true;
497
498 return MEMCACHED_SUCCESS;
499 }
500
501 #else
502
503 void memcached_set_sasl_callbacks(memcached_st *, const sasl_callback_t *)
504 {
505 }
506
507 sasl_callback_t *memcached_get_sasl_callbacks(memcached_st *)
508 {
509 return NULL;
510 }
511
512 memcached_return_t memcached_set_sasl_auth_data(memcached_st *, const char *, const char *)
513 {
514 return MEMCACHED_NOT_SUPPORTED;
515 }
516
517 memcached_return_t memcached_clone_sasl(memcached_st *, const memcached_st *)
518 {
519 return MEMCACHED_NOT_SUPPORTED;
520 }
521
522 #endif