parse_pasv_epsv.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Utility routines.
  3. *
  4. * Copyright (C) 2018 Denys Vlasenko
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. //kbuild:lib-$(CONFIG_FTPGET) += parse_pasv_epsv.o
  9. //kbuild:lib-$(CONFIG_FTPPUT) += parse_pasv_epsv.o
  10. //kbuild:lib-$(CONFIG_WGET) += parse_pasv_epsv.o
  11. #include "libbb.h"
  12. int FAST_FUNC parse_pasv_epsv(char *buf)
  13. {
  14. /*
  15. * PASV command will not work for IPv6. RFC2428 describes
  16. * IPv6-capable "extended PASV" - EPSV.
  17. *
  18. * "EPSV [protocol]" asks server to bind to and listen on a data port
  19. * in specified protocol. Protocol is 1 for IPv4, 2 for IPv6.
  20. * If not specified, defaults to "same as used for control connection".
  21. * If server understood you, it should answer "229 <some text>(|||port|)"
  22. * where "|" are literal pipe chars and "port" is ASCII decimal port#.
  23. *
  24. * There is also an IPv6-capable replacement for PORT (EPRT),
  25. * but we don't need that.
  26. *
  27. * NB: PASV may still work for some servers even over IPv6.
  28. * For example, vsftp happily answers
  29. * "227 Entering Passive Mode (0,0,0,0,n,n)" and proceeds as usual.
  30. */
  31. char *ptr;
  32. int port;
  33. if (!ENABLE_FEATURE_IPV6 || buf[2] == '7' /* "227" */) {
  34. /* Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]"
  35. * Server's IP is N1.N2.N3.N4 (we ignore it)
  36. * Server's port for data connection is P1*256+P2 */
  37. ptr = strrchr(buf, ')');
  38. if (ptr) *ptr = '\0';
  39. ptr = strrchr(buf, ',');
  40. if (!ptr) return -1;
  41. *ptr = '\0';
  42. port = xatou_range(ptr + 1, 0, 255);
  43. ptr = strrchr(buf, ',');
  44. if (!ptr) return -1;
  45. *ptr = '\0';
  46. port += xatou_range(ptr + 1, 0, 255) * 256;
  47. } else {
  48. /* Response is "229 garbage(|||P1|)"
  49. * Server's port for data connection is P1 */
  50. ptr = strrchr(buf, '|');
  51. if (!ptr) return -1;
  52. *ptr = '\0';
  53. ptr = strrchr(buf, '|');
  54. if (!ptr) return -1;
  55. *ptr = '\0';
  56. port = xatou_range(ptr + 1, 0, 65535);
  57. }
  58. return port;
  59. }