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