r15192: Update Samba4 to use current lorikeet-heimdal.
[jelmer/samba4-debian.git] / source / heimdal / lib / krb5 / send_to_kdc.c
1 /*
2  * Copyright (c) 1997 - 2002 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden). 
4  * All rights reserved. 
5  *
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions 
8  * are met: 
9  *
10  * 1. Redistributions of source code must retain the above copyright 
11  *    notice, this list of conditions and the following disclaimer. 
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright 
14  *    notice, this list of conditions and the following disclaimer in the 
15  *    documentation and/or other materials provided with the distribution. 
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors 
18  *    may be used to endorse or promote products derived from this software 
19  *    without specific prior written permission. 
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
31  * SUCH DAMAGE. 
32  */
33
34 #include "krb5_locl.h"
35
36 RCSID("$Id: send_to_kdc.c,v 1.58 2006/04/02 02:32:03 lha Exp $");
37
38 struct send_and_recv {
39         krb5_send_and_recv_func_t func;
40         krb5_send_and_recv_close_func_t close;
41         void *data;
42 };
43
44 krb5_error_code KRB5_LIB_FUNCTION
45 krb5_set_send_recv_func(krb5_context context,
46                         krb5_send_and_recv_func_t func,
47                         krb5_send_and_recv_close_func_t close_fn,
48                         void *data)
49 {
50         free(context->send_and_recv);
51         context->send_and_recv = malloc(sizeof(*context->send_and_recv));
52         if (!context->send_and_recv) {
53                 return ENOMEM;
54         }
55         context->send_and_recv->func = func;
56         context->send_and_recv->close = close_fn;
57         context->send_and_recv->data = data;
58         return 0;
59 }
60
61
62 /*
63  * send the data in `req' on the socket `fd' (which is datagram iff udp)
64  * waiting `tmout' for a reply and returning the reply in `rep'.
65  * iff limit read up to this many bytes
66  * returns 0 and data in `rep' if succesful, otherwise -1
67  */
68
69 static int
70 recv_loop (int fd,
71            time_t tmout,
72            int udp,
73            size_t limit,
74            krb5_data *rep)
75 {
76      fd_set fdset;
77      struct timeval timeout;
78      int ret;
79      int nbytes;
80
81      if (fd >= FD_SETSIZE) {
82          return -1;
83      }
84
85      krb5_data_zero(rep);
86      do {
87          FD_ZERO(&fdset);
88          FD_SET(fd, &fdset);
89          timeout.tv_sec  = tmout;
90          timeout.tv_usec = 0;
91          ret = select (fd + 1, &fdset, NULL, NULL, &timeout);
92          if (ret < 0) {
93              if (errno == EINTR)
94                  continue;
95              return -1;
96          } else if (ret == 0) {
97              return 0;
98          } else {
99              void *tmp;
100
101              if (ioctl (fd, FIONREAD, &nbytes) < 0) {
102                  krb5_data_free (rep);
103                  return -1;
104              }
105              if(nbytes <= 0)
106                  return 0;
107
108              if (limit)
109                  nbytes = min(nbytes, limit - rep->length);
110
111              tmp = realloc (rep->data, rep->length + nbytes);
112              if (tmp == NULL) {
113                  krb5_data_free (rep);
114                  return -1;
115              }
116              rep->data = tmp;
117              ret = recv (fd, (char*)tmp + rep->length, nbytes, 0);
118              if (ret < 0) {
119                  krb5_data_free (rep);
120                  return -1;
121              }
122              rep->length += ret;
123          }
124      } while(!udp && (limit == 0 || rep->length < limit));
125      return 0;
126 }
127
128 /*
129  * Send kerberos requests and receive a reply on a udp or any other kind
130  * of a datagram socket.  See `recv_loop'.
131  */
132
133 static int
134 send_and_recv_udp(int fd, 
135                   time_t tmout,
136                   const krb5_data *req,
137                   krb5_data *rep)
138 {
139     if (send (fd, req->data, req->length, 0) < 0)
140         return -1;
141
142     return recv_loop(fd, tmout, 1, 0, rep);
143 }
144
145 /*
146  * `send_and_recv' for a TCP (or any other stream) socket.
147  * Since there are no record limits on a stream socket the protocol here
148  * is to prepend the request with 4 bytes of its length and the reply
149  * is similarly encoded.
150  */
151
152 static int
153 send_and_recv_tcp(int fd, 
154                   time_t tmout,
155                   const krb5_data *req,
156                   krb5_data *rep)
157 {
158     unsigned char len[4];
159     unsigned long rep_len;
160     krb5_data len_data;
161
162     _krb5_put_int(len, req->length, 4);
163     if(net_write(fd, len, sizeof(len)) < 0)
164         return -1;
165     if(net_write(fd, req->data, req->length) < 0)
166         return -1;
167     if (recv_loop (fd, tmout, 0, 4, &len_data) < 0)
168         return -1;
169     if (len_data.length != 4) {
170         krb5_data_free (&len_data);
171         return -1;
172     }
173     _krb5_get_int(len_data.data, &rep_len, 4);
174     krb5_data_free (&len_data);
175     if (recv_loop (fd, tmout, 0, rep_len, rep) < 0)
176         return -1;
177     if(rep->length != rep_len) {
178         krb5_data_free (rep);
179         return -1;
180     }
181     return 0;
182 }
183
184 int
185 _krb5_send_and_recv_tcp(int fd,
186                         time_t tmout,
187                         const krb5_data *req,
188                         krb5_data *rep)
189 {
190     return send_and_recv_tcp(fd, tmout, req, rep);
191 }
192
193 /*
194  * `send_and_recv' tailored for the HTTP protocol.
195  */
196
197 static int
198 send_and_recv_http(int fd, 
199                    time_t tmout,
200                    const char *prefix,
201                    const krb5_data *req,
202                    krb5_data *rep)
203 {
204     char *request;
205     char *str;
206     int ret;
207     int len = base64_encode(req->data, req->length, &str);
208
209     if(len < 0)
210         return -1;
211     asprintf(&request, "GET %s%s HTTP/1.0\r\n\r\n", prefix, str);
212     free(str);
213     if (request == NULL)
214         return -1;
215     ret = net_write (fd, request, strlen(request));
216     free (request);
217     if (ret < 0)
218         return ret;
219     ret = recv_loop(fd, tmout, 0, 0, rep);
220     if(ret)
221         return ret;
222     {
223         unsigned long rep_len;
224         char *s, *p;
225
226         s = realloc(rep->data, rep->length + 1);
227         if (s == NULL) {
228             krb5_data_free (rep);
229             return -1;
230         }
231         s[rep->length] = 0;
232         p = strstr(s, "\r\n\r\n");
233         if(p == NULL) {
234             krb5_data_zero(rep);
235             free(s);
236             return -1;
237         }
238         p += 4;
239         rep->data = s;
240         rep->length -= p - s;
241         if(rep->length < 4) { /* remove length */
242             krb5_data_zero(rep);
243             free(s);
244             return -1;
245         }
246         rep->length -= 4;
247         _krb5_get_int(p, &rep_len, 4);
248         if (rep_len != rep->length) {
249             krb5_data_zero(rep);
250             free(s);
251             return -1;
252         }
253         memmove(rep->data, p + 4, rep->length);
254     }
255     return 0;
256 }
257
258 static int
259 init_port(const char *s, int fallback)
260 {
261     if (s) {
262         int tmp;
263
264         sscanf (s, "%d", &tmp);
265         return htons(tmp);
266     } else
267         return fallback;
268 }
269
270 /*
271  * Return 0 if succesful, otherwise 1
272  */
273
274 static int
275 send_via_proxy (krb5_context context,
276                 const krb5_krbhst_info *hi,
277                 const krb5_data *send_data,
278                 krb5_data *receive)
279 {
280     char *proxy2 = strdup(context->http_proxy);
281     char *proxy  = proxy2;
282     char *prefix;
283     char *colon;
284     struct addrinfo hints;
285     struct addrinfo *ai, *a;
286     int ret;
287     int s = -1;
288     char portstr[NI_MAXSERV];
289                  
290     if (proxy == NULL)
291         return ENOMEM;
292     if (strncmp (proxy, "http://", 7) == 0)
293         proxy += 7;
294
295     colon = strchr(proxy, ':');
296     if(colon != NULL)
297         *colon++ = '\0';
298     memset (&hints, 0, sizeof(hints));
299     hints.ai_family   = PF_UNSPEC;
300     hints.ai_socktype = SOCK_STREAM;
301     snprintf (portstr, sizeof(portstr), "%d",
302               ntohs(init_port (colon, htons(80))));
303     ret = getaddrinfo (proxy, portstr, &hints, &ai);
304     free (proxy2);
305     if (ret)
306         return krb5_eai_to_heim_errno(ret, errno);
307
308     for (a = ai; a != NULL; a = a->ai_next) {
309         s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
310         if (s < 0)
311             continue;
312         if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
313             close (s);
314             continue;
315         }
316         break;
317     }
318     if (a == NULL) {
319         freeaddrinfo (ai);
320         return 1;
321     }
322     freeaddrinfo (ai);
323
324     asprintf(&prefix, "http://%s/", hi->hostname);
325     if(prefix == NULL) {
326         close(s);
327         return 1;
328     }
329     ret = send_and_recv_http(s, context->kdc_timeout,
330                              prefix, send_data, receive);
331     close (s);
332     free(prefix);
333     if(ret == 0 && receive->length != 0)
334         return 0;
335     return 1;
336 }
337
338 /*
339  * Send the data `send' to one host from `handle` and get back the reply
340  * in `receive'.
341  */
342
343 krb5_error_code KRB5_LIB_FUNCTION
344 krb5_sendto (krb5_context context,
345              const krb5_data *send_data,
346              krb5_krbhst_handle handle,      
347              krb5_data *receive)
348 {
349      krb5_error_code ret = 0;
350      int fd;
351      int i;
352
353      for (i = 0; i < context->max_retries; ++i) {
354          krb5_krbhst_info *hi;
355
356          while (krb5_krbhst_next(context, handle, &hi) == 0) {
357              struct addrinfo *ai, *a;
358
359              if (context->send_and_recv) {
360                  ret = context->send_and_recv->func(context, 
361                                                     context->send_and_recv->data, 
362                                                     hi, send_data, receive);
363                  if (ret) {
364                      continue;
365                  } else if (receive->length != 0) {
366                      return 0;
367                  } else {
368                      continue;
369                  }
370              }
371
372              if(hi->proto == KRB5_KRBHST_HTTP && context->http_proxy) {
373                  if (send_via_proxy (context, hi, send_data, receive)) {
374                      /* Try again, with next host */
375                      continue;
376                  } else {
377                      /* Success */
378                      return 0;
379                  }
380              }
381
382              ret = krb5_krbhst_get_addrinfo(context, hi, &ai);
383              if (ret)
384                  continue;
385
386              for (a = ai; a != NULL; a = a->ai_next) {
387                  fd = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
388                  if (fd < 0)
389                      continue;
390                  if (connect (fd, a->ai_addr, a->ai_addrlen) < 0) {
391                      close (fd);
392                      continue;
393                  }
394                  switch (hi->proto) {
395                  case KRB5_KRBHST_HTTP :
396                      ret = send_and_recv_http(fd, context->kdc_timeout,
397                                               "", send_data, receive);
398                      break;
399                  case KRB5_KRBHST_TCP :
400                      ret = send_and_recv_tcp (fd, context->kdc_timeout,
401                                               send_data, receive);
402                      break;
403                  case KRB5_KRBHST_UDP :
404                      ret = send_and_recv_udp (fd, context->kdc_timeout,
405                                               send_data, receive);
406                      break;
407                  }
408                  close (fd);
409                  if(ret == 0 && receive->length != 0) {
410                      return 0;
411                  }
412              }
413          }
414          krb5_krbhst_reset(context, handle);
415      }
416      krb5_clear_error_string (context);
417      return KRB5_KDC_UNREACH;
418 }
419
420 krb5_error_code KRB5_LIB_FUNCTION
421 krb5_sendto_kdc(krb5_context context,
422                 const krb5_data *send_data,
423                 const krb5_realm *realm,
424                 krb5_data *receive)
425 {
426     return krb5_sendto_kdc_flags(context, send_data, realm, receive, 0);
427 }
428
429 krb5_error_code KRB5_LIB_FUNCTION
430 krb5_sendto_kdc_flags(krb5_context context,
431                       const krb5_data *send_data,
432                       const krb5_realm *realm,
433                       krb5_data *receive,
434                       int flags)
435 {
436     krb5_error_code ret;
437     krb5_krbhst_handle handle;
438     int type;
439
440     if ((flags & KRB5_KRBHST_FLAGS_MASTER) || context->use_admin_kdc)
441         type = KRB5_KRBHST_ADMIN;
442     else
443         type = KRB5_KRBHST_KDC;
444
445     if (send_data->length > context->large_msg_size)
446         flags |= KRB5_KRBHST_FLAGS_LARGE_MSG;
447
448     ret = krb5_krbhst_init_flags(context, *realm, type, flags, &handle);
449     if (ret)
450         return ret;
451
452     ret = krb5_sendto(context, send_data, handle, receive);
453     krb5_krbhst_free(context, handle);
454     if (ret == KRB5_KDC_UNREACH)
455         krb5_set_error_string(context,
456                               "unable to reach any KDC in realm %s", *realm);
457     return ret;
458 }