24 #include <sys/sysinfo.h>
28 #include <mach/mach.h>
32 #include <sys/mount.h>
33 #include <sys/sysctl.h>
37 #include <QReadWriteLock>
38 #include <QNetworkProxy>
39 #include <QStringList>
54 #include "mythconfig.h"
64 if (sysinfo(&sinfo) == -1)
66 LOG(VB_GENERAL, LOG_ERR,
"sysinfo() error");
70 uptime = sinfo.uptime;
72 #elif defined(__FreeBSD__) || CONFIG_DARWIN
75 struct timeval bootTime;
80 len =
sizeof(bootTime);
82 mib[1] = KERN_BOOTTIME;
83 if (sysctl(mib, 2, &bootTime, &len, NULL, 0) == -1)
85 LOG(VB_GENERAL, LOG_ERR,
"sysctl() error");
89 uptime = time(NULL) - bootTime.tv_sec;
90 #elif defined(USING_MINGW)
91 uptime = ::GetTickCount() / 1000;
94 LOG(VB_GENERAL, LOG_NOTICE,
"Unknown platform. How do I get the uptime?");
107 bool getMemStats(
int &totalMB,
int &freeMB,
int &totalVM,
int &freeVM)
110 size_t MB = (1024*1024);
111 struct sysinfo sinfo;
112 if (sysinfo(&sinfo) == -1)
114 LOG(VB_GENERAL, LOG_ERR,
115 "getMemStats(): Error, sysinfo() call failed.");
119 totalMB = (
int)((sinfo.totalram * sinfo.mem_unit)/MB),
120 freeMB = (
int)((sinfo.freeram * sinfo.mem_unit)/MB),
121 totalVM = (
int)((sinfo.totalswap * sinfo.mem_unit)/MB),
122 freeVM = (
int)((sinfo.freeswap * sinfo.mem_unit)/MB);
126 mach_msg_type_number_t count;
128 vm_statistics_data_t s;
130 mp = mach_host_self();
133 if (host_page_size(mp, &pageSize) != KERN_SUCCESS)
136 count = HOST_VM_INFO_COUNT;
137 if (host_statistics(mp, HOST_VM_INFO,
138 (host_info_t)&s, &count) != KERN_SUCCESS)
140 LOG(VB_GENERAL, LOG_ERR,
"getMemStats(): Error, "
141 "failed to get virtual memory statistics.");
146 totalMB = (s.active_count + s.inactive_count +
147 s.wire_count + s.free_count) * pageSize / 1024;
148 freeMB = s.free_count * pageSize / 1024;
154 int64_t total, used, free;
156 totalVM = (
int)(total >> 10);
157 freeVM = (
int)(free >> 10);
160 LOG(VB_GENERAL, LOG_NOTICE,
"getMemStats(): Unknown platform. "
161 "How do I get the memory stats?");
177 const uchar *c = (uchar *) str;
185 if (*c > 0xC1 && *c < 0xF5)
187 int bytesToCheck = 2;
194 while (bytesToCheck--)
201 if (*c < 0x80 || *c > 0xBF)
223 QString cmd = QString(
"%systemroot%\\system32\\ping.exe -i %1 -n 1 %2>NUL")
224 .arg(timeout).arg(host);
230 QString cmd = QString(
"ping -t %1 -c 1 %2 >/dev/null 2>&1")
231 .arg(timeout).arg(host);
239 cmd =
"ping -t 1 -c 1 localhost >/dev/null 2>&1";
245 cmd = QString(
"ping -c 1 %1 >/dev/null 2>&1").arg(host);
264 bool telnet(
const QString &host,
int port)
299 bool odst =
false, osrc =
false;
304 if (!dst.isWritable() && !dst.isOpen())
305 odst = dst.open(QIODevice::Unbuffered |
306 QIODevice::WriteOnly |
307 QIODevice::Truncate);
309 if (!src.isReadable() && !src.isOpen())
310 osrc = src.open(QIODevice::Unbuffered|QIODevice::ReadOnly);
312 bool ok = dst.isWritable() && src.isReadable();
313 long long total_bytes = 0LL;
316 long long rlen, wlen, off = 0;
317 rlen = src.read(buf, buflen);
320 LOG(VB_GENERAL, LOG_ERR,
"read error");
327 total_bytes += (
long long) rlen;
329 while ((rlen-off>0) && ok)
331 wlen = dst.write(buf + off, rlen - off);
336 LOG(VB_GENERAL, LOG_ERR,
"write error");
349 return (ok) ? total_bytes : -1LL;
358 char tempfilename[MAX_PATH] =
"";
360 GetTempPathA(MAX_PATH, temppath);
361 if (GetTempFileNameA(temppath,
"mth", 0, tempfilename))
366 unlink(tempfilename);
367 ret = mkdir(tempfilename);
370 ret =
open(tempfilename, O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
372 QString tmpFileName(tempfilename);
374 QByteArray safe_name_template = name_template.toLatin1();
375 const char *
tmp = safe_name_template.constData();
376 char *ctemplate = strdup(tmp);
380 ret = (mkdtemp(ctemplate)) ? 0 : -1;
384 mode_t cur_umask = umask(S_IRWXO | S_IRWXG);
385 ret = mkstemp(ctemplate);
389 QString tmpFileName(ctemplate);
395 LOG(VB_GENERAL, LOG_ERR, QString(
"createTempFile(%1), Error ")
396 .arg(name_template) + ENO);
397 return name_template;
400 if (!dir && (ret >= 0))
426 QByteArray fname = filename.toLatin1();
427 int ret = chmod(fname.constData(), 0666);
430 LOG(VB_GENERAL, LOG_ERR, QString(
"Unable to change permissions on file. (%1)").arg(filename));
441 QByteArray
tmp = query.toLocal8Bit();
442 cout << tmp.constData();
444 tmp = def.toLocal8Bit();
446 cout <<
" [" << tmp.constData() <<
"] ";
450 if (!isatty(fileno(stdin)) || !isatty(fileno(stdout)))
452 cout << endl <<
"[console is not interactive, using default '"
453 << tmp.constData() <<
"']" << endl;
459 cin.getline(response, 80);
463 LOG(VB_GENERAL, LOG_ERR,
"Read from stdin failed");
467 QString qresponse = response;
469 if (qresponse.isEmpty())
480 QString str_resp =
getResponse(query, QString(
"%1").arg(def));
481 if (str_resp.isEmpty())
484 int resp = str_resp.toInt(&ok);
485 return (ok ? resp : def);
490 QStringList *intermediaries,
494 LOG(VB_GENERAL, LOG_DEBUG,
495 QString(
"getSymlinkTarget('%1', 0x%2, %3)")
496 .arg(start_file).arg((uint64_t)intermediaries,0,16)
500 QString link = QString::null;
501 QString cur_file = start_file; cur_file.detach();
502 QFileInfo fi(cur_file);
506 intermediaries->clear();
507 intermediaries->push_back(start_file);
510 for (
uint i = 0; (i <= maxLinks) && fi.isSymLink() &&
511 !(link = fi.readLink()).isEmpty(); i++)
513 cur_file = (link[0] ==
'/') ?
515 fi.absoluteDir().absolutePath() +
"/" + link;
517 if (intermediaries && !intermediaries->contains(cur_file))
518 intermediaries->push_back(cur_file);
520 fi = QFileInfo(cur_file);
524 intermediaries->detach();
529 for (
uint i = 0; i < intermediaries->size(); i++)
531 LOG(VB_GENERAL, LOG_DEBUG, QString(
" inter%1: %2")
532 .arg(i).arg((*intermediaries)[i]));
536 LOG(VB_GENERAL, LOG_DEBUG,
537 QString(
"getSymlinkTarget() -> '%1'")
538 .arg((!fi.isSymLink()) ? cur_file : QString::null));
541 return (!fi.isSymLink()) ? cur_file : QString::null;
558 QStringList tokens = MAC.split(
':');
559 if (tokens.size() != 6)
561 LOG(VB_NETWORK, LOG_ERR,
562 QString(
"IsMACAddress(%1) = false, doesn't have 6 parts").arg(MAC));
569 for (y = 0; y < 6; y++)
571 if (tokens[y].isEmpty())
573 LOG(VB_NETWORK, LOG_ERR,
574 QString(
"IsMACAddress(%1) = false, part #%2 is empty.")
579 value = tokens[
y].toInt(&ok, 16);
582 LOG(VB_NETWORK, LOG_ERR,
583 QString(
"IsMACAddress(%1) = false, unable to "
584 "convert part '%2' to integer.")
585 .arg(MAC).arg(tokens[y]));
591 LOG(VB_NETWORK, LOG_ERR,
592 QString(
"IsMACAddress(%1) = false, part #%2 "
593 "evaluates to %3 which is higher than 255.")
594 .arg(MAC).arg(y).arg(value));
599 LOG(VB_NETWORK, LOG_DEBUG, QString(
"IsMACAddress(%1) = true").arg(MAC));
605 QFile file(filename);
606 QFileInfo fileinfo(file);
607 qint64 initialsize = fileinfo.size();
610 if (initialsize == 0)
611 return QString(
"NULL");
613 if (file.open(QIODevice::ReadOnly))
617 LOG(VB_GENERAL, LOG_ERR,
618 "Error: Unable to open selected file, missing read permissions?");
619 return QString(
"NULL");
623 QDataStream
stream(&file);
624 stream.setByteOrder(QDataStream::LittleEndian);
625 for (quint64
tmp = 0, i = 0; i < 65536/
sizeof(
tmp); i++)
631 file.seek(initialsize - 65536);
632 for (quint64
tmp = 0, i = 0; i < 65536/
sizeof(
tmp); i++)
640 QString output = QString(
"%1").arg(hash, 0, 16);
646 char msg[1024] =
"\xFF\xFF\xFF\xFF\xFF\xFF";
649 QStringList tokens = MAC.split(
':');
653 if (tokens.size() != 6)
655 LOG(VB_GENERAL, LOG_ERR,
656 QString(
"WakeOnLan(%1): Incorrect MAC length").arg(MAC));
660 for (y = 0; y < 6; y++)
662 macaddr[
y] = tokens[
y].toInt(&ok, 16);
666 LOG(VB_GENERAL, LOG_ERR,
667 QString(
"WakeOnLan(%1): Invalid MAC address").arg(MAC));
672 for (x = 0; x < 16; x++)
673 for (y = 0; y < 6; y++)
674 msg[msglen++] = macaddr[y];
676 LOG(VB_NETWORK, LOG_INFO,
677 QString(
"WakeOnLan(): Sending WOL packet to %1").arg(MAC));
679 QUdpSocket udp_socket;
680 return udp_socket.writeDatagram(
681 msg, msglen, QHostAddress::Broadcast, 32767) == msglen;
690 #if CONFIG_DARWIN || (__FreeBSD__) || defined(__OpenBSD__)
691 const char *command =
"ps -ax | grep -i pulseaudio | grep -v grep > /dev/null";
693 const char *command =
"ps ch -C pulseaudio -o pid > /dev/null";
698 return (res == GENERIC_EXIT_OK);
699 #endif // USING_MINGW
707 if ((-1 == ret) && (0 !=
errno) && (val >= 0))
709 LOG(VB_GENERAL, LOG_ERR,
"Failed to nice process" + ENO);
718 #ifdef _POSIX_PRIORITY_SCHEDULING
743 #if defined(__linux__) && ( defined(__i386__) || defined(__ppc__) || \
744 defined(__x86_64__) || defined(__ia64__) )
751 #include <sys/ptrace.h>
752 #include <asm/unistd.h>
754 #if defined(__i386__)
755 # define __NR_ioprio_set 289
756 # define __NR_ioprio_get 290
757 #elif defined(__ppc__)
758 # define __NR_ioprio_set 273
759 # define __NR_ioprio_get 274
760 #elif defined(__x86_64__)
761 # define __NR_ioprio_set 251
762 # define __NR_ioprio_get 252
763 #elif defined(__ia64__)
764 # define __NR_ioprio_set 1274
765 # define __NR_ioprio_get 1275
768 #define IOPRIO_BITS (16)
769 #define IOPRIO_CLASS_SHIFT (13)
770 #define IOPRIO_PRIO_MASK ((1UL << IOPRIO_CLASS_SHIFT) - 1)
771 #define IOPRIO_PRIO_CLASS(mask) ((mask) >> IOPRIO_CLASS_SHIFT)
772 #define IOPRIO_PRIO_DATA(mask) ((mask) & IOPRIO_PRIO_MASK)
773 #define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | data)
783 int new_ioprio = IOPRIO_PRIO_VALUE(new_ioclass, new_iodata);
787 if (old_ioprio == new_ioprio)
813 QFileInfoList entries = aDir.entryInfoList(QDir::NoDotAndDotDot |
814 QDir::Dirs | QDir::Files);
815 int count = entries.size();
816 bool has_err =
false;
818 for (
int idx = 0; idx < count && !has_err; idx++)
820 QFileInfo entryInfo = entries[idx];
821 QString path = entryInfo.absoluteFilePath();
822 if (entryInfo.isDir())
835 if (!has_err && !aDir.rmdir(aDir.absolutePath()))
854 QString
LOC =
"setHttpProxy() - ";
859 QString var(getenv(
"http_proxy"));
861 var = getenv(
"HTTP_PROXY");
864 if (!var.startsWith(
"http://"))
865 var.prepend(
"http://");
867 QUrl url = QUrl(var, QUrl::TolerantMode);
868 QString host = url.host();
869 int port = url.port();
882 LOG(VB_NETWORK, LOG_INFO, LOC +
883 QString(
"assuming port %1 on host %2") .arg(port).arg(host));
886 else if (!
ping(host, 1))
887 LOG(VB_GENERAL, LOG_ERR, LOC +
888 QString(
"cannot locate host %1").arg(host) +
889 "\n\t\t\tPlease check HTTP_PROXY environment variable!");
890 else if (!
telnet(host,port))
891 LOG(VB_GENERAL, LOG_ERR, LOC +
892 QString(
"%1:%2 - cannot connect!").arg(host).arg(port) +
893 "\n\t\t\tPlease check HTTP_PROXY environment variable!");
896 LOG(VB_NETWORK, LOG_DEBUG, LOC + QString(
"using http://%1:%2@%3:%4")
897 .arg(url.userName()).arg(url.password())
898 .arg(host).arg(port));
900 p = QNetworkProxy(QNetworkProxy::HttpCachingProxy,
901 host, port, url.userName(), url.password());
902 QNetworkProxy::setApplicationProxy(p);
906 LOG(VB_NETWORK, LOG_DEBUG, LOC +
"no HTTP_PROXY environment var.");
911 QNetworkProxyQuery query(QUrl(
"http://www.mythtv.org"));
913 proxies = QNetworkProxyFactory::systemProxyForQuery(query);
915 Q_FOREACH (p, proxies)
917 QString host = p.hostName();
920 if (p.type() == QNetworkProxy::NoProxy)
925 LOG(VB_NETWORK, LOG_ERR, LOC +
926 "failed to contact proxy host " + host);
930 LOG(VB_NETWORK, LOG_INFO, LOC + QString(
"using proxy host %1:%2")
931 .arg(host).arg(port));
932 QNetworkProxy::setApplicationProxy(p);
938 if (p.user().length())
939 url =
"http://%1:%2@%3:%4",
940 url = url.arg(p.user()).arg(p.password());
942 url =
"http://%1:%2";
944 url = url.arg(p.hostName()).arg(p.port());
945 setenv(
"HTTP_PROXY", url.toLatin1(), 1);
946 setenv(
"http_proxy", url.toLatin1(), 0);
951 LOG(VB_NETWORK, LOG_ERR, LOC +
"failed to find a network proxy");
958 for(i = 0; i < list.size(); i++)
960 QString
string = list.at(i);
962 if(
string.
size() <= width )
965 QString left =
string.left(width);
966 bool inserted =
false;
968 while( !inserted && !left.endsWith(
" " ))
970 if(
string.mid(left.size(), 1) ==
" " )
972 list.replace(i, left);
973 list.insert(i+1,
string.mid(left.size()).trimmed());
979 if( !left.contains(
" ") )
982 list.replace(i, left +
"-");
983 list.insert(i+1,
string.mid(left.size()));
992 list.replace(i, left);
993 list.insert(i+1,
string.mid(left.size()).trimmed());
1000 static QReadWriteLock rw_lock;
1001 static QMap<uint,QString> cache;
1003 rw_lock.lockForRead();
1004 QMap<uint,QString>::const_iterator it = cache.find(level);
1005 if (it != cache.end())
1017 rw_lock.lockForWrite();