Coverage Report

Created: 2026-12-01 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/sideband.c
Line
Count
Source
1
#define USE_THE_REPOSITORY_VARIABLE
2
#define DISABLE_SIGN_COMPARE_WARNINGS
3
4
#include "git-compat-util.h"
5
#include "color.h"
6
#include "config.h"
7
#include "editor.h"
8
#include "gettext.h"
9
#include "sideband.h"
10
#include "help.h"
11
#include "pkt-line.h"
12
#include "write-or-die.h"
13
#include "urlmatch.h"
14
15
struct keyword_entry {
16
  /*
17
   * We use keyword as config key so it should be a single alphanumeric word.
18
   */
19
  const char *keyword;
20
  char color[COLOR_MAXLEN];
21
};
22
23
static struct keyword_entry keywords[] = {
24
  { "hint", GIT_COLOR_YELLOW },
25
  { "warning",  GIT_COLOR_BOLD_YELLOW },
26
  { "success",  GIT_COLOR_BOLD_GREEN },
27
  { "error",  GIT_COLOR_BOLD_RED },
28
};
29
30
static enum {
31
  ALLOW_CONTROL_SEQUENCES_UNSET = -1,
32
  ALLOW_NO_CONTROL_CHARACTERS   = 0,
33
  ALLOW_ANSI_COLOR_SEQUENCES    = 1<<0,
34
  ALLOW_ANSI_CURSOR_MOVEMENTS   = 1<<1,
35
  ALLOW_ANSI_ERASE              = 1<<2,
36
  ALLOW_ALL_CONTROL_CHARACTERS  = 1<<3,
37
  ALLOW_DEFAULT_ANSI_SEQUENCES  = ALLOW_ANSI_COLOR_SEQUENCES
38
} allow_control_characters = ALLOW_CONTROL_SEQUENCES_UNSET;
39
40
static inline int skip_prefix_in_csv(const char *value, const char *prefix,
41
             const char **out)
42
0
{
43
0
  if (!skip_prefix(value, prefix, &value) ||
44
0
      (*value && *value != ','))
45
0
    return 0;
46
0
  *out = value + !!*value;
47
0
  return 1;
48
0
}
49
50
int sideband_allow_control_characters_config(const char *var, const char *value)
51
0
{
52
0
  switch (git_parse_maybe_bool(value)) {
53
0
  case 0:
54
0
    allow_control_characters = ALLOW_NO_CONTROL_CHARACTERS;
55
0
    return 0;
56
0
  case 1:
57
0
    allow_control_characters = ALLOW_ALL_CONTROL_CHARACTERS;
58
0
    return 0;
59
0
  default:
60
0
    break;
61
0
  }
62
63
0
  allow_control_characters = ALLOW_NO_CONTROL_CHARACTERS;
64
0
  while (*value) {
65
0
    if (skip_prefix_in_csv(value, "color", &value)) {
66
0
      allow_control_characters |= ALLOW_ANSI_COLOR_SEQUENCES;
67
0
    } else if (skip_prefix_in_csv(value, "cursor", &value)) {
68
0
      allow_control_characters |= ALLOW_ANSI_CURSOR_MOVEMENTS;
69
0
    } else if (skip_prefix_in_csv(value, "erase", &value)) {
70
0
      allow_control_characters |= ALLOW_ANSI_ERASE;
71
0
    } else if (skip_prefix_in_csv(value, "true", &value)) {
72
0
      allow_control_characters = ALLOW_ALL_CONTROL_CHARACTERS;
73
0
    } else if (skip_prefix_in_csv(value, "false", &value)) {
74
0
      allow_control_characters = ALLOW_NO_CONTROL_CHARACTERS;
75
0
    } else {
76
0
      const char *end = strchrnul(value, ',');
77
78
0
      warning(_("unrecognized value for '%s': '%.*s'"),
79
0
        var, (int)(end - value), value);
80
0
      value = end + !!*end;
81
0
    }
82
0
  }
83
0
  return 0;
84
0
}
85
86
static int sideband_config_callback(const char *var, const char *value,
87
            const struct config_context *ctx UNUSED,
88
            void *data UNUSED)
89
0
{
90
0
  if (!strcmp(var, "sideband.allowcontrolcharacters"))
91
0
    return sideband_allow_control_characters_config(var, value);
92
93
0
  return 0;
94
0
}
95
96
void sideband_apply_url_config(const char *url)
97
0
{
98
0
  struct urlmatch_config config = URLMATCH_CONFIG_INIT;
99
0
  char *normalized_url;
100
101
0
  if (!url)
102
0
    BUG("must not call sideband_apply_url_config(NULL)");
103
104
0
  config.section = "sideband";
105
0
  config.collect_fn = sideband_config_callback;
106
107
0
  normalized_url = url_normalize(url, &config.url);
108
0
  repo_config(the_repository, urlmatch_config_entry, &config);
109
0
  free(normalized_url);
110
0
  string_list_clear(&config.vars, 1);
111
0
  urlmatch_config_release(&config);
112
0
}
113
114
/* Returns a color setting (GIT_COLOR_NEVER, etc). */
115
static enum git_colorbool use_sideband_colors(void)
116
0
{
117
0
  static enum git_colorbool use_sideband_colors_cached = GIT_COLOR_UNKNOWN;
118
119
0
  const char *key = "color.remote";
120
0
  struct strbuf sb = STRBUF_INIT;
121
0
  const char *value;
122
0
  int i;
123
124
0
  if (use_sideband_colors_cached != GIT_COLOR_UNKNOWN)
125
0
    return use_sideband_colors_cached;
126
127
0
  if (allow_control_characters == ALLOW_CONTROL_SEQUENCES_UNSET) {
128
0
    if (!repo_config_get_value(the_repository, "sideband.allowcontrolcharacters", &value))
129
0
      sideband_allow_control_characters_config("sideband.allowcontrolcharacters", value);
130
131
0
    if (allow_control_characters == ALLOW_CONTROL_SEQUENCES_UNSET)
132
0
      allow_control_characters = ALLOW_DEFAULT_ANSI_SEQUENCES;
133
0
  }
134
135
0
  if (!repo_config_get_string_tmp(the_repository, key, &value))
136
0
    use_sideband_colors_cached = git_config_colorbool(key, value);
137
0
  else if (!repo_config_get_string_tmp(the_repository, "color.ui", &value))
138
0
    use_sideband_colors_cached = git_config_colorbool("color.ui", value);
139
0
  else
140
0
    use_sideband_colors_cached = GIT_COLOR_AUTO;
141
142
0
  for (i = 0; i < ARRAY_SIZE(keywords); i++) {
143
0
    strbuf_reset(&sb);
144
0
    strbuf_addf(&sb, "%s.%s", key, keywords[i].keyword);
145
0
    if (repo_config_get_string_tmp(the_repository, sb.buf, &value))
146
0
      continue;
147
0
    color_parse(value, keywords[i].color);
148
0
  }
149
150
0
  strbuf_release(&sb);
151
0
  return use_sideband_colors_cached;
152
0
}
153
154
void list_config_color_sideband_slots(struct string_list *list, const char *prefix)
155
0
{
156
0
  int i;
157
158
0
  for (i = 0; i < ARRAY_SIZE(keywords); i++)
159
0
    list_config_item(list, prefix, keywords[i].keyword);
160
0
}
161
162
static int handle_ansi_sequence(struct strbuf *dest, const char *src, int n)
163
0
{
164
0
  int i;
165
166
  /*
167
   * Valid ANSI color sequences are of the form
168
   *
169
   * ESC [ [<n> [; <n>]*] m
170
   *
171
   * where <n> can be either zero-length, or a decimal number, or a
172
   * series of decimal numbers separated by a colon (for 256-color or
173
   * true-color codes).
174
   *
175
   * These are part of the Select Graphic Rendition sequences which
176
   * contain more than just color sequences, for more details see
177
   * https://en.wikipedia.org/wiki/ANSI_escape_code#SGR.
178
   *
179
   * The cursor movement sequences are:
180
   *
181
   * ESC [ n A - Cursor up n lines (CUU)
182
   * ESC [ n B - Cursor down n lines (CUD)
183
   * ESC [ n C - Cursor forward n columns (CUF)
184
   * ESC [ n D - Cursor back n columns (CUB)
185
   * ESC [ n E - Cursor next line, beginning (CNL)
186
   * ESC [ n F - Cursor previous line, beginning (CPL)
187
   * ESC [ n G - Cursor to column n (CHA)
188
   * ESC [ n ; m H - Cursor position (row n, col m) (CUP)
189
   * ESC [ n ; m f - Same as H (HVP)
190
   *
191
   * The sequences to erase characters are:
192
   *
193
   *
194
   * ESC [ 0 J - Clear from cursor to end of screen (ED)
195
   * ESC [ 1 J - Clear from cursor to beginning of screen (ED)
196
   * ESC [ 2 J - Clear entire screen (ED)
197
   * ESC [ 3 J - Clear entire screen + scrollback (ED) - xterm extension
198
   * ESC [ 0 K - Clear from cursor to end of line (EL)
199
   * ESC [ 1 K - Clear from cursor to beginning of line (EL)
200
   * ESC [ 2 K - Clear entire line (EL)
201
   * ESC [ n M - Delete n lines (DL)
202
   * ESC [ n P - Delete n characters (DCH)
203
   * ESC [ n X - Erase n characters (ECH)
204
   *
205
   * For a comprehensive list of common ANSI Escape sequences, see
206
   * https://www.xfree86.org/current/ctlseqs.html
207
   */
208
209
0
  if (n < 3 || src[0] != '\x1b' || src[1] != '[')
210
0
    return 0;
211
212
0
  for (i = 2; i < n; i++) {
213
0
    if (((allow_control_characters & ALLOW_ANSI_COLOR_SEQUENCES) &&
214
0
         src[i] == 'm') ||
215
0
        ((allow_control_characters & ALLOW_ANSI_CURSOR_MOVEMENTS) &&
216
0
         strchr("ABCDEFGHf", src[i])) ||
217
0
        ((allow_control_characters & ALLOW_ANSI_ERASE) &&
218
0
         strchr("JKMPX", src[i]))) {
219
0
      strbuf_add(dest, src, i + 1);
220
0
      return i;
221
0
    }
222
0
    if (!isdigit(src[i]) && src[i] != ':' && src[i] != ';')
223
0
      break;
224
0
  }
225
226
0
  return 0;
227
0
}
228
229
static void strbuf_add_sanitized(struct strbuf *dest, const char *src, int n)
230
0
{
231
0
  int i;
232
233
0
  if ((allow_control_characters & ALLOW_ALL_CONTROL_CHARACTERS)) {
234
0
    strbuf_add(dest, src, n);
235
0
    return;
236
0
  }
237
238
0
  strbuf_grow(dest, n);
239
0
  for (; n && *src; src++, n--) {
240
0
    if (!iscntrl(*src) || *src == '\t' || *src == '\n') {
241
0
      strbuf_addch(dest, *src);
242
0
    } else if (allow_control_characters != ALLOW_NO_CONTROL_CHARACTERS &&
243
0
         (i = handle_ansi_sequence(dest, src, n))) {
244
0
      src += i;
245
0
      n -= i;
246
0
    } else {
247
0
      strbuf_addch(dest, '^');
248
0
      strbuf_addch(dest, *src == 0x7f ? '?' : 0x40 + *src);
249
0
    }
250
0
  }
251
0
}
252
253
/*
254
 * Optionally highlight one keyword in remote output if it appears at the start
255
 * of the line. This should be called for a single line only, which is
256
 * passed as the first N characters of the SRC array.
257
 *
258
 * It is fine to use "int n" here instead of "size_t n" as all calls to this
259
 * function pass an 'int' parameter. Additionally, the buffer involved in
260
 * storing these 'int' values takes input from a packet via the pkt-line
261
 * interface, which is capable of transferring only 64kB at a time.
262
 */
263
static void maybe_colorize_sideband(struct strbuf *dest, const char *src, int n)
264
0
{
265
0
  int i;
266
267
0
  if (!want_color_stderr(use_sideband_colors())) {
268
0
    strbuf_add_sanitized(dest, src, n);
269
0
    return;
270
0
  }
271
272
0
  while (0 < n && isspace(*src)) {
273
0
    strbuf_addch(dest, *src);
274
0
    src++;
275
0
    n--;
276
0
  }
277
278
0
  for (i = 0; i < ARRAY_SIZE(keywords); i++) {
279
0
    struct keyword_entry *p = keywords + i;
280
0
    int len = strlen(p->keyword);
281
282
0
    if (n < len)
283
0
      continue;
284
    /*
285
     * Match case insensitively, so we colorize output from existing
286
     * servers regardless of the case that they use for their
287
     * messages. We only highlight the word precisely, so
288
     * "successful" stays uncolored.
289
     */
290
0
    if (!strncasecmp(p->keyword, src, len) &&
291
0
        (len == n || !isalnum(src[len]))) {
292
0
      strbuf_addstr(dest, p->color);
293
0
      strbuf_add(dest, src, len);
294
0
      strbuf_addstr(dest, GIT_COLOR_RESET);
295
0
      n -= len;
296
0
      src += len;
297
0
      break;
298
0
    }
299
0
  }
300
301
0
  strbuf_add_sanitized(dest, src, n);
302
0
}
303
304
305
0
#define DISPLAY_PREFIX "remote: "
306
307
0
#define ANSI_PREFIX "\033[K"
308
0
#define DUMB_SUFFIX "        "
309
310
int demultiplex_sideband(const char *me, int status,
311
       char *buf, int len,
312
       int die_on_error,
313
       struct strbuf *scratch,
314
       enum sideband_type *sideband_type)
315
0
{
316
0
  static const char *prefix, *suffix;
317
0
  const char *b, *brk;
318
0
  int band;
319
320
0
  if (!suffix) {
321
0
    if (isatty(2) && !is_terminal_dumb()) {
322
0
      prefix = ANSI_PREFIX DISPLAY_PREFIX;
323
0
      suffix = "";
324
0
    } else {
325
0
      prefix = DISPLAY_PREFIX;
326
0
      suffix = DUMB_SUFFIX;
327
0
    }
328
0
  }
329
330
0
  if (status == PACKET_READ_EOF) {
331
0
    strbuf_addf(scratch,
332
0
          "%s%s: unexpected disconnect while reading sideband packet",
333
0
          scratch->len ? "\n" : "", me);
334
0
    *sideband_type = SIDEBAND_PROTOCOL_ERROR;
335
0
    goto cleanup;
336
0
  }
337
338
0
  if (len < 0)
339
0
    BUG("negative length on non-eof packet read");
340
341
0
  if (len == 0) {
342
0
    if (status == PACKET_READ_NORMAL) {
343
0
      strbuf_addf(scratch,
344
0
            "%s%s: protocol error: missing sideband designator",
345
0
            scratch->len ? "\n" : "", me);
346
0
      *sideband_type = SIDEBAND_PROTOCOL_ERROR;
347
0
    } else {
348
      /* covers flush, delim, etc */
349
0
      *sideband_type = SIDEBAND_FLUSH;
350
0
    }
351
0
    goto cleanup;
352
0
  }
353
354
0
  band = buf[0] & 0xff;
355
0
  buf[len] = '\0';
356
0
  len--;
357
0
  switch (band) {
358
0
  case 3:
359
0
    if (die_on_error)
360
0
      die(_("remote error: %s"), buf + 1);
361
0
    strbuf_addf(scratch, "%s%s", scratch->len ? "\n" : "", prefix);
362
0
    maybe_colorize_sideband(scratch, buf + 1, len);
363
364
0
    *sideband_type = SIDEBAND_REMOTE_ERROR;
365
0
    break;
366
0
  case 2:
367
0
    b = buf + 1;
368
369
    /*
370
     * Append a suffix to each nonempty line to clear the
371
     * end of the screen line.
372
     *
373
     * The output is accumulated in a buffer and
374
     * each line is printed to stderr using
375
     * write(2) to ensure inter-process atomicity.
376
     */
377
0
    while ((brk = strpbrk(b, "\n\r"))) {
378
0
      int linelen = brk - b;
379
380
      /*
381
       * For message across packet boundary, there would have
382
       * a nonempty "scratch" buffer from last call of this
383
       * function, and there may have a leading CR/LF in "buf".
384
       * For this case we should add a clear-to-eol suffix to
385
       * clean leftover letters we previously have written on
386
       * the same line.
387
       */
388
0
      if (scratch->len && !linelen)
389
0
        strbuf_addstr(scratch, suffix);
390
391
0
      if (!scratch->len)
392
0
        strbuf_addstr(scratch, prefix);
393
394
      /*
395
       * A use case that we should not add clear-to-eol suffix
396
       * to empty lines:
397
       *
398
       * For progress reporting we may receive a bunch of
399
       * percentage updates followed by '\r' to remain on the
400
       * same line, and at the end receive a single '\n' to
401
       * move to the next line. We should preserve the final
402
       * status report line by not appending clear-to-eol
403
       * suffix to this single line break.
404
       */
405
0
      if (linelen > 0) {
406
0
        maybe_colorize_sideband(scratch, b, linelen);
407
0
        strbuf_addstr(scratch, suffix);
408
0
      }
409
410
0
      strbuf_addch(scratch, *brk);
411
0
      write_in_full(2, scratch->buf, scratch->len);
412
0
      strbuf_reset(scratch);
413
414
0
      b = brk + 1;
415
0
    }
416
417
0
    if (*b) {
418
0
      if (!scratch->len)
419
0
        strbuf_addstr(scratch, prefix);
420
0
      maybe_colorize_sideband(scratch, b, strlen(b));
421
0
    }
422
0
    return 0;
423
0
  case 1:
424
0
    *sideband_type = SIDEBAND_PRIMARY;
425
0
    return 1;
426
0
  default:
427
0
    strbuf_addf(scratch, "%s%s: protocol error: bad band #%d",
428
0
          scratch->len ? "\n" : "", me, band);
429
0
    *sideband_type = SIDEBAND_PROTOCOL_ERROR;
430
0
    break;
431
0
  }
432
433
0
cleanup:
434
0
  if (die_on_error && *sideband_type == SIDEBAND_PROTOCOL_ERROR)
435
0
    die("%s", scratch->buf);
436
0
  if (scratch->len) {
437
0
    strbuf_addch(scratch, '\n');
438
0
    write_in_full(2, scratch->buf, scratch->len);
439
0
  }
440
0
  strbuf_release(scratch);
441
0
  return 1;
442
0
}
443
444
/*
445
 * fd is connected to the remote side; send the sideband data
446
 * over multiplexed packet stream.
447
 */
448
void send_sideband(int fd, int band, const char *data, ssize_t sz, int packet_max)
449
0
{
450
0
  const char *p = data;
451
452
0
  while (sz) {
453
0
    struct iovec iov[2];
454
0
    unsigned n;
455
0
    char hdr[5];
456
457
0
    n = sz;
458
0
    if (packet_max - 5 < n)
459
0
      n = packet_max - 5;
460
0
    if (0 <= band) {
461
0
      xsnprintf(hdr, sizeof(hdr), "%04x", n + 5);
462
0
      hdr[4] = band;
463
0
      iov[0].iov_base = hdr;
464
0
      iov[0].iov_len = 5;
465
0
    } else {
466
0
      xsnprintf(hdr, sizeof(hdr), "%04x", n + 4);
467
0
      iov[0].iov_base = hdr;
468
0
      iov[0].iov_len = 4;
469
0
    }
470
471
0
    iov[1].iov_base = (void *) p;
472
0
    iov[1].iov_len = n;
473
474
0
    writev_or_die(fd, iov, ARRAY_SIZE(iov));
475
476
0
    p += n;
477
0
    sz -= n;
478
0
  }
479
0
}