Coverage Report

Created: 2026-03-28 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/trafficserver/include/ts/ts.h
Line
Count
Source
1
/** @file
2
3
  Traffic Server SDK API header file
4
5
  @section license License
6
7
  Licensed to the Apache Software Foundation (ASF) under one
8
  or more contributor license agreements.  See the NOTICE file
9
  distributed with this work for additional information
10
  regarding copyright ownership.  The ASF licenses this file
11
  to you under the Apache License, Version 2.0 (the
12
  "License"); you may not use this file except in compliance
13
  with the License.  You may obtain a copy of the License at
14
15
      http://www.apache.org/licenses/LICENSE-2.0
16
17
  Unless required by applicable law or agreed to in writing, software
18
  distributed under the License is distributed on an "AS IS" BASIS,
19
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
  See the License for the specific language governing permissions and
21
  limitations under the License.
22
23
  @section developers Developers
24
25
  Developers, when adding a new element to an enum, append it. DO NOT
26
  insert it.  Otherwise, binary compatibility of plugins will be broken!
27
28
 */
29
30
#pragma once
31
32
#if !defined(__cplusplus) || __cplusplus < 201703L
33
#error "Must compile ATS plugin code with C++ version 17 or later."
34
#endif
35
36
#include <type_traits>
37
#include <string_view>
38
#include <vector>
39
40
#include "tsutil/DbgCtl.h"
41
#include "ts/apidefs.h"
42
43
class DiagsConfigState;
44
45
/* --------------------------------------------------------------------------
46
   Memory */
47
void  *_TSmalloc(size_t size, const char *path);
48
void  *_TSrealloc(void *ptr, size_t size, const char *path);
49
char  *_TSstrdup(const char *str, int64_t length, const char *path);
50
size_t TSstrlcpy(char *dst, const char *str, size_t siz);
51
size_t TSstrlcat(char *dst, const char *str, size_t siz);
52
void   TSfree(void *ptr);
53
54
inline void *
55
TSmalloc(size_t s)
56
0
{
57
0
  return _TSmalloc(s, TS_RES_MEM_PATH);
58
0
}
59
inline void *
60
TSrealloc(void *p, size_t s)
61
0
{
62
0
  return _TSrealloc(p, s, TS_RES_MEM_PATH);
63
0
}
64
inline char *
65
TSstrdup(const char *p)
66
0
{
67
0
  return _TSstrdup(p, -1, TS_RES_MEM_PATH);
68
0
}
69
inline char *
70
TSstrndup(const char *p, int64_t n)
71
0
{
72
0
  return _TSstrdup(p, n, TS_RES_MEM_PATH);
73
0
}
74
75
/* --------------------------------------------------------------------------
76
   Component object handles */
77
/**
78
    Releases the TSMLoc mloc created from the TSMLoc parent.
79
    If there is no parent TSMLoc, use TS_NULL_MLOC.
80
81
    @param bufp marshal buffer containing the TSMLoc handle to be
82
      released.
83
    @param parent location of the parent object from which the handle
84
      was created.
85
    @param mloc location of the handle to be released.
86
87
 */
88
TSReturnCode TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc);
89
90
/* --------------------------------------------------------------------------
91
   Install and plugin locations */
92
/**
93
    Gets the path of the directory in which Traffic Server is installed.
94
    Use this function to specify the location of files that the
95
    plugin uses.
96
97
    @return pointer to Traffic Server install directory.
98
99
 */
100
const char *TSInstallDirGet(void);
101
102
/**
103
    Gets the path of the directory of Traffic Server configuration.
104
105
    @return pointer to Traffic Server configuration directory.
106
107
 */
108
const char *TSConfigDirGet(void);
109
110
/**
111
    Gets the path of the directory of Traffic Server runtime.
112
113
    @return pointer to Traffic Server runtime directory.
114
115
 */
116
const char *TSRuntimeDirGet(void);
117
118
/**
119
    Gets the path of the plugin directory relative to the Traffic Server
120
    install directory. For example, to open the file "config_ui.txt" in
121
    the plugin directory:
122
123
    @code
124
    TSfopen("TSPluginInstallDirGet()/TSPluginDirGet()/config_ui.txt");
125
    @endcode
126
127
    @return pointer to plugin directory relative to Traffic Server install
128
    directory.
129
130
 */
131
const char *TSPluginDirGet(void);
132
133
/* --------------------------------------------------------------------------
134
   Traffic Server Version */
135
/**
136
    Gets the version of Traffic Server currently running. Use this
137
    function to make sure that the plugin version and Traffic Server
138
    version are compatible. See the SDK sample code for usage.
139
140
    @return pointer to version of Traffic Server running the plugin.
141
142
 */
143
const char *TSTrafficServerVersionGet(void);
144
145
/**  Get the major version of Traffic Server currently running.
146
     This is the same as the first element of the string
147
     returned by @c TSTrafficServerVersionGet
148
149
     @return The major version as an integer.
150
 */
151
int TSTrafficServerVersionGetMajor(void);
152
153
/**  Get the minor version of Traffic Server currently running.
154
     This is the same as the second element of the string
155
     returned by @c TSTrafficServerVersionGet
156
157
     @return The minor version as an integer.
158
 */
159
int TSTrafficServerVersionGetMinor(void);
160
161
/**  Get the patch version of Traffic Server currently running.
162
     This is the same as the third element of the string
163
     returned by @c TSTrafficServerVersionGet
164
165
     @return The patch version as an integer.
166
 */
167
int TSTrafficServerVersionGetPatch(void);
168
169
/* --------------------------------------------------------------------------
170
   Plugin registration */
171
172
/**
173
    This function registers your plugin with a particular version
174
    of Traffic Server SDK. Use this function to make sure that the
175
    Traffic Server version currently running also supports your plugin.
176
    See the SDK sample code for usage.
177
178
    @param plugin_info contains registration information about your
179
      plugin. See TSPluginRegistrationInfo.
180
    @return TS_ERROR if the plugin registration failed.
181
182
 */
183
TSReturnCode TSPluginRegister(const TSPluginRegistrationInfo *plugin_info);
184
185
/**
186
   This function provides the ability to enable/disable programmatically
187
   the plugin dynamic reloading when the same Dynamic Shared Object (DSO)
188
   is also used as a remap plugin. This overrides `proxy.config.plugin.dynamic_reload_mode`
189
   configuration variable.
190
191
   @param enabled boolean flag. 0/false will disable the reload on the caller plugin.
192
   @return TS_ERROR if the function is not called from within TSPluginInit or if TS is
193
           unable to get the canonical path from the plugin's path. TS_SUCCESS otherwise.
194
195
   @note This function should be called from within TSPluginInit
196
 */
197
TSReturnCode TSPluginDSOReloadEnable(int enabled);
198
199
/* --------------------------------------------------------------------------
200
   Files */
201
/**
202
    Opens a file for reading or writing and returns a descriptor for
203
    accessing the file. The current implementation cannot open a file
204
    for both reading or writing. See the SDK Programmer's Guide for
205
    sample code.
206
207
    @param filename file to be opened.
208
    @param mode specifies whether to open the file for reading or
209
      writing. If mode is "r" then the file is opened for reading.
210
      If mode is "w" then the file is opened for writing. Currently
211
      "r" and "w" are the only two valid modes for opening a file.
212
    @return descriptor for the file that TSfopen opens. Descriptors of
213
      type TSFile can be greater than 256.
214
215
 */
216
TSFile TSfopen(const char *filename, const char *mode);
217
218
/**
219
    Closes the file to which filep points and frees the data structures
220
    and buffers associated with it. If the file was opened for writing,
221
    any pending data is flushed.
222
223
    @param filep file to be closed.
224
225
 */
226
void TSfclose(TSFile filep);
227
228
/**
229
    Attempts to read length bytes of data from the file pointed to by
230
    filep into the buffer buf.
231
232
    @param filep name of the file to read from.
233
    @param buf buffer to read into.
234
    @param length amount of data to read, in bytes.
235
    @return number of bytes read. If end of the file, it returns 0.
236
      If the file was not opened for reading or if an error occurs
237
      while reading the file, it returns -1.
238
239
 */
240
ssize_t TSfread(TSFile filep, void *buf, size_t length);
241
242
/**
243
    Attempts to write length bytes of data from the buffer buf
244
    to the file filep. Make sure that filep is open for writing.
245
    You might want to check the number of bytes written (TSfwrite()
246
    returns this value) against the value of length. If it is less,
247
    there might be insufficient space on disk, for example.
248
249
    @param filep file to write into.
250
    @param buf buffer containing the data to be written.
251
    @param length amount of data to write to filep, in bytes.
252
    @return number of bytes written to filep. If the file was not
253
      opened for writing, it returns -1. If an error occurs while
254
      writing, it returns the number of bytes successfully written.
255
256
 */
257
ssize_t TSfwrite(TSFile filep, const void *buf, size_t length);
258
259
/**
260
    Flushes pending data that has been buffered up in memory from
261
    previous calls to TSfwrite().
262
263
    @param filep file to flush.
264
265
 */
266
void TSfflush(TSFile filep);
267
268
/**
269
    Reads a line from the file pointed to by filep into the buffer buf.
270
    Lines are terminated by a line feed character, '\n'. The line
271
    placed in the buffer includes the line feed character and is
272
    terminated with a null. If the line is longer than length bytes
273
    then only the first length-minus-1 bytes are placed in buf.
274
275
    @param filep file to read from.
276
    @param buf buffer to read into.
277
    @param length size of the buffer to read into.
278
    @return pointer to the string read into the buffer buf.
279
280
 */
281
char *TSfgets(TSFile filep, char *buf, size_t length);
282
283
/* --------------------------------------------------------------------------
284
   Error logging */
285
/**
286
    Writes printf-style error messages to the Traffic Server error
287
    log. One advantage of TSError over printf is that each call is
288
    atomically placed into the error log and is not garbled with other
289
    error entries. This is not an issue in single-threaded programs
290
    but is a definite nuisance in multi-threaded programs.
291
292
    @param fmt printf format description.
293
    @param ... argument for the printf format description.
294
295
    Note: Your log monitoring (e.g. Splunk) needs to alert Ops of log
296
    messages that contain ' ALERT: ' or ' EMERGENCY: ', these require
297
    immediate attention.
298
299
*/
300
void TSStatus(const char *fmt, ...) TS_PRINTFLIKE(1, 2);    // Log information
301
void TSNote(const char *fmt, ...) TS_PRINTFLIKE(1, 2);      // Log significant information
302
void TSWarning(const char *fmt, ...) TS_PRINTFLIKE(1, 2);   // Log concerning information
303
void TSError(const char *fmt, ...) TS_PRINTFLIKE(1, 2);     // Log operational failure, fail CI
304
void TSFatal(const char *fmt, ...) TS_PRINTFLIKE(1, 2);     // Log recoverable crash, fail CI, exit & restart
305
void TSAlert(const char *fmt, ...) TS_PRINTFLIKE(1, 2);     // Log recoverable crash, fail CI, exit & restart, Ops attention
306
void TSEmergency(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log unrecoverable crash, fail CI, exit, Ops attention
307
308
/* --------------------------------------------------------------------------
309
   Assertions */
310
void _TSReleaseAssert(const char *txt, const char *f, int l) TS_NORETURN;
311
int  _TSAssert(const char *txt, const char *f, int l);
312
313
#define TSReleaseAssert(EX) ((void)((EX) ? (void)0 : _TSReleaseAssert(#EX, __FILE__, __LINE__)))
314
315
#define TSAssert(EX) (void)((EX) || (_TSAssert(#EX, __FILE__, __LINE__)))
316
317
/* --------------------------------------------------------------------------
318
   Marshal buffers */
319
/**
320
    Creates a new marshal buffer and initializes the reference count
321
    to 1.
322
323
 */
324
TSMBuffer TSMBufferCreate(void);
325
326
/**
327
    Ignores the reference count and destroys the marshal buffer bufp.
328
    The internal data buffer associated with the marshal buffer is
329
    also destroyed if the marshal buffer allocated it.
330
331
    @param bufp marshal buffer to be destroyed.
332
333
 */
334
TSReturnCode TSMBufferDestroy(TSMBuffer bufp);
335
336
/* --------------------------------------------------------------------------
337
   URLs */
338
/**
339
    Creates a new URL within the marshal buffer bufp. Returns a
340
    location for the URL within the marshal buffer.
341
342
    @param bufp marshal buffer containing the new URL.
343
    @param locp pointer to a TSMLoc to store the MLoc into.
344
345
 */
346
TSReturnCode TSUrlCreate(TSMBuffer bufp, TSMLoc *locp);
347
348
/**
349
    Copies the URL located at src_url within src_bufp to a URL
350
    location within the marshal buffer dest_bufp, and returns the
351
    TSMLoc location of the copied URL. Unlike TSUrlCopy(), you do
352
    not have to create the destination URL before cloning. Release
353
    the returned TSMLoc handle with a call to TSHandleMLocRelease().
354
355
    @param dest_bufp marshal buffer containing the cloned URL.
356
    @param src_bufp marshal buffer containing the URL to be cloned.
357
    @param src_url location of the URL to be cloned, within the marshal
358
      buffer src_bufp.
359
    @param locp pointer to a TSMLoc to store the MLoc into.
360
361
 */
362
TSReturnCode TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp);
363
364
/**
365
    Copies the contents of the URL at location src_loc within the
366
    marshal buffer src_bufp to the location dest_loc within the marshal
367
    buffer dest_bufp. TSUrlCopy() works correctly even if src_bufp
368
    and dest_bufp point to different marshal buffers. Important: create
369
    the destination URL before copying into it. Use TSUrlCreate().
370
371
    @param dest_bufp marshal buffer to contain the copied URL.
372
    @param dest_offset location of the URL to be copied.
373
    @param src_bufp marshal buffer containing the source URL.
374
    @param src_offset location of the source URL within src_bufp.
375
376
 */
377
TSReturnCode TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset);
378
379
/**
380
    Formats a URL stored in an TSMBuffer into an TSIOBuffer.
381
382
    @param bufp marshal buffer contain the URL to be printed.
383
    @param offset location of the URL within bufp.
384
    @param iobufp destination TSIOBuffer for the URL.
385
386
 */
387
void TSUrlPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp);
388
389
/**
390
    Parses a URL. The start pointer is both an input and an output
391
    parameter and marks the start of the URL to be parsed. After
392
    a successful parse, the start pointer equals the end pointer.
393
    The end pointer must be one byte after the last character you
394
    want to parse. The URL parsing routine assumes that everything
395
    between start and end is part of the URL. It is up to higher level
396
    parsing routines, such as TSHttpHdrParseReq(), to determine the
397
    actual end of the URL. Returns TS_PARSE_ERROR if an error occurs,
398
    otherwise TS_PARSE_DONE is returned to indicate success.
399
400
    @param bufp marshal buffer containing the URL to be parsed.
401
    @param offset location of the URL to be parsed.
402
    @param start points to the start of the URL to be parsed AND at
403
      the end of a successful parse it will equal the end pointer.
404
    @param end must be one byte after the last character.
405
    @return TS_PARSE_ERROR or TS_PARSE_DONE.
406
407
 */
408
TSParseResult TSUrlParse(TSMBuffer bufp, TSMLoc offset, const char **start, const char *end);
409
410
/**
411
    Calculates the length of the URL located at url_loc within the
412
    marshal buffer bufp if it were returned as a string. This length
413
    is the same as the length returned by TSUrlStringGet().
414
415
    @param bufp marshal buffer containing the URL whose length you want.
416
    @param offset location of the URL within the marshal buffer bufp.
417
    @return string length of the URL.
418
419
 */
420
int TSUrlLengthGet(TSMBuffer bufp, TSMLoc offset);
421
422
/**
423
    Constructs a string representation of the URL located at url_loc
424
    within bufp. TSUrlStringGet() stores the length of the allocated
425
    string in the parameter length. This is the same length that
426
    TSUrlLengthGet() returns. The returned string is allocated by a
427
    call to TSmalloc(). It should be freed by a call to TSfree().
428
    The length parameter must be present, providing storage for the
429
    URL string length value.
430
    Note: To get the effective URL from a request, use the alternative
431
          TSHttpTxnEffectiveUrlStringGet or
432
          TSHttpHdrEffectiveUrlBufGet APIs.
433
434
    @param bufp marshal buffer containing the URL you want to get.
435
    @param offset location of the URL within bufp.
436
    @param length string length of the URL.
437
    @return The URL as a string.
438
439
 */
440
char *TSUrlStringGet(TSMBuffer bufp, TSMLoc offset, int *length);
441
442
/**
443
    Retrieves the scheme portion of the URL located at url_loc within
444
    the marshal buffer bufp. TSUrlSchemeGet() places the length of
445
    the string in the length argument. If the length is null then no
446
    attempt is made to dereference it.
447
448
    @param bufp marshal buffer storing the URL.
449
    @param offset location of the URL within bufp.
450
    @param length length of the returned string.
451
    @return The scheme portion of the URL, as a string.
452
453
 */
454
const char *TSUrlRawSchemeGet(TSMBuffer bufp, TSMLoc offset, int *length);
455
456
/**
457
    Retrieves the scheme portion of the URL located at url_loc within
458
    the marshal buffer bufp. TSUrlSchemeGet() places the length of
459
    the string in the length argument. If the length is null then no
460
    attempt is made to dereference it.  If there is no explicit scheme,
461
    a scheme of http is returned if the URL type is HTTP, and a scheme
462
    of https is returned if the URL type is HTTPS.
463
464
    @param bufp marshal buffer storing the URL.
465
    @param offset location of the URL within bufp.
466
    @param length length of the returned string.
467
    @return The scheme portion of the URL, as a string.
468
469
 */
470
const char *TSUrlSchemeGet(TSMBuffer bufp, TSMLoc offset, int *length);
471
472
/**
473
    Sets the scheme portion of the URL located at url_loc within
474
    the marshal buffer bufp to the string value. If length is -1
475
    then TSUrlSchemeSet() assumes that value is null-terminated.
476
    Otherwise, the length of the string value is taken to be length.
477
    TSUrlSchemeSet() copies the string to within bufp, so it is OK
478
    to modify or delete value after calling TSUrlSchemeSet().
479
480
    @param bufp marshal buffer containing the URL.
481
    @param offset location of the URL.
482
    @param value value to set the URL's scheme to.
483
    @param length string stored in value.
484
485
 */
486
TSReturnCode TSUrlSchemeSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
487
488
/* --------------------------------------------------------------------------
489
   Internet specific URLs */
490
/**
491
    Retrieves the user portion of the URL located at url_loc
492
    within bufp. Note: the returned string is not guaranteed to
493
    be null-terminated.
494
495
    @param bufp marshal buffer containing the URL.
496
    @param offset location of the URL.
497
    @param length length of the returned string.
498
    @return user portion of the URL.
499
500
 */
501
const char *TSUrlUserGet(TSMBuffer bufp, TSMLoc offset, int *length);
502
503
/**
504
    Sets the user portion of the URL located at url_loc within bufp
505
    to the string value. If length is -1 then TSUrlUserSet() assumes
506
    that value is null-terminated. Otherwise, the length of the string
507
    value is taken to be length. TSUrlUserSet() copies the string to
508
    within bufp, so it is OK to modify or delete value after calling
509
    TSUrlUserSet().
510
511
    @param bufp marshal buffer containing the URL.
512
    @param offset location of the URL whose user is to be set.
513
    @param value holds the new user name.
514
    @param length string length of value.
515
516
 */
517
TSReturnCode TSUrlUserSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
518
519
/**
520
    Retrieves the password portion of the URL located at url_loc
521
    within bufp. TSUrlPasswordGet() places the length of the returned
522
    string in the length argument. Note: the returned string is
523
    not guaranteed to be null-terminated.
524
525
    @param bufp marshal buffer containing the URL.
526
    @param offset
527
    @param length of the returned password string.
528
    @return password portion of the URL.
529
530
 */
531
const char *TSUrlPasswordGet(TSMBuffer bufp, TSMLoc offset, int *length);
532
533
/**
534
    Sets the password portion of the URL located at url_loc within
535
    bufp to the string value. If length is -1 then TSUrlPasswordSet()
536
    assumes that value is null-terminated. Otherwise, the length
537
    of value is taken to be length. TSUrlPasswordSet() copies the
538
    string to within bufp, so it is okay to modify or delete value
539
    after calling TSUrlPasswordSet().
540
541
    @param bufp marshal buffer containing the URL.
542
    @param offset
543
    @param value new password.
544
    @param length of the new password.
545
546
 */
547
TSReturnCode TSUrlPasswordSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
548
549
/**
550
    Retrieves the host portion of the URL located at url_loc
551
    within bufp. Note: the returned string is not guaranteed to be
552
    null-terminated.
553
554
    @param bufp marshal buffer containing the URL.
555
    @param offset location of the URL.
556
    @param length of the returned string.
557
    @return Host portion of the URL.
558
559
 */
560
const char *TSUrlHostGet(TSMBuffer bufp, TSMLoc offset, int *length);
561
562
/**
563
    Sets the host portion of the URL at url_loc to the string value.
564
    If length is -1 then TSUrlHostSet() assumes that value is
565
    null-terminated. Otherwise, the length of the string value is
566
    taken to be length. The string is copied to within bufp, so you
567
    can modify or delete value after calling TSUrlHostSet().
568
569
    @param bufp marshal buffer containing the URL to modify.
570
    @param offset location of the URL.
571
    @param value new host name for the URL.
572
    @param length string length of the new host name of the URL.
573
574
 */
575
TSReturnCode TSUrlHostSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
576
577
/**
578
    Returns the port portion of the URL located at url_loc if explicitly present,
579
    otherwise the canonical port for the URL.
580
581
    @param bufp marshal buffer containing the URL.
582
    @param offset location of the URL.
583
    @return port portion of the URL.
584
585
 */
586
int TSUrlPortGet(TSMBuffer bufp, TSMLoc offset);
587
588
/**
589
    Returns the port portion of the URL located at url_loc if explicitly present,
590
    otherwise 0.
591
592
    @param bufp marshal buffer containing the URL.
593
    @param offset location of the URL.
594
    @return port portion of the URL.
595
596
 */
597
int TSUrlRawPortGet(TSMBuffer bufp, TSMLoc offset);
598
599
/**
600
    Sets the port portion of the URL located at url_loc.
601
602
    @param bufp marshal buffer containing the URL.
603
    @param offset location of the URL.
604
    @param port new port setting for the URL.
605
606
 */
607
TSReturnCode TSUrlPortSet(TSMBuffer bufp, TSMLoc offset, int port);
608
609
/* --------------------------------------------------------------------------
610
   HTTP specific URLs */
611
/**
612
    Retrieves the path portion of the URL located at url_loc within
613
    bufp. TSUrlPathGet() places the length of the returned string in
614
    the length argument. Note: the returned string is not guaranteed to
615
    be null-terminated.
616
617
    @param bufp marshal buffer containing the URL.
618
    @param offset location of the URL.
619
    @param length of the returned string.
620
    @return path portion of the URL.
621
622
 */
623
const char *TSUrlPathGet(TSMBuffer bufp, TSMLoc offset, int *length);
624
625
/**
626
    Sets the path portion of the URL located at url_loc within bufp
627
    to the string value. If length is -1 then TSUrlPathSet() assumes
628
    that value is null-terminated. Otherwise, the length of the value
629
    is taken to be length. TSUrlPathSet() copies the string into bufp,
630
    so you can modify or delete value after calling TSUrlPathSet().
631
632
    @param bufp marshal buffer containing the URL.
633
    @param offset location of the URL.
634
    @param value new path string for the URL.
635
    @param length of the new path string.
636
637
 */
638
TSReturnCode TSUrlPathSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
639
640
/* --------------------------------------------------------------------------
641
   FTP specific URLs */
642
/**
643
    Retrieves the FTP type of the URL located at url_loc within bufp.
644
645
    @param bufp marshal buffer containing the URL.
646
    @param offset location of the URL.
647
    @return FTP type of the URL.
648
649
 */
650
int TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc offset);
651
652
/**
653
    Sets the FTP type portion of the URL located at url_loc within
654
    bufp to the value type.
655
656
    @param bufp marshal buffer containing the URL.
657
    @param offset location of the URL to modify.
658
    @param type new FTP type for the URL.
659
660
 */
661
TSReturnCode TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc offset, int type);
662
663
/* --------------------------------------------------------------------------
664
   HTTP specific URLs */
665
666
/**
667
    Retrieves the HTTP query portion of the URL located at url_loc
668
    within bufp. The length of the returned string is in the length
669
    argument. Note: the returned string is not guaranteed to be
670
    null-terminated.
671
672
    @param bufp marshal buffer containing the URL.
673
    @param offset location of the URL.
674
    @param length of the returned string.
675
    @return HTTP query portion of the URL.
676
677
 */
678
const char *TSUrlHttpQueryGet(TSMBuffer bufp, TSMLoc offset, int *length);
679
680
/**
681
    Sets the HTTP query portion of the URL located at url_loc within
682
    bufp to value. If length is -1, the string value is assumed to
683
    be null-terminated; otherwise, the length of value is taken to be
684
    length. TSUrlHttpQuerySet() copies the string to within bufp, so
685
    you can modify or delete value after calling TSUrlHttpQuerySet().
686
687
    @param bufp marshal buffer containing the URL.
688
    @param offset location of the URL within bufp.
689
    @param value new HTTP query string for the URL.
690
    @param length of the new HTTP query string.
691
692
 */
693
TSReturnCode TSUrlHttpQuerySet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
694
695
/**
696
    Retrieves the HTTP fragment portion of the URL located at url_loc
697
    within bufp. The length of the returned string is in the length
698
    argument. Note: the returned string is not guaranteed to be
699
    null-terminated.
700
701
    @param bufp marshal buffer containing the URL.
702
    @param offset location of the URL.
703
    @param length of the returned string.
704
    @return HTTP fragment portion of the URL.
705
706
 */
707
const char *TSUrlHttpFragmentGet(TSMBuffer bufp, TSMLoc offset, int *length);
708
709
/**
710
    Sets the HTTP fragment portion of the URL located at url_loc
711
    within bufp to value. If length is -1, the string value is
712
    assumed to be null-terminated; otherwise, the length of value
713
    is taken to be length. TSUrlHttpFragmentSet() copies the string
714
    to within bufp, so you can modify or delete value after calling
715
    TSUrlHttpFragmentSet().
716
717
    @param bufp marshal buffer containing the URL.
718
    @param offset location of the URL within bufp.
719
    @param value new HTTP fragment string for the URL.
720
    @param length of the new HTTP query string.
721
722
 */
723
TSReturnCode TSUrlHttpFragmentSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
724
725
/**
726
   Perform percent-encoding of the string in the buffer, storing the
727
   new string in the destination buffer. The length parameter will be
728
   set to the new (encoded) string length, or 0 if the encoding failed.
729
730
   @param str the string buffer to encode.
731
   @param str_len length of the string buffer.
732
   @param dst destination buffer.
733
   @param dst_size size of the destination buffer.
734
   @param length amount of data written to the destination buffer.
735
   @param map optional (can be null) map of characters to encode.
736
737
*/
738
TSReturnCode TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, size_t *length,
739
                                   const unsigned char *map);
740
741
/**
742
   Similar to TSStringPercentEncode(), but works on a URL object.
743
744
   @param bufp marshal buffer containing the URL.
745
   @param offset location of the URL within bufp.
746
   @param dst destination buffer.
747
   @param dst_size size of the destination buffer.
748
   @param length amount of data written to the destination buffer.
749
   @param map optional (can be null) map of characters to encode.
750
751
*/
752
TSReturnCode TSUrlPercentEncode(TSMBuffer bufp, TSMLoc offset, char *dst, size_t dst_size, size_t *length,
753
                                const unsigned char *map);
754
755
/**
756
   Perform percent-decoding of the string in the buffer, writing
757
   to the output buffer. The source and destination can be the same,
758
   in which case they overwrite. The decoded string is always
759
   guaranteed to be no longer than the source string.
760
761
   @param str the string to decode (and possibly write to).
762
   @param str_len length of the input string (or 0).
763
   @param dst output buffer (can be the same as src).
764
   @param dst_len size of the output buffer.
765
   @param length amount of data written to the destination buffer.
766
767
*/
768
TSReturnCode TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length);
769
770
/* --------------------------------------------------------------------------
771
   MIME headers */
772
773
/**
774
    Creates a MIME parser. The parser's data structure contains
775
    information about the header being parsed. A single MIME
776
    parser can be used multiple times, though not simultaneously.
777
    Before being used again, the parser must be cleared by calling
778
    TSMimeParserClear().
779
780
 */
781
TSMimeParser TSMimeParserCreate(void);
782
783
/**
784
    Clears the specified MIME parser so that it can be used again.
785
786
    @param parser to be cleared.
787
788
 */
789
void TSMimeParserClear(TSMimeParser parser);
790
791
/**
792
    Destroys the specified MIME parser and frees the associated memory.
793
794
    @param parser to destroy.
795
 */
796
void TSMimeParserDestroy(TSMimeParser parser);
797
798
/**
799
  Parse a MIME header date string. Candidate for deprecation in v10.0.0
800
 */
801
time_t TSMimeParseDate(char const *const value_str, int const value_len);
802
803
/**
804
    Creates a new MIME header within bufp. Release with a call to
805
    TSHandleMLocRelease().
806
807
    @param bufp marshal buffer to contain the new MIME header.
808
    @param locp buffer pointer to contain the MLoc
809
810
 */
811
TSReturnCode TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp);
812
813
/**
814
    Destroys the MIME header located at hdr_loc within bufp.
815
816
    @param bufp marshal buffer containing the MIME header to destroy.
817
    @param offset location of the MIME header.
818
819
 */
820
TSReturnCode TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc offset);
821
822
/**
823
    Copies a specified MIME header to a specified marshal buffer,
824
    and returns the location of the copied MIME header within the
825
    destination marshal buffer. Unlike TSMimeHdrCopy(), you do not
826
    have to create the destination MIME header before cloning. Release
827
    the returned TSMLoc handle with a call to TSHandleMLocRelease().
828
829
    @param dest_bufp destination marshal buffer.
830
    @param src_bufp source marshal buffer.
831
    @param src_hdr location of the source MIME header.
832
    @param locp where to store the location of the copied MIME header.
833
834
 */
835
TSReturnCode TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp);
836
837
/**
838
    Copies the contents of the MIME header located at src_loc
839
    within src_bufp to the MIME header located at dest_loc within
840
    dest_bufp. TSMimeHdrCopy() works correctly even if src_bufp and
841
    dest_bufp point to different marshal buffers. Important: you must
842
    create the destination MIME header before copying into it--use
843
    TSMimeHdrCreate().
844
845
    @param dest_bufp is the destination marshal buffer.
846
    @param dest_offset
847
    @param src_bufp is the source marshal buffer.
848
    @param src_offset
849
850
 */
851
TSReturnCode TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset);
852
853
/**
854
    Formats the MIME header located at hdr_loc into the
855
    TSIOBuffer iobufp.
856
857
    @param offset The offset of the header to be copied to a TSIOBuffer.
858
    @param iobufp target TSIOBuffer.
859
860
 */
861
void TSMimeHdrPrint(TSMLoc offset, TSIOBuffer iobufp);
862
863
/**
864
    Parses a MIME header. The MIME header must have already been
865
    allocated and both bufp and hdr_loc must point within that header.
866
    It is possible to parse a MIME header a single byte at a time
867
    using repeated calls to TSMimeHdrParse(). As long as an error
868
    does not occur, TSMimeHdrParse() consumes each single byte and
869
    asks for more.
870
871
    @param parser parses the specified MIME header.
872
    @param bufp marshal buffer containing the MIME header to be parsed.
873
    @param offset
874
    @param start both an input and output. On input, the start
875
      argument points to the current position of the buffer being
876
      parsed. On return, start is modified to point past the last
877
      character parsed.
878
    @param end points to one byte after the end of the buffer.
879
    @return One of 3 possible int values:
880
      - TS_PARSE_ERROR if there is a parsing error.
881
      - TS_PARSE_DONE is returned when a "\r\n\r\n" pattern is
882
        encountered, indicating the end of the header.
883
      - TS_PARSE_CONT is returned if parsing of the header stopped
884
        because the end of the buffer was reached.
885
886
 */
887
TSParseResult TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end);
888
889
/**
890
    Calculates the length of the MIME header located at hdr_loc if it
891
    were returned as a string. This the length of the MIME header in
892
    its unparsed form.
893
894
    @param bufp marshal buffer containing the MIME header.
895
    @param offset location of the MIME header.
896
    @return string length of the MIME header located at hdr_loc.
897
898
 */
899
int TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc offset);
900
901
/**
902
    Removes and destroys all the MIME fields within the MIME header
903
    located at hdr_loc within the marshal buffer bufp.
904
905
    @param bufp marshal buffer containing the MIME header.
906
    @param offset location of the MIME header.
907
908
 */
909
TSReturnCode TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc offset);
910
911
/**
912
    Returns a count of the number of MIME fields within the MIME header
913
    located at hdr_loc within the marshal buffer bufp.
914
915
    @param bufp marshal buffer containing the MIME header.
916
    @param offset location of the MIME header within bufp.
917
    @return number of MIME fields within the MIME header located
918
      at hdr_loc.
919
920
 */
921
int TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc offset);
922
923
/**
924
    Retrieves the location of a specified MIME field within the
925
    MIME header located at hdr_loc within bufp. The idx parameter
926
    specifies which field to retrieve. The fields are numbered from 0
927
    to TSMimeHdrFieldsCount(bufp, hdr_loc) - 1. If idx does not lie
928
    within that range then TSMimeHdrFieldGet returns 0. Release the
929
    returned handle with a call to TSHandleMLocRelease.
930
931
    @param bufp marshal buffer containing the MIME header.
932
    @param hdr location of the MIME header.
933
    @param idx index of the field to get with base at 0.
934
    @return location of the specified MIME field.
935
936
 */
937
TSMLoc TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr, int idx);
938
939
/**
940
    Retrieves the TSMLoc location of a specified MIME field from within
941
    the MIME header located at hdr. The name and length parameters
942
    specify which field to retrieve. For each MIME field in the MIME
943
    header, a case insensitive string comparison is done between
944
    the field name and name. If TSMimeHdrFieldFind() cannot find the
945
    requested field, it returns TS_NULL_MLOC. Release the returned
946
    TSMLoc handle with a call to TSHandleMLocRelease().
947
948
    @param bufp marshal buffer containing the MIME header field to find.
949
    @param hdr location of the MIME header containing the field.
950
    @param name of the field to retrieve.
951
    @param length string length of the string name. If length is -1,
952
      then name is assumed to be null-terminated.
953
    @return location of the requested MIME field. If the field could
954
      not be found, returns TS_NULL_MLOC.
955
956
 */
957
TSMLoc TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr, const char *name, int length);
958
959
/**
960
    Appends a MIME field to a header. The field is typically newly created via
961
    @a TSMimeHdrFieldCreateNamed. If the field was found via @a
962
    TSMimeHdrFieldFind and it existed already in the header, then this function
963
    call is effectively a no-op. If the field is newly created via @a
964
    TSMimeHdrFieldCreateNamed and a field with the same name already exists in
965
    the header, then the new field is added as a duplicate field.
966
967
    @param bufp marshal buffer containing the MIME header. Must be modifiable.
968
    @param hdr location of the MIME header to append the field to.
969
    @param field location of the MIME field to append to the header.
970
    @return TS_SUCCESS if the field was successfully appended to the header,
971
      TS_ERROR if the operation failed (e.g., if the buffer is read-only).
972
973
 */
974
TSReturnCode TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
975
976
/**
977
    Removes the MIME field located at field within bufp from the
978
    header located at hdr within bufp. If the specified field cannot
979
    be found in the list of fields associated with the header then
980
    nothing is done.
981
982
    Note: removing the field does not destroy the field, it only
983
    detaches the field, hiding it from the printed output. The field
984
    can be reattached with a call to TSMimeHdrFieldAppend(). If you
985
    do not use the detached field you should destroy it with a call to
986
    TSMimeHdrFieldDestroy() and release the handle field with a call
987
    to TSHandleMLocRelease().
988
989
    @param bufp contains the MIME field to remove.
990
    @param hdr location of the header containing the MIME field to
991
      be removed. This header could be an HTTP header or MIME header.
992
    @param field is the location of the field to remove.
993
994
 */
995
TSReturnCode TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
996
997
TSReturnCode TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc hdr, TSMLoc *locp);
998
999
/****************************************************************************
1000
 *  Create a new field and assign it a name all in one call
1001
 ****************************************************************************/
1002
TSReturnCode TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int name_len, TSMLoc *locp);
1003
1004
/**
1005
    Destroys the MIME field located at field within bufp. You must
1006
    release the TSMLoc field with a call to TSHandleMLocRelease().
1007
1008
    @param bufp contains the MIME field to be destroyed.
1009
    @param hdr location of the parent header containing the field
1010
      to be destroyed. This could be the location of a MIME header or
1011
      HTTP header.
1012
    @param field location of the field to be destroyed.
1013
1014
 */
1015
TSReturnCode TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1016
1017
TSReturnCode TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field,
1018
                                 TSMLoc *locp);
1019
TSReturnCode TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr,
1020
                                TSMLoc src_field);
1021
TSReturnCode TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr,
1022
                                      TSMLoc src_field);
1023
TSMLoc       TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1024
TSMLoc       TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1025
int          TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1026
const char  *TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length);
1027
TSReturnCode TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name, int length);
1028
1029
TSReturnCode TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1030
int          TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1031
1032
const char  *TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int *value_len_ptr);
1033
int          TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx);
1034
int64_t      TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx);
1035
unsigned int TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx);
1036
time_t       TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field);
1037
TSReturnCode TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length);
1038
TSReturnCode TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value);
1039
TSReturnCode TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int64_t value);
1040
TSReturnCode TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value);
1041
TSReturnCode TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value);
1042
1043
TSReturnCode TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length);
1044
/* These Insert() APIs should be considered. Use the corresponding Set() API instead */
1045
TSReturnCode TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length);
1046
TSReturnCode TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value);
1047
TSReturnCode TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value);
1048
TSReturnCode TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value);
1049
1050
TSReturnCode TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx);
1051
const char  *TSMimeHdrStringToWKS(const char *str, int length);
1052
1053
/*
1054
 * Print as a MIME header date string.
1055
 */
1056
TSReturnCode TSMimeFormatDate(time_t const value_time, char *const value_str, int *const value_len);
1057
1058
/* --------------------------------------------------------------------------
1059
   HTTP headers */
1060
TSHttpParser TSHttpParserCreate(void);
1061
void         TSHttpParserClear(TSHttpParser parser);
1062
void         TSHttpParserDestroy(TSHttpParser parser);
1063
1064
/**
1065
    Parses an HTTP request header. The HTTP header must have already
1066
    been created, and must reside inside the marshal buffer bufp.
1067
    The start argument points to the current position of the string
1068
    buffer being parsed. The end argument points to one byte after the
1069
    end of the buffer to be parsed. On return, TSHttpHdrParseReq()
1070
    modifies start to point past the last character parsed.
1071
1072
    It is possible to parse an HTTP request header a single byte at
1073
    a time using repeated calls to TSHttpHdrParseReq(). As long as
1074
    an error does not occur, the TSHttpHdrParseReq() function will
1075
    consume that single byte and ask for more.
1076
1077
    @param parser parses the HTTP header.
1078
    @param bufp marshal buffer containing the HTTP header to be parsed.
1079
    @param offset location of the HTTP header within bufp.
1080
    @param start both an input and output. On input, it points to the
1081
      current position of the string buffer being parsed. On return,
1082
      start is modified to point past the last character parsed.
1083
    @param end points to one byte after the end of the buffer to be parsed.
1084
    @return status of the parse:
1085
      - TS_PARSE_ERROR means there was a parsing error.
1086
      - TS_PARSE_DONE means that the end of the header was reached
1087
        (the parser encountered a "\r\n\r\n" pattern).
1088
      - TS_PARSE_CONT means that parsing of the header stopped because
1089
        the parser reached the end of the buffer (large headers can
1090
        span multiple buffers).
1091
1092
 */
1093
TSParseResult TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end);
1094
1095
TSParseResult TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end);
1096
1097
TSMLoc TSHttpHdrCreate(TSMBuffer bufp);
1098
1099
/**
1100
    Destroys the HTTP header located at hdr_loc within the marshal
1101
    buffer bufp. Do not forget to release the handle hdr_loc with a
1102
    call to TSHandleMLocRelease().
1103
1104
 */
1105
void TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc offset);
1106
1107
TSReturnCode TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp);
1108
1109
/**
1110
    Copies the contents of the HTTP header located at src_loc within
1111
    src_bufp to the HTTP header located at dest_loc within dest_bufp.
1112
    TSHttpHdrCopy() works correctly even if src_bufp and dest_bufp
1113
    point to different marshal buffers. Make sure that you create the
1114
    destination HTTP header before copying into it.
1115
1116
    Note: TSHttpHdrCopy() appends the port number to the domain
1117
    of the URL portion of the header. For example, a copy of
1118
    http://www.example.com appears as http://www.example.com:80 in
1119
    the destination buffer.
1120
1121
    @param dest_bufp marshal buffer to contain the copied header.
1122
    @param dest_offset location of the copied header.
1123
    @param src_bufp marshal buffer containing the source header.
1124
    @param src_offset location of the source header.
1125
1126
 */
1127
TSReturnCode TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset);
1128
1129
void TSHttpHdrPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp);
1130
1131
int TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc offset);
1132
1133
TSHttpType   TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc offset);
1134
TSReturnCode TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc offset, TSHttpType type);
1135
1136
int          TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc offset);
1137
TSReturnCode TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc offset, int ver);
1138
1139
const char  *TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc offset, int *length);
1140
TSReturnCode TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
1141
const char  *TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc offset, int *length);
1142
TSReturnCode TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc offset, TSMLoc *locp);
1143
TSReturnCode TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc offset, TSMLoc url);
1144
1145
TSHttpStatus TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc offset);
1146
/** This is a candidate for deprecation in v10.0.0 in favor of the version that takes the setter. */
1147
TSReturnCode TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc offset, TSHttpStatus status);
1148
TSReturnCode TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc offset, TSHttpStatus status, TSHttpTxn txnp, std::string_view setter);
1149
const char  *TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc offset, int *length);
1150
TSReturnCode TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length);
1151
const char  *TSHttpHdrReasonLookup(TSHttpStatus status);
1152
1153
/* --------------------------------------------------------------------------
1154
   Threads */
1155
TSThread      TSThreadCreate(TSThreadFunc func, void *data);
1156
TSThread      TSThreadInit(void);
1157
void          TSThreadDestroy(TSThread thread);
1158
void          TSThreadWait(TSThread thread);
1159
TSThread      TSThreadSelf(void);
1160
TSEventThread TSEventThreadSelf(void);
1161
1162
/* --------------------------------------------------------------------------
1163
   Mutexes */
1164
TSMutex      TSMutexCreate(void);
1165
void         TSMutexDestroy(TSMutex mutexp);
1166
void         TSMutexLock(TSMutex mutexp);
1167
TSReturnCode TSMutexLockTry(TSMutex mutexp);
1168
1169
void TSMutexUnlock(TSMutex mutexp);
1170
1171
/* --------------------------------------------------------------------------
1172
   cachekey */
1173
/**
1174
    Creates (allocates memory for) a new cache key.
1175
 */
1176
TSCacheKey TSCacheKeyCreate(void);
1177
1178
/**
1179
    Generates a key for an object to be cached (written to the cache).
1180
1181
    @param key to be associated with the cached object. Before
1182
      calling TSCacheKeySetDigest() you must create the key with
1183
      TSCacheKeyCreate().
1184
    @param input string that uniquely identifies the object. In most
1185
      cases, it is the URL of the object.
1186
    @param length of the string input.
1187
1188
 */
1189
TSReturnCode TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length);
1190
1191
TSReturnCode TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url);
1192
1193
/**
1194
    Associates a host name to the cache key. Use this function if the
1195
    cache has been partitioned by hostname. The hostname tells the
1196
    cache which volume to use for the object.
1197
1198
    @param key of the cached object.
1199
    @param hostname to associate with the cache key.
1200
    @param host_len length of the string hostname.
1201
1202
 */
1203
TSReturnCode TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len);
1204
1205
TSReturnCode TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache);
1206
1207
/**
1208
    Destroys a cache key. You must destroy cache keys when you are
1209
    finished with them, i.e. after all reads and writes are completed.
1210
1211
    @param key to be destroyed.
1212
1213
 */
1214
TSReturnCode TSCacheKeyDestroy(TSCacheKey key);
1215
1216
/* --------------------------------------------------------------------------
1217
   cache url */
1218
TSReturnCode TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length);
1219
1220
TSReturnCode TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type);
1221
1222
/* --------------------------------------------------------------------------
1223
   Configuration */
1224
unsigned int TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp);
1225
TSConfig     TSConfigGet(unsigned int id);
1226
void         TSConfigRelease(unsigned int id, TSConfig configp);
1227
void        *TSConfigDataGet(TSConfig configp);
1228
1229
TSReturnCode TSMgmtConfigFileAdd(const char *parent, const char *fileName);
1230
1231
/* --------------------------------------------------------------------------
1232
   Management */
1233
void         TSMgmtUpdateRegister(TSCont contp, const char *plugin_name, const char *plugin_file_name = nullptr);
1234
TSReturnCode TSMgmtIntGet(const char *var_name, TSMgmtInt *result);
1235
TSReturnCode TSMgmtCounterGet(const char *var_name, TSMgmtCounter *result);
1236
TSReturnCode TSMgmtFloatGet(const char *var_name, TSMgmtFloat *result);
1237
TSReturnCode TSMgmtStringGet(const char *var_name, TSMgmtString *result);
1238
TSReturnCode TSMgmtSourceGet(const char *var_name, TSMgmtSource *source);
1239
TSReturnCode TSMgmtConfigFileAdd(const char *parent, const char *fileName);
1240
TSReturnCode TSMgmtDataTypeGet(const char *var_name, TSRecordDataType *result);
1241
1242
/* --------------------------------------------------------------------------
1243
   TSHRTime, this is a candidate for deprecation in v10.0.0 */
1244
TSHRTime TShrtime(void);
1245
1246
/* --------------------------------------------------------------------------
1247
   Continuations */
1248
TSCont                TSContCreate(TSEventFunc funcp, TSMutex mutexp);
1249
void                  TSContDestroy(TSCont contp);
1250
void                  TSContDataSet(TSCont contp, void *data);
1251
void                 *TSContDataGet(TSCont contp);
1252
TSAction              TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp);
1253
TSAction              TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread);
1254
std::vector<TSAction> TSContScheduleOnEntirePool(TSCont contp, TSHRTime timeout, TSThreadPool tp);
1255
TSAction              TSContScheduleEveryOnPool(TSCont contp, TSHRTime every /* millisecs */, TSThreadPool tp);
1256
TSAction              TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEventThread ethread);
1257
std::vector<TSAction> TSContScheduleEveryOnEntirePool(TSCont contp, TSHRTime every /* millisecs */, TSThreadPool tp);
1258
TSReturnCode          TSContThreadAffinitySet(TSCont contp, TSEventThread ethread);
1259
TSEventThread         TSContThreadAffinityGet(TSCont contp);
1260
void                  TSContThreadAffinityClear(TSCont contp);
1261
TSAction              TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout);
1262
int                   TSContCall(TSCont contp, TSEvent event, void *edata);
1263
TSMutex               TSContMutexGet(TSCont contp);
1264
1265
/* --------------------------------------------------------------------------
1266
   Plugin lifecycle  hooks */
1267
void TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp);
1268
/* --------------------------------------------------------------------------
1269
   HTTP hooks */
1270
void TSHttpHookAdd(TSHttpHookID id, TSCont contp);
1271
1272
/* --------------------------------------------------------------------------
1273
   HTTP sessions */
1274
void TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp);
1275
void TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event);
1276
int  TSHttpSsnTransactionCount(TSHttpSsn ssnp);
1277
/* Get the TSVConn from a session. */
1278
TSVConn TSHttpSsnClientVConnGet(TSHttpSsn ssnp);
1279
TSVConn TSHttpSsnServerVConnGet(TSHttpSsn ssnp);
1280
/* Get the TSVConn from a transaction. */
1281
TSVConn TSHttpTxnServerVConnGet(TSHttpTxn txnp);
1282
1283
/* --------------------------------------------------------------------------
1284
   SSL connections */
1285
/* Re-enable an SSL connection from a hook.
1286
   This must be called exactly once before the SSL connection will resume. */
1287
void TSVConnReenable(TSVConn sslvcp);
1288
/* Extended version that allows for passing a status event on reenabling
1289
 */
1290
void TSVConnReenableEx(TSVConn sslvcp, TSEvent event);
1291
/*  Set the connection to go into blind tunnel mode */
1292
TSReturnCode TSVConnTunnel(TSVConn sslp);
1293
/*  Return the SSL object associated with the connection */
1294
TSSslConnection TSVConnSslConnectionGet(TSVConn sslp);
1295
/* Return the file descriptoer associated with the connection */
1296
int TSVConnFdGet(TSVConn sslp);
1297
/* Return the intermediate X509StoreCTX object that references the certificate being validated */
1298
TSSslVerifyCTX TSVConnSslVerifyCTXGet(TSVConn sslp);
1299
/*  Fetch a SSL context from the global lookup table */
1300
TSSslContext TSSslContextFindByName(const char *name);
1301
TSSslContext TSSslContextFindByAddr(struct sockaddr const *);
1302
/* Fetch SSL client contexts from the global lookup table */
1303
TSReturnCode TSSslClientContextsNamesGet(int n, const char **result, int *actual);
1304
TSSslContext TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths);
1305
1306
/* Update SSL certs in internal storage from given path */
1307
TSReturnCode TSSslClientCertUpdate(const char *cert_path, const char *key_path);
1308
TSReturnCode TSSslServerCertUpdate(const char *cert_path, const char *key_path);
1309
1310
/* Update the transient secret table for SSL_CTX loading */
1311
TSReturnCode TSSslSecretSet(const char *secret_name, int secret_name_length, const char *secret_data, int secret_data_length);
1312
1313
/* Returns secret with given name (not null terminted).  If there is no secret with the given name, return value will
1314
** be null and secret_data_lenght will be zero.  Calling code must free data buffer by calling TSfree(). */
1315
char *TSSslSecretGet(const char *secret_name, int secret_name_length, int *secret_data_length);
1316
1317
TSReturnCode TSSslSecretUpdate(const char *secret_name, int secret_name_length);
1318
1319
/* Create a new SSL context based on the settings in records.yaml */
1320
TSSslContext TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_file);
1321
void         TSSslContextDestroy(TSSslContext ctx);
1322
TSReturnCode TSSslTicketKeyUpdate(char *ticketData, int ticketDataLen);
1323
TSAcceptor   TSAcceptorGet(TSVConn sslp);
1324
TSAcceptor   TSAcceptorGetbyID(int ID);
1325
int          TSAcceptorCount();
1326
int          TSAcceptorIDGet(TSAcceptor acceptor);
1327
TSReturnCode TSVConnProtocolDisable(TSVConn connp, const char *protocol_name);
1328
TSReturnCode TSVConnProtocolEnable(TSVConn connp, const char *protocol_name);
1329
1330
/*  Returns 1 if the sslp argument refers to a SSL connection */
1331
int TSVConnIsSsl(TSVConn sslp);
1332
/* Returns 1 if a certificate was provided in the TLS handshake, 0 otherwise.
1333
 */
1334
int         TSVConnProvidedSslCert(TSVConn sslp);
1335
const char *TSVConnSslSniGet(TSVConn sslp, int *length);
1336
1337
/**
1338
    Retrieve TLS Client Hello information from an SSL virtual connection.
1339
1340
    This function extracts TLS Client Hello data from a TLS handshake.
1341
    The returned object provides access to version, cipher suites, and extensions
1342
    in a way that is portable across both BoringSSL and OpenSSL implementations.
1343
1344
    IMPORTANT: This function must be called during the TS_SSL_CLIENT_HELLO_HOOK.
1345
    The underlying SSL context may not be available at other hooks, particularly
1346
    for BoringSSL where the SSL_CLIENT_HELLO structure is only valid during
1347
    specific callback functions. Calling this function outside of the client
1348
    hello hook may result in unavailable object being returned.
1349
1350
    @param[in] sslp The SSL virtual connection handle. Must not be nullptr.
1351
    @return A TSClientHello object containing Client Hello data.
1352
1353
    @see TSClientHelloExtensionGet
1354
 */
1355
TSClientHello TSVConnClientHelloGet(TSVConn sslp);
1356
1357
/**
1358
    Retrieve a specific TLS extension from the Client Hello.
1359
1360
    This function looks up a TLS extension by its type (e.g., 0x10 for ALPN,
1361
    0x00 for SNI) and returns a pointer to its data. The lookup is performed
1362
    using SSL library-specific functions that work with both BoringSSL and
1363
    OpenSSL without requiring conditional compilation in the plugin.
1364
1365
    The returned buffer is still owned by the underlying SSL context and must
1366
    not be freed by the caller. The buffer is valid only in the condition where
1367
    you can get a TSClientHello object from an SSL virtual connection.
1368
1369
    @param[in]  ch The Client Hello object obtained from TSVConnClientHelloGet().
1370
    @param[in]  type The TLS extension type to retrieve.
1371
    @param[out] out Pointer to receive the extension data buffer. Must not be nullptr.
1372
    @param[out] outlen Pointer to receive the length of the extension data in bytes.
1373
                  Must not be nullptr.
1374
1375
    @return TS_SUCCESS if the extension was found and retrieved successfully.
1376
            TS_ERROR if the extension is not present, or if any parameter is nullptr,
1377
            or if an error occurred during lookup.
1378
1379
    @see TSVConnClientHelloGet
1380
 */
1381
TSReturnCode TSClientHelloExtensionGet(TSClientHello ch, unsigned int type, const unsigned char **out, size_t *outlen);
1382
1383
TSSslSession TSSslSessionGet(const TSSslSessionID *session_id);
1384
int          TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_ptr);
1385
TSReturnCode TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, TSSslConnection ssl_conn);
1386
TSReturnCode TSSslSessionRemove(const TSSslSessionID *session_id);
1387
1388
/* --------------------------------------------------------------------------
1389
   HTTP transactions */
1390
void      TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp);
1391
TSHttpSsn TSHttpTxnSsnGet(TSHttpTxn txnp);
1392
1393
/* Gets the client request header for a specified HTTP transaction. */
1394
TSReturnCode TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1395
/* Gets the client response header for a specified HTTP transaction. */
1396
TSReturnCode TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1397
/* Gets the server request header from a specified HTTP transaction. */
1398
TSReturnCode TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1399
/* Gets the server response header from a specified HTTP transaction. */
1400
TSReturnCode TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1401
/* Gets the cached request header for a specified HTTP transaction. */
1402
TSReturnCode TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1403
/* Gets the cached response header for a specified HTTP transaction. */
1404
TSReturnCode TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1405
1406
TSReturnCode TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc);
1407
1408
/**
1409
 * @brief Gets  the number of transactions between the Traffic Server proxy and the origin server from a single session.
1410
 *        Any value greater than zero indicates connection reuse.
1411
 *
1412
 * @param txnp The transaction
1413
 * @return int The number of transactions between the Traffic Server proxy and the origin server from a single session
1414
 */
1415
int TSHttpTxnServerSsnTransactionCount(TSHttpTxn txnp);
1416
1417
/** Get the effective URL for the transaction.
1418
    The effective URL is the URL taking in to account both the explicit
1419
    URL in the request and the HOST field.
1420
1421
    A possibly non-null terminated string is returned.
1422
1423
    @note The returned string is allocated and must be freed by the caller
1424
    after use with @c TSfree.
1425
*/
1426
char *TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length /**< String length return, may be @c nullptr. */
1427
);
1428
1429
/** Get the effective URL for in the header (if any), with the scheme and host normalized to lower case letter.
1430
    The effective URL is the URL taking in to account both the explicit
1431
    URL in the request and the HOST field.
1432
1433
    A possibly non-null terminated string is returned.
1434
1435
    @return TS_SUCCESS if successful, TS_ERROR if no URL in header or other error.
1436
*/
1437
TSReturnCode TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_t size, int64_t *length);
1438
1439
void TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag);
1440
void TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag);
1441
1442
/** Set flag indicating whether or not to cache the server response for
1443
    given TSHttpTxn
1444
1445
    @note This should be done in the HTTP_READ_RESPONSE_HDR_HOOK or earlier.
1446
1447
    @note If TSHttpTxnRespCacheableSet() is not working the way you expect,
1448
    this may be the function you should use instead.
1449
1450
    @param txnp The transaction whose server response you do not want to store.
1451
    @param flag Set 0 to allow storing and 1 to disable storing.
1452
1453
    @return TS_SUCCESS.
1454
*/
1455
TSReturnCode TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag);
1456
1457
/** Get flag indicating whether or not to cache the server response for
1458
    given TSHttpTxn
1459
    @param txnp The transaction whose server response you do not want to store.
1460
1461
    @return TS_SUCCESS.
1462
*/
1463
bool         TSHttpTxnServerRespNoStoreGet(TSHttpTxn txnp);
1464
TSReturnCode TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1465
char        *TSFetchRespGet(TSHttpTxn txnp, int *length);
1466
TSReturnCode TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status);
1467
1468
TSReturnCode TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
1469
1470
/** Set the @a port value for the inbound (user agent) connection in the transaction @a txnp.
1471
    This is used primarily where the connection is synthetic and therefore does not have a port.
1472
    @note @a port is in @b host @b order.
1473
*/
1474
void TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port);
1475
1476
/** Get client address for transaction @a txnp.
1477
    Retrieves the socket address of the remote client that has
1478
    connected to Traffic Server for transaction @a txnp. The
1479
    return structure is the generic socket address storage in
1480
    order to be address-family agnostic. The user of this function
1481
    can then go on to do the appropriate thing with the type
1482
    specified in the ss_family field of the structure whether
1483
    that be for IPv4, IPv6, or any other address family.
1484
1485
    @return Client address for connection to client in transaction @a txnp.
1486
1487
 */
1488
struct sockaddr const *TSHttpTxnClientAddrGet(TSHttpTxn txnp);
1489
/** Get the incoming address.
1490
1491
    @note The pointer is valid only for the current callback. Clients
1492
    that need to keep the value across callbacks must maintain their
1493
    own storage.
1494
1495
    @return Local address of the client connection for transaction @a txnp.
1496
*/
1497
struct sockaddr const *TSHttpTxnIncomingAddrGet(TSHttpTxn txnp);
1498
/** Get the outgoing address.
1499
1500
    @note The pointer is valid only for the current callback. Clients
1501
    that need to keep the value across callbacks must maintain their
1502
    own storage.
1503
1504
    @return Local address of the server connection for transaction @a txnp.
1505
*/
1506
struct sockaddr const *TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp);
1507
/** Get the origin server address.
1508
 *
1509
    @note The pointer is valid only for the current callback. Clients
1510
    that need to keep the value across callbacks must maintain their
1511
    own storage.
1512
1513
    @return The address of the origin server for transaction @a txnp.
1514
*/
1515
struct sockaddr const *TSHttpTxnServerAddrGet(TSHttpTxn txnp);
1516
/** Set the origin server address.
1517
1518
    This must be invoked before the origin server address is looked up.
1519
    If called no lookup is done, the address @a addr is used instead.
1520
1521
    @return @c TS_SUCCESS if the origin server address is set, @c TS_ERROR otherwise.
1522
*/
1523
TSReturnCode TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr /**< Address for origin server. */
1524
);
1525
1526
/** Get the next hop address.
1527
 *
1528
    @note The pointer is valid only for the current callback. Clients
1529
    that need to keep the value across callbacks must maintain their
1530
    own storage.
1531
1532
    @return The address of the next hop for transaction @a txnp.
1533
*/
1534
struct sockaddr const *TSHttpTxnNextHopAddrGet(TSHttpTxn txnp);
1535
1536
/** Get the next hop name.
1537
 *
1538
    @note The pointer is valid only for the current callback. Clients
1539
    that need to keep the value across callbacks must maintain their
1540
    own storage.
1541
1542
    @return The name of the next hop for transaction @a txnp.
1543
*/
1544
const char *TSHttpTxnNextHopNameGet(TSHttpTxn txnp);
1545
1546
/** Get the next hop port.
1547
 *
1548
    Retrieves the next hop parent port.
1549
                Returns -1 if not valid.
1550
1551
    @return The port of the next hop for transaction @a txnp.
1552
1553
 */
1554
int TSHttpTxnNextHopPortGet(TSHttpTxn txnp);
1555
1556
TSReturnCode TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp);
1557
TSReturnCode TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, struct sockaddr const *addr);
1558
TSReturnCode TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag);
1559
TSReturnCode TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp);
1560
1561
/* TS-1008: the above TXN calls for the Client conn should work with SSN */
1562
struct sockaddr const *TSHttpSsnClientAddrGet(TSHttpSsn ssnp);
1563
struct sockaddr const *TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp);
1564
TSReturnCode           TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp);
1565
/* TS-1008 END */
1566
1567
/** Change packet firewall mark for the client side connection
1568
 *
1569
    @note The change takes effect immediately
1570
1571
    @return TS_SUCCESS if the client connection was modified
1572
*/
1573
TSReturnCode TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark);
1574
1575
/** Change packet firewall mark for the server side connection
1576
 *
1577
    @note The change takes effect immediately, if no OS connection has been
1578
    made, then this sets the mark that will be used IF an OS connection
1579
    is established
1580
1581
    @return TS_SUCCESS if the (future?) server connection was modified
1582
*/
1583
TSReturnCode TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark);
1584
1585
/** Change packet DSCP for the client side connection
1586
 *
1587
    @note The change takes effect immediately
1588
1589
    @return TS_SUCCESS if the client connection was modified
1590
*/
1591
TSReturnCode TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp);
1592
1593
/** Change packet DSCP for the server side connection
1594
 *
1595
1596
    @note The change takes effect immediately, if no OS connection has been
1597
    made, then this sets the mark that will be used IF an OS connection
1598
    is established
1599
1600
    @return TS_SUCCESS if the (future?) server connection was modified
1601
*/
1602
TSReturnCode TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp);
1603
1604
/**
1605
   Sets an error type body to a transaction. Note that both string arguments
1606
   must be allocated with TSmalloc() or TSstrdup(). The mimetype argument is
1607
   optional, if not provided it defaults to "text/html". Sending an empty
1608
   string would prevent setting a content type header (but that is not advised).
1609
1610
   @param txnp HTTP transaction whose parent proxy to get.
1611
   @param buf The body message (must be heap allocated).
1612
   @param buflength Length of the body message.
1613
   @param mimetype The MIME type to set the response to (can be null, but must
1614
          be heap allocated if non-null).
1615
*/
1616
void TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetype);
1617
1618
/**
1619
   Retrives the error body, if any, from a transaction. This would be a body as set
1620
   via the API body.
1621
1622
   @param txnp HTTP transaction whose parent proxy to get.
1623
   @param buflength Optional outpu pointer to the length of the body message.
1624
   @param mimetype Optional output pointer to the MIME type of the response.
1625
*/
1626
char *TSHttpTxnErrorBodyGet(TSHttpTxn txnp, size_t *buflength, char **mimetype);
1627
1628
/**
1629
    Sets the Transaction's Next Hop Parent Strategy.
1630
    Calling this after TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK will
1631
    result in bad behavior.
1632
1633
    You can get this strategy pointer by calling TSHttpTxnParentStrategyGet().
1634
1635
    @param txnp HTTP transaction whose parent strategy to set.
1636
    @param pointer to the given strategy.
1637
1638
 */
1639
void TSHttpTxnNextHopStrategySet(TSHttpTxn txnp, void const *strategy);
1640
1641
/**
1642
    Retrieves a pointer to the current next hop selection strategy.
1643
    This value may be a nullptr due to:
1644
      - parent proxying not enabled
1645
      - no parent selection strategy (using parent.config)
1646
1647
    @param txnp HTTP transaction whose next hop strategy to get.
1648
1649
 */
1650
void const *TSHttpTxnNextHopStrategyGet(TSHttpTxn txnp);
1651
1652
/**
1653
    Returns either null pointer or null terminated pointer to name.
1654
                DO NOT FREE.
1655
1656
    This value may be a nullptr due to:
1657
      - parent proxying not enabled
1658
      - no parent selection strategy (using parent.config)
1659
1660
    @param txnp HTTP transaction whose next hop strategy to get.
1661
1662
 */
1663
char const *TSHttpNextHopStrategyNameGet(void const *strategy);
1664
1665
/**
1666
    Retrieves a pointer to the named strategy in the strategy table.
1667
    Returns nullptr if no strategy is set.
1668
    This uses the current transaction's state machine to get
1669
    access to UrlRewrite's NextHopStrategyFactory.
1670
1671
    @param txnp HTTP transaction which holds the strategy table.
1672
    @param name of the strategy to look up.
1673
1674
 */
1675
void const *TSHttpTxnNextHopNamedStrategyGet(TSHttpTxn txnp, const char *name);
1676
1677
/**
1678
    Sets the parent proxy name and port. The string hostname is copied
1679
    into the TSHttpTxn; you can modify or delete the string after
1680
    calling TSHttpTxnParentProxySet().
1681
1682
    @param txnp HTTP transaction whose parent proxy to set.
1683
    @param hostname parent proxy host name string.
1684
    @param port parent proxy port to set.
1685
1686
 */
1687
void TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port);
1688
1689
/**
1690
    Retrieves the parent proxy hostname and port, if parent
1691
    proxying is enabled. If parent proxying is not enabled,
1692
    TSHttpTxnParentProxyGet() sets hostname to nullptr and port to -1.
1693
1694
    @param txnp HTTP transaction whose parent proxy to get.
1695
    @param hostname of the parent proxy.
1696
    @param port parent proxy's port.
1697
1698
 */
1699
TSReturnCode TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port);
1700
1701
/**
1702
    Sets the parent proxy name and port. The string hostname is copied
1703
    into the TSHttpTxn; you can modify or delete the string after
1704
    calling TSHttpTxnParentProxySet().
1705
1706
    @param txnp HTTP transaction whose parent proxy to set.
1707
    @param hostname parent proxy host name string.
1708
    @param port parent proxy port to set.
1709
1710
 */
1711
void TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port);
1712
1713
TSReturnCode TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj);
1714
TSReturnCode TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj);
1715
1716
void TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on);
1717
void TSHttpTxnTransformedRespCache(TSHttpTxn txnp, int on);
1718
1719
/**
1720
    Notifies the HTTP transaction txnp that the plugin is
1721
    finished processing the current hook. The plugin tells the
1722
    transaction to either continue (TS_EVENT_HTTP_CONTINUE) or stop
1723
    (TS_EVENT_HTTP_ERROR).
1724
1725
    You must always reenable the HTTP transaction after the processing
1726
    of each transaction event. However, never reenable twice.
1727
    Reenabling twice is a serious error.
1728
1729
    @param txnp transaction to be reenabled.
1730
    @param event tells the transaction how to continue:
1731
      - TS_EVENT_HTTP_CONTINUE, which means that the transaction
1732
        should continue.
1733
      - TS_EVENT_HTTP_ERROR which terminates the transaction
1734
        and sends an error to the client if no response has already
1735
        been sent.
1736
1737
 */
1738
void         TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event);
1739
TSReturnCode TSHttpCacheReenable(TSCacheTxn txnp, const TSEvent event, const void *data, const uint64_t size);
1740
1741
/* The reserve API should only be use in TSAPI plugins, during plugin initialization!
1742
   The lookup methods can be used anytime, but are best used during initialization as well,
1743
   or at least "cache" the results for best performance. */
1744
TSReturnCode TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *description, int *arg_idx);
1745
TSReturnCode TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description);
1746
TSReturnCode TSUserArgIndexLookup(TSUserArgType type, int arg_idx, const char **name, const char **description);
1747
void         TSUserArgSet(void *data, int arg_idx, void *arg);
1748
void        *TSUserArgGet(void *data, int arg_idx);
1749
1750
/** Set the HTTP status code for a transaction.
1751
 *
1752
 * Sets the transaction's internal status state, triggering Traffic Server's
1753
 * error handling system. This is typically used for access control,
1754
 * authentication failures, and early transaction processing. Traffic Server
1755
 * will automatically generate an appropriate error response body.
1756
 *
1757
 * @note This is a candidate for deprecation in v10.0.0 in favor of the version
1758
 * that takes the setter.
1759
 *
1760
 * @param[in] txnp The associated transaction for the new status.
1761
 * @param[in] status The HTTP status code to set.
1762
 */
1763
void TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status);
1764
1765
/** Set the HTTP status code for a transaction and track the entity that set it.
1766
 *
1767
 * Sets the transaction's internal status state, triggering Traffic Server's
1768
 * error handling system. This is typically used for access control,
1769
 * authentication failures, and early transaction processing. Traffic Server
1770
 * will automatically generate an appropriate error response body.
1771
 *
1772
 * @param[in] txnp The associated transaction for the new status.
1773
 * @param[in] status The HTTP status code to set.
1774
 * @param[in] setter Identifying label for the entity setting the status
1775
 *   (e.g., plugin name). If empty, clears the current setter information.
1776
 */
1777
void TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status, std::string_view setter);
1778
1779
TSHttpStatus TSHttpTxnStatusGet(TSHttpTxn txnp);
1780
1781
void TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout);
1782
void TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout);
1783
void TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout);
1784
void TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout);
1785
1786
TSServerState TSHttpTxnServerStateGet(TSHttpTxn txnp);
1787
1788
/* --------------------------------------------------------------------------
1789
   Transaction specific debugging control  */
1790
1791
/**
1792
       Set the transaction specific debugging flag for this transaction.
1793
       When turned on, internal debug messages related to this transaction
1794
       will be written even if the debug tag isn't on.
1795
1796
    @param txnp transaction to change.
1797
    @param on set to 1 to turn on, 0 to turn off.
1798
*/
1799
void TSHttpTxnDebugSet(TSHttpTxn txnp, int on);
1800
/**
1801
       Returns the transaction specific debugging flag for this transaction.
1802
1803
    @param txnp transaction to check.
1804
    @return 1 if enabled, 0 otherwise.
1805
*/
1806
int TSHttpTxnDebugGet(TSHttpTxn txnp);
1807
/**
1808
       Set the session specific debugging flag for this client session.
1809
       When turned on, internal debug messages related to this session and all transactions
1810
       in the session will be written even if the debug tag isn't on.
1811
1812
    @param ssnp Client session to change.
1813
    @param on set to 1 to turn on, 0 to turn off.
1814
*/
1815
void TSHttpSsnDebugSet(TSHttpSsn ssnp, int on);
1816
/**
1817
       Returns the transaction specific debugging flag for this client session.
1818
1819
    @param txnp Client session to check.
1820
    @return 1 if enabled, 0 otherwise.
1821
*/
1822
int TSHttpSsnDebugGet(TSHttpSsn ssnp, int *on);
1823
1824
/* --------------------------------------------------------------------------
1825
   Intercepting Http Transactions */
1826
1827
/**
1828
    Allows a plugin take over the servicing of the request as though
1829
    it was the origin server. contp will be sent TS_EVENT_NET_ACCEPT.
1830
    The edata passed with TS_NET_EVENT_ACCEPT is an TSVConn just as
1831
    it would be for a normal accept. The plugin must act as if it is
1832
    an http server and read the http request and body off the TSVConn
1833
    and send an http response header and body.
1834
1835
    TSHttpTxnIntercept() must be called be called from only
1836
    TS_HTTP_READ_REQUEST_HOOK. Using TSHttpTxnIntercept will
1837
    bypass the Traffic Server cache. If response sent by the plugin
1838
    should be cached, use TSHttpTxnServerIntercept() instead.
1839
    TSHttpTxnIntercept() primary use is allow plugins to serve data
1840
    about their functioning directly.
1841
1842
    TSHttpTxnIntercept() must only be called once per transaction.
1843
1844
    @param contp continuation called to handle the interception.
1845
    @param txnp transaction to be intercepted.
1846
1847
 */
1848
void TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp);
1849
1850
/**
1851
    Allows a plugin take over the servicing of the request as though
1852
    it was the origin server. In the event a request needs to be
1853
    made to the server for transaction txnp, contp will be sent
1854
    TS_EVENT_NET_ACCEPT. The edata passed with TS_NET_EVENT_ACCEPT
1855
    is an TSVConn just as it would be for a normal accept. The plugin
1856
    must act as if it is an http server and read the http request and
1857
    body off the TSVConn and send an http response header and body.
1858
1859
    TSHttpTxnInterceptServer() must be not be called after
1860
    the connection to the server has taken place. The last hook
1861
    last hook in that TSHttpTxnIntercept() can be called from is
1862
    TS_HTTP_READ_CACHE_HDR_HOOK. If a connection to the server is
1863
    not necessary, contp is not called.
1864
1865
    The response from the plugin is cached subject to standard
1866
    and configured http caching rules. Should the plugin wish the
1867
    response not be cached, the plugin must use appropriate http
1868
    response headers to prevent caching. The primary purpose of
1869
    TSHttpTxnInterceptServer() is allow plugins to provide gateways
1870
    to other protocols or to allow to plugin to it's own transport for
1871
    the next hop to the server. TSHttpTxnInterceptServer() overrides
1872
    parent cache configuration.
1873
1874
    TSHttpTxnInterceptServer() must only be called once per
1875
    transaction.
1876
1877
    @param contp continuation called to handle the interception
1878
    @param txnp transaction to be intercepted.
1879
1880
 */
1881
void TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp);
1882
1883
/* --------------------------------------------------------------------------
1884
   Initiate Http Connection */
1885
1886
/**
1887
    Allows the plugin to initiate an http connection. The TSVConn the
1888
    plugin receives as the result of successful operates identically to
1889
    one created through TSNetConnect. Aside from allowing the plugin
1890
    to set the client ip and port for logging, the functionality of
1891
    TSHttpConnect() is identical to connecting to localhost on the
1892
    proxy port with TSNetConnect(). TSHttpConnect() is more efficient
1893
    than TSNetConnect() to localhost since it avoids the overhead of
1894
    passing the data through the operating system.
1895
1896
    This returns a VConn that connected to the transaction.
1897
1898
    @param options a TSHttpConnectPluginOptions structure that specifies options.
1899
 */
1900
TSVConn TSHttpConnectPlugin(TSHttpConnectOptions *options);
1901
1902
/** Backwards compatible version.
1903
    This function calls This provides a @a buffer_index of 8 and a @a buffer_water_mark of 0.
1904
1905
    @param addr Target address of the origin server.
1906
    @param tag A logging tag that can be accessed via the pitag field. May be @c nullptr.
1907
    @param id A logging id that can be access via the piid field.
1908
 */
1909
TSVConn TSHttpConnectWithPluginId(struct sockaddr const *addr, const char *tag, int64_t id);
1910
1911
/** Backwards compatible version.
1912
    This provides a @a tag of "plugin" and an @a id of 0.
1913
 */
1914
TSVConn TSHttpConnect(struct sockaddr const *addr);
1915
1916
/**
1917
   Get an instance of TSHttpConnectOptions with default values.
1918
 */
1919
TSHttpConnectOptions TSHttpConnectOptionsGet(TSConnectType connect_type);
1920
1921
/**
1922
   Get the value of proxy.config.plugin.vc.default_buffer_index from the TSHttpTxn
1923
 */
1924
TSIOBufferSizeIndex TSPluginVCIOBufferIndexGet(TSHttpTxn txnp);
1925
1926
/**
1927
   Get the value of proxy.config.plugin.vc.default_buffer_water_mark from the TSHttpTxn
1928
 */
1929
TSIOBufferWaterMark TSPluginVCIOBufferWaterMarkGet(TSHttpTxn txnp);
1930
1931
/* --------------------------------------------------------------------------
1932
 Initiate Transparent Http Connection */
1933
/**
1934
    Allows the plugin to initiate a transparent http connection. This operates
1935
    identically to TSHttpConnect except that it is treated as an intercepted
1936
    transparent connection by the session and transaction state machines.
1937
1938
    @param client_addr the address that the resulting connection will be seen as
1939
      coming from
1940
    @param server_addr the address that the resulting connection will be seen as
1941
      attempting to connect to when intercepted
1942
    @param vc will be set to point to the new TSVConn on success.
1943
1944
 */
1945
TSVConn TSHttpConnectTransparent(struct sockaddr const *client_addr, struct sockaddr const *server_addr);
1946
1947
TSFetchSM TSFetchUrl(const char *request, int request_len, struct sockaddr const *addr, TSCont contp,
1948
                     TSFetchWakeUpOptions callback_options, TSFetchEvent event);
1949
void      TSFetchPages(TSFetchUrlParams_t *params);
1950
1951
/**
1952
 * Extended FetchSM's AIPs
1953
 */
1954
1955
/*
1956
 * Create FetchSM, this API will enable stream IO automatically.
1957
 *
1958
 * @param contp: continuation to be callbacked.
1959
 * @param method: request method.
1960
 * @param url: scheme://host[:port]/path.
1961
 * @param version: client http version, eg: "HTTP/1.1".
1962
 * @param client_addr: client addr sent to log.
1963
 * @param flags: can be bitwise OR of several TSFetchFlags.
1964
 *
1965
 * return TSFetchSM which should be destroyed by TSFetchDestroy().
1966
 */
1967
TSFetchSM TSFetchCreate(TSCont contp, const char *method, const char *url, const char *version, struct sockaddr const *client_addr,
1968
                        int flags);
1969
1970
/*
1971
 * Set fetch flags to FetchSM Context
1972
 *
1973
 * @param fetch_sm: returned value of TSFetchCreate().
1974
 * @param flags: can be bitwise OR of several TSFetchFlags.
1975
 *
1976
 * return void
1977
 */
1978
void TSFetchFlagSet(TSFetchSM fetch_sm, int flags);
1979
1980
/*
1981
 * Create FetchSM, this API will enable stream IO automatically.
1982
 *
1983
 * @param fetch_sm: returned value of TSFetchCreate().
1984
 * @param name: name of header.
1985
 * @param name_len: len of name.
1986
 * @param value: value of header.
1987
 * @param name_len: len of value.
1988
 *
1989
 * return TSFetchSM which should be destroyed by TSFetchDestroy().
1990
 */
1991
void TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char *value, int value_len);
1992
1993
/*
1994
 * Write data to FetchSM
1995
 *
1996
 * @param fetch_sm: returned value of TSFetchCreate().
1997
 * @param data/len: data to be written to fetch sm.
1998
 */
1999
void TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len);
2000
2001
/*
2002
 * Read up to *len* bytes from FetchSM into *buf*.
2003
 *
2004
 * @param fetch_sm: returned value of TSFetchCreate().
2005
 * @param buf/len: buffer to contain data from fetch sm.
2006
 */
2007
ssize_t TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len);
2008
2009
/*
2010
 * Launch FetchSM to do http request, before calling this API,
2011
 * you should append http request header into fetch sm through
2012
 * TSFetchWriteData() API
2013
 *
2014
 * @param fetch_sm: comes from returned value of TSFetchCreate().
2015
 */
2016
void TSFetchLaunch(TSFetchSM fetch_sm);
2017
2018
/*
2019
 * Destroy FetchSM
2020
 *
2021
 * @param fetch_sm: returned value of TSFetchCreate().
2022
 */
2023
void TSFetchDestroy(TSFetchSM fetch_sm);
2024
2025
/*
2026
 * Set user-defined data in FetchSM
2027
 */
2028
void TSFetchUserDataSet(TSFetchSM fetch_sm, void *data);
2029
2030
/*
2031
 * Get user-defined data in FetchSM
2032
 */
2033
void *TSFetchUserDataGet(TSFetchSM fetch_sm);
2034
2035
/*
2036
 * Get client response hdr mbuffer
2037
 */
2038
TSMBuffer TSFetchRespHdrMBufGet(TSFetchSM fetch_sm);
2039
2040
/*
2041
 * Get client response hdr mloc
2042
 */
2043
TSMLoc TSFetchRespHdrMLocGet(TSFetchSM fetch_sm);
2044
2045
/* Check if HTTP State machine is internal or not */
2046
int TSHttpTxnIsInternal(TSHttpTxn txnp);
2047
int TSHttpSsnIsInternal(TSHttpSsn ssnp);
2048
2049
/* --------------------------------------------------------------------------
2050
   HTTP alternate selection */
2051
TSReturnCode TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset);
2052
TSReturnCode TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset);
2053
TSReturnCode TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset);
2054
void         TSHttpAltInfoQualitySet(TSHttpAltInfo infop, float quality);
2055
2056
/* --------------------------------------------------------------------------
2057
   Actions */
2058
void TSActionCancel(TSAction actionp);
2059
int  TSActionDone(TSAction actionp);
2060
2061
/* --------------------------------------------------------------------------
2062
   VConnections */
2063
TSVIO TSVConnReadVIOGet(TSVConn connp);
2064
TSVIO TSVConnWriteVIOGet(TSVConn connp);
2065
int   TSVConnClosedGet(TSVConn connp);
2066
2067
TSVIO TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes);
2068
TSVIO TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbytes);
2069
void  TSVConnClose(TSVConn connp);
2070
void  TSVConnAbort(TSVConn connp, int error);
2071
void  TSVConnShutdown(TSVConn connp, int read, int write);
2072
2073
/* --------------------------------------------------------------------------
2074
   Cache VConnections */
2075
int64_t TSVConnCacheObjectSizeGet(TSVConn connp);
2076
2077
/* --------------------------------------------------------------------------
2078
   Transformations */
2079
TSVConn TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp);
2080
TSVConn TSTransformOutputVConnGet(TSVConn connp);
2081
2082
/* --------------------------------------------------------------------------
2083
   Net VConnections */
2084
struct sockaddr const *TSNetVConnRemoteAddrGet(TSVConn vc);
2085
struct sockaddr const *TSNetVConnClientAddrGet(TSVConn vc);
2086
2087
/**
2088
    Opens a network connection to the host specified by ip on the port
2089
    specified by port. If the connection is successfully opened, contp
2090
    is called back with the event TS_EVENT_NET_CONNECT and the new
2091
    network vconnection will be passed in the event data parameter.
2092
    If the connection is not successful, contp is called back with
2093
    the event TS_EVENT_NET_CONNECT_FAILED.
2094
2095
    @return something allows you to check if the connection is complete,
2096
      or cancel the attempt to connect.
2097
2098
 */
2099
TSAction TSNetConnect(
2100
  TSCont                 contp, /**< continuation that is called back when the attempted net connection either succeeds or fails. */
2101
  struct sockaddr const *to     /**< Address to which to connect. */
2102
);
2103
2104
/**
2105
 * Retrieves the continuation associated with creating the TSVConn
2106
 */
2107
TSCont TSNetInvokingContGet(TSVConn conn);
2108
2109
/**
2110
 * Retrieves the transaction associated with creating the TSVConn
2111
 */
2112
TSHttpTxn TSNetInvokingTxnGet(TSVConn conn);
2113
2114
TSAction TSNetAccept(TSCont contp, int port, int domain, int accept_threads);
2115
2116
/**
2117
 Attempt to attach the contp continuation to sockets that have already been
2118
 opened by the traffic Server and defined as belonging to plugins (based on
2119
 records.yaml configuration). If a connection is successfully accepted,
2120
 the TS_EVENT_NET_ACCEPT is delivered to the continuation. The event
2121
 data will be a valid TSVConn bound to the accepted connection.
2122
 In order to configure such a socket, add the "plugin" keyword to a port
2123
 in proxy.config.http.server_ports like "8082:plugin"
2124
 Transparency/IP settings can also be defined, but a port cannot have
2125
 both the "ssl" or "plugin" keywords configured.
2126
2127
 Need to update records.yaml comments on proxy.config.http.server_ports
2128
 when this option is promoted from experimental.
2129
*/
2130
TSReturnCode TSPluginDescriptorAccept(TSCont contp);
2131
2132
/**
2133
  Listen on all SSL ports for connections for the specified protocol name.
2134
2135
  TSNetAcceptNamedProtocol registers the specified protocol for all
2136
  statically configured TLS ports. When a client using the TLS Next Protocol
2137
  Negotiation extension negotiates the requested protocol, TrafficServer will
2138
  route the request to the given handler. Note that the protocol is not
2139
  registered on ports opened by other plugins.
2140
2141
  The event and data provided to the handler are the same as for
2142
  TSNetAccept(). If a connection is successfully accepted, the event code
2143
  will be TS_EVENT_NET_ACCEPT and the event data will be a valid TSVConn
2144
  bound to the accepted connection.
2145
2146
  Neither contp nor protocol are copied. They must remain valid for the
2147
  lifetime of the plugin.
2148
2149
  TSNetAcceptNamedProtocol fails if the requested protocol cannot be
2150
  registered on all of the configured TLS ports. If it fails, the protocol
2151
  will not be registered on any ports (ie.. no partial failure).
2152
*/
2153
TSReturnCode TSNetAcceptNamedProtocol(TSCont contp, const char *protocol);
2154
2155
/**
2156
  Create a new port from the string specification used by the
2157
  proxy.config.http.server_ports configuration value.
2158
 */
2159
TSPortDescriptor TSPortDescriptorParse(const char *descriptor);
2160
2161
/**
2162
   Start listening on the given port descriptor. If a connection is
2163
   successfully accepted, the TS_EVENT_NET_ACCEPT is delivered to the
2164
   continuation. The event data will be a valid TSVConn bound to the accepted
2165
   connection.
2166
 */
2167
TSReturnCode TSPortDescriptorAccept(TSPortDescriptor, TSCont);
2168
2169
/* --------------------------------------------------------------------------
2170
   DNS Lookups */
2171
TSAction TSHostLookup(TSCont contp, const char *hostname, size_t namelen);
2172
/** Retrieve an address from the host lookup.
2173
 *
2174
 * @param lookup_result Result handle passed to event callback.
2175
 * @return A @c sockaddr with the address if successful, a @c nullptr if not.
2176
 */
2177
struct sockaddr const *TSHostLookupResultAddrGet(TSHostLookupResult lookup_result);
2178
2179
/* TODO: Eventually, we might want something like this as well, but it requires
2180
   support for building the HostDBInfo struct:
2181
   void TSHostLookupResultSet(TSHttpTxn txnp, TSHostLookupResult result);
2182
*/
2183
2184
/* --------------------------------------------------------------------------
2185
   Cache VConnections */
2186
/**
2187
    Asks the Traffic Server cache if the object corresponding to key
2188
    exists in the cache and can be read. If the object can be read,
2189
    the Traffic Server cache calls the continuation contp back with
2190
    the event TS_EVENT_CACHE_OPEN_READ. In this case, the cache also
2191
    passes contp a cache vconnection and contp can then initiate a
2192
    read operation on that vconnection using TSVConnRead.
2193
2194
    If the object cannot be read, the cache calls contp back with
2195
    the event TS_EVENT_CACHE_OPEN_READ_FAILED. The user (contp)
2196
    has the option to cancel the action returned by TSCacheRead.
2197
    Note that reentrant calls are possible, i.e. the cache can call
2198
    back the user (contp) in the same call.
2199
2200
    @param contp continuation to be called back if a read operation
2201
      is permissible.
2202
    @param key cache key corresponding to the object to be read.
2203
    @return something allowing the user to cancel or schedule the
2204
      cache read.
2205
2206
 */
2207
TSAction TSCacheRead(TSCont contp, TSCacheKey key);
2208
2209
/**
2210
    Asks the Traffic Server cache if contp can start writing the
2211
    object (corresponding to key) to the cache. If the object
2212
    can be written, the cache calls contp back with the event
2213
    TS_EVENT_CACHE_OPEN_WRITE. In this case, the cache also passes
2214
    contp a cache vconnection and contp can then initiate a write
2215
    operation on that vconnection using TSVConnWrite. The object
2216
    is not committed to the cache until the vconnection is closed.
2217
    When all data has been transferred, the user (contp) must do
2218
    an TSVConnClose. In case of any errors, the user MUST do an
2219
    TSVConnAbort(contp, 0).
2220
2221
    If the object cannot be written, the cache calls contp back with
2222
    the event TS_EVENT_CACHE_OPEN_WRITE_FAILED. This can happen,
2223
    for example, if there is another object with the same key being
2224
    written to the cache. The user (contp) has the option to cancel
2225
    the action returned by TSCacheWrite.
2226
2227
    Note that reentrant calls are possible, i.e. the cache can call
2228
    back the user (contp) in the same call.
2229
2230
    @param contp continuation that the cache calls back (telling it
2231
      whether the write operation can proceed or not).
2232
    @param key cache key corresponding to the object to be cached.
2233
    @return something allowing the user to cancel or schedule the
2234
      cache write.
2235
2236
 */
2237
TSAction TSCacheWrite(TSCont contp, TSCacheKey key);
2238
2239
/**
2240
    Removes the object corresponding to key from the cache. If the
2241
    object was removed successfully, the cache calls contp back
2242
    with the event TS_EVENT_CACHE_REMOVE. If the object was not
2243
    found in the cache, the cache calls contp back with the event
2244
    TS_EVENT_CACHE_REMOVE_FAILED.
2245
2246
    In both of these callbacks, the user (contp) does not have to do
2247
    anything. The user does not get any vconnection from the cache,
2248
    since no data needs to be transferred. When the cache calls
2249
    contp back with TS_EVENT_CACHE_REMOVE, the remove has already
2250
    been committed.
2251
2252
    @param contp continuation that the cache calls back reporting the
2253
      success or failure of the remove.
2254
    @param key cache key corresponding to the object to be removed.
2255
    @return something allowing the user to cancel or schedule the
2256
      remove.
2257
2258
 */
2259
TSAction     TSCacheRemove(TSCont contp, TSCacheKey key);
2260
TSReturnCode TSCacheReady(int *is_ready);
2261
TSAction     TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second);
2262
2263
/* Cache APIs that are not yet fully supported and/or frozen nor complete. */
2264
TSReturnCode TSCacheBufferInfoGet(TSCacheTxn txnp, uint64_t *length, uint64_t *offset);
2265
2266
TSCacheHttpInfo TSCacheHttpInfoCreate();
2267
void            TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj);
2268
void            TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj);
2269
void            TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj);
2270
void            TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj);
2271
void            TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey key);
2272
void            TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size);
2273
int             TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length);
2274
int64_t         TSCacheHttpInfoSizeGet(TSCacheHttpInfo infop);
2275
2276
void TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop);
2277
2278
TSCacheHttpInfo TSCacheHttpInfoCopy(TSCacheHttpInfo infop);
2279
void            TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *offset);
2280
void            TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *offset);
2281
void            TSCacheHttpInfoDestroy(TSCacheHttpInfo infop);
2282
2283
time_t       TSCacheHttpInfoReqSentTimeGet(TSCacheHttpInfo infop);
2284
time_t       TSCacheHttpInfoRespReceivedTimeGet(TSCacheHttpInfo infop);
2285
TSReturnCode TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time);
2286
2287
/* --------------------------------------------------------------------------
2288
   VIOs */
2289
void             TSVIOReenable(TSVIO viop);
2290
TSIOBuffer       TSVIOBufferGet(TSVIO viop);
2291
TSIOBufferReader TSVIOReaderGet(TSVIO viop);
2292
int64_t          TSVIONBytesGet(TSVIO viop);
2293
void             TSVIONBytesSet(TSVIO viop, int64_t nbytes);
2294
int64_t          TSVIONDoneGet(TSVIO viop);
2295
void             TSVIONDoneSet(TSVIO viop, int64_t ndone);
2296
int64_t          TSVIONTodoGet(TSVIO viop);
2297
TSMutex          TSVIOMutexGet(TSVIO viop);
2298
TSCont           TSVIOContGet(TSVIO viop);
2299
TSVConn          TSVIOVConnGet(TSVIO viop);
2300
2301
/* --------------------------------------------------------------------------
2302
   Buffers */
2303
TSIOBuffer TSIOBufferCreate(void);
2304
2305
/**
2306
    Creates a new TSIOBuffer of the specified size. With this function,
2307
    you can create smaller buffers than the 32K buffer created by
2308
    TSIOBufferCreate(). In some situations using smaller buffers can
2309
    improve performance.
2310
2311
    @param index size of the new TSIOBuffer to be created.
2312
    @param new TSIOBuffer of the specified size.
2313
2314
 */
2315
TSIOBuffer TSIOBufferSizedCreate(TSIOBufferSizeIndex index);
2316
2317
/**
2318
    The watermark of an TSIOBuffer is the minimum number of bytes
2319
    of data that have to be in the buffer before calling back any
2320
    continuation that has initiated a read operation on this buffer.
2321
    TSIOBufferWaterMarkGet() will provide the size of the watermark,
2322
    in bytes, for a specified TSIOBuffer.
2323
2324
    @param bufp buffer whose watermark the function gets.
2325
2326
 */
2327
int64_t TSIOBufferWaterMarkGet(TSIOBuffer bufp);
2328
2329
/**
2330
    The watermark of an TSIOBuffer is the minimum number of bytes
2331
    of data that have to be in the buffer before calling back any
2332
    continuation that has initiated a read operation on this buffer.
2333
    As a writer feeds data into the TSIOBuffer, no readers are called
2334
    back until the amount of data reaches the watermark. Setting
2335
    a watermark can improve performance because it avoids frequent
2336
    callbacks to read small amounts of data. TSIOBufferWaterMarkSet()
2337
    assigns a watermark to a particular TSIOBuffer.
2338
2339
    @param bufp buffer whose water mark the function sets.
2340
    @param water_mark watermark setting, as a number of bytes.
2341
2342
 */
2343
void TSIOBufferWaterMarkSet(TSIOBuffer bufp, int64_t water_mark);
2344
2345
void            TSIOBufferDestroy(TSIOBuffer bufp);
2346
TSIOBufferBlock TSIOBufferStart(TSIOBuffer bufp);
2347
int64_t         TSIOBufferCopy(TSIOBuffer bufp, TSIOBufferReader readerp, int64_t length, int64_t offset);
2348
2349
/**
2350
    Writes length bytes of data contained in the string buf to the
2351
    TSIOBuffer bufp. Returns the number of bytes of data successfully
2352
    written to the TSIOBuffer.
2353
2354
    @param bufp is the TSIOBuffer to write into.
2355
    @param buf string to write into the TSIOBuffer.
2356
    @param length of the string buf.
2357
    @return length of data successfully copied into the buffer,
2358
      in bytes.
2359
2360
 */
2361
int64_t TSIOBufferWrite(TSIOBuffer bufp, const void *buf, int64_t length);
2362
void    TSIOBufferProduce(TSIOBuffer bufp, int64_t nbytes);
2363
2364
TSIOBufferBlock TSIOBufferBlockNext(TSIOBufferBlock blockp);
2365
const char     *TSIOBufferBlockReadStart(TSIOBufferBlock blockp, TSIOBufferReader readerp, int64_t *avail);
2366
int64_t         TSIOBufferBlockReadAvail(TSIOBufferBlock blockp, TSIOBufferReader readerp);
2367
char           *TSIOBufferBlockWriteStart(TSIOBufferBlock blockp, int64_t *avail);
2368
int64_t         TSIOBufferBlockWriteAvail(TSIOBufferBlock blockp);
2369
2370
TSIOBufferReader TSIOBufferReaderAlloc(TSIOBuffer bufp);
2371
TSIOBufferReader TSIOBufferReaderClone(TSIOBufferReader readerp);
2372
void             TSIOBufferReaderFree(TSIOBufferReader readerp);
2373
TSIOBufferBlock  TSIOBufferReaderStart(TSIOBufferReader readerp);
2374
void             TSIOBufferReaderConsume(TSIOBufferReader readerp, int64_t nbytes);
2375
int64_t          TSIOBufferReaderAvail(TSIOBufferReader readerp);
2376
int64_t          TSIOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length);
2377
2378
struct sockaddr const *TSNetVConnLocalAddrGet(TSVConn vc);
2379
2380
/* --------------------------------------------------------------------------
2381
   Stats and configs based on librecords raw stats (this is preferred API until we
2382
   rewrite stats).
2383
2384
   This is available as of Apache TS v2.2.*/
2385
enum TSStatPersistence {
2386
  TS_STAT_PERSISTENT = 1,
2387
  TS_STAT_NON_PERSISTENT,
2388
};
2389
2390
enum TSStatSync {
2391
  TS_STAT_SYNC_SUM = 0,
2392
  TS_STAT_SYNC_COUNT,
2393
  TS_STAT_SYNC_AVG,
2394
  TS_STAT_SYNC_TIMEAVG,
2395
};
2396
2397
/* APIs to create new records.yaml configurations */
2398
TSReturnCode TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString data_default,
2399
                                TSRecordUpdateType update_type, TSRecordCheckType check_type, const char *check_regex,
2400
                                TSRecordAccessType access_type);
2401
TSReturnCode TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, TSRecordUpdateType update_type,
2402
                             TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type);
2403
2404
/*  Note that only TS_RECORDDATATYPE_INT is supported at this point. */
2405
int TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence persist, TSStatSync sync);
2406
2407
void TSStatIntIncrement(int the_stat, TSMgmtInt amount);
2408
void TSStatIntDecrement(int the_stat, TSMgmtInt amount);
2409
/* Currently not supported. */
2410
/* void TSStatFloatIncrement(int the_stat, float amount); */
2411
/* void TSStatFloatDecrement(int the_stat, float amount); */
2412
2413
TSMgmtInt TSStatIntGet(int the_stat);
2414
void      TSStatIntSet(int the_stat, TSMgmtInt value);
2415
/* Currently not supported. */
2416
/* TSReturnCode TSStatFloatGet(int the_stat, float* value); */
2417
/* TSReturnCode TSStatFloatSet(int the_stat, float value); */
2418
2419
TSReturnCode TSStatFindName(const char *name, int *idp);
2420
2421
/**
2422
   Records.yaml file handling API.
2423
2424
   If you need to parse a records.yaml file and need to handle each node separately then
2425
   this API should be used, an example of this would be the conf_remap plugin.
2426
2427
   TSYAMLRecNodeHandler
2428
2429
   Callback function for the caller to deal with each parsed node. ``cfg`` holds
2430
   the details of the parsed field. `data` can be used to pass information along.
2431
*/
2432
using TSYAMLRecNodeHandler = TSReturnCode (*)(const TSYAMLRecCfgFieldData *cfg, void *data);
2433
/**
2434
   Parse a YAML node following the record structure internals. On every scalar node
2435
   the @a handler callback will be invoked with the appropriate parsed fields. @a data
2436
   can be used to pass information along to every callback, this could be handy when
2437
   you need to read/set data inside the @c TSYAMLRecNodeHandler to be read at a later stage.
2438
2439
   This will return TS_ERROR if there was an issue while parsing the file. Particular node errors
2440
   should be handled by the @c TSYAMLRecNodeHandler implementation.
2441
*/
2442
TSReturnCode TSRecYAMLConfigParse(TSYaml node, TSYAMLRecNodeHandler handler, void *data);
2443
2444
/* --------------------------------------------------------------------------
2445
   logging api */
2446
2447
/**
2448
    The following enum values are flags, so they should be powers
2449
    of two. With the exception of TS_LOG_MODE_INVALID_FLAG, they
2450
    are all used to configure the creation of an TSTextLogObject
2451
    through the mode argument to TSTextLogObjectCreate().
2452
    TS_LOG_MODE_INVALID_FLAG is used internally to check the validity
2453
    of this argument. Insert new flags before TS_LOG_MODE_INVALID_FLAG,
2454
    and set TS_LOG_MODE_INVALID_FLAG to the largest power of two of
2455
    the enum.
2456
2457
 */
2458
enum {
2459
  TS_LOG_MODE_ADD_TIMESTAMP = 1,
2460
  TS_LOG_MODE_DO_NOT_RENAME = 2,
2461
  TS_LOG_MODE_INVALID_FLAG  = 4,
2462
};
2463
2464
/**
2465
    This type represents a custom log file that you create with
2466
    TSTextLogObjectCreate(). Your plugin writes entries into this
2467
    log file using TSTextLogObjectWrite().
2468
2469
 */
2470
using TSTextLogObject = struct tsapi_textlogobject *;
2471
2472
using TSRecordDumpCb = void (*)(TSRecordType rec_type, void *edata, int registered, const char *name, TSRecordDataType data_type,
2473
                                TSRecordData *datum);
2474
2475
void TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata);
2476
2477
/**
2478
2479
    Creates a new custom log file that your plugin can write to. You
2480
    can design the fields and inputs to the log file using the
2481
    TSTextLogObjectWrite() function. The logs you create are treated
2482
    like ordinary logs; they are rolled if log rolling is enabled.
2483
2484
    @param filename new log file being created. The new log file
2485
      is created in the logs directory. You can specify a path to a
2486
      subdirectory within the log directory, e.g. subdir/filename,
2487
      but make sure you create the subdirectory first. If you do
2488
      not specify a file name extension, the extension ".log" is
2489
      automatically added.
2490
    @param mode is one (or both) of the following:
2491
      - TS_LOG_MODE_ADD_TIMESTAMP Whenever the plugin makes a log
2492
        entry using TSTextLogObjectWrite (see below), it prepends
2493
        the entry with a timestamp.
2494
      - TS_LOG_MODE_DO_NOT_RENAME This means that if there is a
2495
        filename conflict, Traffic Server should not attempt to rename
2496
        the custom log. The consequence of a name conflict is that the
2497
        custom log will simply not be created, e.g. suppose you call:
2498
          @code
2499
          log = TSTextLogObjectCreate("squid" , mode, nullptr, &error);
2500
          @endcode
2501
        If mode is TS_LOG_MODE_DO_NOT_RENAME, you will NOT get a new
2502
        log (you'll get a null pointer) if squid.log already exists.
2503
        If mode is not TS_LOG_MODE_DO_NOT_RENAME, Traffic Server
2504
        tries to rename the log to a new name (it will try squid_1.log).
2505
    @param new_log_obj new custom log file.
2506
    @return error code:
2507
      - TS_LOG_ERROR_NO_ERROR No error; the log object has been
2508
        created successfully.
2509
      - TS_LOG_ERROR_OBJECT_CREATION Log object not created. This
2510
        error is rare and would most likely be caused by the system
2511
        running out of memory.
2512
      - TS_LOG_ERROR_FILENAME_CONFLICTS You get this error if mode =
2513
        TS_LOG_MODE_DO_NOT_RENAME, and if there is a naming conflict.
2514
        The log object is not created.
2515
      - TS_LOG_ERROR_FILE_ACCESS Log object not created because of
2516
        a file access problem (for example, no write permission to the
2517
        logging directory, or a specified subdirectory for the log file
2518
        does not exist).
2519
2520
 */
2521
TSReturnCode TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_log_obj);
2522
2523
/**
2524
    Writes a printf-style formatted statement to an TSTextLogObject
2525
    (a plugin custom log).
2526
2527
    @param the_object log object to write to. You must first create
2528
      this object with TSTextLogObjectCreate().
2529
    @param format printf-style formatted statement to be printed.
2530
    @param ... parameters in the formatted statement. A newline is
2531
      automatically added to the end.
2532
    @return one of the following errors:
2533
      - TS_LOG_ERROR_NO_ERROR Means that the write was successful.
2534
      - TS_LOG_ERROR_LOG_SPACE_EXHAUSTED Means that Traffic Server
2535
        ran out of disk space for logs. If you see this error you might
2536
        want to roll logs more often.
2537
      - TS_LOG_ERROR_INTERNAL_ERROR Indicates some internal problem
2538
        with a log entry (such as an entry larger than the size of the
2539
        log write buffer). This error is very unusual.
2540
2541
 */
2542
TSReturnCode TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...) TS_PRINTFLIKE(2, 3);
2543
2544
/**
2545
    This immediately flushes the contents of the log write buffer for
2546
    the_object to disk. Use this call only if you want to make sure that
2547
    log entries are flushed immediately. This call has a performance
2548
    cost. Traffic Server flushes the log buffer automatically about
2549
    every 1 second.
2550
2551
    @param the_object custom log file whose write buffer is to be
2552
      flushed.
2553
2554
 */
2555
void TSTextLogObjectFlush(TSTextLogObject the_object);
2556
2557
/**
2558
    Destroys a log object and releases the memory allocated to it.
2559
    Use this call if you are done with the log.
2560
2561
    @param  the_object custom log to be destroyed.
2562
2563
 */
2564
TSReturnCode TSTextLogObjectDestroy(TSTextLogObject the_object);
2565
2566
/**
2567
    Set log header.
2568
2569
 */
2570
void TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header);
2571
2572
/**
2573
    Enable/disable rolling.
2574
2575
    @param rolling_enabled a valid proxy.config.log.rolling_enabled value.
2576
2577
 */
2578
TSReturnCode TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled);
2579
2580
/**
2581
    Set the rolling interval.
2582
2583
 */
2584
void TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_interval_sec);
2585
2586
/**
2587
    Set the rolling offset. rolling_offset_hr specifies the hour (between 0 and 23) when log rolling
2588
    should take place.
2589
2590
 */
2591
void TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset_hr);
2592
2593
/**
2594
    Set the rolling size. rolling_size_mb specifies the size in MB when log rolling
2595
    should take place.
2596
2597
 */
2598
void TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb);
2599
2600
/**
2601
    Async disk IO read
2602
2603
    @return TS_SUCCESS or TS_ERROR.
2604
 */
2605
TSReturnCode TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp);
2606
2607
/**
2608
    Async disk IO buffer get
2609
2610
    @return char* to the buffer
2611
 */
2612
char *TSAIOBufGet(TSAIOCallback data);
2613
2614
/**
2615
    Async disk IO get number of bytes
2616
2617
    @return the number of bytes
2618
 */
2619
int TSAIONBytesGet(TSAIOCallback data);
2620
2621
/**
2622
    Async disk IO write
2623
2624
    @return TS_SUCCESS or TS_ERROR.
2625
 */
2626
TSReturnCode TSAIOWrite(int fd, off_t offset, char *buf, size_t bufSize, TSCont contp);
2627
2628
/**
2629
    Async disk IO set number of threads
2630
2631
    @return TS_SUCCESS or TS_ERROR.
2632
 */
2633
TSReturnCode TSAIOThreadNumSet(int thread_num);
2634
2635
/**
2636
    Check if transaction was aborted (due client/server errors etc.)
2637
    Client_abort is set as True, in case the abort was caused by the Client.
2638
2639
    @return 1 if transaction was aborted
2640
*/
2641
TSReturnCode TSHttpTxnAborted(TSHttpTxn txnp, bool *client_abort);
2642
2643
TSVConn TSVConnCreate(TSEventFunc event_funcp, TSMutex mutexp);
2644
TSVConn TSVConnFdCreate(int fd);
2645
2646
/* api functions to access stats */
2647
/* ClientResp APIs exist as well and are exposed in PrivateFrozen  */
2648
int     TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp);
2649
int64_t TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp);
2650
int     TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp);
2651
int64_t TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp);
2652
int     TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp);
2653
int64_t TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp);
2654
int     TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp);
2655
int64_t TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp);
2656
int     TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp);
2657
int64_t TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp);
2658
int     TSVConnIsSslReused(TSVConn sslp);
2659
2660
/****************************************************************************
2661
 *  Allow to set the body of a POST request.
2662
 ****************************************************************************/
2663
void TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength);
2664
2665
/**
2666
   Return the current (if set) SSL Cipher. This is still owned by the
2667
   core, and must not be free'd.
2668
2669
   @param sslp The connection pointer
2670
2671
   @return the SSL Cipher
2672
*/
2673
const char *TSVConnSslCipherGet(TSVConn sslp);
2674
2675
/**
2676
   Return the current (if set) SSL Protocol. This is still owned by the
2677
   core, and must not be free'd.
2678
2679
   @param sslp The connection pointer
2680
2681
   @return the SSL Protocol
2682
*/
2683
const char *TSVConnSslProtocolGet(TSVConn sslp);
2684
2685
/**
2686
   Return the current (if set) SSL Curve. This is still owned by the
2687
   core, and must not be free'd.
2688
2689
   @param txnp the transaction pointer
2690
2691
   @return the SSL Curve
2692
*/
2693
const char *TSVConnSslCurveGet(TSVConn sslp);
2694
2695
/* NetVC timeout APIs. */
2696
void TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout);
2697
void TSVConnInactivityTimeoutCancel(TSVConn connp);
2698
void TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout);
2699
void TSVConnActiveTimeoutCancel(TSVConn connp);
2700
2701
/*
2702
  ability to skip the remap phase of the State Machine
2703
  this only really makes sense in TS_HTTP_READ_REQUEST_HDR_HOOK
2704
*/
2705
void TSSkipRemappingSet(TSHttpTxn txnp, int flag);
2706
2707
/*
2708
  Set or get various overridable configurations, for a transaction. This should
2709
  probably be done as early as possible, e.g. TS_HTTP_READ_REQUEST_HDR_HOOK.
2710
*/
2711
TSReturnCode TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt value);
2712
TSReturnCode TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *value);
2713
TSReturnCode TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat value);
2714
TSReturnCode TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat *value);
2715
TSReturnCode TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char *value, int length);
2716
TSReturnCode TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char **value, int *length);
2717
2718
TSReturnCode TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, TSRecordDataType *type);
2719
2720
/**
2721
   This is a generalization of the old TSHttpTxnFollowRedirect(), but gives finer
2722
   control over the behavior. Instead of using the Location: header for the new
2723
   destination, this API takes the new URL as a parameter. Calling this API
2724
   transfers the ownership of the URL from the plugin to the core, so you must
2725
   make sure it is heap allocated, and that you do not free it.
2726
2727
   Calling this API implicitly also enables the "Follow Redirect" feature, so
2728
   there is no need to set that overridable configuration as well.
2729
2730
   @param txnp the transaction pointer
2731
   @param url  a heap allocated string with the URL
2732
   @param url_len the length of the URL
2733
*/
2734
void TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len);
2735
2736
/**
2737
   Return the current (if set) redirection URL string. This is still owned by the
2738
   core, and must not be free'd.
2739
2740
   @param txnp the transaction pointer
2741
   @param url_len_ptr a pointer to where the URL length is to be stored
2742
2743
   @return the url string
2744
*/
2745
const char *TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr);
2746
2747
/**
2748
   Return the number of redirection retries we have done. This starts off
2749
   at zero, and can be used to select different URLs based on which attempt this
2750
   is. This can be useful for example when providing a list of URLs to try, and
2751
   do so in order until one succeeds.
2752
2753
   @param txnp the transaction pointer
2754
2755
   @return the redirect try count
2756
*/
2757
int TSHttpTxnRedirectRetries(TSHttpTxn txnp);
2758
2759
/* Get current HTTP connection stats */
2760
int TSHttpCurrentClientConnectionsGet(void);
2761
int TSHttpCurrentActiveClientConnectionsGet(void);
2762
int TSHttpCurrentIdleClientConnectionsGet(void);
2763
int TSHttpCurrentCacheConnectionsGet(void);
2764
int TSHttpCurrentServerConnectionsGet(void);
2765
2766
/* =====  Http Transactions =====  */
2767
TSReturnCode TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset);
2768
TSReturnCode TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup);
2769
TSReturnCode TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj);
2770
TSReturnCode TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj);
2771
TSReturnCode TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session);
2772
const char  *TSHttpTxnCacheDiskPathGet(TSHttpTxn txnp, int *length);
2773
int          TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp);
2774
int          TSHttpTxnIsWebsocket(TSHttpTxn txnp);
2775
2776
/* Get the Txn's (HttpSM's) unique identifier, which is a sequence number since server start) */
2777
uint64_t TSHttpTxnIdGet(TSHttpTxn txnp);
2778
2779
/* Get the Ssn's unique identifier */
2780
int64_t TSHttpSsnIdGet(TSHttpSsn ssnp);
2781
2782
/* Expose internal Base64 Encoding / Decoding */
2783
TSReturnCode TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_size, size_t *length);
2784
TSReturnCode TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length);
2785
2786
/* Get milestone timers, useful for measuring where we are spending time in the transaction processing */
2787
/**
2788
   Return the particular milestone timer for the transaction. If 0 is returned, it means
2789
   the transaction has not yet reached that milestone. Asking for an "unknown" milestone is
2790
   an error.
2791
2792
   @param txnp the transaction pointer
2793
   @param milestone the requested milestone timer
2794
   was created.
2795
   @param time a pointer to a TSHRTime where we will store the timer
2796
2797
   @return @c TS_SUCCESS if the milestone is supported, TS_ERROR otherwise
2798
2799
*/
2800
TSReturnCode TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, TSHRTime *time);
2801
2802
/**
2803
  Test whether a request / response header pair would be cacheable under the current
2804
  configuration. This would typically be used in TS_HTTP_READ_RESPONSE_HDR_HOOK, when
2805
  you have both the client request and server response ready.
2806
2807
  @param txnp the transaction pointer
2808
  @param request the client request header. If null, use the transactions client request.
2809
  @param response the server response header. If null, use the transactions origin response.
2810
2811
  @return 1 if the request / response is cacheable, 0 otherwise
2812
*/
2813
int TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response);
2814
2815
/**
2816
  Get the maximum age in seconds as indicated by the origin server.
2817
  This would typically be used in TS_HTTP_READ_RESPONSE_HDR_HOOK, when you have
2818
  the server response ready.
2819
2820
  @param txnp the transaction pointer
2821
  @param response the server response header. If null, use the transactions origin response.
2822
2823
  @return the age in seconds if specified by Cache-Control, -1 otherwise
2824
*/
2825
int TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response);
2826
2827
/**
2828
   Return a string representation for a TSServerState value. This is useful for plugin debugging.
2829
2830
   @param state the value of this TSServerState
2831
2832
   @return the string representation of the state
2833
*/
2834
const char *TSHttpServerStateNameLookup(TSServerState state);
2835
2836
/**
2837
   Return a string representation for a TSHttpHookID value. This is useful for plugin debugging.
2838
2839
   @param hook the value of this TSHttpHookID
2840
2841
   @return the string representation of the hook ID
2842
*/
2843
const char *TSHttpHookNameLookup(TSHttpHookID hook);
2844
2845
/**
2846
   Return a string representation for a TSEvent value. This is useful for plugin debugging.
2847
2848
   @param event the value of this TSHttpHookID
2849
2850
   @return the string representation of the event
2851
*/
2852
const char *TSHttpEventNameLookup(TSEvent event);
2853
2854
/* APIs for dealing with UUIDs, either self made, or the system wide process UUID. See
2855
   https://docs.trafficserver.apache.org/en/latest/developer-guide/api/functions/TSUuidCreate.en.html
2856
*/
2857
TSUuid        TSUuidCreate(void);
2858
TSReturnCode  TSUuidInitialize(TSUuid uuid, TSUuidVersion v);
2859
void          TSUuidDestroy(TSUuid uuid);
2860
TSReturnCode  TSUuidCopy(TSUuid dest, const TSUuid src);
2861
const char   *TSUuidStringGet(const TSUuid uuid);
2862
TSUuidVersion TSUuidVersionGet(const TSUuid uuid);
2863
TSReturnCode  TSUuidStringParse(TSUuid uuid, const char *uuid_str);
2864
TSReturnCode  TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str);
2865
2866
/* Get the process global UUID, resets on every startup */
2867
TSUuid TSProcessUuidGet(void);
2868
2869
/**
2870
   Returns the plugin_tag.
2871
*/
2872
const char *TSHttpTxnPluginTagGet(TSHttpTxn txnp);
2873
2874
/*
2875
 * Return information about the client protocols.
2876
 */
2877
TSReturnCode TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual);
2878
TSReturnCode TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int count, const char **result, int *actual);
2879
const char  *TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, char const *tag);
2880
const char  *TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, char const *tag);
2881
const char  *TSNormalizedProtocolTag(char const *tag);
2882
const char  *TSRegisterProtocolTag(char const *tag);
2883
2884
/*
2885
 * Return information about the server protocols.
2886
 */
2887
TSReturnCode TSHttpTxnServerProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual);
2888
const char  *TSHttpTxnServerProtocolStackContains(TSHttpTxn txnp, char const *tag);
2889
2890
// If, for the given transaction, the URL has been remapped, this function puts the memory location of the "from" URL object in
2891
// the variable pointed to by urlLocp, and returns TS_SUCCESS.  (The URL object will be within memory allocated to the
2892
// transaction object.)  Otherwise, the function returns TS_ERROR.
2893
//
2894
TSReturnCode TSRemapFromUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp);
2895
2896
// If, for the given transaction, the URL has been remapped, this function puts the memory location of the "to" URL object in the
2897
// variable pointed to by urlLocp, and returns TS_SUCCESS.  (The URL object will be within memory allocated to the transaction
2898
// object.)  Otherwise, the function returns TS_ERROR.
2899
//
2900
TSReturnCode TSRemapToUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp);
2901
2902
// Get some plugin details from the TSRemapPluginInfo
2903
void *TSRemapDLHandleGet(TSRemapPluginInfo plugin_info);
2904
2905
// Override response behavior, and hard-set the state machine for whether to succeed or fail, and how.
2906
void TSHttpTxnResponseActionSet(TSHttpTxn txnp, TSResponseAction *action);
2907
2908
// Get the overridden response behavior set by previously called plugins.
2909
void TSHttpTxnResponseActionGet(TSHttpTxn txnp, TSResponseAction *action);
2910
2911
/*
2912
 * Get a TSIOBufferReader to read the buffered body. The return value needs to be freed.
2913
 */
2914
TSIOBufferReader TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp);
2915
2916
/**
2917
 * @brief Get the client error received from the transaction
2918
 *
2919
 * @param txnp The transaction where the error code is stored
2920
 * @param error_class Either session/connection or stream/transaction error
2921
 * @param error_code Error code received from the client
2922
 */
2923
void TSHttpTxnClientReceivedErrorGet(TSHttpTxn txnp, uint32_t *error_class, uint64_t *error_code);
2924
2925
/**
2926
 * @brief Get the client error sent from the transaction
2927
 *
2928
 * @param txnp The transaction where the error code is stored
2929
 * @param error_class Either session/connection or stream/transaction error
2930
 * @param error_code Error code sent to the client
2931
 */
2932
void TSHttpTxnClientSentErrorGet(TSHttpTxn txnp, uint32_t *error_class, uint64_t *error_code);
2933
2934
/**
2935
 * @brief Get the server error received from the transaction
2936
 *
2937
 * @param txnp The transaction where the error code is stored
2938
 * @param error_class Either session/connection or stream/transaction error
2939
 * @param error_code Error code sent from the server
2940
 */
2941
void TSHttpTxnServerReceivedErrorGet(TSHttpTxn txnp, uint32_t *error_class, uint64_t *error_code);
2942
2943
/**
2944
 * @brief Get the server error sent from the transaction
2945
 *
2946
 * @param txnp The transaction where the error code is stored
2947
 * @param error_class Either session/connection or stream/transaction error
2948
 * @param error_code Error code sent to the server
2949
 */
2950
void TSHttpTxnServerSentErrorGet(TSHttpTxn txnp, uint32_t *error_class, uint64_t *error_code);
2951
2952
/**
2953
 * Initiate an HTTP/2 Server Push preload request.
2954
 * Use this api to register a URL that you want to preload with HTTP/2 Server Push.
2955
 *
2956
 * @param url the URL string to preload.
2957
 * @param url_len the length of the URL string.
2958
 */
2959
TSReturnCode TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len);
2960
2961
/** Retrieve the client side stream id for the stream of which the
2962
 * provided transaction is a part.
2963
 *
2964
 * @param[in] txnp The Transaction for which the stream id should be retrieved.
2965
 * @param[out] stream_id The stream id for this transaction.
2966
 *
2967
 * @return TS_ERROR if a stream id cannot be retrieved for the given
2968
 * transaction given its protocol. For instance, if txnp is an HTTP/1.1
2969
 * transaction, then a TS_ERROR will be returned because HTTP/1.1 does not
2970
 * implement streams.
2971
 */
2972
TSReturnCode TSHttpTxnClientStreamIdGet(TSHttpTxn txnp, uint64_t *stream_id);
2973
2974
/** Retrieve the client side priority for the stream of which the
2975
 * provided transaction is a part.
2976
 *
2977
 * @param[in] txnp The Transaction for which the stream id should be retrieved.
2978
 * @param[out] priority The priority for the stream in this transaction.
2979
 *
2980
 * @return TS_ERROR if a priority cannot be retrieved for the given
2981
 * transaction given its protocol. For instance, if txnp is an HTTP/1.1
2982
 * transaction, then a TS_ERROR will be returned because HTTP/1.1 does not
2983
 * implement stream priorities.
2984
 */
2985
TSReturnCode TSHttpTxnClientStreamPriorityGet(TSHttpTxn txnp, TSHttpPriority *priority);
2986
2987
/*
2988
 * Returns TS_SUCCESS if hostname is this machine, as used for parent and remap self-detection.
2989
 * Returns TS_ERROR if hostname is not this machine.
2990
 */
2991
TSReturnCode TSHostnameIsSelf(const char *hostname, size_t hostname_len);
2992
2993
/*
2994
 * Gets the status of hostname in the outparam status, and the status reason in the outparam reason.
2995
 * The reason is a logical-or combination of the reasons in TSHostStatusReason.
2996
 * If either outparam is null, it will not be set and no error will be returned.
2997
 * Returns TS_SUCCESS if the hostname was a parent and existed in the HostStatus, else TS_ERROR.
2998
 */
2999
TSReturnCode TSHostStatusGet(const char *hostname, const size_t hostname_len, TSHostStatus *status, unsigned int *reason);
3000
3001
/*
3002
 * Sets the status of hostname in status, down_time, and reason.
3003
 * The reason is a logical-or combination of the reasons in TSHostStatusReason.
3004
 */
3005
void TSHostStatusSet(const char *hostname, const size_t hostname_len, TSHostStatus status, const unsigned int down_time,
3006
                     const unsigned int reason);
3007
3008
/**
3009
 * Add one or more IP addresses or CIDR ranges to the per-client connection limit exempt list.
3010
 * This function allows plugins to programmatically add to the list of IP addresses
3011
 * that should be exempt from per-client connection limits (see
3012
 * proxy.config.net.per_client.max_connections_in).
3013
 *
3014
 * @param ip_ranges The IP address or CIDR range to exempt, or a comma-separated list of ranges.
3015
 * @return TS_SUCCESS if the exempt list was successfully updated, TS_ERROR otherwise.
3016
 */
3017
TSReturnCode TSConnectionLimitExemptListAdd(std::string_view ip_ranges);
3018
3019
/**
3020
 * Remove one or more IP addresses or CIDR ranges from the per-client connection limit exempt list.
3021
 * This function allows plugins to programmatically remove from the list of IP addresses
3022
 * that should be exempt from per-client connection limits (see
3023
 * proxy.config.net.per_client.max_connections_in).
3024
 *
3025
 * @param ip_ranges The IP address or CIDR range to remove, or a comma-separated list of ranges.
3026
 * @return TS_SUCCESS if the exempt list was successfully updated, TS_ERROR otherwise.
3027
 */
3028
TSReturnCode TSConnectionLimitExemptListRemove(std::string_view ip_ranges);
3029
3030
/**
3031
 * Clear the per-client connection limit exempt list.
3032
 * This function allows plugins to programmatically clear the list of IP addresses
3033
 * that should be exempt from per-client connection limits (see
3034
 * proxy.config.net.per_client.max_connections_in).
3035
 */
3036
void TSConnectionLimitExemptListClear();
3037
3038
/*
3039
 * Set or get various HTTP Transaction control settings.
3040
 */
3041
bool         TSHttpTxnCntlGet(TSHttpTxn txnp, TSHttpCntlType ctrl);
3042
TSReturnCode TSHttpTxnCntlSet(TSHttpTxn txnp, TSHttpCntlType ctrl, bool data);
3043
3044
/**
3045
 * JSONRPC callback signature for method calls.
3046
 */
3047
using TSRPCMethodCb = void (*)(const char *id, TSYaml params);
3048
/**
3049
 * JSONRPC callback signature for notification calls
3050
 */
3051
using TSRPCNotificationCb = void (*)(TSYaml params);
3052
3053
/**
3054
 * @brief Method to perform a registration and validation when a plugin is expected to handle JSONRPC calls.
3055
 *
3056
 * @note YAMLCPP The JSONRPC library will only provide binary compatibility within the life-span of a major release. Plugins must
3057
 * check-in if they intent to handle RPC commands, passing their yamlcpp library version this function will validate it against
3058
 * the one used internally in TS.
3059
 *
3060
 * @param provider_name The name of the provider.
3061
 * @param provider_len The length of the provider string.
3062
 * @param yamlcpp_lib_version a string with the yamlcpp library version.
3063
 * @param yamlcpp_lib_len The length of the yamlcpp_lib_len string.
3064
 * @return A new TSRPCProviderHandle, nullptr if the yamlcpp_lib_version was not set, or the yamlcpp version does not match with
3065
 * the one used internally in TS. The returned TSRPCProviderHandle will be set with the provider's name. The caller should pass
3066
 * the returned TSRPCProviderHandle object to each subsequent TSRPCRegisterMethod/Notification* call.
3067
 */
3068
TSRPCProviderHandle TSRPCRegister(const char *provider_name, size_t provider_len, const char *yamlcpp_lib_version,
3069
                                  size_t yamlcpp_lib_len);
3070
3071
/**
3072
 * @brief Add new registered method handler to the JSON RPC engine.
3073
 *
3074
 * @param name Call name to be exposed by the RPC Engine, this should match the incoming request. i.e: If you register 'get_stats'
3075
 *             then the incoming jsonrpc call should have this very same name in the 'method' field. .. {...'method':
3076
 *             'get_stats'...} .
3077
 * @param name_len The length of the name string.
3078
 * @param callback  The function to be registered. See @c TSRPCMethodCb
3079
 * @param info TSRPCProviderHandle pointer, this will be used to provide more context information about this call. This object
3080
 * ideally should be the one returned by the TSRPCRegister API.
3081
 * @param opt Pointer to @c TSRPCHandlerOptions object. This will be used to store specifics about a particular call, the rpc
3082
 *            manager will use this object to perform certain actions. A copy of this object wil be stored by the rpc manager.
3083
 *
3084
 * @return TS_SUCCESS if the handler was successfully registered, TS_ERROR if the handler is already registered.
3085
 */
3086
TSReturnCode TSRPCRegisterMethodHandler(const char *name, size_t name_len, TSRPCMethodCb callback, TSRPCProviderHandle info,
3087
                                        const TSRPCHandlerOptions *opt);
3088
3089
/**
3090
 * @brief Add new registered notification handler to the JSON RPC engine.
3091
 *
3092
 * @param name Call name to be exposed by the RPC Engine, this should match the incoming request. i.e: If you register 'get_stats'
3093
 *             then the incoming jsonrpc call should have this very same name in the 'method' field. .. {...'method':
3094
 *             'get_stats'...} .
3095
 * @param name_len The length of the name string.
3096
 * @param callback  The function to be registered. See @c TSRPCNotificationCb
3097
 * @param info TSRPCProviderHandle pointer, this will be used to provide more description for instance, when logging before or
3098
 * after a call. This object ideally should be the one returned by the TSRPCRegister API.
3099
 * @param opt Pointer to @c TSRPCHandlerOptions object. This will be used to store specifics about a particular call, the rpc
3100
 *            manager will use this object to perform certain actions. A copy of this object wil be stored by the rpc manager.
3101
 * @return TS_SUCCESS if the handler was successfully registered, TS_ERROR if the handler is already registered.
3102
 */
3103
TSReturnCode TSRPCRegisterNotificationHandler(const char *name, size_t name_len, TSRPCNotificationCb callback,
3104
                                              TSRPCProviderHandle info, const TSRPCHandlerOptions *opt);
3105
3106
/**
3107
 * @brief Function to notify the JSONRPC engine that the current handler is done working.
3108
 *
3109
 * This function must be used when implementing a 'method' rpc handler. Once the work is done and the response is ready to be sent
3110
 * back to the client, this function should be called. Is expected to set the YAML node as response. If the response is empty a
3111
 * 'success' message will be added to the client's response.
3112
 *
3113
 * @note This should not be used if you registered your handler as a notification: @c TSRPCNotificationCb
3114
 * @param resp The YAML node that contains the call response.
3115
 * @return TS_SUCCESS if no issues. TS_ERROR otherwise.
3116
 */
3117
TSReturnCode TSRPCHandlerDone(TSYaml resp);
3118
3119
/**
3120
 * @brief Function to notify the JSONRPC engine that the current handler is done working and an error has arisen.
3121
 *
3122
 * @note This should not be used if you registered your handler as a notification: @c TSRPCNotificationCb
3123
 * call.
3124
 * @param code Error code.
3125
 * @param descr A text with a description of the error.
3126
 * @param descr_len The length of the description string.
3127
 * @note The @c code and @c descr will be part of the @c 'data' field in the jsonrpc error response.
3128
 * @return TS_SUCCESS if no issues. TS_ERROR otherwise.
3129
 */
3130
TSReturnCode TSRPCHandlerError(int code, const char *descr, size_t descr_len);
3131
3132
/** Do another cache lookup with a different cache key.
3133
 *
3134
 * @param txnp Transaction.
3135
 * @param url URL to use for cache key.
3136
 * @param length Length of the string in @a url
3137
 *
3138
 * @return @c TS_SUCCESS on success, @c TS_ERROR if the @a txnp is invalid or the @a url is
3139
 * not a valid URL.
3140
 *
3141
 * If @a length is negative, @c strlen will be used to determine the length of @a url.
3142
 *
3143
 * @a url must be syntactically a URL, but otherwise it is just a string and does not need to
3144
 * be retrievable.
3145
 *
3146
 * This can only be called in a @c TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK callback. To set the cache
3147
 * key for the first lookup, use @c TSCacheUrlSet.
3148
 *
3149
 * @see TSCacheUrlSet
3150
 */
3151
TSReturnCode TSHttpTxnRedoCacheLookup(TSHttpTxn txnp, const char *url, int length);
3152
3153
/* IP addr parsing. This is a candidate for deprecation in v10.0.0, in favor of libswoc */
3154
TSReturnCode TSIpStringToAddr(const char *str, size_t str_len, struct sockaddr *addr);
3155
3156
/**
3157
 * Return information about the type of the transaction. Is it a tunnel transaction or fully parsed?
3158
 * If tunneled is it due to parse failures and TR_PASS or is it due to an explicit configuration.
3159
 *
3160
 * @param[in] txnp The Transaction for which the type should be retrieved.
3161
 *
3162
 * @return enun value of type TSTxnType
3163
 */
3164
TSTxnType TSHttpTxnTypeGet(TSHttpTxn txnp);
3165
3166
TSReturnCode TSHttpTxnVerifiedAddrSet(TSHttpTxn txnp, const struct sockaddr *addr);
3167
3168
TSReturnCode TSHttpTxnVerifiedAddrGet(TSHttpTxn txnp, const struct sockaddr **addr);
3169
3170
/* Get Arbitrary Txn info such as cache lookup details etc as defined in TSHttpTxnInfoKey */
3171
/**
3172
   Return the particular txn info requested.
3173
3174
   @param txnp the transaction pointer
3175
   @param key the requested txn info.
3176
   @param TSMgmtInt a pointer to a integer where the return value is stored
3177
3178
   @return @c TS_SUCCESS if the requested info is supported, TS_ERROR otherwise
3179
3180
*/
3181
TSReturnCode TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value);
3182
3183
/* Get Arbitrary Ssn info such as total transaction count etc as defined in TSHttpSsnInfoKey */
3184
/**
3185
   Return the particular ssn info requested.
3186
3187
   @param ssnp the transaction pointer
3188
   @param key the requested ssn info.
3189
   @param TSMgmtInt a pointer to a integer where the return value is stored
3190
3191
   @return @c TS_SUCCESS if the requested info is supported, TS_ERROR otherwise
3192
3193
*/
3194
TSReturnCode TSHttpSsnInfoIntGet(TSHttpSsn ssnp, TSHttpSsnInfoKey key, TSMgmtInt *value, uint64_t sub_key = 0);
3195
3196
/****************************************************************************
3197
 *  TSHttpTxnCacheLookupCountGet
3198
 *  Return: TS_SUCCESS/TS_ERROR
3199
 ****************************************************************************/
3200
TSReturnCode TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count);
3201
TSReturnCode TSHttpTxnServerRespIgnore(TSHttpTxn txnp);
3202
TSReturnCode TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event);
3203
TSReturnCode TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close);
3204
3205
int          TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp);
3206
TSReturnCode TSHttpTxnUpdateCachedObject(TSHttpTxn txnp);
3207
3208
/**
3209
  Opens a network connection to the host specified by the 'to' sockaddr
3210
  spoofing the client addr to equal the 'from' sockaddr.
3211
  If the connection is successfully opened, contp
3212
  is called back with the event TS_EVENT_NET_CONNECT and the new
3213
  network vconnection will be passed in the event data parameter.
3214
  If the connection is not successful, contp is called back with
3215
  the event TS_EVENT_NET_CONNECT_FAILED.
3216
3217
  Note: It is possible to receive TS_EVENT_NET_CONNECT
3218
  even if the connection failed, because of the implementation of
3219
  network sockets in the underlying operating system. There is an
3220
  exception: if a plugin tries to open a connection to a port on
3221
  its own host machine, then TS_EVENT_NET_CONNECT is sent only
3222
  if the connection is successfully opened. In general, however,
3223
  your plugin needs to look for an TS_EVENT_VCONN_WRITE_READY to
3224
  be sure that the connection is successfully opened.
3225
3226
  @return TSAction which allows you to check if the connection is complete,
3227
    or cancel the attempt to connect.
3228
3229
*/
3230
TSAction TSNetConnectTransparent(
3231
  TSCont                 contp, /**< continuation that is called back when the attempted net connection either succeeds or fails. */
3232
  struct sockaddr const *from,  /**< Address to spoof as connection origin */
3233
  struct sockaddr const *to     /**< Address to which to connect. */
3234
);
3235
3236
/**
3237
  Allocates contiguous, aligned, raw (no construction) memory for a given number number of instances of type T.
3238
3239
  @return Pointer to raw (in spite of pointer type) memory for first instance.
3240
*/
3241
template <typename T>
3242
T *
3243
TSRalloc(size_t count = 1 /**< Number of instances of T to allocate storage for. */
3244
)
3245
{
3246
  return static_cast<std::remove_cv_t<T> *>(TSmalloc(count * sizeof(T)));
3247
}
3248
3249
/**
3250
   Return the particular PROXY protocol info requested.
3251
3252
   @param vconn the vconection pointer
3253
   @param key the requested PROXY protocol info. One of TSVConnPPInfoKey or TLV type ID
3254
   @param value a pointer to a const char pointer where the return value is stored
3255
   @param length a pointer to a integer where the length of return value is stored
3256
3257
   @return @c TS_SUCCESS if the requested info is supported, TS_ERROR otherwise
3258
3259
*/
3260
TSReturnCode TSVConnPPInfoGet(TSVConn vconn, uint16_t key, const char **value, int *length);
3261
3262
/**
3263
   Return the particular PROXY protocol info requested.
3264
3265
   @param vconn the vconection pointer
3266
   @param key the requested PROXY protocol info. One of TSVConnPPInfoKey or TLV type ID
3267
   @param value a pointer to a integer where the return value is stored
3268
3269
   @return @c TS_SUCCESS if the requested info is supported, TS_ERROR otherwise
3270
3271
*/
3272
TSReturnCode TSVConnPPInfoIntGet(TSVConn vconn, uint16_t key, TSMgmtInt *value);
3273
3274
/**
3275
   Registers a custom log field, or modifies an existing log field with a new definition.
3276
3277
   @param name a human friendly name
3278
   @param symbol a symbol to use on the config file
3279
   @param type a type of the new log field
3280
   @param marshal_cb a callback function to marshal log  value
3281
   @param unmarshal_cb a callback function to unmarshal log value
3282
   @param replace a flag to allow replacing an existing log field
3283
3284
   @return @c TS_SCCESS if the registration successes, TS_ERROR otherwise
3285
*/
3286
TSReturnCode TSLogFieldRegister(std::string_view name, std::string_view symbol, TSLogType type, TSLogMarshalCallback marshal_cb,
3287
                                TSLogUnmarshalCallback unmarshal_cb, bool replace = false);
3288
/**
3289
   Helper function to marshal a string
3290
*/
3291
int TSLogStringMarshal(char *buf, std::string_view str);
3292
3293
/**
3294
   Helper function to marshal an integer
3295
*/
3296
int TSLogIntMarshal(char *buf, int64_t value);
3297
3298
/**
3299
   Helper function to marshal an address
3300
*/
3301
int TSLogAddrMarshal(char *buf, sockaddr *addr);
3302
3303
/**
3304
   Helper function to unmarshal a string
3305
*/
3306
std::tuple<int, int> TSLogStringUnmarshal(char **buf, char *dest, int len);
3307
3308
/**
3309
   Helper function to unmarshal an integer
3310
*/
3311
std::tuple<int, int> TSLogIntUnmarshal(char **buf, char *dest, int len);
3312
3313
/**
3314
   Helper function to unmarshal an address
3315
*/
3316
std::tuple<int, int> TSLogAddrUnmarshal(char **buf, char *dest, int len);