Coverage Report

Created: 2022-10-12 06:22

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