1
2 /*
3 * Copyright (C) NGINX, Inc.
4 */
5
6 #include <nxt_router.h>
7 #include <nxt_http.h>
8
9
10 typedef struct {
11 nxt_http_status_t status;
12 nxt_str_t location;
13 } nxt_http_return_conf_t;
14
15
16 static nxt_http_action_t *nxt_http_return(nxt_task_t *task,
17 nxt_http_request_t *r, nxt_http_action_t *action);
18
19
20 static const nxt_http_request_state_t nxt_http_return_send_state;
21
22
23 nxt_int_t
nxt_http_return_init(nxt_mp_t * mp,nxt_http_action_t * action,nxt_http_action_conf_t * acf)24 nxt_http_return_init(nxt_mp_t *mp, nxt_http_action_t *action,
25 nxt_http_action_conf_t *acf)
26 {
27 nxt_str_t *loc;
28 nxt_uint_t encode;
29 nxt_http_return_conf_t *conf;
30
31 conf = nxt_mp_zget(mp, sizeof(nxt_http_return_conf_t));
32 if (nxt_slow_path(conf == NULL)) {
33 return NXT_ERROR;
34 }
35
36 action->handler = nxt_http_return;
37 action->u.conf = conf;
38
39 conf->status = nxt_conf_get_number(acf->ret);
40
41 if (acf->location.length > 0) {
42 if (nxt_is_complex_uri_encoded(acf->location.start,
43 acf->location.length))
44 {
45 loc = nxt_str_dup(mp, &conf->location, &acf->location);
46 if (nxt_slow_path(loc == NULL)) {
47 return NXT_ERROR;
48 }
49
50 } else {
51 loc = &conf->location;
52
53 encode = nxt_encode_complex_uri(NULL, acf->location.start,
54 acf->location.length);
55 loc->length = acf->location.length + encode * 2;
56
57 loc->start = nxt_mp_nget(mp, loc->length);
58 if (nxt_slow_path(loc->start == NULL)) {
59 return NXT_ERROR;
60 }
61
62 nxt_encode_complex_uri(loc->start, acf->location.start,
63 acf->location.length);
64 }
65 }
66
67 return NXT_OK;
68 }
69
70
71 nxt_http_action_t *
nxt_http_return(nxt_task_t * task,nxt_http_request_t * r,nxt_http_action_t * action)72 nxt_http_return(nxt_task_t *task, nxt_http_request_t *r,
73 nxt_http_action_t *action)
74 {
75 nxt_http_field_t *field;
76 nxt_http_return_conf_t *conf;
77
78 conf = action->u.conf;
79
80 nxt_debug(task, "http return: %d (loc: \"%V\")",
81 conf->status, &conf->location);
82
83 if (conf->status >= NXT_HTTP_BAD_REQUEST
84 && conf->status <= NXT_HTTP_SERVER_ERROR_MAX)
85 {
86 nxt_http_request_error(task, r, conf->status);
87 return NULL;
88 }
89
90 r->status = conf->status;
91 r->resp.content_length_n = 0;
92
93 if (conf->location.length > 0) {
94 field = nxt_list_zero_add(r->resp.fields);
95 if (nxt_slow_path(field == NULL)) {
96 nxt_http_request_error(task, r, NXT_HTTP_INTERNAL_SERVER_ERROR);
97 return NULL;
98 }
99
100 nxt_http_field_name_set(field, "Location");
101
102 field->value = conf->location.start;
103 field->value_length = conf->location.length;
104 }
105
106 r->state = &nxt_http_return_send_state;
107
108 nxt_http_request_header_send(task, r, NULL, NULL);
109
110 return NULL;
111 }
112
113
114 static const nxt_http_request_state_t nxt_http_return_send_state
115 nxt_aligned(64) =
116 {
117 .error_handler = nxt_http_request_error_handler,
118 };
119