Coverage Report

Created: 2025-08-29 06:15

/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
990
      : input_(input), tb_(0), te_(0), in_variable_(false) {}
45
46
990
  bool Parse() {
47
990
    if (!ParseTemplate() || !ConsumedAllInput()) {
48
504
      return false;
49
504
    }
50
486
    PostProcessVariables();
51
486
    return true;
52
990
  }
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
486
  bool ValidateParts() {
60
486
    bool found_wild_card = false;
61
1.64M
    for (size_t i = 0; i < segments_.size(); i++) {
62
1.64M
      if (!found_wild_card) {
63
1.64M
        if (segments_[i] == HttpTemplate::kWildCardPathKey) {
64
224
          found_wild_card = true;
65
224
        }
66
1.64M
      } else if (segments_[i] == HttpTemplate::kSingleParameterKey ||
67
2.79k
                 segments_[i] == HttpTemplate::kWildCardPathPartKey ||
68
2.79k
                 segments_[i] == HttpTemplate::kWildCardPathKey) {
69
74
        return false;
70
74
      }
71
1.64M
    }
72
412
    return true;
73
486
  }
74
75
 private:
76
  // Template = "/" Segments [ Verb ] ;
77
990
  bool ParseTemplate() {
78
990
    if (!Consume('/')) {
79
      // Expected '/'
80
28
      return false;
81
28
    }
82
962
    if (!ParseSegments()) {
83
342
      return false;
84
342
    }
85
86
620
    if (EnsureCurrent() && current_char() == ':') {
87
58
      if (!ParseVerb()) {
88
32
        return false;
89
32
      }
90
58
    }
91
588
    return true;
92
620
  }
93
94
  // Segments = Segment { "/" Segment } ;
95
8.61k
  bool ParseSegments() {
96
8.61k
    if (!ParseSegment()) {
97
126
      return false;
98
126
    }
99
100
4.47M
    for (;;) {
101
4.47M
      if (!Consume('/')) break;
102
4.46M
      if (!ParseSegment()) {
103
242
        return false;
104
242
      }
105
4.46M
    }
106
107
8.24k
    return true;
108
8.49k
  }
109
110
  // Segment  = "*" | "**" | LITERAL | Variable ;
111
4.47M
  bool ParseSegment() {
112
4.47M
    if (!EnsureCurrent()) {
113
44
      return false;
114
44
    }
115
4.47M
    switch (current_char()) {
116
2.59M
      case '*': {
117
2.59M
        Consume('*');
118
2.59M
        if (Consume('*')) {
119
          // **
120
60.3k
          segments_.push_back("**");
121
60.3k
          if (in_variable_) {
122
10.6k
            return MarkVariableHasWildCardPath();
123
10.6k
          }
124
49.7k
          return true;
125
2.53M
        } else {
126
2.53M
          segments_.push_back("*");
127
2.53M
          return true;
128
2.53M
        }
129
2.59M
      }
130
131
299k
      case '{':
132
299k
        return ParseVariable();
133
1.57M
      default:
134
1.57M
        return ParseLiteralSegment();
135
4.47M
    }
136
4.47M
  }
137
138
  // Variable = "{" FieldPath [ "=" Segments ] "}" ;
139
299k
  bool ParseVariable() {
140
299k
    if (!Consume('{')) {
141
0
      return false;
142
0
    }
143
299k
    if (!StartVariable()) {
144
10
      return false;
145
10
    }
146
299k
    if (!ParseFieldPath()) {
147
96
      return false;
148
96
    }
149
299k
    if (Consume('=')) {
150
7.65k
      if (!ParseSegments()) {
151
26
        return false;
152
26
      }
153
291k
    } else {
154
      // {field_path} is equivalent to {field_path=*}
155
291k
      segments_.push_back("*");
156
291k
    }
157
299k
    if (!EndVariable()) {
158
0
      return false;
159
0
    }
160
299k
    if (!Consume('}')) {
161
167
      return false;
162
167
    }
163
298k
    return true;
164
299k
  }
165
166
1.57M
  bool ParseLiteralSegment() {
167
1.57M
    std::string ls;
168
1.57M
    if (!ParseLiteral(&ls)) {
169
25
      return false;
170
25
    }
171
1.57M
    segments_.push_back(ls);
172
1.57M
    return true;
173
1.57M
  }
174
175
  // FieldPath = IDENT { "." IDENT } ;
176
299k
  bool ParseFieldPath() {
177
299k
    if (!ParseIdentifier()) {
178
59
      return false;
179
59
    }
180
929k
    while (Consume('.')) {
181
630k
      if (!ParseIdentifier()) {
182
37
        return false;
183
37
      }
184
630k
    }
185
299k
    return true;
186
299k
  }
187
188
  // Verb     = ":" LITERAL ;
189
58
  bool ParseVerb() {
190
58
    if (!Consume(':')) return false;
191
58
    if (!ParseLiteral(&verb_)) return false;
192
26
    return true;
193
58
  }
194
195
929k
  bool ParseIdentifier() {
196
929k
    std::string idf;
197
198
    // Initialize to false to handle empty literal.
199
929k
    bool result = false;
200
201
7.24M
    while (NextChar()) {
202
7.24M
      char c;
203
7.24M
      switch (c = current_char()) {
204
630k
        case '.':
205
921k
        case '}':
206
929k
        case '=':
207
929k
          return result && AddFieldIdentifier(std::move(idf));
208
6.31M
        default:
209
6.31M
          Consume(c);
210
6.31M
          idf.push_back(c);
211
6.31M
          break;
212
7.24M
      }
213
6.31M
      result = true;
214
6.31M
    }
215
189
    return result && AddFieldIdentifier(std::move(idf));
216
929k
  }
217
218
1.57M
  bool ParseLiteral(std::string *lit) {
219
1.57M
    if (!EnsureCurrent()) {
220
30
      return false;
221
30
    }
222
223
    // Initialize to false in case we encounter an empty literal.
224
1.57M
    bool result = false;
225
226
29.0M
    for (;;) {
227
29.0M
      char c;
228
29.0M
      switch (c = current_char()) {
229
1.57M
        case '/':
230
1.57M
        case ':':
231
1.57M
        case '}':
232
1.57M
          return result;
233
27.4M
        default:
234
27.4M
          Consume(c);
235
27.4M
          lit->push_back(c);
236
27.4M
          break;
237
29.0M
      }
238
239
27.4M
      result = true;
240
241
27.4M
      if (!NextChar()) {
242
374
        break;
243
374
      }
244
27.4M
    }
245
374
    return result;
246
1.57M
  }
247
248
45.2M
  bool Consume(char c) {
249
45.2M
    if (tb_ >= te_ && !NextChar()) {
250
940
      return false;
251
940
    }
252
45.2M
    if (current_char() != c) {
253
3.13M
      return false;
254
3.13M
    }
255
42.1M
    tb_++;
256
42.1M
    return true;
257
45.2M
  }
258
259
588
  bool ConsumedAllInput() { return tb_ >= input_.size(); }
260
261
6.05M
  bool EnsureCurrent() { return tb_ < te_ || NextChar(); }
262
263
42.1M
  bool NextChar() {
264
42.1M
    if (te_ < input_.size()) {
265
42.1M
      te_++;
266
42.1M
      return true;
267
42.1M
    } else {
268
2.03k
      return false;
269
2.03k
    }
270
42.1M
  }
271
272
  // Returns the character looked at.
273
85.9M
  char current_char() const {
274
85.9M
    return tb_ < te_ && te_ <= input_.size() ? input_[te_ - 1] : -1;
275
85.9M
  }
276
277
2.13M
  HttpTemplate::Variable &CurrentVariable() { return variables_.back(); }
278
279
299k
  bool StartVariable() {
280
299k
    if (!in_variable_) {
281
299k
      variables_.push_back(HttpTemplate::Variable{});
282
299k
      CurrentVariable().start_segment = segments_.size();
283
299k
      CurrentVariable().has_wildcard_path = false;
284
299k
      in_variable_ = true;
285
299k
      return true;
286
299k
    } else {
287
      // nested variables are not allowed
288
10
      return false;
289
10
    }
290
299k
  }
291
292
299k
  bool EndVariable() {
293
299k
    if (in_variable_ && !variables_.empty()) {
294
299k
      CurrentVariable().end_segment = segments_.size();
295
299k
      in_variable_ = false;
296
299k
      return ValidateVariable(CurrentVariable());
297
299k
    } else {
298
      // something's wrong we're not in a variable
299
0
      return false;
300
0
    }
301
299k
  }
302
303
929k
  bool AddFieldIdentifier(std::string id) {
304
929k
    if (in_variable_ && !variables_.empty()) {
305
929k
      CurrentVariable().field_path.emplace_back(std::move(id));
306
929k
      return true;
307
929k
    } else {
308
      // something's wrong we're not in a variable
309
0
      return false;
310
0
    }
311
929k
  }
312
313
10.6k
  bool MarkVariableHasWildCardPath() {
314
10.6k
    if (in_variable_ && !variables_.empty()) {
315
10.6k
      CurrentVariable().has_wildcard_path = true;
316
10.6k
      return true;
317
10.6k
    } else {
318
      // something's wrong we're not in a variable
319
0
      return false;
320
0
    }
321
10.6k
  }
322
323
299k
  bool ValidateVariable(const HttpTemplate::Variable &var) {
324
299k
    return !var.field_path.empty() && (var.start_segment < var.end_segment) &&
325
299k
           (var.end_segment <= static_cast<int>(segments_.size()));
326
299k
  }
327
328
486
  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
1.03k
        var.end_segment = (var.end_segment - segments_.size() - 1);
337
1.03k
      }
338
257k
    }
339
486
  }
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
991
std::unique_ptr<HttpTemplate> HttpTemplate::Parse(const std::string &ht) {
364
991
  if (ht == "/") {
365
1
    return std::unique_ptr<HttpTemplate>(new HttpTemplate({}, {}, {}));
366
1
  }
367
368
990
  Parser p(ht);
369
990
  if (!p.Parse() || !p.ValidateParts()) {
370
578
    return nullptr;
371
578
  }
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
990
}
376
377
}  // namespace transcoding
378
}  // namespace grpc
379
}  // namespace google