Coverage Report

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