Debian Codegraph @

lib/krb5/send_to_kdc.c

raw
1 /*
2 * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
5 *
6 * Portions Copyright (c) 2010 - 2013 Apple Inc. 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
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * 3. Neither the name of the Institute nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include "krb5_locl.h"
37 #include "send_to_kdc_plugin.h"
38
39 /**
40 * @section send_to_kdc Locating and sending packets to the KDC
41 *
42 * The send to kdc code is responsible to request the list of KDC from
43 * the locate-kdc subsystem and then send requests to each of them.
44 *
45 * - Each second a new hostname is tried.
46 * - If the hostname have several addresses, the first will be tried
47 * directly then in turn the other will be tried every 3 seconds
48 * (host_timeout).
49 * - UDP requests are tried 3 times, and it tried with a individual timeout of kdc_timeout / 3.
50 * - TCP and HTTP requests are tried 1 time.
51 *
52 * Total wait time shorter then (number of addresses * 3) + kdc_timeout seconds.
53 *
54 */
55
56 static int
57 init_port(const char *s, int fallback)
58 {
59 int tmp;
60
61 if (s && sscanf(s, "%d", &tmp) == 1)
62 return htons(tmp);
63 return fallback;
64 }
65
66 struct send_via_plugin_s {
67 krb5_const_realm realm;
68 krb5_krbhst_info *hi;
69 time_t timeout;
70 const krb5_data *send_data;
71 krb5_data *receive;
72 };
73
74
75 static krb5_error_code KRB5_LIB_CALL
76 kdccallback(krb5_context context, const void *plug, void *plugctx, void *userctx)
77 {
78 const krb5plugin_send_to_kdc_ftable *service = (const krb5plugin_send_to_kdc_ftable *)plug;
79 struct send_via_plugin_s *ctx = userctx;
80
81 if (service->send_to_kdc == NULL)
82 return KRB5_PLUGIN_NO_HANDLE;
83 return service->send_to_kdc(context, plugctx, ctx->hi, ctx->timeout,
84 ctx->send_data, ctx->receive);
85 }
86
87 static krb5_error_code KRB5_LIB_CALL
88 realmcallback(krb5_context context, const void *plug, void *plugctx, void *userctx)
89 {
90 const krb5plugin_send_to_kdc_ftable *service = (const krb5plugin_send_to_kdc_ftable *)plug;
91 struct send_via_plugin_s *ctx = userctx;
92
93 if (service->send_to_realm == NULL)
94 return KRB5_PLUGIN_NO_HANDLE;
95 return service->send_to_realm(context, plugctx, ctx->realm, ctx->timeout,
96 ctx->send_data, ctx->receive);
97 }
98
99 static krb5_error_code
100 kdc_via_plugin(krb5_context context,
101 krb5_krbhst_info *hi,
102 time_t timeout,
103 const krb5_data *send_data,
104 krb5_data *receive)
105 {
106 struct send_via_plugin_s userctx;
107
108 userctx.realm = NULL;
109 userctx.hi = hi;
110 userctx.timeout = timeout;
111 userctx.send_data = send_data;
112 userctx.receive = receive;
113
114 return _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_SEND_TO_KDC,
115 KRB5_PLUGIN_SEND_TO_KDC_VERSION_0, 0,
116 &userctx, kdccallback);
117 }
118
119 static krb5_error_code
120 realm_via_plugin(krb5_context context,
121 krb5_const_realm realm,
122 time_t timeout,
123 const krb5_data *send_data,
124 krb5_data *receive)
125 {
126 struct send_via_plugin_s userctx;
127
128 userctx.realm = realm;
129 userctx.hi = NULL;
130 userctx.timeout = timeout;
131 userctx.send_data = send_data;
132 userctx.receive = receive;
133
134 return _krb5_plugin_run_f(context, "krb5", KRB5_PLUGIN_SEND_TO_KDC,
135 KRB5_PLUGIN_SEND_TO_KDC_VERSION_2, 0,
136 &userctx, realmcallback);
137 }
138
139 struct krb5_sendto_ctx_data {
140 int flags;
141 int type;
142 krb5_sendto_ctx_func func;
143 void *data;
144 char *hostname;
145 krb5_krbhst_handle krbhst;
146
147 /* context2 */
148 const krb5_data *send_data;
149 krb5_data response;
150 heim_array_t hosts;
151 int stateflags;
152 #define KRBHST_COMPLETED 1
153
154 /* prexmit */
155 krb5_sendto_prexmit prexmit_func;
156 void *prexmit_ctx;
157
158 /* stats */
159 struct {
160 struct timeval start_time;
161 struct timeval name_resolution;
162 struct timeval krbhst;
163 unsigned long sent_packets;
164 unsigned long num_hosts;
165 } stats;
166 unsigned int stid;
167 };
168
169 static void
170 dealloc_sendto_ctx(void *ptr)
171 {
172 krb5_sendto_ctx ctx = (krb5_sendto_ctx)ptr;
173 if (ctx->hostname)
174 free(ctx->hostname);
175 heim_release(ctx->hosts);
176 heim_release(ctx->krbhst);
177 }
178
179 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
180 krb5_sendto_ctx_alloc(krb5_context context, krb5_sendto_ctx *ctx)
181 {
182 *ctx = heim_alloc(sizeof(**ctx), "sendto-context", dealloc_sendto_ctx);
183 if (*ctx == NULL)
184 return krb5_enomem(context);
185 (*ctx)->hosts = heim_array_create();
186
187 return 0;
188 }
189
190 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
191 krb5_sendto_ctx_add_flags(krb5_sendto_ctx ctx, int flags)
192 {
193 ctx->flags |= flags;
194 }
195
196 KRB5_LIB_FUNCTION int KRB5_LIB_CALL
197 krb5_sendto_ctx_get_flags(krb5_sendto_ctx ctx)
198 {
199 return ctx->flags;
200 }
201
202 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
203 krb5_sendto_ctx_set_type(krb5_sendto_ctx ctx, int type)
204 {
205 ctx->type = type;
206 }
207
208 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
209 krb5_sendto_ctx_set_func(krb5_sendto_ctx ctx,
210 krb5_sendto_ctx_func func,
211 void *data)
212 {
213 ctx->func = func;
214 ctx->data = data;
215 }
216
217 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
218 _krb5_sendto_ctx_set_prexmit(krb5_sendto_ctx ctx,
219 krb5_sendto_prexmit prexmit,
220 void *data)
221 {
222 ctx->prexmit_func = prexmit;
223 ctx->prexmit_ctx = data;
224 }
225
226 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
227 krb5_sendto_set_hostname(krb5_context context,
228 krb5_sendto_ctx ctx,
229 const char *hostname)
230 {
231 if (ctx->hostname == NULL)
232 free(ctx->hostname);
233 ctx->hostname = strdup(hostname);
234 if (ctx->hostname == NULL) {
235 krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
236 return ENOMEM;
237 }
238 return 0;
239 }
240
241 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
242 _krb5_sendto_ctx_set_krb5hst(krb5_context context,
243 krb5_sendto_ctx ctx,
244 krb5_krbhst_handle handle)
245 {
246 heim_release(ctx->krbhst);
247 ctx->krbhst = heim_retain(handle);
248 }
249
250 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
251 krb5_sendto_ctx_free(krb5_context context, krb5_sendto_ctx ctx)
252 {
253 heim_release(ctx);
254 }
255
256 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
257 _krb5_kdc_retry(krb5_context context, krb5_sendto_ctx ctx, void *data,
258 const krb5_data *reply, int *action)
259 {
260 krb5_error_code ret;
261 KRB_ERROR error;
262
263 if(krb5_rd_error(context, reply, &error))
264 return 0;
265
266 ret = krb5_error_from_rd_error(context, &error, NULL);
267 krb5_free_error_contents(context, &error);
268
269 switch(ret) {
270 case KRB5KRB_ERR_RESPONSE_TOO_BIG: {
271 if (krb5_sendto_ctx_get_flags(ctx) & KRB5_KRBHST_FLAGS_LARGE_MSG)
272 break;
273 krb5_sendto_ctx_add_flags(ctx, KRB5_KRBHST_FLAGS_LARGE_MSG);
274 *action = KRB5_SENDTO_RESET;
275 break;
276 }
277 case KRB5KDC_ERR_SVC_UNAVAILABLE:
278 *action = KRB5_SENDTO_CONTINUE;
279 break;
280 }
281 return 0;
282 }
283
284 /*
285 *
286 */
287
288 struct host;
289
290 struct host_fun {
291 krb5_error_code (*prepare)(krb5_context, struct host *, const krb5_data *);
292 krb5_error_code (*send_fn)(krb5_context, struct host *);
293 krb5_error_code (*recv_fn)(krb5_context, struct host *, krb5_data *);
294 int ntries;
295 };
296
297 struct host {
298 enum host_state { CONNECT, CONNECTING, CONNECTED, WAITING_REPLY, DEAD } state;
299 krb5_krbhst_info *hi;
300 struct addrinfo *ai;
301 rk_socket_t fd;
302 struct host_fun *fun;
303 unsigned int tries;
304 time_t timeout;
305 krb5_data data;
306 unsigned int tid;
307 };
308
309 static void
310 debug_host(krb5_context context, int level, struct host *host, const char *fmt, ...)
311 __attribute__ ((__format__ (__printf__, 4, 5)));
312
313 static void
314 debug_host(krb5_context context, int level, struct host *host, const char *fmt, ...)
315 {
316 const char *proto = "unknown";
317 const char *state;
318 char name[NI_MAXHOST], port[NI_MAXSERV];
319 char *text = NULL;
320 va_list ap;
321 int ret;
322
323 if (!_krb5_have_debug(context, 5))
324 return;
325
326 va_start(ap, fmt);
327 ret = vasprintf(&text, fmt, ap);
328 va_end(ap);
329 if (ret == -1 || text == NULL)
330 return;
331
332 if (host->hi->proto == KRB5_KRBHST_HTTP)
333 proto = "http";
334 else if (host->hi->proto == KRB5_KRBHST_TCP)
335 proto = "tcp";
336 else if (host->hi->proto == KRB5_KRBHST_UDP)
337 proto = "udp";
338
339 if (getnameinfo(host->ai->ai_addr, host->ai->ai_addrlen,
340 name, sizeof(name), port, sizeof(port), NI_NUMERICHOST) != 0)
341 name[0] = '\0';
342
343 switch (host->state) {
344 case CONNECT: state = "CONNECT"; break;
345 case CONNECTING: state = "CONNECTING"; break;
346 case CONNECTED: state = "CONNECTED"; break;
347 case WAITING_REPLY: state = "WAITING_REPLY"; break;
348 case DEAD: state = "DEAD"; break;
349 default: state = "unknown"; break;
350 }
351
352 _krb5_debug(context, level, "%s: %s %s:%s (%s) state=%s tid: %08x", text,
353 proto, name, port, host->hi->hostname, state, host->tid);
354 free(text);
355 }
356
357
358 static void
359 deallocate_host(void *ptr)
360 {
361 struct host *host = ptr;
362 if (!rk_IS_BAD_SOCKET(host->fd))
363 rk_closesocket(host->fd);
364 krb5_data_free(&host->data);
365 host->ai = NULL;
366 }
367
368 static void
369 host_dead(krb5_context context, struct host *host, const char *msg)
370 {
371 debug_host(context, 5, host, "%s", msg);
372 rk_closesocket(host->fd);
373 host->fd = rk_INVALID_SOCKET;
374 host->state = DEAD;
375 }
376
377 static krb5_error_code
378 send_stream(krb5_context context, struct host *host)
379 {
380 ssize_t len;
381
382 len = krb5_net_write(context, &host->fd, host->data.data, host->data.length);
383
384 if (len < 0)
385 return errno;
386 else if (len < host->data.length) {
387 host->data.length -= len;
388 memmove(host->data.data, ((uint8_t *)host->data.data) + len, host->data.length - len);
389 return -1;
390 } else {
391 krb5_data_free(&host->data);
392 return 0;
393 }
394 }
395
396 static krb5_error_code
397 recv_stream(krb5_context context, struct host *host)
398 {
399 krb5_error_code ret;
400 size_t oldlen;
401 ssize_t sret;
402 int nbytes;
403
404 if (rk_SOCK_IOCTL(host->fd, FIONREAD, &nbytes) != 0 || nbytes <= 0)
405 return HEIM_NET_CONN_REFUSED;
406
407 if (context->max_msg_size - host->data.length < nbytes) {
408 krb5_set_error_message(context, KRB5KRB_ERR_FIELD_TOOLONG,
409 N_("TCP message from KDC too large %d", ""),
410 (int)(host->data.length + nbytes));
411 return KRB5KRB_ERR_FIELD_TOOLONG;
412 }
413
414 oldlen = host->data.length;
415
416 ret = krb5_data_realloc(&host->data, oldlen + nbytes + 1 /* NUL */);
417 if (ret)
418 return ret;
419
420 sret = krb5_net_read(context, &host->fd, ((uint8_t *)host->data.data) + oldlen, nbytes);
421 if (sret <= 0) {
422 ret = errno;
423 return ret;
424 }
425 host->data.length = oldlen + sret;
426 /* zero terminate for http transport */
427 ((uint8_t *)host->data.data)[host->data.length] = '\0';
428
429 return 0;
430 }
431
432 /*
433 *
434 */
435
436 static void
437 host_next_timeout(krb5_context context, struct host *host)
438 {
439 host->timeout = context->kdc_timeout / host->fun->ntries;
440 if (host->timeout == 0)
441 host->timeout = 1;
442
443 host->timeout += time(NULL);
444 }
445
446 /*
447 * connected host
448 */
449
450 static void
451 host_connected(krb5_context context, krb5_sendto_ctx ctx, struct host *host)
452 {
453 krb5_error_code ret;
454
455 host->state = CONNECTED;
456 /*
457 * Now prepare data to send to host
458 */
459 if (ctx->prexmit_func) {
460 krb5_data data;
461
462 krb5_data_zero(&data);
463
464 ret = ctx->prexmit_func(context, host->hi->proto,
465 ctx->prexmit_ctx, host->fd, &data);
466 if (ret == 0) {
467 if (data.length == 0) {
468 host_dead(context, host, "prexmit function didn't send data");
469 return;
470 }
471 ret = host->fun->prepare(context, host, &data);
472 krb5_data_free(&data);
473 }
474
475 } else {
476 ret = host->fun->prepare(context, host, ctx->send_data);
477 }
478 if (ret)
479 debug_host(context, 5, host, "failed to prexmit/prepare");
480 }
481
482 /*
483 * connect host
484 */
485
486 static void
487 host_connect(krb5_context context, krb5_sendto_ctx ctx, struct host *host)
488 {
489 krb5_krbhst_info *hi = host->hi;
490 struct addrinfo *ai = host->ai;
491
492 debug_host(context, 5, host, "connecting to host");
493
494 if (connect(host->fd, ai->ai_addr, ai->ai_addrlen) < 0) {
495 #ifdef HAVE_WINSOCK
496 if (WSAGetLastError() == WSAEWOULDBLOCK)
497 errno = EINPROGRESS;
498 #endif /* HAVE_WINSOCK */
499 if (errno == EINPROGRESS && (hi->proto == KRB5_KRBHST_HTTP || hi->proto == KRB5_KRBHST_TCP)) {
500 debug_host(context, 5, host, "connecting to %d", host->fd);
501 host->state = CONNECTING;
502 } else {
503 host_dead(context, host, "failed to connect");
504 }
505 } else {
506 host_connected(context, ctx, host);
507 }
508
509 host_next_timeout(context, host);
510 }
511
512 /*
513 * HTTP transport
514 */
515
516 static krb5_error_code
517 prepare_http(krb5_context context, struct host *host, const krb5_data *data)
518 {
519 char *str = NULL, *request = NULL;
520 krb5_error_code ret;
521 int len;
522
523 heim_assert(host->data.length == 0, "prepare_http called twice");
524
525 len = rk_base64_encode(data->data, data->length, &str);
526 if(len < 0)
527 return ENOMEM;
528
529 if (context->http_proxy)
530 ret = asprintf(&request, "GET http://%s/%s HTTP/1.0\r\n\r\n", host->hi->hostname, str);
531 else
532 ret = asprintf(&request, "GET /%s HTTP/1.0\r\n\r\n", str);
533 free(str);
534 if(ret < 0 || request == NULL)
535 return ENOMEM;
536
537 host->data.data = request;
538 host->data.length = strlen(request);
539
540 return 0;
541 }
542
543 static krb5_error_code
544 recv_http(krb5_context context, struct host *host, krb5_data *data)
545 {
546 krb5_error_code ret;
547 unsigned long rep_len;
548 size_t len;
549 char *p;
550
551 /*
552 * recv_stream returns a NUL terminated stream
553 */
554
555 ret = recv_stream(context, host);
556 if (ret)
557 return ret;
558
559 p = strstr(host->data.data, "\r\n\r\n");
560 if (p == NULL)
561 return -1;
562 p += 4;
563
564 len = host->data.length - (p - (char *)host->data.data);
565 if (len < 4)
566 return -1;
567
568 _krb5_get_int(p, &rep_len, 4);
569 if (len < rep_len)
570 return -1;
571
572 p += 4;
573
574 memmove(host->data.data, p, rep_len);
575 host->data.length = rep_len;
576
577 *data = host->data;
578 krb5_data_zero(&host->data);
579
580 return 0;
581 }
582
583 /*
584 * TCP transport
585 */
586
587 static krb5_error_code
588 prepare_tcp(krb5_context context, struct host *host, const krb5_data *data)
589 {
590 krb5_error_code ret;
591 krb5_storage *sp;
592
593 heim_assert(host->data.length == 0, "prepare_tcp called twice");
594
595 sp = krb5_storage_emem();
596 if (sp == NULL)
597 return ENOMEM;
598
599 ret = krb5_store_data(sp, *data);
600 if (ret) {
601 krb5_storage_free(sp);
602 return ret;
603 }
604 ret = krb5_storage_to_data(sp, &host->data);
605 krb5_storage_free(sp);
606
607 return ret;
608 }
609
610 static krb5_error_code
611 recv_tcp(krb5_context context, struct host *host, krb5_data *data)
612 {
613 krb5_error_code ret;
614 unsigned long pktlen;
615
616 ret = recv_stream(context, host);
617 if (ret)
618 return ret;
619
620 if (host->data.length < 4)
621 return -1;
622
623 _krb5_get_int(host->data.data, &pktlen, 4);
624
625 if (pktlen > host->data.length - 4)
626 return -1;
627
628 memmove(host->data.data, ((uint8_t *)host->data.data) + 4, host->data.length - 4);
629 host->data.length -= 4;
630
631 *data = host->data;
632 krb5_data_zero(&host->data);
633
634 return 0;
635 }
636
637 /*
638 * UDP transport
639 */
640
641 static krb5_error_code
642 prepare_udp(krb5_context context, struct host *host, const krb5_data *data)
643 {
644 return krb5_data_copy(&host->data, data->data, data->length);
645 }
646
647 static krb5_error_code
648 send_udp(krb5_context context, struct host *host)
649 {
650 if (send(host->fd, host->data.data, host->data.length, 0) < 0)
651 return errno;
652 return 0;
653 }
654
655 static krb5_error_code
656 recv_udp(krb5_context context, struct host *host, krb5_data *data)
657 {
658 krb5_error_code ret;
659 int nbytes;
660
661
662 if (rk_SOCK_IOCTL(host->fd, FIONREAD, &nbytes) != 0 || nbytes <= 0)
663 return HEIM_NET_CONN_REFUSED;
664
665 if (context->max_msg_size < nbytes) {
666 krb5_set_error_message(context, KRB5KRB_ERR_FIELD_TOOLONG,
667 N_("UDP message from KDC too large %d", ""),
668 (int)nbytes);
669 return KRB5KRB_ERR_FIELD_TOOLONG;
670 }
671
672 ret = krb5_data_alloc(data, nbytes);
673 if (ret)
674 return ret;
675
676 ret = recv(host->fd, data->data, data->length, 0);
677 if (ret < 0) {
678 ret = errno;
679 krb5_data_free(data);
680 return ret;
681 }
682 data->length = ret;
683
684 return 0;
685 }
686
687 static struct host_fun http_fun = {
688 prepare_http,
689 send_stream,
690 recv_http,
691 1
692 };
693 static struct host_fun tcp_fun = {
694 prepare_tcp,
695 send_stream,
696 recv_tcp,
697 1
698 };
699 static struct host_fun udp_fun = {
700 prepare_udp,
701 send_udp,
702 recv_udp,
703 3
704 };
705
706
707 /*
708 * Host state machine
709 */
710
711 static int
712 eval_host_state(krb5_context context,
713 krb5_sendto_ctx ctx,
714 struct host *host,
715 int readable, int writeable)
716 {
717 krb5_error_code ret;
718
719 if (host->state == CONNECT) {
720 /* check if its this host time to connect */
721 if (host->timeout < time(NULL))
722 host_connect(context, ctx, host);
723 return 0;
724 }
725
726 if (host->state == CONNECTING && writeable)
727 host_connected(context, ctx, host);
728
729 if (readable) {
730
731 debug_host(context, 5, host, "reading packet");
732
733 ret = host->fun->recv_fn(context, host, &ctx->response);
734 if (ret == -1) {
735 /* not done yet */
736 } else if (ret == 0) {
737 /* if recv_foo function returns 0, we have a complete reply */
738 debug_host(context, 5, host, "host completed");
739 return 1;
740 } else {
741 host_dead(context, host, "host disconnected");
742 }
743 }
744
745 /* check if there is anything to send, state might DEAD after read */
746 if (writeable && host->state == CONNECTED) {
747
748 ctx->stats.sent_packets++;
749
750 debug_host(context, 5, host, "writing packet");
751
752 ret = host->fun->send_fn(context, host);
753 if (ret == -1) {
754 /* not done yet */
755 } else if (ret) {
756 host_dead(context, host, "host dead, write failed");
757 } else
758 host->state = WAITING_REPLY;
759 }
760
761 return 0;
762 }
763
764 /*
765 *
766 */
767
768 static krb5_error_code
769 submit_request(krb5_context context, krb5_sendto_ctx ctx, krb5_krbhst_info *hi)
770 {
771 unsigned long submitted_host = 0;
772 krb5_boolean freeai = FALSE;
773 struct timeval nrstart, nrstop;
774 krb5_error_code ret;
775 struct addrinfo *ai = NULL, *a;
776 struct host *host;
777
778 ret = kdc_via_plugin(context, hi, context->kdc_timeout,
779 ctx->send_data, &ctx->response);
780 if (ret == 0) {
781 return 0;
782 } else if (ret != KRB5_PLUGIN_NO_HANDLE) {
783 _krb5_debug(context, 5, "send via plugin failed %s: %d",
784 hi->hostname, ret);
785 return ret;
786 }
787
788 /*
789 * If we have a proxy, let use the address of the proxy instead of
790 * the KDC and let the proxy deal with the resolving of the KDC.
791 */
792
793 gettimeofday(&nrstart, NULL);
794
795 if (hi->proto == KRB5_KRBHST_HTTP && context->http_proxy) {
796 char *proxy2 = strdup(context->http_proxy);
797 char *el, *proxy = proxy2;
798 struct addrinfo hints;
799 char portstr[NI_MAXSERV];
800 unsigned short nport;
801
802 if (proxy == NULL)
803 return ENOMEM;
804 if (strncmp(proxy, "http://", 7) == 0)
805 proxy += 7;
806
807 /* check for url terminating slash */
808 el = strchr(proxy, '/');
809 if (el != NULL)
810 *el = '\0';
811
812 /* check for port in hostname, used below as port */
813 el = strchr(proxy, ':');
814 if(el != NULL)
815 *el++ = '\0';
816
817 memset(&hints, 0, sizeof(hints));
818 hints.ai_family = PF_UNSPEC;
819 hints.ai_socktype = SOCK_STREAM;
820
821 /* On some systems ntohs(foo(..., htons(...))) causes shadowing */
822 nport = init_port(el, htons(80));
823 snprintf(portstr, sizeof(portstr), "%d", ntohs(nport));
824
825 ret = getaddrinfo(proxy, portstr, &hints, &ai);
826 free(proxy2);
827 if (ret)
828 return krb5_eai_to_heim_errno(ret, errno);
829
830 freeai = TRUE;
831
832 } else {
833 ret = krb5_krbhst_get_addrinfo(context, hi, &ai);
834 if (ret)
835 return ret;
836 }
837
838 /* add up times */
839 gettimeofday(&nrstop, NULL);
840 timevalsub(&nrstop, &nrstart);
841 timevaladd(&ctx->stats.name_resolution, &nrstop);
842
843 ctx->stats.num_hosts++;
844
845 for (a = ai; a != NULL; a = a->ai_next) {
846 rk_socket_t fd;
847
848 fd = socket(a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_protocol);
849 if (rk_IS_BAD_SOCKET(fd))
850 continue;
851 rk_cloexec(fd);
852
853 #ifndef NO_LIMIT_FD_SETSIZE
854 if (fd >= FD_SETSIZE) {
855 _krb5_debug(context, 0, "fd too large for select");
856 rk_closesocket(fd);
857 continue;
858 }
859 #endif
860 socket_set_nonblocking(fd, 1);
861
862 host = heim_alloc(sizeof(*host), "sendto-host", deallocate_host);
863 if (host == NULL) {
864 if (freeai)
865 freeaddrinfo(ai);
866 rk_closesocket(fd);
867 return ENOMEM;
868 }
869 host->hi = hi;
870 host->fd = fd;
871 host->ai = a;
872 /* next version of stid */
873 host->tid = ctx->stid = (ctx->stid & 0xffff0000) | ((ctx->stid & 0xffff) + 1);
874
875 host->state = CONNECT;
876
877 switch (host->hi->proto) {
878 case KRB5_KRBHST_HTTP :
879 host->fun = &http_fun;
880 break;
881 case KRB5_KRBHST_TCP :
882 host->fun = &tcp_fun;
883 break;
884 case KRB5_KRBHST_UDP :
885 host->fun = &udp_fun;
886 break;
887 default:
888 heim_abort("undefined http transport protocol: %d", (int)host->hi->proto);
889 }
890
891 host->tries = host->fun->ntries;
892
893 /*
894 * Connect directly next host, wait a host_timeout for each next address.
895 * We try host_connect() here, checking the return code because as we do
896 * non-blocking connects, any error here indicates that the address is just
897 * offline. That is, it's something like "No route to host" which is not
898 * worth retrying. And so, we fail directly and immediately to the next
899 * address for this host without enqueueing the address for retries.
900 */
901 if (submitted_host == 0) {
902 host_connect(context, ctx, host);
903 if (host->state == DEAD)
904 continue;
905 } else {
906 debug_host(context, 5, host,
907 "Queuing host in future (in %ds), its the %lu address on the same name",
908 (int)(context->host_timeout * submitted_host), submitted_host + 1);
909 host->timeout = time(NULL) + (submitted_host * context->host_timeout);
910 }
911
912 heim_array_append_value(ctx->hosts, host);
913 heim_release(host);
914 submitted_host++;
915 }
916
917 if (freeai)
918 freeaddrinfo(ai);
919
920 if (submitted_host == 0)
921 return KRB5_KDC_UNREACH;
922
923 return 0;
924 }
925
926 struct wait_ctx {
927 krb5_context context;
928 krb5_sendto_ctx ctx;
929 fd_set rfds;
930 fd_set wfds;
931 rk_socket_t max_fd;
932 int got_reply;
933 time_t timenow;
934 };
935
936 static void
937 wait_setup(heim_object_t obj, void *iter_ctx, int *stop)
938 {
939 struct wait_ctx *wait_ctx = iter_ctx;
940 struct host *h = (struct host *)obj;
941
942 if (h->state == CONNECT) {
943 if (h->timeout >= wait_ctx->timenow)
944 return;
945 host_connect(wait_ctx->context, wait_ctx->ctx, h);
946 }
947
948 /* skip dead hosts */
949 if (h->state == DEAD)
950 return;
951
952 /* if host timed out, dec tries and (retry or kill host) */
953 if (h->timeout < wait_ctx->timenow) {
954 heim_assert(h->tries != 0, "tries should not reach 0");
955 h->tries--;
956 if (h->tries == 0) {
957 host_dead(wait_ctx->context, h, "host timed out");
958 return;
959 } else {
960 debug_host(wait_ctx->context, 5, h, "retrying sending to");
961 host_next_timeout(wait_ctx->context, h);
962 host_connected(wait_ctx->context, wait_ctx->ctx, h);
963 }
964 }
965
966 #ifndef NO_LIMIT_FD_SETSIZE
967 heim_assert(h->fd < FD_SETSIZE, "fd too large");
968 #endif
969 switch (h->state) {
970 case WAITING_REPLY:
971 FD_SET(h->fd, &wait_ctx->rfds);
972 break;
973 case CONNECTING:
974 case CONNECTED:
975 FD_SET(h->fd, &wait_ctx->rfds);
976 FD_SET(h->fd, &wait_ctx->wfds);
977 break;
978 default:
979 debug_host(wait_ctx->context, 5, h, "invalid sendto host state");
980 heim_abort("invalid sendto host state");
981 }
982 if (h->fd > wait_ctx->max_fd || wait_ctx->max_fd == rk_INVALID_SOCKET)
983 wait_ctx->max_fd = h->fd;
984 }
985
986 static int
987 wait_filter_dead(heim_object_t obj, void *ctx)
988 {
989 struct host *h = (struct host *)obj;
990 return (int)((h->state == DEAD) ? true : false);
991 }
992
993 static void
994 wait_accelerate(heim_object_t obj, void *ctx, int *stop)
995 {
996 struct host *h = (struct host *)obj;
997
998 if (h->state == CONNECT && h->timeout > 0)
999 h->timeout--;
1000 }
1001
1002 static void
1003 wait_process(heim_object_t obj, void *ctx, int *stop)
1004 {
1005 struct wait_ctx *wait_ctx = ctx;
1006 struct host *h = (struct host *)obj;
1007 int readable, writeable;
1008 heim_assert(h->state != DEAD, "dead host resurected");
1009
1010 #ifndef NO_LIMIT_FD_SETSIZE
1011 heim_assert(h->fd < FD_SETSIZE, "fd too large");
1012 #endif
1013 readable = FD_ISSET(h->fd, &wait_ctx->rfds);
1014 writeable = FD_ISSET(h->fd, &wait_ctx->wfds);
1015
1016 if (readable || writeable || h->state == CONNECT)
1017 wait_ctx->got_reply |= eval_host_state(wait_ctx->context, wait_ctx->ctx, h, readable, writeable);
1018
1019 /* if there is already a reply, just fall though the array */
1020 if (wait_ctx->got_reply)
1021 *stop = 1;
1022 }
1023
1024 static krb5_error_code
1025 wait_response(krb5_context context, int *action, krb5_sendto_ctx ctx)
1026 {
1027 struct wait_ctx wait_ctx;
1028 struct timeval tv;
1029 int ret;
1030
1031 wait_ctx.context = context;
1032 wait_ctx.ctx = ctx;
1033 FD_ZERO(&wait_ctx.rfds);
1034 FD_ZERO(&wait_ctx.wfds);
1035 wait_ctx.max_fd = rk_INVALID_SOCKET;
1036
1037 /* oh, we have a reply, it must be a plugin that got it for us */
1038 if (ctx->response.length) {
1039 *action = KRB5_SENDTO_FILTER;
1040 return 0;
1041 }
1042
1043 wait_ctx.timenow = time(NULL);
1044
1045 heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_setup);
1046 heim_array_filter_f(ctx->hosts, &wait_ctx, wait_filter_dead);
1047
1048 if (heim_array_get_length(ctx->hosts) == 0) {
1049 if (ctx->stateflags & KRBHST_COMPLETED) {
1050 _krb5_debug(context, 5, "no more hosts to send/recv packets to/from "
1051 "trying to pulling more hosts");
1052 *action = KRB5_SENDTO_FAILED;
1053 } else {
1054 _krb5_debug(context, 5, "no more hosts to send/recv packets to/from "
1055 "and no more hosts -> failure");
1056 *action = KRB5_SENDTO_TIMEOUT;
1057 }
1058 return 0;
1059 }
1060
1061 if (wait_ctx.max_fd == rk_INVALID_SOCKET) {
1062 /*
1063 * If we don't find a host which can make progress, then
1064 * we accelerate the process by moving all of the contestants
1065 * up by 1s.
1066 */
1067 _krb5_debug(context, 5, "wait_response: moving the contestants forward");
1068 heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_accelerate);
1069 return 0;
1070 }
1071
1072 tv.tv_sec = 1;
1073 tv.tv_usec = 0;
1074
1075 ret = select(wait_ctx.max_fd + 1, &wait_ctx.rfds, &wait_ctx.wfds, NULL, &tv);
1076 if (ret < 0)
1077 return errno;
1078 if (ret == 0) {
1079 *action = KRB5_SENDTO_TIMEOUT;
1080 return 0;
1081 }
1082
1083 wait_ctx.got_reply = 0;
1084 heim_array_iterate_f(ctx->hosts, &wait_ctx, wait_process);
1085 if (wait_ctx.got_reply)
1086 *action = KRB5_SENDTO_FILTER;
1087 else
1088 *action = KRB5_SENDTO_CONTINUE;
1089
1090 return 0;
1091 }
1092
1093 static void
1094 reset_context(krb5_context context, krb5_sendto_ctx ctx)
1095 {
1096 krb5_data_free(&ctx->response);
1097 heim_release(ctx->hosts);
1098 ctx->hosts = heim_array_create();
1099 ctx->stateflags = 0;
1100 }
1101
1102
1103 /*
1104 *
1105 */
1106
1107 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
1108 krb5_sendto_context(krb5_context context,
1109 krb5_sendto_ctx ctx,
1110 const krb5_data *send_data,
1111 krb5_const_realm realm,
1112 krb5_data *receive)
1113 {
1114 krb5_error_code ret = 0;
1115 krb5_krbhst_handle handle = NULL;
1116 struct timeval nrstart, nrstop, stop_time;
1117 int type, freectx = 0;
1118 int action;
1119 int numreset = 0;
1120
1121 krb5_data_zero(receive);
1122
1123 if (ctx == NULL) {
1124 ret = krb5_sendto_ctx_alloc(context, &ctx);
1125 if (ret)
1126 goto out;
1127 freectx = 1;
1128 }
1129
1130 ctx->stid = (context->num_kdc_requests++) << 16;
1131
1132 memset(&ctx->stats, 0, sizeof(ctx->stats));
1133 gettimeofday(&ctx->stats.start_time, NULL);
1134
1135 type = ctx->type;
1136 if (type == 0) {
1137 if ((ctx->flags & KRB5_KRBHST_FLAGS_MASTER) || context->use_admin_kdc)
1138 type = KRB5_KRBHST_ADMIN;
1139 else
1140 type = KRB5_KRBHST_KDC;
1141 }
1142
1143 ctx->send_data = send_data;
1144
1145 if ((int)send_data->length > context->large_msg_size)
1146 ctx->flags |= KRB5_KRBHST_FLAGS_LARGE_MSG;
1147
1148 /* loop until we get back a appropriate response */
1149
1150 action = KRB5_SENDTO_INITIAL;
1151
1152 while (action != KRB5_SENDTO_DONE && action != KRB5_SENDTO_FAILED) {
1153 krb5_krbhst_info *hi;
1154
1155 switch (action) {
1156 case KRB5_SENDTO_INITIAL:
1157 ret = realm_via_plugin(context, realm, context->kdc_timeout,
1158 send_data, &ctx->response);
1159 if (ret == 0 || ret != KRB5_PLUGIN_NO_HANDLE) {
1160 action = KRB5_SENDTO_DONE;
1161 break;
1162 }
1163 action = KRB5_SENDTO_KRBHST;
1164 /* FALLTHROUGH */
1165 case KRB5_SENDTO_KRBHST:
1166 if (ctx->krbhst == NULL) {
1167 ret = krb5_krbhst_init_flags(context, realm, type,
1168 ctx->flags, &handle);
1169 if (ret)
1170 goto out;
1171
1172 if (ctx->hostname) {
1173 ret = krb5_krbhst_set_hostname(context, handle, ctx->hostname);
1174 if (ret)
1175 goto out;
1176 }
1177
1178 } else {
1179 handle = heim_retain(ctx->krbhst);
1180 }
1181 action = KRB5_SENDTO_TIMEOUT;
1182 /* FALLTHROUGH */
1183 case KRB5_SENDTO_TIMEOUT:
1184
1185 /*
1186 * If we completed, just got to next step
1187 */
1188
1189 if (ctx->stateflags & KRBHST_COMPLETED) {
1190 action = KRB5_SENDTO_CONTINUE;
1191 break;
1192 }
1193
1194 /*
1195 * Pull out next host, if there is no more, close the
1196 * handle and mark as completed.
1197 *
1198 * Collect time spent in krbhst (dns, plugin, etc)
1199 */
1200
1201
1202 gettimeofday(&nrstart, NULL);
1203
1204 ret = krb5_krbhst_next(context, handle, &hi);
1205
1206 gettimeofday(&nrstop, NULL);
1207 timevalsub(&nrstop, &nrstart);
1208 timevaladd(&ctx->stats.krbhst, &nrstop);
1209
1210 action = KRB5_SENDTO_CONTINUE;
1211 if (ret == 0) {
1212 _krb5_debug(context, 5, "submitting new requests to new host");
1213 if (submit_request(context, ctx, hi) != 0)
1214 action = KRB5_SENDTO_TIMEOUT;
1215 } else {
1216 _krb5_debug(context, 5, "out of hosts, waiting for replies");
1217 ctx->stateflags |= KRBHST_COMPLETED;
1218 }
1219
1220 break;
1221 case KRB5_SENDTO_CONTINUE:
1222
1223 ret = wait_response(context, &action, ctx);
1224 if (ret)
1225 goto out;
1226
1227 break;
1228 case KRB5_SENDTO_RESET:
1229 /* start over */
1230 _krb5_debug(context, 5,
1231 "krb5_sendto trying over again (reset): %d",
1232 numreset);
1233 reset_context(context, ctx);
1234 if (handle) {
1235 krb5_krbhst_free(context, handle);
1236 handle = NULL;
1237 }
1238 numreset++;
1239 if (numreset >= 3)
1240 action = KRB5_SENDTO_FAILED;
1241 else
1242 action = KRB5_SENDTO_KRBHST;
1243
1244 break;
1245 case KRB5_SENDTO_FILTER:
1246 /* default to next state, the filter function might modify this */
1247 action = KRB5_SENDTO_DONE;
1248
1249 if (ctx->func) {
1250 ret = (*ctx->func)(context, ctx, ctx->data,
1251 &ctx->response, &action);
1252 if (ret)
1253 goto out;
1254 }
1255 break;
1256 case KRB5_SENDTO_FAILED:
1257 ret = KRB5_KDC_UNREACH;
1258 break;
1259 case KRB5_SENDTO_DONE:
1260 ret = 0;
1261 break;
1262 default:
1263 heim_abort("invalid krb5_sendto_context state");
1264 }
1265 }
1266
1267 out:
1268 gettimeofday(&stop_time, NULL);
1269 timevalsub(&stop_time, &ctx->stats.start_time);
1270 if (ret == 0 && ctx->response.length) {
1271 *receive = ctx->response;
1272 krb5_data_zero(&ctx->response);
1273 } else {
1274 krb5_data_free(&ctx->response);
1275 krb5_clear_error_message (context);
1276 ret = KRB5_KDC_UNREACH;
1277 krb5_set_error_message(context, ret,
1278 N_("unable to reach any KDC in realm %s", ""),
1279 realm);
1280 }
1281
1282 _krb5_debug(context, 1,
1283 "%s %s done: %d hosts: %lu packets: %lu"
1284 " wc: %lld.%06lu nr: %lld.%06lu kh: %lld.%06lu tid: %08x",
1285 __func__, realm, ret,
1286 ctx->stats.num_hosts, ctx->stats.sent_packets,
1287 (long long)stop_time.tv_sec,
1288 (unsigned long)stop_time.tv_usec,
1289 (long long)ctx->stats.name_resolution.tv_sec,
1290 (unsigned long)ctx->stats.name_resolution.tv_usec,
1291 (long long)ctx->stats.krbhst.tv_sec,
1292 (unsigned long)ctx->stats.krbhst.tv_usec, ctx->stid);
1293
1294
1295 if (freectx)
1296 krb5_sendto_ctx_free(context, ctx);
1297 else
1298 reset_context(context, ctx);
1299
1300 if (handle)
1301 krb5_krbhst_free(context, handle);
1302
1303 return ret;
1304 }