MythTV  master
mythmiscutil.cpp
Go to the documentation of this file.
1 
2 #include "mythmiscutil.h"
3 
4 // C++ headers
5 #include <array>
6 #include <cerrno>
7 #include <cstdlib>
8 #include <ctime>
9 #include <iostream>
10 
11 // POSIX
12 #include <unistd.h>
13 #include <fcntl.h>
14 #include <sched.h>
15 
16 // System specific C headers
17 #include "compat.h"
18 
19 #ifdef linux
20 #include <sys/vfs.h>
21 #include <sys/sysinfo.h>
22 #include <sys/stat.h> // for umask, chmod
23 #endif
24 
25 #if CONFIG_DARWIN
26 #include <mach/mach.h>
27 #endif
28 
29 #ifdef BSD
30 #include <sys/mount.h> // for struct statfs
31 #include <sys/sysctl.h>
32 #include <sys/stat.h> // for umask, chmod
33 #endif
34 
35 // Qt headers
36 #include <QReadWriteLock>
37 #include <QNetworkProxy>
38 #include <QStringList>
39 #include <QDataStream>
40 #include <QUdpSocket>
41 #include <QFileInfo>
42 #include <QFile>
43 #include <QDir>
44 #include <QUrl>
45 #include <QHostAddress>
46 #include <QDataStream>
47 #include <QRegularExpression>
48 #include <QRegularExpressionMatchIterator>
49 
50 // Myth headers
51 #include "mythcorecontext.h"
52 #include "exitcodes.h"
53 #include "mythlogging.h"
54 #include "mythsocket.h"
55 #include "mythcoreutil.h"
56 #include "mythsystemlegacy.h"
57 
58 #include "mythconfig.h" // for CONFIG_DARWIN
59 
60 #if QT_VERSION < QT_VERSION_CHECK(5,10,0)
61 #define qEnvironmentVariable getenv
62 #endif
63 
68 bool getUptime(std::chrono::seconds &uptime)
69 {
70 #ifdef __linux__
71  struct sysinfo sinfo {};
72  if (sysinfo(&sinfo) == -1)
73  {
74  LOG(VB_GENERAL, LOG_ERR, "sysinfo() error");
75  return false;
76  }
77  uptime = std::chrono::seconds(sinfo.uptime);
78 
79 #elif defined(__FreeBSD__) || CONFIG_DARWIN
80 
81  std::array<int,2> mib { CTL_KERN, KERN_BOOTTIME };
82  struct timeval bootTime;
83  size_t len;
84 
85  // Uptime is calculated. Get this machine's boot time
86  // and subtract it from the current machine time
87  len = sizeof(bootTime);
88  if (sysctl(mib.data(), 2, &bootTime, &len, nullptr, 0) == -1)
89  {
90  LOG(VB_GENERAL, LOG_ERR, "sysctl() error");
91  return false;
92  }
93  uptime = std::chrono::seconds(time(nullptr) - bootTime.tv_sec);
94 #elif defined(_WIN32)
95  uptime = std::chrono::seconds(::GetTickCount() / 1000);
96 #else
97  // Hmmm. Not Linux, not FreeBSD or Darwin. What else is there :-)
98  LOG(VB_GENERAL, LOG_NOTICE, "Unknown platform. How do I get the uptime?");
99  return false;
100 #endif
101 
102  return true;
103 }
104 
111 bool getMemStats(int &totalMB, int &freeMB, int &totalVM, int &freeVM)
112 {
113 #ifdef __linux__
114  const size_t MB = (1024*1024);
115  struct sysinfo sinfo {};
116  if (sysinfo(&sinfo) == -1)
117  {
118  LOG(VB_GENERAL, LOG_ERR,
119  "getMemStats(): Error, sysinfo() call failed.");
120  return false;
121  }
122 
123  totalMB = (int)((sinfo.totalram * sinfo.mem_unit)/MB);
124  freeMB = (int)((sinfo.freeram * sinfo.mem_unit)/MB);
125  totalVM = (int)((sinfo.totalswap * sinfo.mem_unit)/MB);
126  freeVM = (int)((sinfo.freeswap * sinfo.mem_unit)/MB);
127  return true;
128 #elif CONFIG_DARWIN
129  mach_port_t mp;
130  mach_msg_type_number_t count;
131  vm_size_t pageSize;
132  vm_statistics_data_t s;
133 
134  mp = mach_host_self();
135 
136  // VM page size
137  if (host_page_size(mp, &pageSize) != KERN_SUCCESS)
138  pageSize = 4096; // If we can't look it up, 4K is a good guess
139 
140  count = HOST_VM_INFO_COUNT;
141  if (host_statistics(mp, HOST_VM_INFO,
142  (host_info_t)&s, &count) != KERN_SUCCESS)
143  {
144  LOG(VB_GENERAL, LOG_ERR, "getMemStats(): Error, "
145  "failed to get virtual memory statistics.");
146  return false;
147  }
148 
149  pageSize >>= 10; // This gives usages in KB
150  totalMB = (s.active_count + s.inactive_count +
151  s.wire_count + s.free_count) * pageSize / 1024;
152  freeMB = s.free_count * pageSize / 1024;
153 
154 
155  // This is a real hack. I have not found a way to ask the kernel how much
156  // swap it is using, and the dynamic_pager daemon doesn't even seem to be
157  // able to report what filesystem it is using for the swapfiles. So, we do:
158  int64_t total, used, free;
159  free = getDiskSpace("/private/var/vm", total, used);
160  totalVM = (int)(total >> 10);
161  freeVM = (int)(free >> 10);
162  return true;
163 #else
164  Q_UNUSED(totalMB);
165  Q_UNUSED(freeMB);
166  Q_UNUSED(totalVM);
167  Q_UNUSED(freeVM);
168  return false;
169 #endif
170 }
171 
179 {
180 #if !defined(_WIN32) && !defined(Q_OS_ANDROID)
181  loadArray loads {};
182  if (getloadavg(loads.data(), loads.size()) != -1)
183  return loads;
184 #endif
185  return {-1, -1, -1};
186 }
187 
195 bool hasUtf8(const char *str)
196 {
197  const uchar *c = (uchar *) str;
198 
199  while (*c++)
200  {
201  // ASCII is < 0x80.
202  // 0xC2..0xF4 is probably UTF-8.
203  // Anything else probably ISO-8859-1 (Latin-1, Unicode)
204 
205  if (*c > 0xC1 && *c < 0xF5)
206  {
207  int bytesToCheck = 2; // Assume 0xC2-0xDF (2 byte sequence)
208 
209  if (*c > 0xDF) // Maybe 0xE0-0xEF (3 byte sequence)
210  ++bytesToCheck;
211  if (*c > 0xEF) // Matches 0xF0-0xF4 (4 byte sequence)
212  ++bytesToCheck;
213 
214  while (bytesToCheck--)
215  {
216  ++c;
217 
218  if (! *c) // String ended in middle
219  return false; // Not valid UTF-8
220 
221  if (*c < 0x80 || *c > 0xBF) // Bad UTF-8 sequence
222  break; // Keep checking in outer loop
223  }
224 
225  if (!bytesToCheck) // Have checked all the bytes in the sequence
226  return true; // Hooray! We found valid UTF-8!
227  }
228  }
229 
230  return false;
231 }
232 
247 bool ping(const QString &host, std::chrono::milliseconds timeout)
248 {
249 #ifdef _WIN32
250  QString cmd = QString("%systemroot%\\system32\\ping.exe -w %1 -n 1 %2>NUL")
251  .arg(timeout.count()) .arg(host);
252 
255 #else
256  QString addrstr =
258  QHostAddress addr = QHostAddress(addrstr);
259 #if defined(__FreeBSD__) || CONFIG_DARWIN
260  QString timeoutparam("-t");
261 #else
262  // Linux, NetBSD, OpenBSD
263  QString timeoutparam("-w");
264 #endif
265  QString pingcmd =
266  addr.protocol() == QAbstractSocket::IPv6Protocol ? "ping6" : "ping";
267  QString cmd = QString("%1 %2 %3 -c 1 %4 >/dev/null 2>&1")
268  .arg(pingcmd, timeoutparam,
269  QString::number(duration_cast<std::chrono::seconds>(timeout).count()),
270  host);
271 
274 #endif
275 }
276 
280 bool telnet(const QString &host, int port)
281 {
282  auto *s = new MythSocket();
283 
284  bool connected = s->ConnectToHost(host, port);
285  s->DecrRef();
286 
287  return connected;
288 }
289 
311 long long copy(QFile &dst, QFile &src, uint block_size)
312 {
313  uint buflen = (block_size < 1024) ? (16 * 1024) : block_size;
314  char *buf = new char[buflen];
315  bool odst = false;
316  bool osrc = false;
317 
318  if (!buf)
319  return -1LL;
320 
321  if (!dst.isWritable() && !dst.isOpen())
322  {
323  odst = dst.open(QIODevice::Unbuffered |
324  QIODevice::WriteOnly |
325  QIODevice::Truncate);
326  }
327 
328  if (!src.isReadable() && !src.isOpen())
329  osrc = src.open(QIODevice::Unbuffered|QIODevice::ReadOnly);
330 
331  bool ok = dst.isWritable() && src.isReadable();
332  long long total_bytes = 0LL;
333  while (ok)
334  {
335  long long off = 0;
336  long long rlen = src.read(buf, buflen);
337  if (rlen<0)
338  {
339  LOG(VB_GENERAL, LOG_ERR, "read error");
340  ok = false;
341  break;
342  }
343  if (rlen==0)
344  break;
345 
346  total_bytes += rlen;
347 
348  while ((rlen-off>0) && ok)
349  {
350  long long wlen = dst.write(buf + off, rlen - off);
351  if (wlen>=0)
352  off+= wlen;
353  if (wlen<0)
354  {
355  LOG(VB_GENERAL, LOG_ERR, "write error");
356  ok = false;
357  }
358  }
359  }
360  delete[] buf;
361 
362  if (odst)
363  dst.close();
364 
365  if (osrc)
366  src.close();
367 
368  return (ok) ? total_bytes : -1LL;
369 }
370 
371 QString createTempFile(QString name_template, bool dir)
372 {
373  int ret = -1;
374 
375 #ifdef _WIN32
376  char temppath[MAX_PATH] = ".";
377  char tempfilename[MAX_PATH] = "";
378  // if GetTempPath fails, use current dir
379  GetTempPathA(MAX_PATH, temppath);
380  if (GetTempFileNameA(temppath, "mth", 0, tempfilename))
381  {
382  if (dir)
383  {
384  // GetTempFileNameA creates the file, so delete it before mkdir
385  unlink(tempfilename);
386  ret = mkdir(tempfilename);
387  }
388  else
389  ret = open(tempfilename, O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
390  }
391  QString tmpFileName(tempfilename);
392 #else
393  QByteArray safe_name_template = name_template.toLatin1();
394  const char *tmp = safe_name_template.constData();
395  char *ctemplate = strdup(tmp);
396 
397  if (dir)
398  {
399  ret = (mkdtemp(ctemplate)) ? 0 : -1;
400  }
401  else
402  {
403  mode_t cur_umask = umask(S_IRWXO | S_IRWXG);
404  ret = mkstemp(ctemplate);
405  umask(cur_umask);
406  }
407 
408  QString tmpFileName(ctemplate);
409  free(ctemplate);
410 #endif
411 
412  if (ret == -1)
413  {
414  LOG(VB_GENERAL, LOG_ERR, QString("createTempFile(%1), Error ")
415  .arg(name_template) + ENO);
416  return name_template;
417  }
418 
419  if (!dir && (ret >= 0))
420  close(ret);
421 
422  return tmpFileName;
423 }
424 
443 bool makeFileAccessible(const QString& filename)
444 {
445  QByteArray fname = filename.toLatin1();
446  int ret = chmod(fname.constData(), 0666);
447  if (ret == -1)
448  {
449  LOG(VB_GENERAL, LOG_ERR, QString("Unable to change permissions on file. (%1)").arg(filename));
450  return false;
451  }
452  return true;
453 }
454 
458 QString getResponse(const QString &query, const QString &def)
459 {
460  QByteArray tmp = query.toLocal8Bit();
461  std::cout << tmp.constData();
462 
463  tmp = def.toLocal8Bit();
464  if (!def.isEmpty())
465  std::cout << " [" << tmp.constData() << "] ";
466  else
467  std::cout << " ";
468 
469  if (!isatty(fileno(stdin)) || !isatty(fileno(stdout)))
470  {
471  std::cout << std::endl << "[console is not interactive, using default '"
472  << tmp.constData() << "']" << std::endl;
473  return def;
474  }
475 
476  QTextStream stream(stdin);
477  QString qresponse = stream.readLine();
478 
479  if (qresponse.isEmpty())
480  qresponse = def;
481 
482  return qresponse;
483 }
484 
488 int intResponse(const QString &query, int def)
489 {
490  QString str_resp = getResponse(query, QString("%1").arg(def));
491  if (str_resp.isEmpty())
492  return def;
493  bool ok = false;
494  int resp = str_resp.toInt(&ok);
495  return (ok ? resp : def);
496 }
497 
498 
499 QString getSymlinkTarget(const QString &start_file,
500  QStringList *intermediaries,
501  unsigned maxLinks)
502 {
503 #if 0
504  LOG(VB_GENERAL, LOG_DEBUG,
505  QString("getSymlinkTarget('%1', 0x%2, %3)")
506  .arg(start_file).arg((uint64_t)intermediaries,0,16)
507  .arg(maxLinks));
508 #endif
509 
510  QString link;
511  QString cur_file = start_file;
512  QFileInfo fi(cur_file);
513 
514  if (intermediaries)
515  {
516  intermediaries->clear();
517  intermediaries->push_back(start_file);
518  }
519 
520  for (uint i = 0; (i <= maxLinks) && fi.isSymLink() &&
521  !(link = fi.symLinkTarget()).isEmpty(); i++)
522  {
523  cur_file = (link[0] == '/') ?
524  link : // absolute link
525  fi.absoluteDir().absolutePath() + "/" + link; // relative link
526 
527  if (intermediaries && !intermediaries->contains(cur_file))
528  intermediaries->push_back(cur_file);
529 
530  fi = QFileInfo(cur_file);
531  }
532 
533 #if 0
534  if (intermediaries)
535  {
536  for (uint i = 0; i < intermediaries->size(); i++)
537  {
538  LOG(VB_GENERAL, LOG_DEBUG, QString(" inter%1: %2")
539  .arg(i).arg((*intermediaries)[i]));
540  }
541  }
542 
543  LOG(VB_GENERAL, LOG_DEBUG,
544  QString("getSymlinkTarget() -> '%1'")
545  .arg((!fi.isSymLink()) ? cur_file : QString()));
546 #endif
547 
548  return (!fi.isSymLink()) ? cur_file : QString();
549 }
550 
551 bool IsMACAddress(const QString& MAC)
552 {
553  QStringList tokens = MAC.split(':');
554  if (tokens.size() != 6)
555  {
556  LOG(VB_NETWORK, LOG_ERR,
557  QString("IsMACAddress(%1) = false, doesn't have 6 parts").arg(MAC));
558  return false;
559  }
560 
561  for (int y = 0; y < 6; y++)
562  {
563  if (tokens[y].isEmpty())
564  {
565  LOG(VB_NETWORK, LOG_ERR,
566  QString("IsMACAddress(%1) = false, part #%2 is empty.")
567  .arg(MAC).arg(y));
568  return false;
569  }
570 
571  bool ok = false;
572  int value = tokens[y].toInt(&ok, 16);
573  if (!ok)
574  {
575  LOG(VB_NETWORK, LOG_ERR,
576  QString("IsMACAddress(%1) = false, unable to "
577  "convert part '%2' to integer.")
578  .arg(MAC, tokens[y]));
579  return false;
580  }
581 
582  if (value > 255)
583  {
584  LOG(VB_NETWORK, LOG_ERR,
585  QString("IsMACAddress(%1) = false, part #%2 "
586  "evaluates to %3 which is higher than 255.")
587  .arg(MAC).arg(y).arg(value));
588  return false;
589  }
590  }
591 
592  LOG(VB_NETWORK, LOG_DEBUG, QString("IsMACAddress(%1) = true").arg(MAC));
593  return true;
594 }
595 
596 QString FileHash(const QString& filename)
597 {
598  QFile file(filename);
599  QFileInfo fileinfo(file);
600  qint64 initialsize = fileinfo.size();
601  quint64 hash = 0;
602 
603  if (initialsize == 0)
604  return QString("NULL");
605 
606  if (file.open(QIODevice::ReadOnly))
607  hash = initialsize;
608  else
609  {
610  LOG(VB_GENERAL, LOG_ERR,
611  "Error: Unable to open selected file, missing read permissions?");
612  return QString("NULL");
613  }
614 
615  file.seek(0);
616  QDataStream stream(&file);
617  stream.setByteOrder(QDataStream::LittleEndian);
618  for (quint64 tmp = 0, i = 0; i < 65536/sizeof(tmp); i++)
619  {
620  stream >> tmp;
621  hash += tmp;
622  }
623 
624  file.seek(initialsize - 65536);
625  for (quint64 tmp = 0, i = 0; i < 65536/sizeof(tmp); i++)
626  {
627  stream >> tmp;
628  hash += tmp;
629  }
630 
631  file.close();
632 
633  QString output = QString("%1").arg(hash, 0, 16);
634  return output;
635 }
636 
637 bool WakeOnLAN(const QString& MAC)
638 {
639  std::vector<char> msg(6, static_cast<char>(0xFF));
640  std::array<char,6> macaddr {};
641  QStringList tokens = MAC.split(':');
642 
643  if (tokens.size() != 6)
644  {
645  LOG(VB_GENERAL, LOG_ERR,
646  QString( "WakeOnLan(%1): Incorrect MAC length").arg(MAC));
647  return false;
648  }
649 
650  for (int y = 0; y < 6; y++)
651  {
652  bool ok = false;
653  macaddr[y] = tokens[y].toInt(&ok, 16);
654 
655  if (!ok)
656  {
657  LOG(VB_GENERAL, LOG_ERR,
658  QString( "WakeOnLan(%1): Invalid MAC address").arg(MAC));
659  return false;
660  }
661  }
662 
663  msg.reserve(1024);
664  for (int x = 0; x < 16; x++)
665  msg.insert(msg.end(), macaddr.cbegin(), macaddr.cend());
666 
667  LOG(VB_NETWORK, LOG_INFO,
668  QString("WakeOnLan(): Sending WOL packet to %1").arg(MAC));
669 
670  QUdpSocket udp_socket;
671  qlonglong msglen = msg.size();
672  return udp_socket.writeDatagram(
673  msg.data(), msglen, QHostAddress::Broadcast, 32767) == msglen;
674 }
675 
676 // Wake up either by command or by MAC address
677 // return true = success
678 bool MythWakeup(const QString &wakeUpCommand, uint flags, std::chrono::seconds timeout)
679 {
680  if (!IsMACAddress(wakeUpCommand))
681  return myth_system(wakeUpCommand, flags, timeout) == 0U;
682 
683  return WakeOnLAN(wakeUpCommand);
684 }
685 
687 {
688 #ifdef _WIN32
689  return false;
690 #else
691 
692 #if CONFIG_DARWIN || (__FreeBSD__) || defined(__OpenBSD__)
693  const char *command = "ps -ax | grep -i pulseaudio | grep -v grep > /dev/null";
694 #else
695  const char *command = "ps ch -C pulseaudio -o pid > /dev/null";
696 #endif
697  // Do NOT use kMSProcessEvents here, it will cause deadlock
698  uint res = myth_system(command, kMSDontBlockInputDevs |
700  return (res == GENERIC_EXIT_OK);
701 #endif // _WIN32
702 }
703 
704 bool myth_nice(int val)
705 {
706  errno = 0;
707  int ret = nice(val);
708 
709  if ((-1 == ret) && (0 != errno) && (val >= 0))
710  {
711  LOG(VB_GENERAL, LOG_ERR, "Failed to nice process" + ENO);
712  return false;
713  }
714 
715  return true;
716 }
717 
718 void myth_yield(void)
719 {
720 #ifdef _POSIX_PRIORITY_SCHEDULING
721  if (sched_yield()<0)
722  usleep(5000);
723 #else
724  usleep(5000);
725 #endif
726 }
727 
745 #if defined(__linux__) && ( defined(__i386__) || defined(__ppc__) || \
746  defined(__x86_64__) || defined(__ia64__) )
747 
748 #include <cstdio>
749 #include <cstdlib>
750 #include <cerrno>
751 #include <getopt.h>
752 #include <unistd.h>
753 #include <sys/ptrace.h>
754 #include <asm/unistd.h>
755 
756 #if defined(__i386__)
757 # define NR_ioprio_set 289
758 # define NR_ioprio_get 290
759 #elif defined(__ppc__)
760 # define NR_ioprio_set 273
761 # define NR_ioprio_get 274
762 #elif defined(__x86_64__)
763 # define NR_ioprio_set 251
764 # define NR_ioprio_get 252
765 #elif defined(__ia64__)
766 # define NR_ioprio_set 1274
767 # define NR_ioprio_get 1275
768 #endif
769 
770 #define IOPRIO_BITS (16)
771 #define IOPRIO_CLASS_SHIFT (13)
772 #define IOPRIO_PRIO_MASK ((1UL << IOPRIO_CLASS_SHIFT) - 1)
773 #define IOPRIO_PRIO_CLASS(mask) ((mask) >> IOPRIO_CLASS_SHIFT)
774 #define IOPRIO_PRIO_DATA(mask) ((mask) & IOPRIO_PRIO_MASK)
775 #define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | (data))
776 
777 enum { IOPRIO_CLASS_NONE,IOPRIO_CLASS_RT,IOPRIO_CLASS_BE,IOPRIO_CLASS_IDLE, };
778 enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER, };
779 
780 bool myth_ioprio(int val)
781 {
782  int new_ioclass = (val < 0) ? IOPRIO_CLASS_RT :
783  (val > 7) ? IOPRIO_CLASS_IDLE : IOPRIO_CLASS_BE;
784  int new_iodata = (new_ioclass == IOPRIO_CLASS_BE) ? val : 0;
785  int new_ioprio = IOPRIO_PRIO_VALUE(new_ioclass, new_iodata);
786 
787  int pid = getpid();
788  int old_ioprio = syscall(NR_ioprio_get, IOPRIO_WHO_PROCESS, pid);
789  if (old_ioprio == new_ioprio)
790  return true;
791 
792  int ret = syscall(NR_ioprio_set, IOPRIO_WHO_PROCESS, pid, new_ioprio);
793 
794  if (-1 == ret && EPERM == errno && IOPRIO_CLASS_BE != new_ioclass)
795  {
796  new_iodata = (new_ioclass == IOPRIO_CLASS_RT) ? 0 : 7;
797  new_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, new_iodata);
798  ret = syscall(NR_ioprio_set, IOPRIO_WHO_PROCESS, pid, new_ioprio);
799  }
800 
801  return 0 == ret;
802 }
803 
804 #else
805 
806 bool myth_ioprio(int) { return true; }
807 
808 #endif
809 
810 bool MythRemoveDirectory(QDir &aDir)
811 {
812  if (!aDir.exists())//QDir::NoDotAndDotDot
813  return false;
814 
815  QFileInfoList entries = aDir.entryInfoList(QDir::NoDotAndDotDot |
816  QDir::Dirs | QDir::Files);
817  int count = entries.size();
818  bool has_err = false;
819 
820  for (int idx = 0; idx < count && !has_err; idx++)
821  {
822  QFileInfo entryInfo = entries[idx];
823  QString path = entryInfo.absoluteFilePath();
824  if (entryInfo.isDir())
825  {
826  QDir dir(path);
827  has_err = MythRemoveDirectory(dir);
828  }
829  else
830  {
831  QFile file(path);
832  if (!file.remove())
833  has_err = true;
834  }
835  }
836 
837  if (!has_err && !aDir.rmdir(aDir.absolutePath()))
838  has_err = true;
839 
840  return(has_err);
841 }
842 
854 void setHttpProxy(void)
855 {
856  QString LOC = "setHttpProxy() - ";
857 
858  // Set http proxy for the application if specified in environment variable
859  QString var(qEnvironmentVariable("http_proxy"));
860  if (var.isEmpty())
861  var = qEnvironmentVariable("HTTP_PROXY"); // Sadly, some OS envs are case sensitive
862  if (!var.isEmpty())
863  {
864  if (!var.startsWith("http://")) // i.e. just a host name
865  var.prepend("http://");
866 
867  QUrl url = QUrl(var, QUrl::TolerantMode);
868  QString host = url.host();
869  int port = url.port();
870 
871  if (port == -1) // Parsing error
872  {
873  port = 0; // The default when creating a QNetworkProxy
874 
875  if (telnet(host, 1080)) // Socks?
876  port = 1080;
877  if (telnet(host, 3128)) // Squid
878  port = 3128;
879  if (telnet(host, 8080)) // MS ISA
880  port = 8080;
881 
882  LOG(VB_NETWORK, LOG_INFO, LOC +
883  QString("assuming port %1 on host %2") .arg(port).arg(host));
884  url.setPort(port);
885  }
886  else if (!ping(host, 1s))
887  {
888  LOG(VB_GENERAL, LOG_ERR, LOC +
889  QString("cannot locate host %1").arg(host) +
890  "\n\t\t\tPlease check HTTP_PROXY environment variable!");
891  }
892  else if (!telnet(host,port))
893  {
894  LOG(VB_GENERAL, LOG_ERR, LOC +
895  QString("%1:%2 - cannot connect!").arg(host).arg(port) +
896  "\n\t\t\tPlease check HTTP_PROXY environment variable!");
897  }
898 
899 #if 0
900  LOG(VB_NETWORK, LOG_DEBUG, LOC + QString("using http://%1:%2@%3:%4")
901  .arg(url.userName()).arg(url.password())
902  .arg(host).arg(port));
903 #endif
904  QNetworkProxy p =
905  QNetworkProxy(QNetworkProxy::HttpCachingProxy,
906  host, port, url.userName(), url.password());
907  QNetworkProxy::setApplicationProxy(p);
908  return;
909  }
910 
911  LOG(VB_NETWORK, LOG_DEBUG, LOC + "no HTTP_PROXY environment var.");
912 
913  // Use Qt to look for user proxy settings stored by the OS or browser:
914 
915  QList<QNetworkProxy> proxies;
916  QNetworkProxyQuery query(QUrl("http://www.mythtv.org"));
917 
918  proxies = QNetworkProxyFactory::systemProxyForQuery(query);
919 
920  for (const auto& p : qAsConst(proxies))
921  {
922  QString host = p.hostName();
923  int port = p.port();
924 
925  if (p.type() == QNetworkProxy::NoProxy)
926  continue;
927 
928  if (!telnet(host, port))
929  {
930  LOG(VB_NETWORK, LOG_ERR, LOC +
931  "failed to contact proxy host " + host);
932  continue;
933  }
934 
935  LOG(VB_NETWORK, LOG_INFO, LOC + QString("using proxy host %1:%2")
936  .arg(host).arg(port));
937  QNetworkProxy::setApplicationProxy(p);
938 
939  // Allow sub-commands to use this proxy
940  // via myth_system(command), by setting HTTP_PROXY
941  QString url;
942 
943  if (!p.user().isEmpty())
944  {
945  url = "http://%1:%2@%3:%4",
946  url = url.arg(p.user(), p.password());
947  }
948  else
949  {
950  url = "http://%1:%2";
951  }
952 
953  url = url.arg(p.hostName()).arg(p.port());
954  setenv("HTTP_PROXY", url.toLatin1(), 1);
955  setenv("http_proxy", url.toLatin1(), 0);
956 
957  return;
958  }
959 
960  LOG(VB_NETWORK, LOG_ERR, LOC + "failed to find a network proxy");
961 }
962 
963 void wrapList(QStringList &list, int width)
964 {
965  // if this is triggered, something has gone seriously wrong
966  // the result won't really be usable, but at least it won't crash
967  width = std::max(width, 5);
968 
969  for (int i = 0; i < list.size(); i++)
970  {
971  QString string = list.at(i);
972 
973  if( string.size() <= width )
974  continue;
975 
976  QString left = string.left(width);
977  bool inserted = false;
978 
979  while( !inserted && !left.endsWith(" " ))
980  {
981  if( string.mid(left.size(), 1) == " " )
982  {
983  list.replace(i, left);
984  list.insert(i+1, string.mid(left.size()).trimmed());
985  inserted = true;
986  }
987  else
988  {
989  left.chop(1);
990  if( !left.contains(" ") )
991  {
992  // Line is too long, just hyphenate it
993  list.replace(i, left + "-");
994  list.insert(i+1, string.mid(left.size()));
995  inserted = true;
996  }
997  }
998  }
999 
1000  if( !inserted )
1001  {
1002  left.chop(1);
1003  list.replace(i, left);
1004  list.insert(i+1, string.mid(left.size()).trimmed());
1005  }
1006  }
1007 }
1008 
1009 QString xml_indent(uint level)
1010 {
1011  static QReadWriteLock s_rwLock;
1012  static QMap<uint,QString> s_cache;
1013 
1014  s_rwLock.lockForRead();
1015  QMap<uint,QString>::const_iterator it = s_cache.constFind(level);
1016  if (it != s_cache.constEnd())
1017  {
1018  QString tmp = *it;
1019  s_rwLock.unlock();
1020  return tmp;
1021  }
1022  s_rwLock.unlock();
1023 
1024  QString ret = "";
1025  for (uint i = 0; i < level; i++)
1026  ret += " ";
1027 
1028  s_rwLock.lockForWrite();
1029  s_cache[level] = ret;
1030  s_rwLock.unlock();
1031 
1032  return ret;
1033 }
1034 
1035 int naturalCompare(const QString &_a, const QString &_b, Qt::CaseSensitivity caseSensitivity)
1036 {
1037  // This method chops the input a and b into pieces of
1038  // digits and non-digits (a1.05 becomes a | 1 | . | 05)
1039  // and compares these pieces of a and b to each other
1040  // (first with first, second with second, ...).
1041  //
1042  // This is based on the natural sort order code code by Martin Pool
1043  // http://sourcefrog.net/projects/natsort/
1044  // Martin Pool agreed to license this under LGPL or GPL.
1045 
1046  // FIXME: Using toLower() to implement case insensitive comparison is
1047  // sub-optimal, but is needed because we compare strings with
1048  // localeAwareCompare(), which does not know about case sensitivity.
1049  // A task has been filled for this in Qt Task Tracker with ID 205990.
1050  // http://trolltech.com/developer/task-tracker/index_html?method=entry&id=205990
1051 
1052  QString a;
1053  QString b;
1054 
1055  if (caseSensitivity == Qt::CaseSensitive)
1056  {
1057  a = _a;
1058  b = _b;
1059  }
1060  else
1061  {
1062  a = _a.toLower();
1063  b = _b.toLower();
1064  }
1065 
1066  const QChar* currA = a.unicode(); // iterator over a
1067  const QChar* currB = b.unicode(); // iterator over b
1068 
1069  if (currA == currB)
1070  {
1071  return 0;
1072  }
1073 
1074  while (!currA->isNull() && !currB->isNull())
1075  {
1076  const QChar* begSeqA = currA; // beginning of a new character sequence of a
1077  const QChar* begSeqB = currB;
1078 
1079  if (currA->unicode() == QChar::ObjectReplacementCharacter)
1080  {
1081  return 1;
1082  }
1083 
1084  if (currB->unicode() == QChar::ObjectReplacementCharacter)
1085  {
1086  return -1;
1087  }
1088 
1089  if (currA->unicode() == QChar::ReplacementCharacter)
1090  {
1091  return 1;
1092  }
1093 
1094  if (currB->unicode() == QChar::ReplacementCharacter)
1095  {
1096  return -1;
1097  }
1098 
1099  // find sequence of characters ending at the first non-character
1100  while (!currA->isNull() && !currA->isDigit() && !currA->isPunct() &&
1101  !currA->isSpace())
1102  {
1103  ++currA;
1104  }
1105 
1106  while (!currB->isNull() && !currB->isDigit() && !currB->isPunct() &&
1107  !currB->isSpace())
1108  {
1109  ++currB;
1110  }
1111 
1112  // compare these sequences
1113  const QString& subA(a.mid(begSeqA - a.unicode(), currA - begSeqA));
1114  const QString& subB(b.mid(begSeqB - b.unicode(), currB - begSeqB));
1115  const int cmp = QString::localeAwareCompare(subA, subB);
1116 
1117  if (cmp != 0)
1118  {
1119  return cmp < 0 ? -1 : +1;
1120  }
1121 
1122  if (currA->isNull() || currB->isNull())
1123  {
1124  break;
1125  }
1126 
1127  // find sequence of characters ending at the first non-character
1128  while ((currA->isPunct() || currA->isSpace()) &&
1129  (currB->isPunct() || currB->isSpace()))
1130  {
1131  if (*currA != *currB)
1132  {
1133  return (*currA < *currB) ? -1 : +1;
1134  }
1135  ++currA;
1136  ++currB;
1137  if (currA->isNull() || currB->isNull())
1138  {
1139  break;
1140  }
1141  }
1142 
1143  // now some digits follow...
1144  if ((*currA == QLatin1Char('0')) || (*currB == QLatin1Char('0')))
1145  {
1146  // one digit-sequence starts with 0 -> assume we are in a fraction part
1147  // do left aligned comparison (numbers are considered left aligned)
1148  while (true)
1149  {
1150  if (!currA->isDigit() && !currB->isDigit())
1151  {
1152  break;
1153  }
1154  if (!currA->isDigit())
1155  {
1156  return +1;
1157  }
1158  if (!currB->isDigit())
1159  {
1160  return -1;
1161  }
1162  if (*currA < *currB)
1163  {
1164  return -1;
1165  }
1166  if (*currA > *currB)
1167  {
1168  return + 1;
1169  }
1170  ++currA;
1171  ++currB;
1172  }
1173  }
1174  else
1175  {
1176  // No digit-sequence starts with 0 -> assume we are looking at some integer
1177  // do right aligned comparison.
1178  //
1179  // The longest run of digits wins. That aside, the greatest
1180  // value wins, but we can't know that it will until we've scanned
1181  // both numbers to know that they have the same magnitude.
1182 
1183  bool isFirstRun = true;
1184  int weight = 0;
1185 
1186  while (true)
1187  {
1188  if (!currA->isDigit() && !currB->isDigit())
1189  {
1190  if (weight != 0)
1191  {
1192  return weight;
1193  }
1194  break;
1195  }
1196  if (!currA->isDigit())
1197  {
1198  if (isFirstRun)
1199  {
1200  return *currA < *currB ? -1 : +1;
1201  }
1202  return -1;
1203  }
1204  if (!currB->isDigit())
1205  {
1206  if (isFirstRun)
1207  {
1208  return *currA < *currB ? -1 : +1;
1209  }
1210  return +1;
1211  }
1212  if ((*currA < *currB) && (weight == 0))
1213  {
1214  weight = -1;
1215  }
1216  else if ((*currA > *currB) && (weight == 0))
1217  {
1218  weight = + 1;
1219  }
1220  ++currA;
1221  ++currB;
1222  isFirstRun = false;
1223  }
1224  }
1225  }
1226 
1227  if (currA->isNull() && currB->isNull())
1228  {
1229  return 0;
1230  }
1231 
1232  return currA->isNull() ? -1 : + 1;
1233 }
1234 
1235 QString MythFormatTime(std::chrono::milliseconds msecs, const QString& fmt)
1236 {
1237  return QTime::fromMSecsSinceStartOfDay(msecs.count()).toString(fmt);
1238 }
1239 
1240 /*
1241  * States for the command line parser.
1242  */
1243 enum states {
1244  START, // No current token.
1245  INTEXT, // Collecting token text.
1246  INSQUOTE, // Collecting token, inside single quotes.
1247  INDQUOTE, // Collecting token, inside double quotes.
1248  ESCTEXT, // Saw backslash. Returns to generic text.
1249  ESCSQUOTE, // Saw backslash. Returns to single quotes.
1250  ESCDQUOTE, // Saw backslash. Returns to double quotes.
1251 };
1252 
1253 /*
1254  * Parse a string into separate tokens. This function understands
1255  * quoting and the escape character.
1256  */
1257 QStringList MythSplitCommandString(const QString &line)
1258 {
1259  QStringList fields;
1260  states state = START;
1261  int tokenStart = -1;
1262 
1263  for (int i = 0; i < line.size(); i++)
1264  {
1265  const QChar c = line.at(i);
1266 
1267  switch (state) {
1268  case START:
1269  tokenStart = i;
1270  if (c.isSpace()) break;
1271  if (c == '\'') state = INSQUOTE;
1272  else if (c == '\"') state = INDQUOTE;
1273  else if (c == '\\') state = ESCTEXT;
1274  else state = INTEXT;
1275  break;
1276  case INTEXT:
1277  if (c.isSpace()) {
1278  fields += line.mid(tokenStart, i - tokenStart);
1279  state = START;
1280  break;
1281  }
1282  else if (c == '\'') state = INSQUOTE;
1283  else if (c == '\"') state = INDQUOTE;
1284  else if (c == '\\') state = ESCTEXT;
1285  break;
1286  case INSQUOTE:
1287  if (c == '\'') state = INTEXT;
1288  else if (c == '\\') state = ESCSQUOTE;
1289  break;
1290  case INDQUOTE:
1291  if (c == '\"') state = INTEXT;
1292  else if (c == '\\') state = ESCDQUOTE;
1293  break;
1294  case ESCTEXT: state = INTEXT; break;
1295  case ESCSQUOTE: state = INSQUOTE; break;
1296  case ESCDQUOTE: state = INDQUOTE; break;
1297  }
1298  }
1299 
1300  if (state != START)
1301  fields += line.mid(tokenStart);
1302  return fields;
1303 }
1304 
1305 /* vim: set expandtab tabstop=4 shiftwidth=4: */
ENO
#define ENO
This can be appended to the LOG args with "+".
Definition: mythlogging.h:72
hardwareprofile.smolt.timeout
float timeout
Definition: smolt.py:103
GENERIC_EXIT_OK
#define GENERIC_EXIT_OK
Exited with no error.
Definition: exitcodes.h:10
setHttpProxy
void setHttpProxy(void)
Get network proxy settings from OS, and use for [Q]Http[Comms].
Definition: mythmiscutil.cpp:854
copy
long long copy(QFile &dst, QFile &src, uint block_size)
Copies src file to dst file.
Definition: mythmiscutil.cpp:311
kMSDontBlockInputDevs
@ kMSDontBlockInputDevs
avoid blocking LIRC & Joystick Menu
Definition: mythsystem.h:36
getDiskSpace
int64_t getDiskSpace(const QString &file_on_disk, int64_t &total, int64_t &used)
Definition: mythcoreutil.cpp:43
myth_ioprio
bool myth_ioprio(int)
Allows setting the I/O priority of the current process/thread.
Definition: mythmiscutil.cpp:806
mythcoreutil.h
getLoadAvgs
loadArray getLoadAvgs(void)
Returns the system load averages.
Definition: mythmiscutil.cpp:178
LOC
#define LOC
Definition: audioconvert.cpp:38
setenv
#define setenv(x, y, z)
Definition: compat.h:157
getSymlinkTarget
QString getSymlinkTarget(const QString &start_file, QStringList *intermediaries, unsigned maxLinks)
Definition: mythmiscutil.cpp:499
WakeOnLAN
bool WakeOnLAN(const QString &MAC)
Definition: mythmiscutil.cpp:637
LOG
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23
build_compdb.file
file
Definition: build_compdb.py:55
myth_system
uint myth_system(const QString &command, uint flags, std::chrono::seconds timeout)
Definition: mythsystemlegacy.cpp:502
telnet
bool telnet(const QString &host, int port)
Can we talk to port on host?
Definition: mythmiscutil.cpp:280
ESCDQUOTE
@ ESCDQUOTE
Definition: mythmiscutil.cpp:1250
getloadavg
#define getloadavg(x, y)
Definition: compat.h:303
close
#define close
Definition: compat.h:17
tmp
static guint32 * tmp
Definition: goom_core.cpp:31
mythsystemlegacy.h
IsPulseAudioRunning
bool IsPulseAudioRunning(void)
Is A/V Sync destruction daemon is running on this host?
Definition: mythmiscutil.cpp:686
MythSocket
Class for communcating between myth backends and frontends.
Definition: mythsocket.h:25
MythRemoveDirectory
bool MythRemoveDirectory(QDir &aDir)
Definition: mythmiscutil.cpp:810
wrapList
void wrapList(QStringList &list, int width)
Definition: mythmiscutil.cpp:963
INSQUOTE
@ INSQUOTE
Definition: mythmiscutil.cpp:1246
mythlogging.h
hardwareprofile.config.p
p
Definition: config.py:33
compat.h
START
@ START
Definition: mythmiscutil.cpp:1244
createTempFile
QString createTempFile(QString name_template, bool dir)
Definition: mythmiscutil.cpp:371
getResponse
QString getResponse(const QString &query, const QString &def)
In an interactive shell, prompt the user to input a string.
Definition: mythmiscutil.cpp:458
MythWakeup
bool MythWakeup(const QString &wakeUpCommand, uint flags, std::chrono::seconds timeout)
Definition: mythmiscutil.cpp:678
loadArray
std::array< double, 3 > loadArray
Definition: mythmiscutil.h:33
hardwareprofile.distros.mythtv_data.main.stdout
stdout
Definition: main.py:87
naturalCompare
int naturalCompare(const QString &_a, const QString &_b, Qt::CaseSensitivity caseSensitivity)
Definition: mythmiscutil.cpp:1035
uint
unsigned int uint
Definition: compat.h:140
gCoreContext
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
Definition: mythcorecontext.cpp:60
MythFormatTime
QString MythFormatTime(std::chrono::milliseconds msecs, const QString &fmt)
Format a milliseconds time value.
Definition: mythmiscutil.cpp:1235
getUptime
bool getUptime(std::chrono::seconds &uptime)
Definition: mythmiscutil.cpp:68
states
states
Definition: mythmiscutil.cpp:1243
MythCoreContext::resolveAddress
static QString resolveAddress(const QString &host, ResolveType type=ResolveAny, bool keepscope=false)
if host is an IP address, it will be returned or resolved otherwise.
Definition: mythcorecontext.cpp:1204
block_size
unsigned int block_size
Definition: freesurround.cpp:47
ESCSQUOTE
@ ESCSQUOTE
Definition: mythmiscutil.cpp:1249
hasUtf8
bool hasUtf8(const char *str)
Guess whether a string is UTF-8.
Definition: mythmiscutil.cpp:195
INDQUOTE
@ INDQUOTE
Definition: mythmiscutil.cpp:1247
ping
bool ping(const QString &host, std::chrono::milliseconds timeout)
Can we ping host within timeout seconds?
Definition: mythmiscutil.cpp:247
mythmiscutil.h
makeFileAccessible
bool makeFileAccessible(const QString &filename)
Definition: mythmiscutil.cpp:443
mythcorecontext.h
intResponse
int intResponse(const QString &query, int def)
In an interactive shell, prompt the user to input a number.
Definition: mythmiscutil.cpp:488
kMSProcessEvents
@ kMSProcessEvents
process events while waiting
Definition: mythsystem.h:39
xml_indent
QString xml_indent(uint level)
Definition: mythmiscutil.cpp:1009
INTEXT
@ INTEXT
Definition: mythmiscutil.cpp:1245
nice
#define nice(x)
Definition: compat.h:196
getMemStats
bool getMemStats(int &totalMB, int &freeMB, int &totalVM, int &freeVM)
Returns memory statistics in megabytes.
Definition: mythmiscutil.cpp:111
myth_nice
bool myth_nice(int val)
Definition: mythmiscutil.cpp:704
MythSplitCommandString
QStringList MythSplitCommandString(const QString &line)
Definition: mythmiscutil.cpp:1257
mythburn.temppath
string temppath
Definition: mythburn.py:161
kMSDontDisableDrawing
@ kMSDontDisableDrawing
avoid disabling UI drawing
Definition: mythsystem.h:37
exitcodes.h
build_compdb.filename
filename
Definition: build_compdb.py:21
FileHash
QString FileHash(const QString &filename)
Definition: mythmiscutil.cpp:596
IsMACAddress
bool IsMACAddress(const QString &MAC)
Definition: mythmiscutil.cpp:551
mythsocket.h
hardwareprofile.smolt.proxies
proxies
Definition: smolt.py:104
output
#define output
Definition: synaesthesia.cpp:220
ESCTEXT
@ ESCTEXT
Definition: mythmiscutil.cpp:1248
MythCoreContext::ResolveAny
@ ResolveAny
Definition: mythcorecontext.h:211
myth_yield
void myth_yield(void)
Definition: mythmiscutil.cpp:718