Coverage Report

Created: 2025-09-08 06:52

/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
994
      : input_(input), tb_(0), te_(0), in_variable_(false) {}
45
46
994
  bool Parse() {
47
994
    if (!ParseTemplate() || !ConsumedAllInput()) {
48
493
      return false;
49
493
    }
50
501
    PostProcessVariables();
51
501
    return true;
52
994
  }
53
54
433
  std::vector<std::string> &segments() { return segments_; }
55
433
  std::string &verb() { return verb_; }
56
433
  std::vector<HttpTemplate::Variable> &variables() { return variables_; }
57
58
  // only constant path segments are allowed after '**'.
59
501
  bool ValidateParts() {
60
501
    bool found_wild_card = false;
61
1.23M
    for (size_t i = 0; i < segments_.size(); i++) {
62
1.23M
      if (!found_wild_card) {
63
1.23M
        if (segments_[i] == HttpTemplate::kWildCardPathKey) {
64
223
          found_wild_card = true;
65
223
        }
66
1.23M
      } else if (segments_[i] == HttpTemplate::kSingleParameterKey ||
67
2.69k
                 segments_[i] == HttpTemplate::kWildCardPathPartKey ||
68
2.69k
                 segments_[i] == HttpTemplate::kWildCardPathKey) {
69
68
        return false;
70
68
      }
71
1.23M
    }
72
433
    return true;
73
501
  }
74
75
 private:
76
  // Template = "/" Segments [ Verb ] ;
77
994
  bool ParseTemplate() {
78
994
    if (!Consume('/')) {
79
      // Expected '/'
80
27
      return false;
81
27
    }
82
967
    if (!ParseSegments()) {
83
346
      return false;
84
346
    }
85
86
621
    if (EnsureCurrent() && current_char() == ':') {
87
56
      if (!ParseVerb()) {
88
27
        return false;
89
27
      }
90
56
    }
91
594
    return true;
92
621
  }
93
94
  // Segments = Segment { "/" Segment } ;
95
8.29k
  bool ParseSegments() {
96
8.29k
    if (!ParseSegment()) {
97
135
      return false;
98
135
    }
99
100
4.41M
    for (;;) {
101
4.41M
      if (!Consume('/')) break;
102
4.40M
      if (!ParseSegment()) {
103
235
        return false;
104
235
      }
105
4.40M
    }
106
107
7.92k
    return true;
108
8.16k
  }
109
110
  // Segment  = "*" | "**" | LITERAL | Variable ;
111
4.41M
  bool ParseSegment() {
112
4.41M
    if (!EnsureCurrent()) {
113
46
      return false;
114
46
    }
115
4.41M
    switch (current_char()) {
116
2.57M
      case '*': {
117
2.57M
        Consume('*');
118
2.57M
        if (Consume('*')) {
119
          // **
120
54.1k
          segments_.push_back("**");
121
54.1k
          if (in_variable_) {
122
8.82k
            return MarkVariableHasWildCardPath();
123
8.82k
          }
124
45.3k
          return true;
125
2.52M
        } else {
126
2.52M
          segments_.push_back("*");
127
2.52M
          return true;
128
2.52M
        }
129
2.57M
      }
130
131
358k
      case '{':
132
358k
        return ParseVariable();
133
1.48M
      default:
134
1.48M
        return ParseLiteralSegment();
135
4.41M
    }
136
4.41M
  }
137
138
  // Variable = "{" FieldPath [ "=" Segments ] "}" ;
139
358k
  bool ParseVariable() {
140
358k
    if (!Consume('{')) {
141
0
      return false;
142
0
    }
143
358k
    if (!StartVariable()) {
144
5
      return false;
145
5
    }
146
358k
    if (!ParseFieldPath()) {
147
104
      return false;
148
104
    }
149
358k
    if (Consume('=')) {
150
7.33k
      if (!ParseSegments()) {
151
24
        return false;
152
24
      }
153
351k
    } else {
154
      // {field_path} is equivalent to {field_path=*}
155
351k
      segments_.push_back("*");
156
351k
    }
157
358k
    if (!EndVariable()) {
158
0
      return false;
159
0
    }
160
358k
    if (!Consume('}')) {
161
166
      return false;
162
166
    }
163
358k
    return true;
164
358k
  }
165
166
1.48M
  bool ParseLiteralSegment() {
167
1.48M
    std::string ls;
168
1.48M
    if (!ParseLiteral(&ls)) {
169
25
      return false;
170
25
    }
171
1.48M
    segments_.push_back(ls);
172
1.48M
    return true;
173
1.48M
  }
174
175
  // FieldPath = IDENT { "." IDENT } ;
176
358k
  bool ParseFieldPath() {
177
358k
    if (!ParseIdentifier()) {
178
62
      return false;
179
62
    }
180
948k
    while (Consume('.')) {
181
590k
      if (!ParseIdentifier()) {
182
42
        return false;
183
42
      }
184
590k
    }
185
358k
    return true;
186
358k
  }
187
188
  // Verb     = ":" LITERAL ;
189
56
  bool ParseVerb() {
190
56
    if (!Consume(':')) return false;
191
56
    if (!ParseLiteral(&verb_)) return false;
192
29
    return true;
193
56
  }
194
195
948k
  bool ParseIdentifier() {
196
948k
    std::string idf;
197
198
    // Initialize to false to handle empty literal.
199
948k
    bool result = false;
200
201
6.59M
    while (NextChar()) {
202
6.59M
      char c;
203
6.59M
      switch (c = current_char()) {
204
590k
        case '.':
205
941k
        case '}':
206
948k
        case '=':
207
948k
          return result && AddFieldIdentifier(std::move(idf));
208
5.64M
        default:
209
5.64M
          Consume(c);
210
5.64M
          idf.push_back(c);
211
5.64M
          break;
212
6.59M
      }
213
5.64M
      result = true;
214
5.64M
    }
215
197
    return result && AddFieldIdentifier(std::move(idf));
216
948k
  }
217
218
1.48M
  bool ParseLiteral(std::string *lit) {
219
1.48M
    if (!EnsureCurrent()) {
220
24
      return false;
221
24
    }
222
223
    // Initialize to false in case we encounter an empty literal.
224
1.48M
    bool result = false;
225
226
33.1M
    for (;;) {
227
33.1M
      char c;
228
33.1M
      switch (c = current_char()) {
229
1.47M
        case '/':
230
1.47M
        case ':':
231
1.48M
        case '}':
232
1.48M
          return result;
233
31.6M
        default:
234
31.6M
          Consume(c);
235
31.6M
          lit->push_back(c);
236
31.6M
          break;
237
33.1M
      }
238
239
31.6M
      result = true;
240
241
31.6M
      if (!NextChar()) {
242
389
        break;
243
389
      }
244
31.6M
    }
245
389
    return result;
246
1.48M
  }
247
248
48.9M
  bool Consume(char c) {
249
48.9M
    if (tb_ >= te_ && !NextChar()) {
250
946
      return false;
251
946
    }
252
48.9M
    if (current_char() != c) {
253
3.23M
      return false;
254
3.23M
    }
255
45.6M
    tb_++;
256
45.6M
    return true;
257
48.9M
  }
258
259
594
  bool ConsumedAllInput() { return tb_ >= input_.size(); }
260
261
5.90M
  bool EnsureCurrent() { return tb_ < te_ || NextChar(); }
262
263
45.6M
  bool NextChar() {
264
45.6M
    if (te_ < input_.size()) {
265
45.6M
      te_++;
266
45.6M
      return true;
267
45.6M
    } else {
268
2.07k
      return false;
269
2.07k
    }
270
45.6M
  }
271
272
  // Returns the character looked at.
273
93.0M
  char current_char() const {
274
93.0M
    return tb_ < te_ && te_ <= input_.size() ? input_[te_ - 1] : -1;
275
93.0M
  }
276
277
2.39M
  HttpTemplate::Variable &CurrentVariable() { return variables_.back(); }
278
279
358k
  bool StartVariable() {
280
358k
    if (!in_variable_) {
281
358k
      variables_.push_back(HttpTemplate::Variable{});
282
358k
      CurrentVariable().start_segment = segments_.size();
283
358k
      CurrentVariable().has_wildcard_path = false;
284
358k
      in_variable_ = true;
285
358k
      return true;
286
358k
    } else {
287
      // nested variables are not allowed
288
5
      return false;
289
5
    }
290
358k
  }
291
292
358k
  bool EndVariable() {
293
358k
    if (in_variable_ && !variables_.empty()) {
294
358k
      CurrentVariable().end_segment = segments_.size();
295
358k
      in_variable_ = false;
296
358k
      return ValidateVariable(CurrentVariable());
297
358k
    } else {
298
      // something's wrong we're not in a variable
299
0
      return false;
300
0
    }
301
358k
  }
302
303
948k
  bool AddFieldIdentifier(std::string id) {
304
948k
    if (in_variable_ && !variables_.empty()) {
305
948k
      CurrentVariable().field_path.emplace_back(std::move(id));
306
948k
      return true;
307
948k
    } else {
308
      // something's wrong we're not in a variable
309
0
      return false;
310
0
    }
311
948k
  }
312
313
8.82k
  bool MarkVariableHasWildCardPath() {
314
8.82k
    if (in_variable_ && !variables_.empty()) {
315
8.82k
      CurrentVariable().has_wildcard_path = true;
316
8.82k
      return true;
317
8.82k
    } else {
318
      // something's wrong we're not in a variable
319
0
      return false;
320
0
    }
321
8.82k
  }
322
323
358k
  bool ValidateVariable(const HttpTemplate::Variable &var) {
324
358k
    return !var.field_path.empty() && (var.start_segment < var.end_segment) &&
325
358k
           (var.end_segment <= static_cast<int>(segments_.size()));
326
358k
  }
327
328
501
  void PostProcessVariables() {
329
226k
    for (auto &var : variables_) {
330
226k
      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.09k
        var.end_segment = (var.end_segment - segments_.size() - 1);
337
1.09k
      }
338
226k
    }
339
501
  }
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
995
std::unique_ptr<HttpTemplate> HttpTemplate::Parse(const std::string &ht) {
364
995
  if (ht == "/") {
365
1
    return std::unique_ptr<HttpTemplate>(new HttpTemplate({}, {}, {}));
366
1
  }
367
368
994
  Parser p(ht);
369
994
  if (!p.Parse() || !p.ValidateParts()) {
370
561
    return nullptr;
371
561
  }
372
373
433
  return std::unique_ptr<HttpTemplate>(new HttpTemplate(
374
433
      std::move(p.segments()), std::move(p.verb()), std::move(p.variables())));
375
994
}
376
377
}  // namespace transcoding
378
}  // namespace grpc
379
}  // namespace google