r8302: import mini HEIMDAL into the tree
[amitay/samba.git] / source4 / 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.56 2005/06/17 04:33:11 lha Exp $");
37
38 /*
39  * send the data in `req' on the socket `fd' (which is datagram iff udp)
40  * waiting `tmout' for a reply and returning the reply in `rep'.
41  * iff limit read up to this many bytes
42  * returns 0 and data in `rep' if succesful, otherwise -1
43  */
44
45 static int
46 recv_loop (int fd,
47            time_t tmout,
48            int udp,
49            size_t limit,
50            krb5_data *rep)
51 {
52      fd_set fdset;
53      struct timeval timeout;
54      int ret;
55      int nbytes;
56
57      if (fd >= FD_SETSIZE) {
58          return -1;
59      }
60
61      krb5_data_zero(rep);
62      do {
63          FD_ZERO(&fdset);
64          FD_SET(fd, &fdset);
65          timeout.tv_sec  = tmout;
66          timeout.tv_usec = 0;
67          ret = select (fd + 1, &fdset, NULL, NULL, &timeout);
68          if (ret < 0) {
69              if (errno == EINTR)
70                  continue;
71              return -1;
72          } else if (ret == 0) {
73              return 0;
74          } else {
75              void *tmp;
76
77              if (ioctl (fd, FIONREAD, &nbytes) < 0) {
78                  krb5_data_free (rep);
79                  return -1;
80              }
81              if(nbytes == 0)
82                  return 0;
83
84              if (limit)
85                  nbytes = min(nbytes, limit - rep->length);
86
87              tmp = realloc (rep->data, rep->length + nbytes);
88              if (tmp == NULL) {
89                  krb5_data_free (rep);
90                  return -1;
91              }
92              rep->data = tmp;
93              ret = recv (fd, (char*)tmp + rep->length, nbytes, 0);
94              if (ret < 0) {
95                  krb5_data_free (rep);
96                  return -1;
97              }
98              rep->length += ret;
99          }
100      } while(!udp && (limit == 0 || rep->length < limit));
101      return 0;
102 }
103
104 /*
105  * Send kerberos requests and receive a reply on a udp or any other kind
106  * of a datagram socket.  See `recv_loop'.
107  */
108
109 static int
110 send_and_recv_udp(int fd, 
111                   time_t tmout,
112                   const krb5_data *req,
113                   krb5_data *rep)
114 {
115     if (send (fd, req->data, req->length, 0) < 0)
116         return -1;
117
118     return recv_loop(fd, tmout, 1, 0, rep);
119 }
120
121 /*
122  * `send_and_recv' for a TCP (or any other stream) socket.
123  * Since there are no record limits on a stream socket the protocol here
124  * is to prepend the request with 4 bytes of its length and the reply
125  * is similarly encoded.
126  */
127
128 static int
129 send_and_recv_tcp(int fd, 
130                   time_t tmout,
131                   const krb5_data *req,
132                   krb5_data *rep)
133 {
134     unsigned char len[4];
135     unsigned long rep_len;
136     krb5_data len_data;
137
138     _krb5_put_int(len, req->length, 4);
139     if(net_write(fd, len, sizeof(len)) < 0)
140         return -1;
141     if(net_write(fd, req->data, req->length) < 0)
142         return -1;
143     if (recv_loop (fd, tmout, 0, 4, &len_data) < 0)
144         return -1;
145     if (len_data.length != 4) {
146         krb5_data_free (&len_data);
147         return -1;
148     }
149     _krb5_get_int(len_data.data, &rep_len, 4);
150     krb5_data_free (&len_data);
151     if (recv_loop (fd, tmout, 0, rep_len, rep) < 0)
152         return -1;
153     if(rep->length != rep_len) {
154         krb5_data_free (rep);
155         return -1;
156     }
157     return 0;
158 }
159
160 int
161 _krb5_send_and_recv_tcp(int fd,
162                         time_t tmout,
163                         const krb5_data *req,
164                         krb5_data *rep)
165 {
166     return send_and_recv_tcp(fd, tmout, req, rep);
167 }
168
169 /*
170  * `send_and_recv' tailored for the HTTP protocol.
171  */
172
173 static int
174 send_and_recv_http(int fd, 
175                    time_t tmout,
176                    const char *prefix,
177                    const krb5_data *req,
178                    krb5_data *rep)
179 {
180     char *request;
181     char *str;
182     int ret;
183     int len = base64_encode(req->data, req->length, &str);
184
185     if(len < 0)
186         return -1;
187     asprintf(&request, "GET %s%s HTTP/1.0\r\n\r\n", prefix, str);
188     free(str);
189     if (request == NULL)
190         return -1;
191     ret = net_write (fd, request, strlen(request));
192     free (request);
193     if (ret < 0)
194         return ret;
195     ret = recv_loop(fd, tmout, 0, 0, rep);
196     if(ret)
197         return ret;
198     {
199         unsigned long rep_len;
200         char *s, *p;
201
202         s = realloc(rep->data, rep->length + 1);
203         if (s == NULL) {
204             krb5_data_free (rep);
205             return -1;
206         }
207         s[rep->length] = 0;
208         p = strstr(s, "\r\n\r\n");
209         if(p == NULL) {
210             free(s);
211             return -1;
212         }
213         p += 4;
214         rep->data = s;
215         rep->length -= p - s;
216         if(rep->length < 4) { /* remove length */
217             free(s);
218             return -1;
219         }
220         rep->length -= 4;
221         _krb5_get_int(p, &rep_len, 4);
222         if (rep_len != rep->length) {
223             free(s);
224             return -1;
225         }
226         memmove(rep->data, p + 4, rep->length);
227     }
228     return 0;
229 }
230
231 static int
232 init_port(const char *s, int fallback)
233 {
234     if (s) {
235         int tmp;
236
237         sscanf (s, "%d", &tmp);
238         return htons(tmp);
239     } else
240         return fallback;
241 }
242
243 /*
244  * Return 0 if succesful, otherwise 1
245  */
246
247 static int
248 send_via_proxy (krb5_context context,
249                 const krb5_krbhst_info *hi,
250                 const krb5_data *send_data,
251                 krb5_data *receive)
252 {
253     char *proxy2 = strdup(context->http_proxy);
254     char *proxy  = proxy2;
255     char *prefix;
256     char *colon;
257     struct addrinfo hints;
258     struct addrinfo *ai, *a;
259     int ret;
260     int s = -1;
261     char portstr[NI_MAXSERV];
262                  
263     if (proxy == NULL)
264         return ENOMEM;
265     if (strncmp (proxy, "http://", 7) == 0)
266         proxy += 7;
267
268     colon = strchr(proxy, ':');
269     if(colon != NULL)
270         *colon++ = '\0';
271     memset (&hints, 0, sizeof(hints));
272     hints.ai_family   = PF_UNSPEC;
273     hints.ai_socktype = SOCK_STREAM;
274     snprintf (portstr, sizeof(portstr), "%d",
275               ntohs(init_port (colon, htons(80))));
276     ret = getaddrinfo (proxy, portstr, &hints, &ai);
277     free (proxy2);
278     if (ret)
279         return krb5_eai_to_heim_errno(ret, errno);
280
281     for (a = ai; a != NULL; a = a->ai_next) {
282         s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
283         if (s < 0)
284             continue;
285         if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
286             close (s);
287             continue;
288         }
289         break;
290     }
291     if (a == NULL) {
292         freeaddrinfo (ai);
293         return 1;
294     }
295     freeaddrinfo (ai);
296
297     asprintf(&prefix, "http://%s/", hi->hostname);
298     if(prefix == NULL) {
299         close(s);
300         return 1;
301     }
302     ret = send_and_recv_http(s, context->kdc_timeout,
303                              prefix, send_data, receive);
304     close (s);
305     free(prefix);
306     if(ret == 0 && receive->length != 0)
307         return 0;
308     return 1;
309 }
310
311 /*
312  * Send the data `send' to one host from `handle` and get back the reply
313  * in `receive'.
314  */
315
316 krb5_error_code KRB5_LIB_FUNCTION
317 krb5_sendto (krb5_context context,
318              const krb5_data *send_data,
319              krb5_krbhst_handle handle,      
320              krb5_data *receive)
321 {
322      krb5_error_code ret = 0;
323      int fd;
324      int i;
325
326      for (i = 0; i < context->max_retries; ++i) {
327          krb5_krbhst_info *hi;
328
329          while (krb5_krbhst_next(context, handle, &hi) == 0) {
330              struct addrinfo *ai, *a;
331
332              if(hi->proto == KRB5_KRBHST_HTTP && context->http_proxy) {
333                  if (send_via_proxy (context, hi, send_data, receive))
334                      continue;
335                  else
336                      goto out;
337              }
338
339              ret = krb5_krbhst_get_addrinfo(context, hi, &ai);
340              if (ret)
341                  continue;
342
343              for (a = ai; a != NULL; a = a->ai_next) {
344                  fd = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
345                  if (fd < 0)
346                      continue;
347                  if (connect (fd, a->ai_addr, a->ai_addrlen) < 0) {
348                      close (fd);
349                      continue;
350                  }
351                  switch (hi->proto) {
352                  case KRB5_KRBHST_HTTP :
353                      ret = send_and_recv_http(fd, context->kdc_timeout,
354                                               "", send_data, receive);
355                      break;
356                  case KRB5_KRBHST_TCP :
357                      ret = send_and_recv_tcp (fd, context->kdc_timeout,
358                                               send_data, receive);
359                      break;
360                  case KRB5_KRBHST_UDP :
361                      ret = send_and_recv_udp (fd, context->kdc_timeout,
362                                               send_data, receive);
363                      break;
364                  }
365                  close (fd);
366                  if(ret == 0 && receive->length != 0)
367                      goto out;
368              }
369          }
370          krb5_krbhst_reset(context, handle);
371      }
372      krb5_clear_error_string (context);
373      ret = KRB5_KDC_UNREACH;
374 out:
375      return ret;
376 }
377
378 krb5_error_code KRB5_LIB_FUNCTION
379 krb5_sendto_kdc(krb5_context context,
380                 const krb5_data *send_data,
381                 const krb5_realm *realm,
382                 krb5_data *receive)
383 {
384     return krb5_sendto_kdc_flags(context, send_data, realm, receive, 0);
385 }
386
387 krb5_error_code KRB5_LIB_FUNCTION
388 krb5_sendto_kdc_flags(krb5_context context,
389                       const krb5_data *send_data,
390                       const krb5_realm *realm,
391                       krb5_data *receive,
392                       int flags)
393 {
394     krb5_error_code ret;
395     krb5_krbhst_handle handle;
396     int type;
397
398     if ((flags & KRB5_KRBHST_FLAGS_MASTER) || context->use_admin_kdc)
399         type = KRB5_KRBHST_ADMIN;
400     else
401         type = KRB5_KRBHST_KDC;
402
403     if (send_data->length > context->large_msg_size)
404         flags |= KRB5_KRBHST_FLAGS_LARGE_MSG;
405
406     ret = krb5_krbhst_init_flags(context, *realm, type, flags, &handle);
407     if (ret)
408         return ret;
409
410     ret = krb5_sendto(context, send_data, handle, receive);
411     krb5_krbhst_free(context, handle);
412     if (ret == KRB5_KDC_UNREACH)
413         krb5_set_error_string(context,
414                               "unable to reach any KDC in realm %s", *realm);
415     return ret;
416 }