Coverage Report

Created: 2025-08-26 06:33

/proc/self/cwd/src/http_template.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2016 Google Inc. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
////////////////////////////////////////////////////////////////////////////////
16
//
17
#include "grpc_transcoding/http_template.h"
18
19
#include <string>
20
#include <vector>
21
22
namespace google {
23
namespace grpc {
24
namespace transcoding {
25
26
namespace {
27
28
// TODO: implement an error sink.
29
30
// HTTP Template Grammar:
31
// Questions:
32
//   - what are the constraints on LITERAL and IDENT?
33
//   - what is the character set for the grammar?
34
//
35
// Template = "/" | "/" Segments [ Verb ] ;
36
// Segments = Segment { "/" Segment } ;
37
// Segment  = "*" | "**" | LITERAL | Variable ;
38
// Variable = "{" FieldPath [ "=" Segments ] "}" ;
39
// FieldPath = IDENT { "." IDENT } ;
40
// Verb     = ":" LITERAL ;
41
class Parser {
42
 public:
43
  Parser(const std::string &input)
44
1.00k
      : input_(input), tb_(0), te_(0), in_variable_(false) {}
45
46
1.00k
  bool Parse() {
47
1.00k
    if (!ParseTemplate() || !ConsumedAllInput()) {
48
515
      return false;
49
515
    }
50
490
    PostProcessVariables();
51
490
    return true;
52
1.00k
  }
53
54
412
  std::vector<std::string> &segments() { return segments_; }
55
412
  std::string &verb() { return verb_; }
56
412
  std::vector<HttpTemplate::Variable> &variables() { return variables_; }
57
58
  // only constant path segments are allowed after '**'.
59
490
  bool ValidateParts() {
60
490
    bool found_wild_card = false;
61
1.34M
    for (size_t i = 0; i < segments_.size(); i++) {
62
1.33M
      if (!found_wild_card) {
63
1.32M
        if (segments_[i] == HttpTemplate::kWildCardPathKey) {
64
224
          found_wild_card = true;
65
224
        }
66
1.32M
      } else if (segments_[i] == HttpTemplate::kSingleParameterKey ||
67
10.4k
                 segments_[i] == HttpTemplate::kWildCardPathPartKey ||
68
10.4k
                 segments_[i] == HttpTemplate::kWildCardPathKey) {
69
78
        return false;
70
78
      }
71
1.33M
    }
72
412
    return true;
73
490
  }
74
75
 private:
76
  // Template = "/" Segments [ Verb ] ;
77
1.00k
  bool ParseTemplate() {
78
1.00k
    if (!Consume('/')) {
79
      // Expected '/'
80
28
      return false;
81
28
    }
82
977
    if (!ParseSegments()) {
83
348
      return false;
84
348
    }
85
86
629
    if (EnsureCurrent() && current_char() == ':') {
87
56
      if (!ParseVerb()) {
88
30
        return false;
89
30
      }
90
56
    }
91
599
    return true;
92
629
  }
93
94
  // Segments = Segment { "/" Segment } ;
95
9.58k
  bool ParseSegments() {
96
9.58k
    if (!ParseSegment()) {
97
126
      return false;
98
126
    }
99
100
4.72M
    for (;;) {
101
4.72M
      if (!Consume('/')) break;
102
4.71M
      if (!ParseSegment()) {
103
250
        return false;
104
250
      }
105
4.71M
    }
106
107
9.20k
    return true;
108
9.45k
  }
109
110
  // Segment  = "*" | "**" | LITERAL | Variable ;
111
4.72M
  bool ParseSegment() {
112
4.72M
    if (!EnsureCurrent()) {
113
45
      return false;
114
45
    }
115
4.72M
    switch (current_char()) {
116
2.74M
      case '*': {
117
2.74M
        Consume('*');
118
2.74M
        if (Consume('*')) {
119
          // **
120
58.0k
          segments_.push_back("**");
121
58.0k
          if (in_variable_) {
122
10.7k
            return MarkVariableHasWildCardPath();
123
10.7k
          }
124
47.3k
          return true;
125
2.68M
        } else {
126
2.68M
          segments_.push_back("*");
127
2.68M
          return true;
128
2.68M
        }
129
2.74M
      }
130
131
304k
      case '{':
132
304k
        return ParseVariable();
133
1.67M
      default:
134
1.67M
        return ParseLiteralSegment();
135
4.72M
    }
136
4.72M
  }
137
138
  // Variable = "{" FieldPath [ "=" Segments ] "}" ;
139
304k
  bool ParseVariable() {
140
304k
    if (!Consume('{')) {
141
0
      return false;
142
0
    }
143
304k
    if (!StartVariable()) {
144
11
      return false;
145
11
    }
146
304k
    if (!ParseFieldPath()) {
147
96
      return false;
148
96
    }
149
303k
    if (Consume('=')) {
150
8.60k
      if (!ParseSegments()) {
151
28
        return false;
152
28
      }
153
295k
    } else {
154
      // {field_path} is equivalent to {field_path=*}
155
295k
      segments_.push_back("*");
156
295k
    }
157
303k
    if (!EndVariable()) {
158
0
      return false;
159
0
    }
160
303k
    if (!Consume('}')) {
161
174
      return false;
162
174
    }
163
303k
    return true;
164
303k
  }
165
166
1.67M
  bool ParseLiteralSegment() {
167
1.67M
    std::string ls;
168
1.67M
    if (!ParseLiteral(&ls)) {
169
22
      return false;
170
22
    }
171
1.67M
    segments_.push_back(ls);
172
1.67M
    return true;
173
1.67M
  }
174
175
  // FieldPath = IDENT { "." IDENT } ;
176
304k
  bool ParseFieldPath() {
177
304k
    if (!ParseIdentifier()) {
178
58
      return false;
179
58
    }
180
937k
    while (Consume('.')) {
181
633k
      if (!ParseIdentifier()) {
182
38
        return false;
183
38
      }
184
633k
    }
185
303k
    return true;
186
303k
  }
187
188
  // Verb     = ":" LITERAL ;
189
56
  bool ParseVerb() {
190
56
    if (!Consume(':')) return false;
191
56
    if (!ParseLiteral(&verb_)) return false;
192
26
    return true;
193
56
  }
194
195
937k
  bool ParseIdentifier() {
196
937k
    std::string idf;
197
198
    // Initialize to false to handle empty literal.
199
937k
    bool result = false;
200
201
7.63M
    while (NextChar()) {
202
7.63M
      char c;
203
7.63M
      switch (c = current_char()) {
204
633k
        case '.':
205
928k
        case '}':
206
937k
        case '=':
207
937k
          return result && AddFieldIdentifier(std::move(idf));
208
6.69M
        default:
209
6.69M
          Consume(c);
210
6.69M
          idf.push_back(c);
211
6.69M
          break;
212
7.63M
      }
213
6.69M
      result = true;
214
6.69M
    }
215
196
    return result && AddFieldIdentifier(std::move(idf));
216
937k
  }
217
218
1.67M
  bool ParseLiteral(std::string *lit) {
219
1.67M
    if (!EnsureCurrent()) {
220
27
      return false;
221
27
    }
222
223
    // Initialize to false in case we encounter an empty literal.
224
1.67M
    bool result = false;
225
226
29.5M
    for (;;) {
227
29.5M
      char c;
228
29.5M
      switch (c = current_char()) {
229
1.67M
        case '/':
230
1.67M
        case ':':
231
1.67M
        case '}':
232
1.67M
          return result;
233
27.8M
        default:
234
27.8M
          Consume(c);
235
27.8M
          lit->push_back(c);
236
27.8M
          break;
237
29.5M
      }
238
239
27.8M
      result = true;
240
241
27.8M
      if (!NextChar()) {
242
379
        break;
243
379
      }
244
27.8M
    }
245
379
    return result;
246
1.67M
  }
247
248
46.5M
  bool Consume(char c) {
249
46.5M
    if (tb_ >= te_ && !NextChar()) {
250
974
      return false;
251
974
    }
252
46.5M
    if (current_char() != c) {
253
3.29M
      return false;
254
3.29M
    }
255
43.2M
    tb_++;
256
43.2M
    return true;
257
46.5M
  }
258
259
599
  bool ConsumedAllInput() { return tb_ >= input_.size(); }
260
261
6.39M
  bool EnsureCurrent() { return tb_ < te_ || NextChar(); }
262
263
43.3M
  bool NextChar() {
264
43.3M
    if (te_ < input_.size()) {
265
43.2M
      te_++;
266
43.2M
      return true;
267
43.2M
    } else {
268
2.09k
      return false;
269
2.09k
    }
270
43.3M
  }
271
272
  // Returns the character looked at.
273
88.4M
  char current_char() const {
274
88.4M
    return tb_ < te_ && te_ <= input_.size() ? input_[te_ - 1] : -1;
275
88.4M
  }
276
277
2.16M
  HttpTemplate::Variable &CurrentVariable() { return variables_.back(); }
278
279
304k
  bool StartVariable() {
280
304k
    if (!in_variable_) {
281
304k
      variables_.push_back(HttpTemplate::Variable{});
282
304k
      CurrentVariable().start_segment = segments_.size();
283
304k
      CurrentVariable().has_wildcard_path = false;
284
304k
      in_variable_ = true;
285
304k
      return true;
286
304k
    } else {
287
      // nested variables are not allowed
288
11
      return false;
289
11
    }
290
304k
  }
291
292
303k
  bool EndVariable() {
293
303k
    if (in_variable_ && !variables_.empty()) {
294
303k
      CurrentVariable().end_segment = segments_.size();
295
303k
      in_variable_ = false;
296
303k
      return ValidateVariable(CurrentVariable());
297
303k
    } else {
298
      // something's wrong we're not in a variable
299
0
      return false;
300
0
    }
301
303k
  }
302
303
937k
  bool AddFieldIdentifier(std::string id) {
304
937k
    if (in_variable_ && !variables_.empty()) {
305
937k
      CurrentVariable().field_path.emplace_back(std::move(id));
306
937k
      return true;
307
937k
    } else {
308
      // something's wrong we're not in a variable
309
0
      return false;
310
0
    }
311
937k
  }
312
313
10.7k
  bool MarkVariableHasWildCardPath() {
314
10.7k
    if (in_variable_ && !variables_.empty()) {
315
10.7k
      CurrentVariable().has_wildcard_path = true;
316
10.7k
      return true;
317
10.7k
    } else {
318
      // something's wrong we're not in a variable
319
0
      return false;
320
0
    }
321
10.7k
  }
322
323
303k
  bool ValidateVariable(const HttpTemplate::Variable &var) {
324
303k
    return !var.field_path.empty() && (var.start_segment < var.end_segment) &&
325
303k
           (var.end_segment <= static_cast<int>(segments_.size()));
326
303k
  }
327
328
490
  void PostProcessVariables() {
329
257k
    for (auto &var : variables_) {
330
257k
      if (var.has_wildcard_path) {
331
        // if the variable contains a '**', store the end_positon
332
        // relative to the end, such that -1 corresponds to the end
333
        // of the path. As we only support fixed path after '**',
334
        // this will allow the matcher code to reconstruct the variable
335
        // value based on the url segments.
336
750
        var.end_segment = (var.end_segment - segments_.size() - 1);
337
750
      }
338
257k
    }
339
490
  }
340
341
  const std::string &input_;
342
343
  // Token delimiter indexes
344
  size_t tb_;
345
  size_t te_;
346
347
  // are we in nested Segments of a variable?
348
  bool in_variable_;
349
350
  std::vector<std::string> segments_;
351
  std::string verb_;
352
  std::vector<HttpTemplate::Variable> variables_;
353
};
354
355
}  // namespace
356
357
const char HttpTemplate::kSingleParameterKey[] = "/.";
358
359
const char HttpTemplate::kWildCardPathPartKey[] = "*";
360
361
const char HttpTemplate::kWildCardPathKey[] = "**";
362
363
1.00k
std::unique_ptr<HttpTemplate> HttpTemplate::Parse(const std::string &ht) {
364
1.00k
  if (ht == "/") {
365
1
    return std::unique_ptr<HttpTemplate>(new HttpTemplate({}, {}, {}));
366
1
  }
367
368
1.00k
  Parser p(ht);
369
1.00k
  if (!p.Parse() || !p.ValidateParts()) {
370
593
    return nullptr;
371
593
  }
372
373
412
  return std::unique_ptr<HttpTemplate>(new HttpTemplate(
374
412
      std::move(p.segments()), std::move(p.verb()), std::move(p.variables())));
375
1.00k
}
376
377
}  // namespace transcoding
378
}  // namespace grpc
379
}  // namespace google