|
import AppKit |
|
import Foundation |
|
|
|
let app = NSApplication.shared |
|
|
|
func stderrWrite(_ string: String) { |
|
FileHandle.standardError.write(Data(string.utf8)) |
|
} |
|
|
|
class AppDelegate: NSObject, NSApplicationDelegate { |
|
func applicationDidFinishLaunching(_ notification: Notification) { |
|
NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: nil) { _ in |
|
let sock = socket(AF_INET, SOCK_STREAM, 0) |
|
var readBuf = [CChar](repeating: 0, count: Int(BUFSIZ)) |
|
|
|
if sock < 0 { |
|
perror("Error: socket") |
|
app.terminate(self) |
|
} |
|
|
|
var sockName = sockaddr_in(sin_len: 0, |
|
sin_family: sa_family_t(AF_INET), |
|
sin_port: in_port_t(UInt16(4321).bigEndian), |
|
sin_addr: in_addr(s_addr: inet_addr("127.0.0.1")), |
|
sin_zero: (0,0,0,0,0,0,0,0)) |
|
|
|
let connectReturn = withUnsafePointer(to: &sockName) { pointer in |
|
pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { pointer in |
|
connect(sock, pointer, socklen_t(MemoryLayout<sockaddr_in>.size)) |
|
} |
|
} |
|
if connectReturn < 0 { |
|
perror("Error: connect") |
|
app.terminate(self) |
|
} |
|
|
|
let guestSyncStr = "{\"execute\":\"guest-sync\", \"arguments\":{\"id\":1234}}" |
|
let guestSyncResponse = "{\"return\": 1234}\n" |
|
|
|
if write(sock, guestSyncStr, guestSyncStr.count) < 0 { |
|
perror("Error: write guest-sync") |
|
app.terminate(self) |
|
} |
|
|
|
if read(sock, &readBuf, Int(BUFSIZ)) < 0 { |
|
perror("Error: read guest-sync") |
|
app.terminate(self) |
|
} |
|
readBuf.withUnsafeBufferPointer { pointer in |
|
let readStr = String(cString: pointer.baseAddress!) |
|
if readStr != guestSyncResponse { |
|
stderrWrite("Bad guest-sync response. Response: \(readStr)\n") |
|
app.terminate(self) |
|
} |
|
} |
|
|
|
// Clear readBuf back to zero |
|
readBuf = readBuf.map { _ in 0 } |
|
|
|
let guestSetTimeStr = "{\"execute\":\"guest-set-time\"}" |
|
let guestSetTimeResponse = "{\"return\": {}}\n" |
|
|
|
if write(sock, guestSetTimeStr, guestSetTimeStr.count) < 0 { |
|
perror("Error: write guest-set-time") |
|
app.terminate(self) |
|
} |
|
|
|
if read(sock, &readBuf, Int(BUFSIZ)) < 0 { |
|
perror("Error: read guest-set-time") |
|
app.terminate(self) |
|
} |
|
readBuf.withUnsafeBufferPointer { pointer in |
|
let readStr = String(cString: pointer.baseAddress!) |
|
if readStr != guestSetTimeResponse { |
|
stderrWrite("Bad guest-set-time response. Response: \(readStr)\n") |
|
app.terminate(self) |
|
} |
|
} |
|
|
|
if close(sock) < 0 { |
|
perror("Error: close") |
|
app.terminate(self) |
|
} |
|
|
|
print("Successfully re-synced guest time") |
|
} |
|
} |
|
} |
|
|
|
let delegate = AppDelegate() |
|
app.delegate = delegate |
|
app.run() |