Coverage Report

Created: 2025-07-18 06:50

/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
498
      return false;
49
498
    }
50
509
    PostProcessVariables();
51
509
    return true;
52
1.00k
  }
53
54
424
  std::vector<std::string> &segments() { return segments_; }
55
424
  std::string &verb() { return verb_; }
56
424
  std::vector<HttpTemplate::Variable> &variables() { return variables_; }
57
58
  // only constant path segments are allowed after '**'.
59
509
  bool ValidateParts() {
60
509
    bool found_wild_card = false;
61
1.05M
    for (size_t i = 0; i < segments_.size(); i++) {
62
1.05M
      if (!found_wild_card) {
63
1.03M
        if (segments_[i] == HttpTemplate::kWildCardPathKey) {
64
225
          found_wild_card = true;
65
225
        }
66
1.03M
      } else if (segments_[i] == HttpTemplate::kSingleParameterKey ||
67
22.3k
                 segments_[i] == HttpTemplate::kWildCardPathPartKey ||
68
22.3k
                 segments_[i] == HttpTemplate::kWildCardPathKey) {
69
85
        return false;
70
85
      }
71
1.05M
    }
72
424
    return true;
73
509
  }
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
979
    if (!ParseSegments()) {
83
330
      return false;
84
330
    }
85
86
649
    if (EnsureCurrent() && current_char() == ':') {
87
61
      if (!ParseVerb()) {
88
29
        return false;
89
29
      }
90
61
    }
91
620
    return true;
92
649
  }
93
94
  // Segments = Segment { "/" Segment } ;
95
10.8k
  bool ParseSegments() {
96
10.8k
    if (!ParseSegment()) {
97
111
      return false;
98
111
    }
99
100
3.64M
    for (;;) {
101
3.64M
      if (!Consume('/')) break;
102
3.63M
      if (!ParseSegment()) {
103
242
        return false;
104
242
      }
105
3.63M
    }
106
107
10.5k
    return true;
108
10.7k
  }
109
110
  // Segment  = "*" | "**" | LITERAL | Variable ;
111
3.64M
  bool ParseSegment() {
112
3.64M
    if (!EnsureCurrent()) {
113
45
      return false;
114
45
    }
115
3.64M
    switch (current_char()) {
116
1.78M
      case '*': {
117
1.78M
        Consume('*');
118
1.78M
        if (Consume('*')) {
119
          // **
120
92.6k
          segments_.push_back("**");
121
92.6k
          if (in_variable_) {
122
9.03k
            return MarkVariableHasWildCardPath();
123
9.03k
          }
124
83.5k
          return true;
125
1.69M
        } else {
126
1.69M
          segments_.push_back("*");
127
1.69M
          return true;
128
1.69M
        }
129
1.78M
      }
130
131
302k
      case '{':
132
302k
        return ParseVariable();
133
1.56M
      default:
134
1.56M
        return ParseLiteralSegment();
135
3.64M
    }
136
3.64M
  }
137
138
  // Variable = "{" FieldPath [ "=" Segments ] "}" ;
139
302k
  bool ParseVariable() {
140
302k
    if (!Consume('{')) {
141
0
      return false;
142
0
    }
143
302k
    if (!StartVariable()) {
144
8
      return false;
145
8
    }
146
302k
    if (!ParseFieldPath()) {
147
95
      return false;
148
95
    }
149
302k
    if (Consume('=')) {
150
9.91k
      if (!ParseSegments()) {
151
23
        return false;
152
23
      }
153
292k
    } else {
154
      // {field_path} is equivalent to {field_path=*}
155
292k
      segments_.push_back("*");
156
292k
    }
157
302k
    if (!EndVariable()) {
158
0
      return false;
159
0
    }
160
302k
    if (!Consume('}')) {
161
164
      return false;
162
164
    }
163
302k
    return true;
164
302k
  }
165
166
1.56M
  bool ParseLiteralSegment() {
167
1.56M
    std::string ls;
168
1.56M
    if (!ParseLiteral(&ls)) {
169
18
      return false;
170
18
    }
171
1.56M
    segments_.push_back(ls);
172
1.56M
    return true;
173
1.56M
  }
174
175
  // FieldPath = IDENT { "." IDENT } ;
176
302k
  bool ParseFieldPath() {
177
302k
    if (!ParseIdentifier()) {
178
59
      return false;
179
59
    }
180
981k
    while (Consume('.')) {
181
679k
      if (!ParseIdentifier()) {
182
36
        return false;
183
36
      }
184
679k
    }
185
302k
    return true;
186
302k
  }
187
188
  // Verb     = ":" LITERAL ;
189
61
  bool ParseVerb() {
190
61
    if (!Consume(':')) return false;
191
61
    if (!ParseLiteral(&verb_)) return false;
192
32
    return true;
193
61
  }
194
195
981k
  bool ParseIdentifier() {
196
981k
    std::string idf;
197
198
    // Initialize to false to handle empty literal.
199
981k
    bool result = false;
200
201
8.23M
    while (NextChar()) {
202
8.23M
      char c;
203
8.23M
      switch (c = current_char()) {
204
679k
        case '.':
205
971k
        case '}':
206
981k
        case '=':
207
981k
          return result && AddFieldIdentifier(std::move(idf));
208
7.25M
        default:
209
7.25M
          Consume(c);
210
7.25M
          idf.push_back(c);
211
7.25M
          break;
212
8.23M
      }
213
7.25M
      result = true;
214
7.25M
    }
215
190
    return result && AddFieldIdentifier(std::move(idf));
216
981k
  }
217
218
1.56M
  bool ParseLiteral(std::string *lit) {
219
1.56M
    if (!EnsureCurrent()) {
220
26
      return false;
221
26
    }
222
223
    // Initialize to false in case we encounter an empty literal.
224
1.56M
    bool result = false;
225
226
34.7M
    for (;;) {
227
34.7M
      char c;
228
34.7M
      switch (c = current_char()) {
229
1.55M
        case '/':
230
1.55M
        case ':':
231
1.56M
        case '}':
232
1.56M
          return result;
233
33.1M
        default:
234
33.1M
          Consume(c);
235
33.1M
          lit->push_back(c);
236
33.1M
          break;
237
34.7M
      }
238
239
33.1M
      result = true;
240
241
33.1M
      if (!NextChar()) {
242
382
        break;
243
382
      }
244
33.1M
    }
245
382
    return result;
246
1.56M
  }
247
248
49.4M
  bool Consume(char c) {
249
49.4M
    if (tb_ >= te_ && !NextChar()) {
250
963
      return false;
251
963
    }
252
49.4M
    if (current_char() != c) {
253
2.29M
      return false;
254
2.29M
    }
255
47.1M
    tb_++;
256
47.1M
    return true;
257
49.4M
  }
258
259
620
  bool ConsumedAllInput() { return tb_ >= input_.size(); }
260
261
5.21M
  bool EnsureCurrent() { return tb_ < te_ || NextChar(); }
262
263
47.2M
  bool NextChar() {
264
47.2M
    if (te_ < input_.size()) {
265
47.1M
      te_++;
266
47.1M
      return true;
267
47.1M
    } else {
268
2.08k
      return false;
269
2.08k
    }
270
47.2M
  }
271
272
  // Returns the character looked at.
273
96.0M
  char current_char() const {
274
96.0M
    return tb_ < te_ && te_ <= input_.size() ? input_[te_ - 1] : -1;
275
96.0M
  }
276
277
2.19M
  HttpTemplate::Variable &CurrentVariable() { return variables_.back(); }
278
279
302k
  bool StartVariable() {
280
302k
    if (!in_variable_) {
281
302k
      variables_.push_back(HttpTemplate::Variable{});
282
302k
      CurrentVariable().start_segment = segments_.size();
283
302k
      CurrentVariable().has_wildcard_path = false;
284
302k
      in_variable_ = true;
285
302k
      return true;
286
302k
    } else {
287
      // nested variables are not allowed
288
8
      return false;
289
8
    }
290
302k
  }
291
292
302k
  bool EndVariable() {
293
302k
    if (in_variable_ && !variables_.empty()) {
294
302k
      CurrentVariable().end_segment = segments_.size();
295
302k
      in_variable_ = false;
296
302k
      return ValidateVariable(CurrentVariable());
297
302k
    } else {
298
      // something's wrong we're not in a variable
299
0
      return false;
300
0
    }
301
302k
  }
302
303
981k
  bool AddFieldIdentifier(std::string id) {
304
981k
    if (in_variable_ && !variables_.empty()) {
305
981k
      CurrentVariable().field_path.emplace_back(std::move(id));
306
981k
      return true;
307
981k
    } else {
308
      // something's wrong we're not in a variable
309
0
      return false;
310
0
    }
311
981k
  }
312
313
9.03k
  bool MarkVariableHasWildCardPath() {
314
9.03k
    if (in_variable_ && !variables_.empty()) {
315
9.03k
      CurrentVariable().has_wildcard_path = true;
316
9.03k
      return true;
317
9.03k
    } else {
318
      // something's wrong we're not in a variable
319
0
      return false;
320
0
    }
321
9.03k
  }
322
323
302k
  bool ValidateVariable(const HttpTemplate::Variable &var) {
324
302k
    return !var.field_path.empty() && (var.start_segment < var.end_segment) &&
325
302k
           (var.end_segment <= static_cast<int>(segments_.size()));
326
302k
  }
327
328
509
  void PostProcessVariables() {
329
63.6k
    for (auto &var : variables_) {
330
63.6k
      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
2.55k
        var.end_segment = (var.end_segment - segments_.size() - 1);
337
2.55k
      }
338
63.6k
    }
339
509
  }
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
583
    return nullptr;
371
583
  }
372
373
424
  return std::unique_ptr<HttpTemplate>(new HttpTemplate(
374
424
      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