usbip_detach.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * Copyright (C) 2011 matt mooney <mfm@muteddisk.com>
  3. * 2005-2007 Takahiro Hirofuchi
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <ctype.h>
  19. #include <limits.h>
  20. #include <stdint.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <getopt.h>
  25. #include <unistd.h>
  26. #include "vhci_driver.h"
  27. #include "usbip_common.h"
  28. #include "usbip_network.h"
  29. #include "usbip.h"
  30. static const char usbip_detach_usage_string[] =
  31. "usbip detach <args>\n"
  32. " -p, --port=<port> " USBIP_VHCI_DRV_NAME
  33. " port the device is on\n";
  34. void usbip_detach_usage(void)
  35. {
  36. printf("usage: %s", usbip_detach_usage_string);
  37. }
  38. static int detach_port(char *port)
  39. {
  40. int ret;
  41. uint8_t portnum;
  42. char path[PATH_MAX+1];
  43. for (unsigned int i = 0; i < strlen(port); i++)
  44. if (!isdigit(port[i])) {
  45. err("invalid port %s", port);
  46. return -1;
  47. }
  48. /* check max port */
  49. portnum = atoi(port);
  50. /* remove the port state file */
  51. snprintf(path, PATH_MAX, VHCI_STATE_PATH"/port%d", portnum);
  52. remove(path);
  53. rmdir(VHCI_STATE_PATH);
  54. ret = usbip_vhci_driver_open();
  55. if (ret < 0) {
  56. err("open vhci_driver");
  57. return -1;
  58. }
  59. ret = usbip_vhci_detach_device(portnum);
  60. if (ret < 0)
  61. return -1;
  62. usbip_vhci_driver_close();
  63. return ret;
  64. }
  65. int usbip_detach(int argc, char *argv[])
  66. {
  67. static const struct option opts[] = {
  68. { "port", required_argument, NULL, 'p' },
  69. { NULL, 0, NULL, 0 }
  70. };
  71. int opt;
  72. int ret = -1;
  73. for (;;) {
  74. opt = getopt_long(argc, argv, "p:", opts, NULL);
  75. if (opt == -1)
  76. break;
  77. switch (opt) {
  78. case 'p':
  79. ret = detach_port(optarg);
  80. goto out;
  81. default:
  82. goto err_out;
  83. }
  84. }
  85. err_out:
  86. usbip_detach_usage();
  87. out:
  88. return ret;
  89. }