Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Hold back a running Spring Boot server's folder while its port listens

Țugui Dragoșba5d8bda0d66
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index e2c5e0f1..cc43800f 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -101228,6 +101228,113 @@
}
}
},
+ "Not selected: a server on this Mac still listens on the port this folder is named for, and keeps its uploads here." : {
+ "comment" : "Under a folder a Spring Boot server makes in the temporary folder, named for its port, such as tomcat.8080.12345, while a process still listens on that port.",
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nevybráno: server v tomto Macu stále naslouchá na portu, podle kterého je tato složka pojmenovaná, a ukládá sem nahrané soubory."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nicht ausgewählt: Ein Server auf diesem Mac lauscht noch auf dem Port, nach dem dieser Ordner benannt ist, und legt hier seine Uploads ab."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Sin seleccionar: un servidor de este Mac sigue escuchando en el puerto que da nombre a esta carpeta, y guarda aquí los archivos que se le suben."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non sélectionné : un serveur de ce Mac écoute encore sur le port qui donne son nom à ce dossier, et y conserve les fichiers qu’on lui envoie."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Non selezionato: un server su questo Mac è ancora in ascolto sulla porta da cui questa cartella prende il nome, e qui conserva i file caricati."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未選択: このフォルダ名が示すポートで、このMac上のサーバがまだ待ち受けていて、アップロードされたファイルをここに保管しています。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "선택되지 않음: 이 Mac의 서버가 이 폴더 이름에 들어 있는 포트에서 아직 수신 대기 중이며, 업로드된 파일을 이곳에 보관합니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Niet geselecteerd: een server op deze Mac luistert nog op de poort waarnaar deze map is genoemd, en bewaart zijn uploads hier."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Nie zaznaczono: serwer na tym Macu nadal nasłuchuje na porcie, którego numer jest w nazwie tego folderu, i przechowuje tu przesłane do niego pliki."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Não selecionado: um servidor deste Mac ainda escuta na porta que dá nome a esta pasta e guarda aqui os uploads que recebe."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Neselectat: un server de pe acest Mac ascultă încă pe portul după care este denumit acest dosar și își păstrează aici fișierele încărcate."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Не выбрано: сервер на этом Mac все еще прослушивает порт, по номеру которого названа эта папка, и хранит здесь загруженные на него файлы."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Inte markerad: en server på den här datorn lyssnar fortfarande på porten som den här mappens namn anger, och sparar sina uppladdningar här."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Seçilmedi: bu Mac’teki bir sunucu, bu klasörün adındaki kapıyı hâlâ dinliyor ve kendisine yüklenen dosyaları burada tutuyor."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Не вибрано: сервер на цьому Mac досі прослуховує порт, за яким названо цю папку, і зберігає тут передані на нього файли."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未选择:这台Mac上有服务器仍在监听此文件夹名称所指的端口,并在这里存放上传的文件。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未選取:這部Mac上仍有伺服器在監聽此檔案夾名稱所指的連接埠,並將上傳的檔案存放在這裡。"
+ }
+ }
+ }
+ },
"Not selected: a wallet or a signing key is inside. Once the Trash is emptied, what it opens is gone for good unless you have a backup." : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
index cf2d7ff8..61857e14 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
@@ -397,6 +397,7 @@ extension HoldBack {
case .changedRecently: "changed in the last day, so it may still be downloading"
case .mayStillBeResumed: "a program that resumes downloads, such as a torrent client, may still finish it"
case .writtenRecently: "written to in the last 15 minutes, so a program may still be using it"
+ case .serverStillListens: "a server still listens on the port it is named for and keeps its uploads here"
case .keptByAnApp: "in an app's folder in Application Support, and the app may still need it"
case .appIsRunning: "its app is running and may install this update when it quits"
case .mayBeTheOnlyCopy: "outside Downloads and no installed app's installer, so it may be yours, not a download"
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
index e6d8ea9e..e1c31f5f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
@@ -194,12 +194,16 @@ public enum DeveloperCaches {
/// True for a folder a running program may use without holding it open, which is listed and not selected
/// while something wrote to it within `HoldBack.stillInUse`.
let holdsBackRecentWrites: Bool
+ /// True for a server's folder named `<kind>.<port>.<number>` at each start: the newest of its kind on a port a
+ /// process of this account listens on is the running server's.
+ let namesItsPort: Bool
init(
_ path: String, _ kind: DeveloperEnvironment.ContentKind, source: String, storeInside: String? = nil,
rowsDepth: Int = 0, rowEnding: String? = nil, rowsAreDerivedData: Bool = false,
rowsAreProjectState: Bool = false, movedBy: Relocation? = nil, base: Base = .home,
- launchers: [String] = [], clonedFrom: String? = nil, holdsBackRecentWrites: Bool = false
+ launchers: [String] = [], clonedFrom: String? = nil, holdsBackRecentWrites: Bool = false,
+ namesItsPort: Bool = false
) {
self.path = path
self.kind = kind
@@ -214,6 +218,7 @@ public enum DeveloperCaches {
self.launchers = launchers
self.clonedFrom = clonedFrom
self.holdsBackRecentWrites = holdsBackRecentWrites
+ self.namesItsPort = namesItsPort
}
/// Whether what is at `url` is the tool's own, as far as where it was cloned from says.
@@ -730,17 +735,17 @@ public enum DeveloperCaches {
Folder(
"tomcat.*.*/", .cache,
source: "https://github.com/spring-projects/spring-boot/blob/e5e959e3b66bba353aa87f49d9b8036ebb63f0dc/module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/TomcatWebServerFactory.java#L412",
- base: .userTemporary, holdsBackRecentWrites: true
+ base: .userTemporary, holdsBackRecentWrites: true, namesItsPort: true
),
Folder(
"tomcat-docbase.*.*/", .cache,
source: "https://github.com/spring-projects/spring-boot/blob/e5e959e3b66bba353aa87f49d9b8036ebb63f0dc/module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/servlet/TomcatServletWebServerFactory.java#L191",
- base: .userTemporary, holdsBackRecentWrites: true
+ base: .userTemporary, holdsBackRecentWrites: true, namesItsPort: true
),
Folder(
"jetty-docbase.*.*/", .cache,
source: "https://github.com/spring-projects/spring-boot/blob/e5e959e3b66bba353aa87f49d9b8036ebb63f0dc/module/spring-boot-jetty/src/main/java/org/springframework/boot/jetty/servlet/JettyServletWebServerFactory.java#L305",
- base: .userTemporary, holdsBackRecentWrites: true
+ base: .userTemporary, holdsBackRecentWrites: true, namesItsPort: true
),
]),
// Java Web Start keeps the applications a person installed in its cache, beside the ones it only cached.
@@ -1582,19 +1587,36 @@ public enum DeveloperCaches {
openFiles: OpenFiles = OpenFiles()
) async -> [DeveloperEnvironment] {
let settings = ToolSettings(home: homeDirectory)
+ let listening = definitions.contains { $0.folders.contains(where: \.namesItsPort) }
+ ? ListeningPorts.ofThisAccount() : []
// Four tools at a time: measured all at once, their big folders would share the disk and each run out of
// the time `FileSize` gives a walk, where alone they would finish.
return await definitions.concurrentMap(width: 4) { definition in
await environment(
for: definition, homeDirectory: homeDirectory, userCacheDirectory: userCacheDirectory,
userTemporaryDirectory: userTemporaryDirectory, exclusions: exclusions, measure: measure,
- preference: preference, settings: settings, openFiles: openFiles
+ preference: preference, settings: settings, openFiles: openFiles, listening: listening
)
}
.compactMap(\.self)
.sorted { $0.total != $1.total ? $0.total > $1.total : $0.name < $1.name }
}
+ /// Among folders named `<kind>.<port>.<number>`, the newest of each kind on a port in `listening`.
+ static func runningServersFolders(_ urls: [URL], listening: Set<Int>) -> Set<String> {
+ var newest: [String: (url: URL, made: Date)] = [:]
+ for url in urls {
+ let parts = url.lastPathComponent.split(separator: ".")
+ guard parts.count >= 3, let port = Int(parts[1]), listening.contains(port) else { continue }
+ let key = "\(parts[0]).\(port)"
+ let made = (try? url.resourceValues(forKeys: [.creationDateKey]))?.creationDate ?? .distantPast
+ if made >= newest[key]?.made ?? .distantPast {
+ newest[key] = (url, made)
+ }
+ }
+ return Set(newest.values.map { PathPattern.comparablePath(of: $0.url) })
+ }
+
private static func environment(
for definition: Definition,
homeDirectory: URL,
@@ -1604,7 +1626,8 @@ public enum DeveloperCaches {
measure: @escaping LeftoverScanner.Measure,
preference: @escaping @Sendable (String) -> String?,
settings: ToolSettings,
- openFiles: OpenFiles
+ openFiles: OpenFiles,
+ listening: Set<Int>
) async -> DeveloperEnvironment? {
var found: [(url: URL, folder: Folder, project: String?)] = []
for folder in definition.folders {
@@ -1633,6 +1656,7 @@ public enum DeveloperCaches {
// A pattern can reach inside a folder another pattern lists, as `*/GPUCache` reaches
// `GPUPersistentCache/GPUCache`, and that folder goes with the one around it.
let paths = found.map { PathPattern.comparablePath(of: $0.url) }
+ let serving = runningServersFolders(found.filter(\.folder.namesItsPort).map(\.url), listening: listening)
var locations: [DeveloperEnvironment.Location] = []
for (url, folder, project) in found {
guard !Task.isCancelled else { return nil }
@@ -1658,6 +1682,7 @@ public enum DeveloperCaches {
lastWritten: contents.flatMap { $0.couldNotBeRead ? nil : $0.newestChange },
heldBack: contents.flatMap(HoldBack.secret(in:))
?? (holdsAnotherRepository ? .holdsRepository : nil)
+ ?? (serving.contains(path) ? .serverStillListens : nil)
?? (folder.holdsBackRecentWrites && HoldBack.wasWrittenRecently(url, contents: contents)
? .writtenRecently : nil)
))
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/ListeningPorts.swift b/Packages/PeelCore/Sources/PeelCore/Developer/ListeningPorts.swift
new file mode 100644
index 00000000..e5a76ee8
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/ListeningPorts.swift
@@ -0,0 +1,37 @@
+import Darwin
+
+/// The TCP ports this account's processes listen on, read from each one's sockets (`PROC_PIDFDSOCKETINFO`,
+/// `sys/proc_info.h`). Another account's processes, root's included, don't let Peel read them.
+enum ListeningPorts {
+ static func ofThisAccount() -> Set<Int> {
+ var pids = [pid_t](repeating: 0, count: 8_192)
+ let count = Int(proc_listallpids(&pids, Int32(pids.count * MemoryLayout<pid_t>.size)))
+ var ports: Set<Int> = []
+ for pid in pids.prefix(max(count, 0)) where pid > 0 && !(kill(pid, 0) != 0 && errno == EPERM) {
+ ports.formUnion(listening(by: pid))
+ }
+ return ports
+ }
+
+ static func listening(by pid: pid_t) -> Set<Int> {
+ let size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, nil, 0)
+ guard size > 0 else { return [] }
+ var descriptors = [proc_fdinfo](repeating: proc_fdinfo(), count: Int(size) / MemoryLayout<proc_fdinfo>.size)
+ let filled = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &descriptors, size)
+ guard filled > 0 else { return [] }
+ var ports: Set<Int> = []
+ for descriptor in descriptors.prefix(Int(filled) / MemoryLayout<proc_fdinfo>.size)
+ where descriptor.proc_fdtype == PROX_FDTYPE_SOCKET {
+ var info = socket_fdinfo()
+ let expected = Int32(MemoryLayout<socket_fdinfo>.size)
+ guard proc_pidfdinfo(pid, descriptor.proc_fd, PROC_PIDFDSOCKETINFO, &info, expected) == expected,
+ info.psi.soi_kind == Int32(SOCKINFO_TCP),
+ info.psi.soi_proto.pri_tcp.tcpsi_state == Int32(TSI_S_LISTEN)
+ else { continue }
+ // The local port is kept in network byte order.
+ let port = UInt16(truncatingIfNeeded: info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport)
+ ports.insert(Int(UInt16(bigEndian: port)))
+ }
+ return ports
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
index 9037713e..e874a3a2 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
@@ -143,6 +143,8 @@ public enum HoldBack: String, Sendable, Hashable {
case mayStillBeResumed
/// A cache something wrote to in the last few minutes, which a program may still be using.
case writtenRecently
+ /// The folder of a server that still listens on the port it is named for, which keeps its uploads there.
+ case serverStillListens
/// An installer package in a folder an app keeps in Application Support, which the app may still need.
case keptByAnApp
/// A receipt whose package also left items outside the app, which Package Receipts lists only while it stays.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
index a43c83b1..c1f67465 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
@@ -1862,6 +1862,37 @@ struct DeveloperCachesTests {
#expect(locations.filter { $0.url != running.url }.allSatisfy { $0.kind == .cache && $0.isRecommended })
}
+ @Test func holdsBackTheNewestFolderOfAServerThatStillListensOnItsPort() async throws {
+ let (socket, port) = try ListeningPortsTests.listeningSocket()
+ defer { close(socket) }
+ let directory = try TemporaryDirectory()
+ let temporary = try directory.directory("var/T")
+ let anHourAgo = Date.now.addingTimeInterval(-3600)
+ let names = ["tomcat.\(port).1", "tomcat.\(port).2", "tomcat-docbase.\(port).3", "tomcat.1.4"]
+ for (index, name) in names.enumerated() {
+ let file = try directory.file("var/T/\(name)/work/SESSIONS.ser", bytes: 400_000)
+ let work = file.deletingLastPathComponent()
+ // macOS keeps a birth date no later than the last change, so both are set to when the server started.
+ let made = anHourAgo.addingTimeInterval(TimeInterval(index * 60))
+ for url in [file, work, work.deletingLastPathComponent()] {
+ try FileManager.default.setAttributes(
+ [.creationDate: made, .modificationDate: made], ofItemAtPath: url.path(percentEncoded: false)
+ )
+ }
+ }
+
+ let locations = await DeveloperCaches.scan(
+ DeveloperCaches.definitions.filter { $0.id == "springboot" },
+ homeDirectory: directory.url.appending(path: "home"), userTemporaryDirectory: temporary,
+ openFiles: OpenFiles(excluding: nil)
+ ).flatMap(\.locations)
+
+ let held = locations.filter { $0.heldBack == .serverStillListens }.map(\.url.lastPathComponent).sorted()
+ #expect(held == ["tomcat-docbase.\(port).3", "tomcat.\(port).2"])
+ let recommended = Set(locations.filter(\.isRecommended).map(\.url.lastPathComponent))
+ #expect(recommended == ["tomcat.\(port).1", "tomcat.1.4"])
+ }
+
@Test func offersMetrosCachesInTheTemporaryFolderAndNothingInUse() async throws {
let directory = try TemporaryDirectory()
let temporary = try directory.directory("var/T")
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ListeningPortsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ListeningPortsTests.swift
new file mode 100644
index 00000000..2d267e93
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ListeningPortsTests.swift
@@ -0,0 +1,34 @@
+import Darwin
+@testable import PeelCore
+import Testing
+
+struct ListeningPortsTests {
+ /// A socket listening on a port the kernel chooses, on the loopback only.
+ static func listeningSocket() throws -> (socket: Int32, port: Int) {
+ let socket = Darwin.socket(AF_INET, SOCK_STREAM, 0)
+ try #require(socket >= 0)
+ var address = sockaddr_in()
+ address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
+ address.sin_family = sa_family_t(AF_INET)
+ address.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let size = socklen_t(MemoryLayout<sockaddr_in>.size)
+ let bound = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(socket, $0, size) }
+ }
+ try #require(bound == 0 && listen(socket, 1) == 0)
+ var named = sockaddr_in()
+ var length = socklen_t(MemoryLayout<sockaddr_in>.size)
+ _ = withUnsafeMutablePointer(to: &named) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(socket, $0, &length) }
+ }
+ return (socket, Int(UInt16(bigEndian: named.sin_port)))
+ }
+
+ @Test func readsThePortsThisAccountListensOn() throws {
+ let (socket, port) = try Self.listeningSocket()
+ #expect(ListeningPorts.listening(by: getpid()).contains(port))
+ #expect(ListeningPorts.ofThisAccount().contains(port))
+ close(socket)
+ #expect(!ListeningPorts.listening(by: getpid()).contains(port))
+ }
+}
diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swift
index 8f29286d..d72d040d 100644
--- a/Peel/Views/Presentation.swift
+++ b/Peel/Views/Presentation.swift
@@ -414,6 +414,8 @@ extension HoldBack {
"Not selected: a program that resumes downloads, such as a torrent client, may still finish this."
case .writtenRecently:
"Not selected: something wrote to this in the last 15 minutes, so a program may still be using it."
+ case .serverStillListens:
+ "Not selected: a server on this Mac still listens on the port this folder is named for, and keeps its uploads here."
case .keptByAnApp:
"Not selected: this is in a folder an app keeps in Application Support, and the app may still need it."
case .appIsRunning: