Coverage Report

Created: 2025-07-11 06:41

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