fake-getaddrinfo.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * fake library for ssh
  3. *
  4. * This file includes getaddrinfo(), freeaddrinfo() and gai_strerror().
  5. * These functions are defined in rfc2133.
  6. *
  7. * But these functions are not implemented correctly. The minimum subset
  8. * is implemented for ssh use only. For example, this routine assumes
  9. * that ai_family is AF_INET. Don't use it for another purpose.
  10. */
  11. #include "system.h"
  12. #include "ipv4.h"
  13. #include "ipv6.h"
  14. #include "fake-getaddrinfo.h"
  15. #include "xalloc.h"
  16. #if !HAVE_DECL_GAI_STRERROR
  17. char *gai_strerror(int ecode) {
  18. switch(ecode) {
  19. case EAI_NODATA:
  20. return "No address associated with hostname";
  21. case EAI_MEMORY:
  22. return "Memory allocation failure";
  23. case EAI_FAMILY:
  24. return "Address family not supported";
  25. default:
  26. return "Unknown error";
  27. }
  28. }
  29. #endif /* !HAVE_GAI_STRERROR */
  30. #if !HAVE_DECL_FREEADDRINFO
  31. void freeaddrinfo(struct addrinfo *ai) {
  32. struct addrinfo *next;
  33. while(ai) {
  34. next = ai->ai_next;
  35. free(ai);
  36. ai = next;
  37. }
  38. }
  39. #endif /* !HAVE_FREEADDRINFO */
  40. #if !HAVE_DECL_GETADDRINFO
  41. static struct addrinfo *malloc_ai(uint16_t port, uint32_t addr) {
  42. struct addrinfo *ai;
  43. ai = xmalloc_and_zero(sizeof(struct addrinfo) + sizeof(struct sockaddr_in));
  44. ai->ai_addr = (struct sockaddr *)(ai + 1);
  45. ai->ai_addrlen = sizeof(struct sockaddr_in);
  46. ai->ai_addr->sa_family = ai->ai_family = AF_INET;
  47. ((struct sockaddr_in *)(ai)->ai_addr)->sin_port = port;
  48. ((struct sockaddr_in *)(ai)->ai_addr)->sin_addr.s_addr = addr;
  49. return ai;
  50. }
  51. int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res) {
  52. struct addrinfo *prev = NULL;
  53. struct hostent *hp;
  54. struct in_addr in = {0};
  55. int i;
  56. uint16_t port = 0;
  57. if(hints && hints->ai_family != AF_INET && hints->ai_family != AF_UNSPEC) {
  58. return EAI_FAMILY;
  59. }
  60. if(servname) {
  61. port = htons(atoi(servname));
  62. }
  63. if(hints && hints->ai_flags & AI_PASSIVE) {
  64. *res = malloc_ai(port, htonl(0x00000000));
  65. return 0;
  66. }
  67. if(!hostname) {
  68. *res = malloc_ai(port, htonl(0x7f000001));
  69. return 0;
  70. }
  71. hp = gethostbyname(hostname);
  72. if(!hp || !hp->h_addr_list || !hp->h_addr_list[0]) {
  73. return EAI_NODATA;
  74. }
  75. for(i = 0; hp->h_addr_list[i]; i++) {
  76. *res = malloc_ai(port, ((struct in_addr *)hp->h_addr_list[i])->s_addr);
  77. if(prev) {
  78. prev->ai_next = *res;
  79. }
  80. prev = *res;
  81. }
  82. return 0;
  83. }
  84. #endif /* !HAVE_GETADDRINFO */