Include complete fake-getname/addrinfo from OpenSSH.
[tinc] / lib / fake-getnameinfo.c
1 /*
2  * fake library for ssh
3  *
4  * This file includes getnameinfo().
5  * These funtions are defined in rfc2133.
6  *
7  * But these functions are not implemented correctly. The minimum subset
8  * is implemented for ssh use only. For exapmle, this routine assumes
9  * that ai_family is AF_INET. Don't use it for another purpose.
10  */
11
12 #include "config.h"
13
14 #include <sys/types.h>
15 #include <netinet/in.h>
16 #include <sys/socket.h>
17 #include <netdb.h>
18 #include <string.h>
19
20 #include <system.h>
21
22 #include "fake-getnameinfo.h"
23
24 #ifndef HAVE_GETNAMEINFO
25
26 int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, 
27                 size_t hostlen, char *serv, size_t servlen, int flags)
28 {
29         struct sockaddr_in *sin = (struct sockaddr_in *)sa;
30         struct hostent *hp;
31         char tmpserv[16];
32
33         if (serv) {
34                 snprintf(tmpserv, sizeof(tmpserv), "%d", ntohs(sin->sin_port));
35                 if (strlen(tmpserv) >= servlen)
36                         return EAI_MEMORY;
37                 else
38                         strcpy(serv, tmpserv);
39         }
40
41         if (host) {
42                 if (flags & NI_NUMERICHOST) {
43                         if (strlen(inet_ntoa(sin->sin_addr)) >= hostlen)
44                                 return EAI_MEMORY;
45
46                         strcpy(host, inet_ntoa(sin->sin_addr));
47                         return 0;
48                 } else {
49                         hp = gethostbyaddr((char *)&sin->sin_addr, 
50                                 sizeof(struct in_addr), AF_INET);
51                         if (hp == NULL)
52                                 return EAI_NODATA;
53                         
54                         if (strlen(hp->h_name) >= hostlen)
55                                 return EAI_MEMORY;
56
57                         strcpy(host, hp->h_name);
58                         return 0;
59                 }
60         }
61         return 0;
62 }
63 #endif /* !HAVE_GETNAMEINFO */