Coverage Report

Created: 2024-02-25 06:31

/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 <cassert>
18
#include <string>
19
#include <vector>
20
21
#include "grpc_transcoding/http_template.h"
22
23
namespace google {
24
namespace grpc {
25
namespace transcoding {
26
27
namespace {
28
29
// TODO: implement an error sink.
30
31
// HTTP Template Grammar:
32
// Questions:
33
//   - what are the constraints on LITERAL and IDENT?
34
//   - what is the character set for the grammar?
35
//
36
// Template = "/" | "/" Segments [ Verb ] ;
37
// Segments = Segment { "/" Segment } ;
38
// Segment  = "*" | "**" | LITERAL | Variable ;
39
// Variable = "{" FieldPath [ "=" Segments ] "}" ;
40
// FieldPath = IDENT { "." IDENT } ;
41
// Verb     = ":" LITERAL ;
42
class Parser {
43
 public:
44
  Parser(const std::string &input)
45
944
      : input_(input), tb_(0), te_(0), in_variable_(false) {}
46
47
944
  bool Parse() {
48
944
    if (!ParseTemplate() || !ConsumedAllInput()) {
49
486
      return false;
50
486
    }
51
458
    PostProcessVariables();
52
458
    return true;
53
944
  }
54
55
386
  std::vector<std::string> &segments() { return segments_; }
56
386
  std::string &verb() { return verb_; }
57
386
  std::vector<HttpTemplate::Variable> &variables() { return variables_; }
58
59
  // only constant path segments are allowed after '**'.
60
458
  bool ValidateParts() {
61
458
    bool found_wild_card = false;
62
4.23M
    for (size_t i = 0; i < segments_.size(); i++) {
63
4.23M
      if (!found_wild_card) {
64
4.22M
        if (segments_[i] == HttpTemplate::kWildCardPathKey) {
65
220
          found_wild_card = true;
66
220
        }
67
4.22M
      } else if (segments_[i] == HttpTemplate::kSingleParameterKey ||
68
6.69k
                 segments_[i] == HttpTemplate::kWildCardPathPartKey ||
69
6.69k
                 segments_[i] == HttpTemplate::kWildCardPathKey) {
70
72
        return false;
71
72
      }
72
4.23M
    }
73
386
    return true;
74
458
  }
75
76
 private:
77
  // Template = "/" Segments [ Verb ] ;
78
944
  bool ParseTemplate() {
79
944
    if (!Consume('/')) {
80
      // Expected '/'
81
26
      return false;
82
26
    }
83
918
    if (!ParseSegments()) {
84
321
      return false;
85
321
    }
86
87
597
    if (EnsureCurrent() && current_char() == ':') {
88
69
      if (!ParseVerb()) {
89
43
        return false;
90
43
      }
91
69
    }
92
554
    return true;
93
597
  }
94
95
  // Segments = Segment { "/" Segment } ;
96
9.51k
  bool ParseSegments() {
97
9.51k
    if (!ParseSegment()) {
98
117
      return false;
99
117
    }
100
101
6.41M
    for (;;) {
102
6.41M
      if (!Consume('/')) break;
103
6.41M
      if (!ParseSegment()) {
104
230
        return false;
105
230
      }
106
6.41M
    }
107
108
9.17k
    return true;
109
9.40k
  }
110
111
  // Segment  = "*" | "**" | LITERAL | Variable ;
112
6.42M
  bool ParseSegment() {
113
6.42M
    if (!EnsureCurrent()) {
114
51
      return false;
115
51
    }
116
6.42M
    switch (current_char()) {
117
3.02M
      case '*': {
118
3.02M
        Consume('*');
119
3.02M
        if (Consume('*')) {
120
          // **
121
14.1k
          segments_.push_back("**");
122
14.1k
          if (in_variable_) {
123
9.22k
            return MarkVariableHasWildCardPath();
124
9.22k
          }
125
4.87k
          return true;
126
3.01M
        } else {
127
3.01M
          segments_.push_back("*");
128
3.01M
          return true;
129
3.01M
        }
130
3.02M
      }
131
132
370k
      case '{':
133
370k
        return ParseVariable();
134
3.02M
      default:
135
3.02M
        return ParseLiteralSegment();
136
6.42M
    }
137
6.42M
  }
138
139
  // Variable = "{" FieldPath [ "=" Segments ] "}" ;
140
370k
  bool ParseVariable() {
141
370k
    if (!Consume('{')) {
142
0
      return false;
143
0
    }
144
370k
    if (!StartVariable()) {
145
8
      return false;
146
8
    }
147
370k
    if (!ParseFieldPath()) {
148
76
      return false;
149
76
    }
150
370k
    if (Consume('=')) {
151
8.60k
      if (!ParseSegments()) {
152
26
        return false;
153
26
      }
154
361k
    } else {
155
      // {field_path} is equivalent to {field_path=*}
156
361k
      segments_.push_back("*");
157
361k
    }
158
370k
    if (!EndVariable()) {
159
0
      return false;
160
0
    }
161
370k
    if (!Consume('}')) {
162
164
      return false;
163
164
    }
164
369k
    return true;
165
370k
  }
166
167
3.02M
  bool ParseLiteralSegment() {
168
3.02M
    std::string ls;
169
3.02M
    if (!ParseLiteral(&ls)) {
170
22
      return false;
171
22
    }
172
3.02M
    segments_.push_back(ls);
173
3.02M
    return true;
174
3.02M
  }
175
176
  // FieldPath = IDENT { "." IDENT } ;
177
370k
  bool ParseFieldPath() {
178
370k
    if (!ParseIdentifier()) {
179
48
      return false;
180
48
    }
181
992k
    while (Consume('.')) {
182
622k
      if (!ParseIdentifier()) {
183
28
        return false;
184
28
      }
185
622k
    }
186
370k
    return true;
187
370k
  }
188
189
  // Verb     = ":" LITERAL ;
190
69
  bool ParseVerb() {
191
69
    if (!Consume(':')) return false;
192
69
    if (!ParseLiteral(&verb_)) return false;
193
26
    return true;
194
69
  }
195
196
992k
  bool ParseIdentifier() {
197
992k
    std::string idf;
198
199
    // Initialize to false to handle empty literal.
200
992k
    bool result = false;
201
202
7.42M
    while (NextChar()) {
203
7.42M
      char c;
204
7.42M
      switch (c = current_char()) {
205
622k
        case '.':
206
983k
        case '}':
207
992k
        case '=':
208
992k
          return result && AddFieldIdentifier(std::move(idf));
209
6.42M
        default:
210
6.42M
          Consume(c);
211
6.42M
          idf.push_back(c);
212
6.42M
          break;
213
7.42M
      }
214
6.42M
      result = true;
215
6.42M
    }
216
177
    return result && AddFieldIdentifier(std::move(idf));
217
992k
  }
218
219
3.02M
  bool ParseLiteral(std::string *lit) {
220
3.02M
    if (!EnsureCurrent()) {
221
39
      return false;
222
39
    }
223
224
    // Initialize to false in case we encounter an empty literal.
225
3.02M
    bool result = false;
226
227
21.4M
    for (;;) {
228
21.4M
      char c;
229
21.4M
      switch (c = current_char()) {
230
3.01M
        case '/':
231
3.01M
        case ':':
232
3.02M
        case '}':
233
3.02M
          return result;
234
18.4M
        default:
235
18.4M
          Consume(c);
236
18.4M
          lit->push_back(c);
237
18.4M
          break;
238
21.4M
      }
239
240
18.4M
      result = true;
241
242
18.4M
      if (!NextChar()) {
243
323
        break;
244
323
      }
245
18.4M
    }
246
323
    return result;
247
3.02M
  }
248
249
39.4M
  bool Consume(char c) {
250
39.4M
    if (tb_ >= te_ && !NextChar()) {
251
930
      return false;
252
930
    }
253
39.4M
    if (current_char() != c) {
254
3.75M
      return false;
255
3.75M
    }
256
35.7M
    tb_++;
257
35.7M
    return true;
258
39.4M
  }
259
260
554
  bool ConsumedAllInput() { return tb_ >= input_.size(); }
261
262
9.44M
  bool EnsureCurrent() { return tb_ < te_ || NextChar(); }
263
264
35.7M
  bool NextChar() {
265
35.7M
    if (te_ < input_.size()) {
266
35.7M
      te_++;
267
35.7M
      return true;
268
35.7M
    } else {
269
1.95k
      return false;
270
1.95k
    }
271
35.7M
  }
272
273
  // Returns the character looked at.
274
74.7M
  char current_char() const {
275
74.7M
    return tb_ < te_ && te_ <= input_.size() ? input_[te_ - 1] : -1;
276
74.7M
  }
277
278
2.48M
  HttpTemplate::Variable &CurrentVariable() { return variables_.back(); }
279
280
370k
  bool StartVariable() {
281
370k
    if (!in_variable_) {
282
370k
      variables_.push_back(HttpTemplate::Variable{});
283
370k
      CurrentVariable().start_segment = segments_.size();
284
370k
      CurrentVariable().has_wildcard_path = false;
285
370k
      in_variable_ = true;
286
370k
      return true;
287
370k
    } else {
288
      // nested variables are not allowed
289
8
      return false;
290
8
    }
291
370k
  }
292
293
370k
  bool EndVariable() {
294
370k
    if (in_variable_ && !variables_.empty()) {
295
370k
      CurrentVariable().end_segment = segments_.size();
296
370k
      in_variable_ = false;
297
370k
      return ValidateVariable(CurrentVariable());
298
370k
    } else {
299
      // something's wrong we're not in a variable
300
0
      return false;
301
0
    }
302
370k
  }
303
304
992k
  bool AddFieldIdentifier(std::string id) {
305
992k
    if (in_variable_ && !variables_.empty()) {
306
992k
      CurrentVariable().field_path.emplace_back(std::move(id));
307
992k
      return true;
308
992k
    } else {
309
      // something's wrong we're not in a variable
310
0
      return false;
311
0
    }
312
992k
  }
313
314
9.22k
  bool MarkVariableHasWildCardPath() {
315
9.22k
    if (in_variable_ && !variables_.empty()) {
316
9.22k
      CurrentVariable().has_wildcard_path = true;
317
9.22k
      return true;
318
9.22k
    } else {
319
      // something's wrong we're not in a variable
320
0
      return false;
321
0
    }
322
9.22k
  }
323
324
370k
  bool ValidateVariable(const HttpTemplate::Variable &var) {
325
370k
    return !var.field_path.empty() && (var.start_segment < var.end_segment) &&
326
370k
           (var.end_segment <= static_cast<int>(segments_.size()));
327
370k
  }
328
329
458
  void PostProcessVariables() {
330
246k
    for (auto &var : variables_) {
331
246k
      if (var.has_wildcard_path) {
332
        // if the variable contains a '**', store the end_positon
333
        // relative to the end, such that -1 corresponds to the end
334
        // of the path. As we only support fixed path after '**',
335
        // this will allow the matcher code to reconstruct the variable
336
        // value based on the url segments.
337
2.93k
        var.end_segment = (var.end_segment - segments_.size() - 1);
338
2.93k
      }
339
246k
    }
340
458
  }
341
342
  const std::string &input_;
343
344
  // Token delimiter indexes
345
  size_t tb_;
346
  size_t te_;
347
348
  // are we in nested Segments of a variable?
349
  bool in_variable_;
350
351
  std::vector<std::string> segments_;
352
  std::string verb_;
353
  std::vector<HttpTemplate::Variable> variables_;
354
};
355
356
}  // namespace
357
358
const char HttpTemplate::kSingleParameterKey[] = "/.";
359
360
const char HttpTemplate::kWildCardPathPartKey[] = "*";
361
362
const char HttpTemplate::kWildCardPathKey[] = "**";
363
364
945
std::unique_ptr<HttpTemplate> HttpTemplate::Parse(const std::string &ht) {
365
945
  if (ht == "/") {
366
1
    return std::unique_ptr<HttpTemplate>(new HttpTemplate({}, {}, {}));
367
1
  }
368
369
944
  Parser p(ht);
370
944
  if (!p.Parse() || !p.ValidateParts()) {
371
558
    return nullptr;
372
558
  }
373
374
386
  return std::unique_ptr<HttpTemplate>(new HttpTemplate(
375
386
      std::move(p.segments()), std::move(p.verb()), std::move(p.variables())));
376
944
}
377
378
}  // namespace transcoding
379
}  // namespace grpc
380
}  // namespace google