util.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <boost/process.hpp>
  2. #include "util.h"
  3. using namespace boost::process;
  4. using namespace std;
  5. namespace nmrpflash {
  6. namespace {
  7. template<typename... T> vector<string> run(const string& cmd, const vector<string>& argv)
  8. {
  9. try {
  10. ipstream pipe;
  11. child c(cmd, args(argv), std_out > pipe);
  12. vector<string> ret;
  13. string line;
  14. while (pipe && getline(pipe, line)) {
  15. ret.push_back(line);
  16. }
  17. c.wait();
  18. return ret;
  19. } catch (const exception& e) {
  20. return {};
  21. }
  22. }
  23. #if BOOST_OS_LINUX
  24. std::string nm_get(const string& dev, const string& property)
  25. {
  26. auto lines = run("/usr/bin/nmcli", { "-g", property, "device", "show", dev });
  27. return lines.empty() ? "" : lines[0];
  28. }
  29. #endif
  30. }
  31. #if BOOST_OS_LINUX
  32. bool nm_is_managed(const string& dev)
  33. {
  34. auto s = nm_get(dev, "GENERAL.STATE");
  35. if (s.find("unmanaged") != string::npos) {
  36. return false;
  37. }
  38. return true;
  39. }
  40. void nm_set_managed(const string& dev, bool managed)
  41. {
  42. run("/usr/bin/nmcli", { "device", "set", "ifname", dev, "managed", "no" });
  43. }
  44. string nm_get_connection(const string& dev)
  45. {
  46. return nm_get(dev, "GENERAL.CONNECTION");
  47. }
  48. #elif BOOST_OS_MACOS
  49. cf_ref<CFStringRef> to_cf_string(const std::string& str)
  50. {
  51. CFStringRef ret = CFStringCreateWithFileSystemRepresentation(
  52. kCFAllocatorDefault, str.c_str());
  53. if (!ret) {
  54. throw runtime_error("CFStringCreateWithFileSystemRepresentation");
  55. }
  56. return make_cf_ref(ret);
  57. }
  58. string from_cf_string(const CFStringRef str)
  59. {
  60. auto len = CFStringGetLength(str) + 1;
  61. auto buf = make_unique<char[]>(len);
  62. auto ok = CFStringGetFileSystemRepresentation(
  63. str, buf.get(), len);
  64. if (!ok) {
  65. throw runtime_error("CFStringGetFileSystemRepresentation");
  66. }
  67. return string(buf.get(), len - 1);
  68. }
  69. #endif
  70. }