File: Plugin.cc

package info (click to toggle)
trafficserver 9.2.5%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 53,008 kB
  • sloc: cpp: 345,484; ansic: 31,134; python: 24,200; sh: 7,271; makefile: 3,045; perl: 2,261; java: 277; pascal: 119; sql: 94; xml: 2
file content (367 lines) | stat: -rw-r--r-- 9,603 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/** @file

  Plugin init

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include <cstdio>
#include "tscore/ink_platform.h"
#include "tscore/ink_file.h"
#include "tscore/ParseRules.h"
#include "records/I_RecCore.h"
#include "tscore/I_Layout.h"
#include "InkAPIInternal.h"
#include "Plugin.h"
#include "tscore/ink_cap.h"
#include "tscore/Filenames.h"

#define MAX_PLUGIN_ARGS 64

static PluginDynamicReloadMode plugin_dynamic_reload_mode = PluginDynamicReloadMode::RELOAD_ON;

bool
isPluginDynamicReloadEnabled()
{
  return PluginDynamicReloadMode::RELOAD_ON == plugin_dynamic_reload_mode;
}

void
parsePluginDynamicReloadConfig()
{
  int int_plugin_dynamic_reload_mode;

  REC_ReadConfigInteger(int_plugin_dynamic_reload_mode, "proxy.config.plugin.dynamic_reload_mode");
  plugin_dynamic_reload_mode = static_cast<PluginDynamicReloadMode>(int_plugin_dynamic_reload_mode);

  if (plugin_dynamic_reload_mode < 0 || plugin_dynamic_reload_mode >= PluginDynamicReloadMode::RELOAD_COUNT) {
    Warning("proxy.config.plugin.dynamic_reload_mode out of range. using default value.");
    plugin_dynamic_reload_mode = PluginDynamicReloadMode::RELOAD_ON;
  }
  Note("Initialized plugin_dynamic_reload_mode: %d", plugin_dynamic_reload_mode);
}

void
parsePluginConfig()
{
  parsePluginDynamicReloadConfig();
}

static const char *plugin_dir = ".";

using init_func_t = void (*)(int, char **);

// Plugin registration vars
//
//    plugin_reg_list has an entry for each plugin
//      we've successfully been able to load
//    plugin_reg_current is used to associate the
//      plugin we're in the process of loading with
//      it struct.  We need this global pointer since
//      the API doesn't have any plugin context.  Init
//      is single threaded so we can get away with the
//      global pointer
//
DLL<PluginRegInfo> plugin_reg_list;
PluginRegInfo *plugin_reg_current = nullptr;

PluginRegInfo::PluginRegInfo() = default;

PluginRegInfo::~PluginRegInfo()
{
  // We don't support unloading plugins once they are successfully loaded, so assert
  // that we don't accidentally attempt this.
  ink_release_assert(this->plugin_registered == false);
  ink_release_assert(this->link.prev == nullptr);

  ats_free(this->plugin_path);
  ats_free(this->plugin_name);
  ats_free(this->vendor_name);
  ats_free(this->support_email);
  if (dlh) {
    dlclose(dlh);
  }
}

bool
plugin_dso_load(const char *path, void *&handle, void *&init, std::string &error)
{
  handle = dlopen(path, RTLD_NOW);
  init   = nullptr;
  if (!handle) {
    error.assign("unable to load '").append(path).append("': ").append(dlerror());
    Error("%s", error.c_str());
    return false;
  }

  init = dlsym(handle, "TSPluginInit");
  if (!init) {
    error.assign("unable to find TSPluginInit function in '").append(path).append("': ").append(dlerror());
    Error("%s", error.c_str());
    dlclose(handle);
    handle = nullptr;
    return false;
  }

  return true;
}

static bool
single_plugin_init(int argc, char *argv[], bool validateOnly)
{
  char path[PATH_NAME_MAX];
  init_func_t init;

  if (argc < 1) {
    return true;
  }
  ink_filepath_make(path, sizeof(path), plugin_dir, argv[0]);

  Note("loading plugin '%s'", path);

  for (PluginRegInfo *plugin_reg_temp = plugin_reg_list.head; plugin_reg_temp != nullptr;
       plugin_reg_temp                = (plugin_reg_temp->link).next) {
    if (strcmp(plugin_reg_temp->plugin_path, path) == 0) {
      Warning("multiple loading of plugin %s", path);
      break;
    }
  }

  // elevate the access to read files as root if compiled with capabilities, if not
  // change the effective user to root
  {
    uint32_t elevate_access = 0;
    REC_ReadConfigInteger(elevate_access, "proxy.config.plugin.load_elevated");
    ElevateAccess access(elevate_access ? ElevateAccess::FILE_PRIVILEGE : 0);

    void *handle, *initptr = nullptr;
    std::string error;
    bool loaded = plugin_dso_load(path, handle, initptr, error);
    init        = reinterpret_cast<init_func_t>(initptr);

    if (!loaded) {
      if (validateOnly) {
        return false;
      }
      Fatal("%s", error.c_str());
      return false; // this line won't get called since Fatal brings down ATS
    }

    // Allocate a new registration structure for the
    //    plugin we're starting up
    ink_assert(plugin_reg_current == nullptr);
    plugin_reg_current              = new PluginRegInfo;
    plugin_reg_current->plugin_path = ats_strdup(path);
    plugin_reg_current->dlh         = handle;

#if (!defined(kfreebsd) && defined(freebsd)) || defined(darwin)
    optreset = 1;
#endif
#if defined(__GLIBC__)
    optind = 0;
#else
    optind = 1;
#endif
    opterr = 0;
    optarg = nullptr;
    init(argc, argv);
  } // done elevating access

  if (plugin_reg_current->plugin_registered) {
    plugin_reg_list.push(plugin_reg_current);
  } else {
    Fatal("plugin not registered by calling TSPluginRegister");
    return false; // this line won't get called since Fatal brings down ATS
  }

  plugin_reg_current = nullptr;

  return true;
}

static char *
plugin_expand(char *arg)
{
  RecDataT data_type;
  char *str = nullptr;

  if (*arg != '$') {
    return (char *)nullptr;
  }
  // skip the $ character
  arg += 1;

  if (RecGetRecordDataType(arg, &data_type) != REC_ERR_OKAY) {
    goto not_found;
  }

  switch (data_type) {
  case RECD_STRING: {
    RecString str_val;
    if (RecGetRecordString_Xmalloc(arg, &str_val) != REC_ERR_OKAY) {
      goto not_found;
    }
    return static_cast<char *>(str_val);
    break;
  }
  case RECD_FLOAT: {
    RecFloat float_val;
    if (RecGetRecordFloat(arg, &float_val) != REC_ERR_OKAY) {
      goto not_found;
    }
    str = static_cast<char *>(ats_malloc(128));
    snprintf(str, 128, "%f", static_cast<float>(float_val));
    return str;
    break;
  }
  case RECD_INT: {
    RecInt int_val;
    if (RecGetRecordInt(arg, &int_val) != REC_ERR_OKAY) {
      goto not_found;
    }
    str = static_cast<char *>(ats_malloc(128));
    snprintf(str, 128, "%ld", static_cast<long int>(int_val));
    return str;
    break;
  }
  case RECD_COUNTER: {
    RecCounter count_val;
    if (RecGetRecordCounter(arg, &count_val) != REC_ERR_OKAY) {
      goto not_found;
    }
    str = static_cast<char *>(ats_malloc(128));
    snprintf(str, 128, "%ld", static_cast<long int>(count_val));
    return str;
    break;
  }
  default:
    goto not_found;
    break;
  }

not_found:
  Warning("%s: unable to find parameter %s", ts::filename::PLUGIN, arg);
  return nullptr;
}

bool
plugin_init(bool validateOnly)
{
  ats_scoped_str path;
  char line[1024], *p;
  char *argv[MAX_PLUGIN_ARGS];
  char *vars[MAX_PLUGIN_ARGS];
  int argc;
  int fd;
  int i;
  bool retVal           = true;
  static bool INIT_ONCE = true;

  if (INIT_ONCE) {
    api_init();
    plugin_dir = ats_stringdup(RecConfigReadPluginDir());
    INIT_ONCE  = false;
  }

  Note("%s loading ...", ts::filename::PLUGIN);
  path = RecConfigReadConfigPath(nullptr, ts::filename::PLUGIN);
  fd   = open(path, O_RDONLY);
  if (fd < 0) {
    Warning("%s failed to load: %d, %s", ts::filename::PLUGIN, errno, strerror(errno));
    return false;
  }

  while (ink_file_fd_readline(fd, sizeof(line) - 1, line) > 0) {
    argc = 0;
    p    = line;

    // strip leading white space and test for comment or blank line
    while (*p && ParseRules::is_wslfcr(*p)) {
      ++p;
    }
    if ((*p == '\0') || (*p == '#')) {
      continue;
    }

    // not comment or blank, so rip line into tokens
    while (true) {
      if (argc >= MAX_PLUGIN_ARGS) {
        Warning("Exceeded max number of args (%d) for plugin: [%s]", MAX_PLUGIN_ARGS, argc > 0 ? argv[0] : "???");
        break;
      }

      while (*p && ParseRules::is_wslfcr(*p)) {
        ++p;
      }
      if ((*p == '\0') || (*p == '#')) {
        break; // EOL
      }

      if (*p == '\"') {
        p += 1;

        argv[argc++] = p;

        while (*p && (*p != '\"')) {
          p += 1;
        }
        if (*p == '\0') {
          break;
        }
        *p++ = '\0';
      } else {
        argv[argc++] = p;

        while (*p && !ParseRules::is_wslfcr(*p) && (*p != '#')) {
          p += 1;
        }
        if ((*p == '\0') || (*p == '#')) {
          break;
        }
        *p++ = '\0';
      }
    }

    for (i = 0; i < argc; i++) {
      vars[i] = plugin_expand(argv[i]);
      if (vars[i]) {
        argv[i] = vars[i];
      }
    }

    if (argc < MAX_PLUGIN_ARGS) {
      argv[argc] = nullptr;
    } else {
      argv[MAX_PLUGIN_ARGS - 1] = nullptr;
    }
    retVal = single_plugin_init(argc, argv, validateOnly);

    for (i = 0; i < argc; i++) {
      ats_free(vars[i]);
    }
  }

  close(fd);
  if (retVal) {
    Note("%s finished loading", ts::filename::PLUGIN);
  } else {
    Error("%s failed to load", ts::filename::PLUGIN);
  }
  return retVal;
}