aboutsummaryrefslogtreecommitdiff
path: root/goldfishterm/terminfo.cc
blob: b58fb5b19c9e3ad1a901853a62f1728eea9e77e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright 2021 Benjamin Barenblat
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

#include "goldfishterm/terminfo.h"

#include <byteswap.h>
#include <stdint.h>
#include <stdlib.h>

#include <fstream>
#include <istream>
#include <stdexcept>
#include <string>
#include <vector>

#include "third_party/abseil/absl/base/config.h"
#include "third_party/abseil/absl/meta/type_traits.h"
#include "third_party/abseil/absl/strings/str_cat.h"
#include "third_party/abseil/absl/strings/str_format.h"
#include "third_party/abseil/absl/strings/str_split.h"
#include "third_party/abseil/absl/types/optional.h"

namespace goldfishterm {

namespace {

constexpr int16_t kTerminfoMagic = 0432;
constexpr int16_t kTerminfoExtendedNumberFormatMagic = 01036;
constexpr char kSystemTerminfoDirectory[] = "/etc/terminfo";

template <typename T>
constexpr absl::underlying_type_t<T> FromEnum(T x) {
  return static_cast<absl::underlying_type_t<T>>(x);
}

std::string GetEnv(const char* var) noexcept {
  const char* val = getenv(var);
  if (val == nullptr) {
    return "";
  }
  return val;
}

// Reads a potentially unaligned little-endian int16_t.
int16_t ReadShort(std::istream& in) {
  // TODO(bbarenblat@gmail.com): Do we need to support anything else here (maybe
  // PDP-11-endian)?
#if !defined(ABSL_IS_LITTLE_ENDIAN) && !defined(ABSL_IS_BIG_ENDIAN)
#error Neither ABSL_IS_LITTLE_ENDIAN nor ABSL_IS_BIG_ENDIAN is defined
#endif

  int16_t n;
  in.read(reinterpret_cast<char*>(&n), sizeof(int16_t));
#ifdef ABSL_IS_BIG_ENDIAN
  n = bswap_16(n);
#endif
  return n;
}

// Reads a potentially unaligned little-endian int32_t.
int32_t ReadInt(std::istream& in) {
  // TODO(bbarenblat@gmail.com): Do we need to support anything else here (maybe
  // PDP-11-endian)?
#if !defined(ABSL_IS_LITTLE_ENDIAN) && !defined(ABSL_IS_BIG_ENDIAN)
#error Neither ABSL_IS_LITTLE_ENDIAN nor ABSL_IS_BIG_ENDIAN is defined
#endif

  int32_t n;
  in.read(reinterpret_cast<char*>(&n), sizeof(int32_t));
#ifdef ABSL_IS_BIG_ENDIAN
  n = bswap_32(n);
#endif
  return n;
}

int16_t ReadNonnegativeShort(const char* error_message, std::istream& in) {
  int16_t n = ReadShort(in);
  if (n < 0) {
    throw std::runtime_error(error_message);
  }
  return n;
}

void RequireValidNumber(const char* error_message, int n) {
  // -1 and -2 are reserved to mean "not present" and "canceled", respectively.
  if (n < -2) {
    throw std::runtime_error(absl::StrCat(error_message, " ", n));
  }
}

struct Header final {
  bool extended_number_format;
  int names_bytes;
  int booleans_bytes;
  int numbers_count;
  int strings_offsets_count;
  int strings_bytes;

  Header(std::istream& description) {
    switch (ReadShort(description)) {
      case kTerminfoMagic:
        extended_number_format = false;
        break;
      case kTerminfoExtendedNumberFormatMagic:
        extended_number_format = true;
        break;
      default:
        throw std::runtime_error("bad magic");
    }
    names_bytes = ReadNonnegativeShort(
        "terminal names section cannot have negative length", description);
    booleans_bytes = ReadNonnegativeShort(
        "boolean flags section cannot have negative length", description);
    numbers_count = ReadNonnegativeShort(
        "numbers section cannot have negative length", description);
    strings_offsets_count = ReadNonnegativeShort(
        "strings section cannot have negative numbers of entries", description);
    strings_bytes = ReadNonnegativeShort(
        "strings table cannot have negative length", description);
  }
};

std::vector<std::string> ReadTerminalNames(int bytes, std::istream& in) {
  assert(bytes > 0);
  std::string names(bytes - 1, '\0');
  in.read(names.data(), names.size());
  // Discard the null at the end of the names list.
  if (in.get() != '\0') {
    throw std::runtime_error("terminal names were not null-terminated");
  }
  return absl::StrSplit(names, '|');
}

std::vector<int8_t> ReadBooleanFlags(int bytes, std::istream& in) {
  std::vector<int8_t> booleans(bytes);
  in.read(reinterpret_cast<char*>(booleans.data()), booleans.size());
  for (int8_t b : booleans) {
    RequireValidNumber("invalid boolean capability", b);
  }
  return booleans;
}

std::vector<int32_t> ReadNumbers(bool extended_number_format, int count,
                                 std::istream& in) {
  std::vector<int32_t> numbers;
  numbers.reserve(count);
  for (int i = 0; i < count; ++i) {
    int32_t n;
    if (extended_number_format) {
      n = ReadInt(in);
    } else {
      n = ReadShort(in);
    }
    RequireValidNumber("invalid numeric capability", n);
    numbers.push_back(n);
  }
  return numbers;
}

std::vector<absl::optional<std::string>> ReadStrings(int offsets_count,
                                                     int bytes,
                                                     std::istream& in) {
  std::vector<int16_t> offsets;
  offsets.reserve(offsets_count);
  for (int i = 0; i < offsets_count; ++i) {
    int16_t n = ReadShort(in);
    RequireValidNumber("invalid string offset", n);
    offsets.push_back(n);
  }

  // Read the string table, including the trailing null (so we can easily find
  // the end of each capability).
  std::string data(bytes, '\0');
  in.read(data.data(), data.size());

  std::vector<absl::optional<std::string>> result;
  for (int16_t offset : offsets) {
    if (offset < 0) {
      result.push_back(absl::nullopt);
    } else {
      result.push_back(std::string(data.data() + offset));
    }
  }
  return result;
}

std::vector<std::string> DatabasePaths() noexcept {
  // If TERMINFO is set, only look there.
  if (std::string terminfo = GetEnv("TERMINFO"); !terminfo.empty()) {
    return {terminfo};
  }

  std::vector<std::string> paths;

  // Start by looking in HOME.
  if (std::string home = GetEnv("HOME"); !home.empty()) {
    paths.push_back(absl::StrCat(home, "/.terminfo"));
  }

  // Next, look in TERMINFO_DIRS.
  if (std::string terminfo_dirs = GetEnv("TERMINFO_DIRS");
      !terminfo_dirs.empty()) {
    for (absl::string_view dir : absl::StrSplit(terminfo_dirs, ':')) {
      if (dir.empty()) {
        paths.push_back(kSystemTerminfoDirectory);
      } else {
        paths.push_back(std::string(dir));
      }
    }
  }

  // Finally, look in system locations.
  paths.push_back(kSystemTerminfoDirectory);
  paths.push_back("/lib/terminfo");
  paths.push_back("/usr/share/terminfo");

  return paths;
}

std::ifstream OpenDescriptionForTerminal(absl::string_view db_path,
                                         absl::string_view name) {
  // The path to the terminal entry inside the database takes the general form
  // `c/name`, where c is the first character of the name (on file systems that
  // are case-sensitive) and the hex encoding of the name (on file systems that
  // are not).

  if (name.empty()) {
    throw std::invalid_argument("empty terminal name");
  }

  std::ifstream entry(absl::StrFormat("%s/%02x/%s", db_path, name[0], name));
  if (!entry.fail()) {
    return entry;
  }

  entry = std::ifstream(absl::StrFormat("%s/%c/%s", db_path, name[0], name));
  if (!entry.fail()) {
    return entry;
  }

  throw std::runtime_error("terminfo entry not found");
}

}  // namespace

TerminfoEntry TerminfoEntry::FromSystemDatabase(
    absl::string_view terminal_name) {
  for (const auto& path : DatabasePaths()) {
    try {
      std::ifstream binary = OpenDescriptionForTerminal(path, terminal_name);
      return TerminfoEntry(binary);
    } catch (const std::runtime_error&) {
      continue;
    }
  }
  throw std::runtime_error("no valid system entry by that name");
}

TerminfoEntry::TerminfoEntry(std::istream& description) {
  description.exceptions(std::istream::badbit | std::istream::failbit);

  Header header(description);
  if (header.names_bytes > 0) {
    names_ = ReadTerminalNames(header.names_bytes, description);
  }
  booleans_ = ReadBooleanFlags(header.booleans_bytes, description);

  // Discard the padding byte between the boolean flags section and the number
  // section, if it exists.
  if ((header.names_bytes + header.booleans_bytes) % 2 == 1 &&
      (header.numbers_count != 0 || header.strings_offsets_count != 0 ||
       header.strings_bytes != 0) &&
      description.get() != '\0') {
    throw std::runtime_error("padding byte was nonnull");
  }

  numbers_ = ReadNumbers(header.extended_number_format, header.numbers_count,
                         description);
  strings_ = ReadStrings(header.strings_offsets_count, header.strings_bytes,
                         description);
}

bool TerminfoEntry::get(BooleanCapability cap) const noexcept {
  try {
    return booleans_.at(FromEnum(cap)) > 0;
  } catch (const std::out_of_range&) {
    return false;
  }
}

absl::optional<int> TerminfoEntry::get(NumericCapability cap) const noexcept {
  try {
    int r = numbers_.at(FromEnum(cap));
    if (r >= 0) {
      return r;
    } else {
      return absl::nullopt;
    }
  } catch (const std::out_of_range&) {
    return absl::nullopt;
  }
}

const absl::optional<std::string>& TerminfoEntry::get(
    StringCapability cap) const noexcept {
  try {
    return strings_.at(FromEnum(cap));
  } catch (const std::out_of_range&) {
    static const absl::optional<std::string> kNone = absl::nullopt;
    return kNone;
  }
}

}  // namespace goldfishterm