]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/util/IOUtils.java
b4c4c6dd883f1ea24cc81df9ed99283e62078971
[signal-cli] / src / main / java / org / asamk / signal / util / IOUtils.java
1 package org.asamk.signal.util;
2
3 import org.asamk.signal.commands.exceptions.IOErrorException;
4 import org.asamk.signal.commands.exceptions.UserErrorException;
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7
8 import java.io.BufferedReader;
9 import java.io.File;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.Reader;
13 import java.io.StringWriter;
14 import java.net.InetSocketAddress;
15 import java.net.SocketAddress;
16 import java.net.StandardProtocolFamily;
17 import java.net.UnixDomainSocketAddress;
18 import java.nio.channels.ServerSocketChannel;
19 import java.nio.channels.SocketChannel;
20 import java.nio.charset.Charset;
21 import java.nio.file.Files;
22 import java.nio.file.attribute.PosixFilePermission;
23 import java.nio.file.attribute.PosixFilePermissions;
24 import java.util.EnumSet;
25 import java.util.Set;
26 import java.util.function.Supplier;
27
28 import jdk.net.ExtendedSocketOptions;
29 import jdk.net.UnixDomainPrincipal;
30
31 import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE;
32 import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
33 import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
34
35 public class IOUtils {
36
37 private final static Logger logger = LoggerFactory.getLogger(IOUtils.class);
38
39 private IOUtils() {
40 }
41
42 public static String readAll(InputStream in, Charset charset) throws IOException {
43 var output = new StringWriter();
44 var buffer = new byte[4096];
45 int n;
46 while (-1 != (n = in.read(buffer))) {
47 output.write(new String(buffer, 0, n, charset));
48 }
49 return output.toString();
50 }
51
52 public static void createPrivateDirectories(File file) throws IOException {
53 if (file.exists()) {
54 return;
55 }
56
57 final var path = file.toPath();
58 try {
59 Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
60 Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));
61 } catch (UnsupportedOperationException e) {
62 Files.createDirectories(path);
63 }
64 }
65
66 public static File getDataHomeDir() {
67 var dataHome = System.getenv("XDG_DATA_HOME");
68 if (dataHome != null) {
69 return new File(dataHome);
70 }
71
72 logger.debug("XDG_DATA_HOME not set, falling back to home dir");
73 return new File(new File(System.getProperty("user.home"), ".local"), "share");
74 }
75
76 public static File getRuntimeDir() {
77 var runtimeDir = System.getenv("XDG_RUNTIME_DIR");
78 if (runtimeDir != null) {
79 return new File(runtimeDir);
80 }
81
82 logger.debug("XDG_RUNTIME_DIR not set, falling back to temp dir");
83 return new File(System.getProperty("java.io.tmpdir"));
84 }
85
86 public static Supplier<String> getLineSupplier(final Reader reader) {
87 final var bufferedReader = new BufferedReader(reader);
88 return () -> {
89 try {
90 return bufferedReader.readLine();
91 } catch (IOException e) {
92 logger.error("Error occurred while reading line", e);
93 return null;
94 }
95 };
96 }
97
98 public static InetSocketAddress parseInetSocketAddress(final String tcpAddress) throws UserErrorException {
99 final var colonIndex = tcpAddress.lastIndexOf(':');
100 if (colonIndex < 0) {
101 throw new UserErrorException("Invalid tcp bind address: " + tcpAddress);
102 }
103 final String host = tcpAddress.substring(0, colonIndex);
104 final int port;
105 try {
106 port = Integer.parseInt(tcpAddress.substring(colonIndex + 1));
107 } catch (NumberFormatException e) {
108 throw new UserErrorException("Invalid tcp bind address: " + tcpAddress, e);
109 }
110 return new InetSocketAddress(host, port);
111 }
112
113 public static UnixDomainPrincipal getUnixDomainPrincipal(final SocketChannel channel) throws IOException {
114 UnixDomainPrincipal principal = null;
115 try {
116 principal = channel.getOption(ExtendedSocketOptions.SO_PEERCRED);
117 } catch (UnsupportedOperationException ignored) {
118 }
119 return principal;
120 }
121
122 public static ServerSocketChannel bindSocket(final SocketAddress address) throws IOErrorException {
123 final ServerSocketChannel serverChannel;
124 try {
125 preBind(address);
126 serverChannel = address instanceof UnixDomainSocketAddress
127 ? ServerSocketChannel.open(StandardProtocolFamily.UNIX)
128 : ServerSocketChannel.open();
129 serverChannel.bind(address);
130 logger.info("Listening on socket: " + address);
131 postBind(address);
132 } catch (IOException e) {
133 throw new IOErrorException("Failed to bind socket: " + e.getMessage(), e);
134 }
135 return serverChannel;
136 }
137
138 private static void preBind(SocketAddress address) throws IOException {
139 if (address instanceof UnixDomainSocketAddress usa) {
140 createPrivateDirectories(usa.getPath().toFile().getParentFile());
141 }
142 }
143
144 private static void postBind(SocketAddress address) {
145 if (address instanceof UnixDomainSocketAddress usa) {
146 usa.getPath().toFile().deleteOnExit();
147 }
148 }
149 }