1 /* Copyright (C) 2007-2022 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3 
4    The GNU C Library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Lesser General Public
6    License as published by the Free Software Foundation; either
7    version 2.1 of the License, or (at your option) any later version.
8 
9    The GNU C Library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Lesser General Public License for more details.
13 
14    You should have received a copy of the GNU Lesser General Public
15    License along with the GNU C Library; if not, see
16    <https://www.gnu.org/licenses/>.  */
17 
18 #include <assert.h>
19 #include <errno.h>
20 #include <string.h>
21 #include <not-cancel.h>
22 #include <_itoa.h>
23 #include <stdint.h>
24 
25 #include "nscd-client.h"
26 #include "nscd_proto.h"
27 
28 
29 int __nss_not_use_nscd_services;
30 
31 
32 static int nscd_getserv_r (const char *crit, size_t critlen, const char *proto,
33 			   request_type type, struct servent *resultbuf,
34 			   char *buf, size_t buflen, struct servent **result);
35 
36 
37 int
__nscd_getservbyname_r(const char * name,const char * proto,struct servent * result_buf,char * buf,size_t buflen,struct servent ** result)38 __nscd_getservbyname_r (const char *name, const char *proto,
39 			struct servent *result_buf, char *buf, size_t buflen,
40 			struct servent **result)
41 {
42   return nscd_getserv_r (name, strlen (name), proto, GETSERVBYNAME, result_buf,
43 			 buf, buflen, result);
44 }
45 
46 
47 int
__nscd_getservbyport_r(int port,const char * proto,struct servent * result_buf,char * buf,size_t buflen,struct servent ** result)48 __nscd_getservbyport_r (int port, const char *proto,
49 			struct servent *result_buf, char *buf, size_t buflen,
50 			struct servent **result)
51 {
52   char portstr[3 * sizeof (int) + 2];
53   portstr[sizeof (portstr) - 1] = '\0';
54   char *cp = _itoa_word (port, portstr + sizeof (portstr) - 1, 10, 0);
55 
56   return nscd_getserv_r (cp, portstr + sizeof (portstr) - 1 - cp, proto,
57 			 GETSERVBYPORT, result_buf, buf, buflen, result);
58 }
59 
60 
61 libc_locked_map_ptr (, __serv_map_handle) attribute_hidden;
62 /* Note that we only free the structure if necessary.  The memory
63    mapping is not removed since it is not visible to the malloc
64    handling.  */
libc_freeres_fn(serv_map_free)65 libc_freeres_fn (serv_map_free)
66 {
67   if (__serv_map_handle.mapped != NO_MAPPING)
68     {
69       void *p = __serv_map_handle.mapped;
70       __serv_map_handle.mapped = NO_MAPPING;
71       free (p);
72     }
73 }
74 
75 
76 static int
nscd_getserv_r(const char * crit,size_t critlen,const char * proto,request_type type,struct servent * resultbuf,char * buf,size_t buflen,struct servent ** result)77 nscd_getserv_r (const char *crit, size_t critlen, const char *proto,
78 		request_type type, struct servent *resultbuf,
79 		char *buf, size_t buflen, struct servent **result)
80 {
81   int gc_cycle;
82   int nretries = 0;
83   size_t alloca_used = 0;
84 
85   /* If the mapping is available, try to search there instead of
86      communicating with the nscd.  */
87   struct mapped_database *mapped;
88   mapped = __nscd_get_map_ref (GETFDSERV, "services", &__serv_map_handle,
89 			       &gc_cycle);
90   size_t protolen = proto == NULL ? 0 : strlen (proto);
91   size_t keylen = critlen + 1 + protolen + 1;
92   int alloca_key = __libc_use_alloca (keylen);
93   char *key;
94   if (alloca_key)
95     key = alloca_account (keylen, alloca_used);
96   else
97     {
98       key = malloc (keylen);
99       if (key == NULL)
100 	return -1;
101     }
102   memcpy (__mempcpy (__mempcpy (key, crit, critlen),
103 		     "/", 1), proto ?: "", protolen + 1);
104 
105  retry:;
106   const char *s_name = NULL;
107   const char *s_proto = NULL;
108   int alloca_aliases_len = 0;
109   const uint32_t *aliases_len = NULL;
110   const char *aliases_list = NULL;
111   int retval = -1;
112   const char *recend = (const char *) ~UINTMAX_C (0);
113   int sock = -1;
114   serv_response_header serv_resp;
115 
116   if (mapped != NO_MAPPING)
117     {
118       struct datahead *found = __nscd_cache_search (type, key, keylen, mapped,
119 						    sizeof serv_resp);
120 
121       if (found != NULL)
122 	{
123 	  s_name = (char *) (&found->data[0].servdata + 1);
124 	  serv_resp = found->data[0].servdata;
125 	  s_proto = s_name + serv_resp.s_name_len;
126 	  alloca_aliases_len = 1;
127 	  aliases_len = (uint32_t *) (s_proto + serv_resp.s_proto_len);
128 	  aliases_list = ((char *) aliases_len
129 			  + serv_resp.s_aliases_cnt * sizeof (uint32_t));
130 	  recend = (const char *) found->data + found->recsize;
131 	  /* Now check if we can trust serv_resp fields.  If GC is
132 	     in progress, it can contain anything.  */
133 	  if (mapped->head->gc_cycle != gc_cycle)
134 	    {
135 	      retval = -2;
136 	      goto out;
137 	    }
138 	  if (__builtin_expect ((const char *) aliases_len
139 				+ serv_resp.s_aliases_cnt * sizeof (uint32_t)
140 				> recend, 0))
141 	    goto out;
142 
143 #if !_STRING_ARCH_unaligned
144 	  /* The aliases_len array in the mapped database might very
145 	     well be unaligned.  We will access it word-wise so on
146 	     platforms which do not tolerate unaligned accesses we
147 	     need to make an aligned copy.  */
148 	  if (((uintptr_t) aliases_len & (__alignof__ (*aliases_len) - 1))
149 	      != 0)
150 	    {
151 	      uint32_t *tmp;
152 	      alloca_aliases_len
153 		= __libc_use_alloca (alloca_used
154 				     + (serv_resp.s_aliases_cnt
155 					* sizeof (uint32_t)));
156 	      if (alloca_aliases_len)
157 		tmp = alloca_account (serv_resp.s_aliases_cnt
158 				      * sizeof (uint32_t),
159 				      alloca_used);
160 	      else
161 		{
162 		  tmp = malloc (serv_resp.s_aliases_cnt * sizeof (uint32_t));
163 		  if (tmp == NULL)
164 		    {
165 		      retval = ENOMEM;
166 		      goto out;
167 		    }
168 		}
169 	      aliases_len = memcpy (tmp, aliases_len,
170 				    serv_resp.s_aliases_cnt
171 				    * sizeof (uint32_t));
172 	    }
173 #endif
174 	}
175     }
176 
177   if (s_name == NULL)
178     {
179       sock = __nscd_open_socket (key, keylen, type, &serv_resp,
180 				 sizeof (serv_resp));
181       if (sock == -1)
182 	{
183 	  __nss_not_use_nscd_services = 1;
184 	  goto out;
185 	}
186     }
187 
188   /* No value found so far.  */
189   *result = NULL;
190 
191   if (__glibc_unlikely (serv_resp.found == -1))
192     {
193       /* The daemon does not cache this database.  */
194       __nss_not_use_nscd_services = 1;
195       goto out_close;
196     }
197 
198   if (serv_resp.found == 1)
199     {
200       char *cp = buf;
201       uintptr_t align1;
202       uintptr_t align2;
203       size_t total_len;
204       ssize_t cnt;
205       int n;
206 
207       /* A first check whether the buffer is sufficiently large is possible.  */
208       /* Now allocate the buffer the array for the group members.  We must
209 	 align the pointer and the base of the h_addr_list pointers.  */
210       align1 = ((__alignof__ (char *) - (cp - ((char *) 0)))
211 		& (__alignof__ (char *) - 1));
212       align2 = ((__alignof__ (char *) - ((cp + align1 + serv_resp.s_name_len
213 					  + serv_resp.s_proto_len)
214 					 - ((char *) 0)))
215 		& (__alignof__ (char *) - 1));
216       if (buflen < (align1 + serv_resp.s_name_len + serv_resp.s_proto_len
217 		    + align2
218 		    + (serv_resp.s_aliases_cnt + 1) * sizeof (char *)))
219 	{
220 	no_room:
221 	  __set_errno (ERANGE);
222 	  retval = ERANGE;
223 	  goto out_close;
224 	}
225       cp += align1;
226 
227       /* Prepare the result as far as we can.  */
228       resultbuf->s_aliases = (char **) cp;
229       cp += (serv_resp.s_aliases_cnt + 1) * sizeof (char *);
230 
231       resultbuf->s_name = cp;
232       cp += serv_resp.s_name_len;
233       resultbuf->s_proto = cp;
234       cp += serv_resp.s_proto_len + align2;
235       resultbuf->s_port = serv_resp.s_port;
236 
237       if (s_name == NULL)
238 	{
239 	  struct iovec vec[2];
240 
241 	  vec[0].iov_base = resultbuf->s_name;
242 	  vec[0].iov_len = serv_resp.s_name_len + serv_resp.s_proto_len;
243 	  total_len = vec[0].iov_len;
244 	  n = 1;
245 
246 	  if (serv_resp.s_aliases_cnt > 0)
247 	    {
248 	      assert (alloca_aliases_len == 0);
249 	      alloca_aliases_len
250 		= __libc_use_alloca (alloca_used
251 				     + (serv_resp.s_aliases_cnt
252 					* sizeof (uint32_t)));
253 	      if (alloca_aliases_len)
254 		aliases_len = alloca_account (serv_resp.s_aliases_cnt
255 					      * sizeof (uint32_t),
256 					      alloca_used);
257 	      else
258 		{
259 		  aliases_len = malloc (serv_resp.s_aliases_cnt
260 					* sizeof (uint32_t));
261 		  if (aliases_len == NULL)
262 		    {
263 		      retval = ENOMEM;
264 		      goto out_close;
265 		    }
266 		}
267 	      vec[n].iov_base = (void *) aliases_len;
268 	      vec[n].iov_len = serv_resp.s_aliases_cnt * sizeof (uint32_t);
269 
270 	      total_len += serv_resp.s_aliases_cnt * sizeof (uint32_t);
271 	      ++n;
272 	    }
273 
274 	  if ((size_t) __readvall (sock, vec, n) != total_len)
275 	    goto out_close;
276 	}
277       else
278 	memcpy (resultbuf->s_name, s_name,
279 		serv_resp.s_name_len + serv_resp.s_proto_len);
280 
281       /*  Now we also can read the aliases.  */
282       total_len = 0;
283       for (cnt = 0; cnt < serv_resp.s_aliases_cnt; ++cnt)
284 	{
285 	  resultbuf->s_aliases[cnt] = cp;
286 	  cp += aliases_len[cnt];
287 	  total_len += aliases_len[cnt];
288 	}
289       resultbuf->s_aliases[cnt] = NULL;
290 
291       if (__builtin_expect ((const char *) aliases_list + total_len > recend,
292 			    0))
293 	{
294 	  /* aliases_len array might contain garbage during nscd GC cycle,
295 	     retry rather than fail in that case.  */
296 	  if (aliases_list != NULL && mapped->head->gc_cycle != gc_cycle)
297 	    retval = -2;
298 	  goto out_close;
299 	}
300 
301       /* See whether this would exceed the buffer capacity.  */
302       if (__glibc_unlikely (cp > buf + buflen))
303 	{
304 	  /* aliases_len array might contain garbage during nscd GC cycle,
305 	     retry rather than fail in that case.  */
306 	  if (aliases_list != NULL && mapped->head->gc_cycle != gc_cycle)
307 	    {
308 	      retval = -2;
309 	      goto out_close;
310 	    }
311 	  goto no_room;
312 	}
313 
314       /* And finally read the aliases.  */
315       if (aliases_list == NULL)
316 	{
317 	  if (total_len == 0
318 	      || ((size_t) __readall (sock, resultbuf->s_aliases[0], total_len)
319 		  == total_len))
320 	    {
321 	      retval = 0;
322 	      *result = resultbuf;
323 	    }
324 	}
325       else
326 	{
327 	  memcpy (resultbuf->s_aliases[0], aliases_list, total_len);
328 
329 	  /* Try to detect corrupt databases.  */
330 	  if (resultbuf->s_name[serv_resp.s_name_len - 1] != '\0'
331 	      || resultbuf->s_proto[serv_resp.s_proto_len - 1] != '\0'
332 	      || ({for (cnt = 0; cnt < serv_resp.s_aliases_cnt; ++cnt)
333 		     if (resultbuf->s_aliases[cnt][aliases_len[cnt] - 1]
334 			 != '\0')
335 		       break;
336 		   cnt < serv_resp.s_aliases_cnt; }))
337 	    {
338 	      /* We cannot use the database.  */
339 	      if (mapped->head->gc_cycle != gc_cycle)
340 		retval = -2;
341 	      goto out_close;
342 	    }
343 
344 	  retval = 0;
345 	  *result = resultbuf;
346 	}
347     }
348   else
349     {
350       /* Set errno to 0 to indicate no error, just no found record.  */
351       __set_errno (0);
352       /* Even though we have not found anything, the result is zero.  */
353       retval = 0;
354     }
355 
356  out_close:
357   if (sock != -1)
358     __close_nocancel_nostatus (sock);
359  out:
360   if (__nscd_drop_map_ref (mapped, &gc_cycle) != 0)
361     {
362       /* When we come here this means there has been a GC cycle while we
363 	 were looking for the data.  This means the data might have been
364 	 inconsistent.  Retry if possible.  */
365       if ((gc_cycle & 1) != 0 || ++nretries == 5 || retval == -1)
366 	{
367 	  /* nscd is just running gc now.  Disable using the mapping.  */
368 	  if (atomic_decrement_val (&mapped->counter) == 0)
369 	    __nscd_unmap (mapped);
370 	  mapped = NO_MAPPING;
371 	}
372 
373       if (retval != -1)
374 	{
375 	  if (!alloca_aliases_len)
376 	    free ((void *) aliases_len);
377 	  goto retry;
378 	}
379     }
380 
381   if (!alloca_aliases_len)
382     free ((void *) aliases_len);
383   if (!alloca_key)
384     free (key);
385 
386   return retval;
387 }
388