Debian Codegraph @

lib/ProcessInfo.cpp

raw symbols SCIP
1 /*
2 Copyright 2007-2008 by Robert Knight <[email protected]>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 02110-1301 USA.
18 */
19
20 // Own
21 #include "ProcessInfo.h"
22
23 // Unix
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 #include <unistd.h>
28 #include <pwd.h>
29 #include <sys/param.h>
30
31 // Qt
32 #include <QtCore/QDir>
33 #include <QtCore/QFileInfo>
34 #include <QtCore/QFlags>
35 #include <QtCore/QTextStream>
36 #include <QtCore/QStringList>
37 #include <QtNetwork/QHostInfo>
38
39 // KDE
40 // #include <KConfigGroup>
41 // #include <KSharedConfig>
42 #include <QDebug>
43
44 #if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) || defined(Q_OS_MAC)
45 #include <sys/sysctl.h>
46 #endif
47
48 #if defined(Q_OS_MAC)
49 #include <libproc.h>
50 #endif
51
52 #if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
53 #include <sys/types.h>
54 #include <sys/user.h>
55 #include <sys/syslimits.h>
56 # if defined(Q_OS_FREEBSD)
57 # include <libutil.h>
58 # endif
59 #endif
60
61 using namespace Konsole;
62
63 ProcessInfo::ProcessInfo(int aPid , bool enableEnvironmentRead)
64 : _fields(ARGUMENTS | ENVIRONMENT) // arguments and environments
65 // are currently always valid,
66 // they just return an empty
67 // vector / map respectively
68 // if no arguments
69 // or environment bindings
70 // have been explicitly set
71 , _enableEnvironmentRead(enableEnvironmentRead)
72 , _pid(aPid)
73 , _parentPid(0)
74 , _foregroundPid(0)
75 , _userId(0)
76 , _lastError(NoError)
77 , _userName(QString())
78 , _userHomeDir(QString())
79 {
80 }
81
82 ProcessInfo::Error ProcessInfo::error() const
83 {
84 return _lastError;
85 }
86 void ProcessInfo::setError(Error error)
87 {
88 _lastError = error;
89 }
90
91 void ProcessInfo::update()
92 {
93 readProcessInfo(_pid, _enableEnvironmentRead);
94 }
95
96 QString ProcessInfo::validCurrentDir() const
97 {
98 bool ok = false;
99
100 // read current dir, if an error occurs try the parent as the next
101 // best option
102 int currentPid = parentPid(&ok);
103 QString dir = currentDir(&ok);
104 while (!ok && currentPid != 0) {
105 ProcessInfo* current = ProcessInfo::newInstance(currentPid);
106 current->update();
107 currentPid = current->parentPid(&ok);
108 dir = current->currentDir(&ok);
109 delete current;
110 }
111
112 return dir;
113 }
114
115 QString ProcessInfo::format(const QString& input) const
116 {
117 bool ok = false;
118
119 QString output(input);
120
121 // search for and replace known marker
122 output.replace("%u", userName());
123 output.replace("%h", localHost());
124 output.replace("%n", name(&ok));
125
126 QString dir = validCurrentDir();
127 if (output.contains("%D")) {
128 QString homeDir = userHomeDir();
129 QString tempDir = dir;
130 // Change User's Home Dir w/ ~ only at the beginning
131 if (tempDir.startsWith(homeDir)) {
132 tempDir.remove(0, homeDir.length());
133 tempDir.prepend('~');
134 }
135 output.replace("%D", tempDir);
136 }
137 output.replace("%d", formatShortDir(dir));
138
139 return output;
140 }
141
142 QSet<QString> ProcessInfo::_commonDirNames;
143
144 QSet<QString> ProcessInfo::commonDirNames()
145 {
146 // static bool forTheFirstTime = true;
147 //
148 // if (forTheFirstTime) {
149 // const KSharedConfigPtr& config = KSharedConfig::openConfig();
150 // const KConfigGroup& configGroup = config->group("ProcessInfo");
151 // _commonDirNames = QSet<QString>::fromList(configGroup.readEntry("CommonDirNames", QStringList()));
152 //
153 // forTheFirstTime = false;
154 // }
155
156 return _commonDirNames;
157 }
158
159 QString ProcessInfo::formatShortDir(const QString& input) const
160 {
161 QString result;
162
163 const QStringList& parts = input.split(QDir::separator());
164
165 QSet<QString> dirNamesToShorten = commonDirNames();
166
167 QListIterator<QString> iter(parts);
168 iter.toBack();
169
170 // go backwards through the list of the path's parts
171 // adding abbreviations of common directory names
172 // and stopping when we reach a dir name which is not
173 // in the commonDirNames set
174 while (iter.hasPrevious()) {
175 const QString& part = iter.previous();
176
177 if (dirNamesToShorten.contains(part)) {
178 result.prepend(QString(QDir::separator()) + part[0]);
179 } else {
180 result.prepend(part);
181 break;
182 }
183 }
184
185 return result;
186 }
187
188 QVector<QString> ProcessInfo::arguments(bool* ok) const
189 {
190 *ok = _fields.testFlag(ARGUMENTS);
191
192 return _arguments;
193 }
194
195 QMap<QString, QString> ProcessInfo::environment(bool* ok) const
196 {
197 *ok = _fields.testFlag(ENVIRONMENT);
198
199 return _environment;
200 }
201
202 bool ProcessInfo::isValid() const
203 {
204 return _fields.testFlag(PROCESS_ID);
205 }
206
207 int ProcessInfo::pid(bool* ok) const
208 {
209 *ok = _fields.testFlag(PROCESS_ID);
210
211 return _pid;
212 }
213
214 int ProcessInfo::parentPid(bool* ok) const
215 {
216 *ok = _fields.testFlag(PARENT_PID);
217
218 return _parentPid;
219 }
220
221 int ProcessInfo::foregroundPid(bool* ok) const
222 {
223 *ok = _fields.testFlag(FOREGROUND_PID);
224
225 return _foregroundPid;
226 }
227
228 QString ProcessInfo::name(bool* ok) const
229 {
230 *ok = _fields.testFlag(NAME);
231
232 return _name;
233 }
234
235 int ProcessInfo::userId(bool* ok) const
236 {
237 *ok = _fields.testFlag(UID);
238
239 return _userId;
240 }
241
242 QString ProcessInfo::userName() const
243 {
244 return _userName;
245 }
246
247 QString ProcessInfo::userHomeDir() const
248 {
249 return _userHomeDir;
250 }
251
252 QString ProcessInfo::localHost()
253 {
254 return QHostInfo::localHostName();
255 }
256
257 void ProcessInfo::setPid(int aPid)
258 {
259 _pid = aPid;
260 _fields |= PROCESS_ID;
261 }
262
263 void ProcessInfo::setUserId(int uid)
264 {
265 _userId = uid;
266 _fields |= UID;
267 }
268
269 void ProcessInfo::setUserName(const QString& name)
270 {
271 _userName = name;
272 setUserHomeDir();
273 }
274
275 void ProcessInfo::setUserHomeDir()
276 {
277 _userHomeDir = QDir::homePath();
278 }
279
280 void ProcessInfo::setParentPid(int aPid)
281 {
282 _parentPid = aPid;
283 _fields |= PARENT_PID;
284 }
285 void ProcessInfo::setForegroundPid(int aPid)
286 {
287 _foregroundPid = aPid;
288 _fields |= FOREGROUND_PID;
289 }
290
291 QString ProcessInfo::currentDir(bool* ok) const
292 {
293 if (ok)
294 *ok = _fields & CURRENT_DIR;
295
296 return _currentDir;
297 }
298 void ProcessInfo::setCurrentDir(const QString& dir)
299 {
300 _fields |= CURRENT_DIR;
301 _currentDir = dir;
302 }
303
304 void ProcessInfo::setName(const QString& name)
305 {
306 _name = name;
307 _fields |= NAME;
308 }
309 void ProcessInfo::addArgument(const QString& argument)
310 {
311 _arguments << argument;
312 }
313
314 void ProcessInfo::clearArguments()
315 {
316 _arguments.clear();
317 }
318
319 void ProcessInfo::addEnvironmentBinding(const QString& name , const QString& value)
320 {
321 _environment.insert(name, value);
322 }
323
324 void ProcessInfo::setFileError(QFile::FileError error)
325 {
326 switch (error) {
327 case QFile::PermissionsError:
328 setError(ProcessInfo::PermissionsError);
329 break;
330 case QFile::NoError:
331 setError(ProcessInfo::NoError);
332 break;
333 default:
334 setError(ProcessInfo::UnknownError);
335 }
336 }
337
338 //
339 // ProcessInfo::newInstance() is way at the bottom so it can see all of the
340 // implementations of the UnixProcessInfo abstract class.
341 //
342
343 NullProcessInfo::NullProcessInfo(int aPid, bool enableEnvironmentRead)
344 : ProcessInfo(aPid, enableEnvironmentRead)
345 {
346 }
347
348 bool NullProcessInfo::readProcessInfo(int /*pid*/ , bool /*enableEnvironmentRead*/)
349 {
350 return false;
351 }
352
353 void NullProcessInfo::readUserName()
354 {
355 }
356
357 #if !defined(Q_OS_WIN)
358 UnixProcessInfo::UnixProcessInfo(int aPid, bool enableEnvironmentRead)
359 : ProcessInfo(aPid, enableEnvironmentRead)
360 {
361 }
362
363 bool UnixProcessInfo::readProcessInfo(int aPid , bool enableEnvironmentRead)
364 {
365 // prevent _arguments from growing longer and longer each time this
366 // method is called.
367 clearArguments();
368
369 bool ok = readProcInfo(aPid);
370 if (ok) {
371 ok |= readArguments(aPid);
372 ok |= readCurrentDir(aPid);
373 if (enableEnvironmentRead) {
374 ok |= readEnvironment(aPid);
375 }
376 }
377 return ok;
378 }
379
380 void UnixProcessInfo::readUserName()
381 {
382 bool ok = false;
383 const int uid = userId(&ok);
384 if (!ok) return;
385
386 struct passwd passwdStruct;
387 struct passwd* getpwResult;
388 char* getpwBuffer;
389 long getpwBufferSize;
390 int getpwStatus;
391
392 getpwBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX);
393 if (getpwBufferSize == -1)
394 getpwBufferSize = 16384;
395
396 getpwBuffer = new char[getpwBufferSize];
397 if (getpwBuffer == NULL)
398 return;
399 getpwStatus = getpwuid_r(uid, &passwdStruct, getpwBuffer, getpwBufferSize, &getpwResult);
400 if ((getpwStatus == 0) && (getpwResult != NULL)) {
401 setUserName(QString(passwdStruct.pw_name));
402 } else {
403 setUserName(QString());
404 qWarning() << "getpwuid_r returned error : " << getpwStatus;
405 }
406 delete [] getpwBuffer;
407 }
408 #endif
409
410 #if defined(Q_OS_LINUX)
411 class LinuxProcessInfo : public UnixProcessInfo
412 {
413 public:
414 LinuxProcessInfo(int aPid, bool env) :
415 UnixProcessInfo(aPid, env) {
416 }
417
418 private:
419 virtual bool readProcInfo(int aPid) {
420 // indicies of various fields within the process status file which
421 // contain various information about the process
422 const int PARENT_PID_FIELD = 3;
423 const int PROCESS_NAME_FIELD = 1;
424 const int GROUP_PROCESS_FIELD = 7;
425
426 QString parentPidString;
427 QString processNameString;
428 QString foregroundPidString;
429 QString uidLine;
430 QString uidString;
431 QStringList uidStrings;
432
433 // For user id read process status file ( /proc/<pid>/status )
434 // Can not use getuid() due to it does not work for 'su'
435 QFile statusInfo(QString("/proc/%1/status").arg(aPid));
436 if (statusInfo.open(QIODevice::ReadOnly)) {
437 QTextStream stream(&statusInfo);
438 QString statusLine;
439 do {
440 statusLine = stream.readLine();
441 if (statusLine.startsWith(QLatin1String("Uid:")))
442 uidLine = statusLine;
443 } while (!statusLine.isNull() && uidLine.isNull());
444
445 uidStrings << uidLine.split('\t', QString::SkipEmptyParts);
446 // Must be 5 entries: 'Uid: %d %d %d %d' and
447 // uid string must be less than 5 chars (uint)
448 if (uidStrings.size() == 5)
449 uidString = uidStrings[1];
450 if (uidString.size() > 5)
451 uidString.clear();
452
453 bool ok = false;
454 const int uid = uidString.toInt(&ok);
455 if (ok)
456 setUserId(uid);
457 readUserName();
458 } else {
459 setFileError(statusInfo.error());
460 return false;
461 }
462
463 // read process status file ( /proc/<pid/stat )
464 //
465 // the expected file format is a list of fields separated by spaces, using
466 // parenthesies to escape fields such as the process name which may itself contain
467 // spaces:
468 //
469 // FIELD FIELD (FIELD WITH SPACES) FIELD FIELD
470 //
471 QFile processInfo(QString("/proc/%1/stat").arg(aPid));
472 if (processInfo.open(QIODevice::ReadOnly)) {
473 QTextStream stream(&processInfo);
474 const QString& data = stream.readAll();
475
476 int stack = 0;
477 int field = 0;
478 int pos = 0;
479
480 while (pos < data.count()) {
481 QChar c = data[pos];
482
483 if (c == '(') {
484 stack++;
485 } else if (c == ')') {
486 stack--;
487 } else if (stack == 0 && c == ' ') {
488 field++;
489 } else {
490 switch (field) {
491 case PARENT_PID_FIELD:
492 parentPidString.append(c);
493 break;
494 case PROCESS_NAME_FIELD:
495 processNameString.append(c);
496 break;
497 case GROUP_PROCESS_FIELD:
498 foregroundPidString.append(c);
499 break;
500 }
501 }
502
503 pos++;
504 }
505 } else {
506 setFileError(processInfo.error());
507 return false;
508 }
509
510 // check that data was read successfully
511 bool ok = false;
512 const int foregroundPid = foregroundPidString.toInt(&ok);
513 if (ok)
514 setForegroundPid(foregroundPid);
515
516 const int parentPid = parentPidString.toInt(&ok);
517 if (ok)
518 setParentPid(parentPid);
519
520 if (!processNameString.isEmpty())
521 setName(processNameString);
522
523 // update object state
524 setPid(aPid);
525
526 return ok;
527 }
528
529 virtual bool readArguments(int aPid) {
530 // read command-line arguments file found at /proc/<pid>/cmdline
531 // the expected format is a list of strings delimited by null characters,
532 // and ending in a double null character pair.
533
534 QFile argumentsFile(QString("/proc/%1/cmdline").arg(aPid));
535 if (argumentsFile.open(QIODevice::ReadOnly)) {
536 QTextStream stream(&argumentsFile);
537 const QString& data = stream.readAll();
538
539 const QStringList& argList = data.split(QChar('\0'));
540
541 foreach(const QString & entry , argList) {
542 if (!entry.isEmpty())
543 addArgument(entry);
544 }
545 } else {
546 setFileError(argumentsFile.error());
547 }
548
549 return true;
550 }
551
552 virtual bool readCurrentDir(int aPid) {
553 char path_buffer[MAXPATHLEN + 1];
554 path_buffer[MAXPATHLEN] = 0;
555 QByteArray procCwd = QFile::encodeName(QString("/proc/%1/cwd").arg(aPid));
556 const int length = readlink(procCwd.constData(), path_buffer, MAXPATHLEN);
557 if (length == -1) {
558 setError(UnknownError);
559 return false;
560 }
561
562 path_buffer[length] = '\0';
563 QString path = QFile::decodeName(path_buffer);
564
565 setCurrentDir(path);
566 return true;
567 }
568
569 virtual bool readEnvironment(int aPid) {
570 // read environment bindings file found at /proc/<pid>/environ
571 // the expected format is a list of KEY=VALUE strings delimited by null
572 // characters and ending in a double null character pair.
573
574 QFile environmentFile(QString("/proc/%1/environ").arg(aPid));
575 if (environmentFile.open(QIODevice::ReadOnly)) {
576 QTextStream stream(&environmentFile);
577 const QString& data = stream.readAll();
578
579 const QStringList& bindingList = data.split(QChar('\0'));
580
581 foreach(const QString & entry , bindingList) {
582 QString name;
583 QString value;
584
585 const int splitPos = entry.indexOf('=');
586
587 if (splitPos != -1) {
588 name = entry.mid(0, splitPos);
589 value = entry.mid(splitPos + 1, -1);
590
591 addEnvironmentBinding(name, value);
592 }
593 }
594 } else {
595 setFileError(environmentFile.error());
596 }
597
598 return true;
599 }
600 };
601
602 #elif defined(Q_OS_FREEBSD)
603 class FreeBSDProcessInfo : public UnixProcessInfo
604 {
605 public:
606 FreeBSDProcessInfo(int aPid, bool readEnvironment) :
607 UnixProcessInfo(aPid, readEnvironment) {
608 }
609
610 private:
611 virtual bool readProcInfo(int aPid) {
612 int managementInfoBase[4];
613 size_t mibLength;
614 struct kinfo_proc* kInfoProc;
615
616 managementInfoBase[0] = CTL_KERN;
617 managementInfoBase[1] = KERN_PROC;
618 managementInfoBase[2] = KERN_PROC_PID;
619 managementInfoBase[3] = aPid;
620
621 if (sysctl(managementInfoBase, 4, NULL, &mibLength, NULL, 0) == -1)
622 return false;
623
624 kInfoProc = new struct kinfo_proc [mibLength];
625
626 if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, NULL, 0) == -1) {
627 delete [] kInfoProc;
628 return false;
629 }
630
631 #if defined(HAVE_OS_DRAGONFLYBSD)
632 setName(kInfoProc->kp_comm);
633 setPid(kInfoProc->kp_pid);
634 setParentPid(kInfoProc->kp_ppid);
635 setForegroundPid(kInfoProc->kp_pgid);
636 setUserId(kInfoProc->kp_uid);
637 #else
638 setName(kInfoProc->ki_comm);
639 setPid(kInfoProc->ki_pid);
640 setParentPid(kInfoProc->ki_ppid);
641 setForegroundPid(kInfoProc->ki_pgid);
642 setUserId(kInfoProc->ki_uid);
643 #endif
644
645 readUserName();
646
647 delete [] kInfoProc;
648 return true;
649 }
650
651 virtual bool readArguments(int aPid) {
652 char args[ARG_MAX];
653 int managementInfoBase[4];
654 size_t len;
655
656 managementInfoBase[0] = CTL_KERN;
657 managementInfoBase[1] = KERN_PROC;
658 managementInfoBase[2] = KERN_PROC_PID;
659 managementInfoBase[3] = aPid;
660
661 len = sizeof(args);
662 if (sysctl(managementInfoBase, 4, args, &len, NULL, 0) == -1)
663 return false;
664
665 const QStringList& argumentList = QString(args).split(QChar('\0'));
666
667 for (QStringList::const_iterator it = argumentList.begin(); it != argumentList.end(); ++it) {
668 addArgument(*it);
669 }
670
671 return true;
672 }
673
674 virtual bool readEnvironment(int aPid) {
675 Q_UNUSED(aPid);
676 // Not supported in FreeBSD?
677 return false;
678 }
679
680 virtual bool readCurrentDir(int aPid) {
681 #if defined(HAVE_OS_DRAGONFLYBSD)
682 char buf[PATH_MAX];
683 int managementInfoBase[4];
684 size_t len;
685
686 managementInfoBase[0] = CTL_KERN;
687 managementInfoBase[1] = KERN_PROC;
688 managementInfoBase[2] = KERN_PROC_CWD;
689 managementInfoBase[3] = aPid;
690
691 len = sizeof(buf);
692 if (sysctl(managementInfoBase, 4, buf, &len, NULL, 0) == -1)
693 return false;
694
695 setCurrentDir(buf);
696
697 return true;
698 #else
699 int numrecords;
700 struct kinfo_file* info = 0;
701
702 info = kinfo_getfile(aPid, &numrecords);
703
704 if (!info)
705 return false;
706
707 for (int i = 0; i < numrecords; ++i) {
708 if (info[i].kf_fd == KF_FD_TYPE_CWD) {
709 setCurrentDir(info[i].kf_path);
710
711 free(info);
712 return true;
713 }
714 }
715
716 free(info);
717 return false;
718 #endif
719 }
720 };
721
722 #elif defined(Q_OS_OPENBSD)
723 class OpenBSDProcessInfo : public UnixProcessInfo
724 {
725 public:
726 OpenBSDProcessInfo(int aPid, bool readEnvironment) :
727 UnixProcessInfo(aPid, readEnvironment) {
728 }
729
730 private:
731 virtual bool readProcInfo(int aPid) {
732 int managementInfoBase[6];
733 size_t mibLength;
734 struct kinfo_proc* kInfoProc;
735
736 managementInfoBase[0] = CTL_KERN;
737 managementInfoBase[1] = KERN_PROC;
738 managementInfoBase[2] = KERN_PROC_PID;
739 managementInfoBase[3] = aPid;
740 managementInfoBase[4] = sizeof(struct kinfo_proc);
741 managementInfoBase[5] = 1;
742
743 if (::sysctl(managementInfoBase, 6, NULL, &mibLength, NULL, 0) == -1) {
744 qWarning() << "first sysctl() call failed with code" << errno;
745 return false;
746 }
747
748 kInfoProc = (struct kinfo_proc*)malloc(mibLength);
749
750 if (::sysctl(managementInfoBase, 6, kInfoProc, &mibLength, NULL, 0) == -1) {
751 qWarning() << "second sysctl() call failed with code" << errno;
752 free(kInfoProc);
753 return false;
754 }
755
756 setName(kInfoProc->p_comm);
757 setPid(kInfoProc->p_pid);
758 setParentPid(kInfoProc->p_ppid);
759 setForegroundPid(kInfoProc->p_tpgid);
760 setUserId(kInfoProc->p_uid);
761 setUserName(kInfoProc->p_login);
762
763 free(kInfoProc);
764 return true;
765 }
766
767 char** readProcArgs(int aPid, int whatMib) {
768 void* buf = NULL;
769 void* nbuf;
770 size_t len = 4096;
771 int rc = -1;
772 int managementInfoBase[4];
773
774 managementInfoBase[0] = CTL_KERN;
775 managementInfoBase[1] = KERN_PROC_ARGS;
776 managementInfoBase[2] = aPid;
777 managementInfoBase[3] = whatMib;
778
779 do {
780 len *= 2;
781 nbuf = realloc(buf, len);
782 if (nbuf == NULL) {
783 break;
784 }
785
786 buf = nbuf;
787 rc = ::sysctl(managementInfoBase, 4, buf, &len, NULL, 0);
788 qWarning() << "sysctl() call failed with code" << errno;
789 } while (rc == -1 && errno == ENOMEM);
790
791 if (nbuf == NULL || rc == -1) {
792 free(buf);
793 return NULL;
794 }
795
796 return (char**)buf;
797 }
798
799 virtual bool readArguments(int aPid) {
800 char** argv;
801
802 argv = readProcArgs(aPid, KERN_PROC_ARGV);
803 if (argv == NULL) {
804 return false;
805 }
806
807 for (char** p = argv; *p != NULL; p++) {
808 addArgument(QString(*p));
809 }
810 free(argv);
811 return true;
812 }
813
814 virtual bool readEnvironment(int aPid) {
815 char** envp;
816 char* eqsign;
817
818 envp = readProcArgs(aPid, KERN_PROC_ENV);
819 if (envp == NULL) {
820 return false;
821 }
822
823 for (char **p = envp; *p != NULL; p++) {
824 eqsign = strchr(*p, '=');
825 if (eqsign == NULL || eqsign[1] == '\0') {
826 continue;
827 }
828 *eqsign = '\0';
829 addEnvironmentBinding(QString((const char *)p),
830 QString((const char *)eqsign + 1));
831 }
832 free(envp);
833 return true;
834 }
835
836 virtual bool readCurrentDir(int aPid) {
837 char buf[PATH_MAX];
838 int managementInfoBase[3];
839 size_t len;
840
841 managementInfoBase[0] = CTL_KERN;
842 managementInfoBase[1] = KERN_PROC_CWD;
843 managementInfoBase[2] = aPid;
844
845 len = sizeof(buf);
846 if (::sysctl(managementInfoBase, 3, buf, &len, NULL, 0) == -1) {
847 qWarning() << "sysctl() call failed with code" << errno;
848 return false;
849 }
850
851 setCurrentDir(buf);
852 return true;
853 }
854 };
855
856 #elif defined(Q_OS_MAC)
857 class MacProcessInfo : public UnixProcessInfo
858 {
859 public:
860 MacProcessInfo(int aPid, bool env) :
861 UnixProcessInfo(aPid, env) {
862 }
863
864 private:
865 virtual bool readProcInfo(int aPid) {
866 int managementInfoBase[4];
867 size_t mibLength;
868 struct kinfo_proc* kInfoProc;
869 /*
870 KDE_struct_stat statInfo;
871
872 // Find the tty device of 'pid' (Example: /dev/ttys001)
873 managementInfoBase[0] = CTL_KERN;
874 managementInfoBase[1] = KERN_PROC;
875 managementInfoBase[2] = KERN_PROC_PID;
876 managementInfoBase[3] = aPid;
877
878 if (sysctl(managementInfoBase, 4, NULL, &mibLength, NULL, 0) == -1) {
879 return false;
880 } else {
881 kInfoProc = new struct kinfo_proc [mibLength];
882 if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, NULL, 0) == -1) {
883 delete [] kInfoProc;
884 return false;
885 } else {
886 const QString deviceNumber = QString(devname(((&kInfoProc->kp_eproc)->e_tdev), S_IFCHR));
887 const QString fullDeviceName = QString("/dev/") + deviceNumber.rightJustified(3, '0');
888 delete [] kInfoProc;
889
890 const QByteArray deviceName = fullDeviceName.toLatin1();
891 const char* ttyName = deviceName.data();
892
893 if (KDE::stat(ttyName, &statInfo) != 0)
894 return false;
895
896 // Find all processes attached to ttyName
897 managementInfoBase[0] = CTL_KERN;
898 managementInfoBase[1] = KERN_PROC;
899 managementInfoBase[2] = KERN_PROC_TTY;
900 managementInfoBase[3] = statInfo.st_rdev;
901
902 mibLength = 0;
903 if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), NULL, &mibLength, NULL, 0) == -1)
904 return false;
905
906 kInfoProc = new struct kinfo_proc [mibLength];
907 if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), kInfoProc, &mibLength, NULL, 0) == -1)
908 return false;
909
910 // The foreground program is the first one
911 setName(QString(kInfoProc->kp_proc.p_comm));
912
913 delete [] kInfoProc;
914 }
915 setPid(aPid);
916 }
917 return true;
918 */
919 return false;
920 }
921
922 virtual bool readArguments(int aPid) {
923 Q_UNUSED(aPid);
924 return false;
925 }
926 virtual bool readCurrentDir(int aPid) {
927 struct proc_vnodepathinfo vpi;
928 const int nb = proc_pidinfo(aPid, PROC_PIDVNODEPATHINFO, 0, &vpi, sizeof(vpi));
929 if (nb == sizeof(vpi)) {
930 setCurrentDir(QString(vpi.pvi_cdir.vip_path));
931 return true;
932 }
933 return false;
934 }
935 virtual bool readEnvironment(int aPid) {
936 Q_UNUSED(aPid);
937 return false;
938 }
939 };
940
941 #elif defined(Q_OS_SOLARIS)
942 // The procfs structure definition requires off_t to be
943 // 32 bits, which only applies if FILE_OFFSET_BITS=32.
944 // Futz around here to get it to compile regardless,
945 // although some of the structure sizes might be wrong.
946 // Fortunately, the structures we actually use don't use
947 // off_t, and we're safe.
948 #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS==64)
949 #undef _FILE_OFFSET_BITS
950 #endif
951 #include <procfs.h>
952
953 class SolarisProcessInfo : public UnixProcessInfo
954 {
955 public:
956 SolarisProcessInfo(int aPid, bool readEnvironment)
957 : UnixProcessInfo(aPid, readEnvironment) {
958 }
959 private:
960 virtual bool readProcInfo(int aPid) {
961 QFile psinfo(QString("/proc/%1/psinfo").arg(aPid));
962 if (psinfo.open(QIODevice::ReadOnly)) {
963 struct psinfo info;
964 if (psinfo.read((char *)&info, sizeof(info)) != sizeof(info)) {
965 return false;
966 }
967
968 setParentPid(info.pr_ppid);
969 setForegroundPid(info.pr_pgid);
970 setName(info.pr_fname);
971 setPid(aPid);
972
973 // Bogus, because we're treating the arguments as one single string
974 info.pr_psargs[PRARGSZ - 1] = 0;
975 addArgument(info.pr_psargs);
976 }
977 return true;
978 }
979
980 virtual bool readArguments(int /*pid*/) {
981 // Handled in readProcInfo()
982 return false;
983 }
984
985 virtual bool readEnvironment(int /*pid*/) {
986 // Not supported in Solaris
987 return false;
988 }
989
990 // FIXME: This will have the same issues as BKO 251351; the Linux
991 // version uses readlink.
992 virtual bool readCurrentDir(int aPid) {
993 QFileInfo info(QString("/proc/%1/path/cwd").arg(aPid));
994 const bool readable = info.isReadable();
995
996 if (readable && info.isSymLink()) {
997 setCurrentDir(info.symLinkTarget());
998 return true;
999 } else {
1000 if (!readable)
1001 setError(PermissionsError);
1002 else
1003 setError(UnknownError);
1004
1005 return false;
1006 }
1007 }
1008 };
1009 #endif
1010
1011 SSHProcessInfo::SSHProcessInfo(const ProcessInfo& process)
1012 : _process(process)
1013 {
1014 bool ok = false;
1015
1016 // check that this is a SSH process
1017 const QString& name = _process.name(&ok);
1018
1019 if (!ok || name != "ssh") {
1020 if (!ok)
1021 qWarning() << "Could not read process info";
1022 else
1023 qWarning() << "Process is not a SSH process";
1024
1025 return;
1026 }
1027
1028 // read arguments
1029 const QVector<QString>& args = _process.arguments(&ok);
1030
1031 // SSH options
1032 // these are taken from the SSH manual ( accessed via 'man ssh' )
1033
1034 // options which take no arguments
1035 static const QString noArgumentOptions("1246AaCfgKkMNnqsTtVvXxYy");
1036 // options which take one argument
1037 static const QString singleArgumentOptions("bcDeFIiLlmOopRSWw");
1038
1039 if (ok) {
1040 // find the username, host and command arguments
1041 //
1042 // the username/host is assumed to be the first argument
1043 // which is not an option
1044 // ( ie. does not start with a dash '-' character )
1045 // or an argument to a previous option.
1046 //
1047 // the command, if specified, is assumed to be the argument following
1048 // the username and host
1049 //
1050 // note that we skip the argument at index 0 because that is the
1051 // program name ( expected to be 'ssh' in this case )
1052 for (int i = 1 ; i < args.count() ; i++) {
1053 // If this one is an option ...
1054 // Most options together with its argument will be skipped.
1055 if (args[i].startsWith('-')) {
1056 const QChar optionChar = (args[i].length() > 1) ? args[i][1] : '\0';
1057 // for example: -p2222 or -p 2222 ?
1058 const bool optionArgumentCombined = args[i].length() > 2;
1059
1060 if (noArgumentOptions.contains(optionChar)) {
1061 continue;
1062 } else if (singleArgumentOptions.contains(optionChar)) {
1063 QString argument;
1064 if (optionArgumentCombined) {
1065 argument = args[i].mid(2);
1066 } else {
1067 // Verify correct # arguments are given
1068 if ((i + 1) < args.count()) {
1069 argument = args[i + 1];
1070 }
1071 i++;
1072 }
1073
1074 // support using `-l user` to specify username.
1075 if (optionChar == 'l')
1076 _user = argument;
1077 // support using `-p port` to specify port.
1078 else if (optionChar == 'p')
1079 _port = argument;
1080
1081 continue;
1082 }
1083 }
1084
1085 // check whether the host has been found yet
1086 // if not, this must be the username/host argument
1087 if (_host.isEmpty()) {
1088 // check to see if only a hostname is specified, or whether
1089 // both a username and host are specified ( in which case they
1090 // are separated by an '@' character: username@host )
1091
1092 const int separatorPosition = args[i].indexOf('@');
1093 if (separatorPosition != -1) {
1094 // username and host specified
1095 _user = args[i].left(separatorPosition);
1096 _host = args[i].mid(separatorPosition + 1);
1097 } else {
1098 // just the host specified
1099 _host = args[i];
1100 }
1101 } else {
1102 // host has already been found, this must be the command argument
1103 _command = args[i];
1104 }
1105 }
1106 } else {
1107 qWarning() << "Could not read arguments";
1108
1109 return;
1110 }
1111 }
1112
1113 QString SSHProcessInfo::userName() const
1114 {
1115 return _user;
1116 }
1117 QString SSHProcessInfo::host() const
1118 {
1119 return _host;
1120 }
1121 QString SSHProcessInfo::port() const
1122 {
1123 return _port;
1124 }
1125 QString SSHProcessInfo::command() const
1126 {
1127 return _command;
1128 }
1129 QString SSHProcessInfo::format(const QString& input) const
1130 {
1131 QString output(input);
1132
1133 // test whether host is an ip address
1134 // in which case 'short host' and 'full host'
1135 // markers in the input string are replaced with
1136 // the full address
1137 bool isIpAddress = false;
1138
1139 struct in_addr address;
1140 if (inet_aton(_host.toLocal8Bit().constData(), &address) != 0)
1141 isIpAddress = true;
1142 else
1143 isIpAddress = false;
1144
1145 // search for and replace known markers
1146 output.replace("%u", _user);
1147
1148 if (isIpAddress)
1149 output.replace("%h", _host);
1150 else
1151 output.replace("%h", _host.left(_host.indexOf('.')));
1152
1153 output.replace("%H", _host);
1154 output.replace("%c", _command);
1155
1156 return output;
1157 }
1158
1159 ProcessInfo* ProcessInfo::newInstance(int aPid, bool enableEnvironmentRead)
1160 {
1161 #if defined(Q_OS_LINUX)
1162 return new LinuxProcessInfo(aPid, enableEnvironmentRead);
1163 #elif defined(Q_OS_SOLARIS)
1164 return new SolarisProcessInfo(aPid, enableEnvironmentRead);
1165 #elif defined(Q_OS_MAC)
1166 return new MacProcessInfo(aPid, enableEnvironmentRead);
1167 #elif defined(Q_OS_FREEBSD)
1168 return new FreeBSDProcessInfo(aPid, enableEnvironmentRead);
1169 #elif defined(Q_OS_OPENBSD)
1170 return new OpenBSDProcessInfo(aPid, enableEnvironmentRead);
1171 #else
1172 return new NullProcessInfo(aPid, enableEnvironmentRead);
1173 #endif
1174 }