3
0

parse_pasv_epsv.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 = strrchr(buf, '\r'); /* for PASV responses not ending with ')' */
  39. if (!ptr) ptr = strrchr(buf, '\n'); /* for PASV responses not ending with ')' */
  40. if (ptr) *ptr = '\0';
  41. ptr = strrchr(buf, ',');
  42. if (!ptr) return -1;
  43. *ptr = '\0';
  44. port = xatou_range(ptr + 1, 0, 255);
  45. ptr = strrchr(buf, ',');
  46. if (!ptr) return -1;
  47. *ptr = '\0';
  48. port += xatou_range(ptr + 1, 0, 255) * 256;
  49. } else {
  50. /* Response is "229 garbage(|||P1|)"
  51. * Server's port for data connection is P1 */
  52. ptr = strrchr(buf, '|');
  53. if (!ptr) return -1;
  54. *ptr = '\0';
  55. ptr = strrchr(buf, '|');
  56. if (!ptr) return -1;
  57. *ptr = '\0';
  58. port = xatou_range(ptr + 1, 0, 65535);
  59. }
  60. return port;
  61. }