summaryrefslogtreecommitdiff
path: root/qpid/cpp/src/qpid/broker/amqp/Translation.cpp
blob: d4b3f555b2371883c3dbb0f046d67e96ac36c6ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
#include "qpid/broker/amqp/Translation.h"
#include "qpid/broker/amqp/Outgoing.h"
#include "qpid/broker/amqp_0_10/MessageTransfer.h"
#include "qpid/broker/Broker.h"
#include "qpid/amqp/Decoder.h"
#include "qpid/amqp/descriptors.h"
#include "qpid/amqp/MessageEncoder.h"
#include "qpid/amqp_0_10/Codecs.h"
#include "qpid/types/Variant.h"
#include "qpid/types/encodings.h"
#include "qpid/framing/MessageTransferBody.h"
#include "qpid/log/Statement.h"
#include <boost/lexical_cast.hpp>

namespace qpid {
namespace broker {
namespace amqp {
namespace {

const std::string EMPTY;
const std::string FORWARD_SLASH("/");
const std::string TEXT_PLAIN("text/plain");
const std::string SUBJECT_KEY("qpid.subject");
const std::string APP_ID("x-amqp-0-10.app-id");

qpid::framing::ReplyTo translate(const std::string address, Broker* broker)
{
    size_t i = address.find(FORWARD_SLASH);
    if (i == std::string::npos) {
        //is it a queue or an exchange?
        if (broker && broker->getQueues().find(address)) {
            return qpid::framing::ReplyTo(EMPTY, address);
        } else if (broker && broker->getExchanges().find(address)) {
            return qpid::framing::ReplyTo(address, EMPTY);
        } else {
            return qpid::framing::ReplyTo();
        }
    } else {
        return qpid::framing::ReplyTo(i > 0 ? address.substr(0, i) : EMPTY, (i+1) < address.size() ? address.substr(i+1) : EMPTY);
    }
}
std::string translate(const qpid::framing::ReplyTo r)
{
    if (r.getExchange().size()) {
        if (r.getRoutingKey().size()) return r.getExchange() + FORWARD_SLASH + r.getRoutingKey();
        else return r.getExchange();
    } else return r.getRoutingKey();
}
std::string translate(const qpid::amqp::CharSequence& chars)
{
    if (chars.data && chars.size) return std::string(chars.data, chars.size);
    else return EMPTY;
}
bool setMessageId(qpid::framing::MessageProperties& m, const qpid::amqp::CharSequence& chars)
{
    if (chars.data && chars.size) {
        if (chars.size == 16) {
            m.setMessageId(qpid::framing::Uuid(chars.data));
            return true;
        } else {
            std::istringstream in(translate(chars));
            qpid::framing::Uuid uuid;
            in >> uuid;
            if (!in.fail()) {
                m.setMessageId(uuid);
                return true;
            }
        }
    }
    return false;
}
class Properties_0_10 : public qpid::amqp::MessageEncoder::Properties
{
  public:
    bool hasMessageId() const { return messageProperties && messageProperties->hasMessageId(); }
    std::string getMessageId() const { return messageProperties ? messageProperties->getMessageId().str() : EMPTY; }
    bool hasUserId() const { return messageProperties && messageProperties->hasUserId(); }
    std::string getUserId() const { return messageProperties ? messageProperties->getUserId() : EMPTY; }
    bool hasTo() const { return getDestination().size() || hasSubject(); }
    std::string getTo() const { return  getDestination().size() ? getDestination() : getSubject(); }
    bool hasSubject() const
    {
        if (getDestination().empty()) {
            return getApplicationProperties().isSet(SUBJECT_KEY);
        } else {
            return deliveryProperties && deliveryProperties->hasRoutingKey();
        }
    }
    std::string getSubject() const
    {
        if (getDestination().empty()) {
            //message was sent to default exchange, routing key is the queue name
            return getApplicationProperties().getAsString(SUBJECT_KEY);
        } else if (deliveryProperties) {
            return deliveryProperties->getRoutingKey();
        } else {
            return EMPTY;
        }
    }
    bool hasReplyTo() const { return messageProperties && messageProperties->hasReplyTo(); }
    std::string getReplyTo() const { return messageProperties ? translate(messageProperties->getReplyTo()) : EMPTY; }
    bool hasCorrelationId() const { return messageProperties && messageProperties->hasCorrelationId(); }
    std::string getCorrelationId() const { return messageProperties ? messageProperties->getCorrelationId() : EMPTY; }
    bool hasContentType() const { return messageProperties && messageProperties->hasContentType(); }
    std::string getContentType() const { return messageProperties ? messageProperties->getContentType() : EMPTY; }
    bool hasContentEncoding() const { return messageProperties && messageProperties->hasContentEncoding(); }
    std::string getContentEncoding() const { return messageProperties ? messageProperties->getContentEncoding() : EMPTY; }
    bool hasAbsoluteExpiryTime() const { return deliveryProperties && deliveryProperties->hasExpiration(); }
    int64_t getAbsoluteExpiryTime() const { return deliveryProperties ? deliveryProperties->getExpiration() : 0; }
    bool hasCreationTime() const { return false; }
    int64_t getCreationTime() const { return 0; }
    bool hasGroupId() const {return false; }
    std::string getGroupId() const { return EMPTY; }
    bool hasGroupSequence() const { return false; }
    uint32_t getGroupSequence() const { return 0; }
    bool hasReplyToGroupId() const { return false; }
    std::string getReplyToGroupId() const { return EMPTY; }

    const qpid::framing::FieldTable& getApplicationProperties() const { return messageProperties->getApplicationHeaders(); }
    Properties_0_10(const qpid::broker::amqp_0_10::MessageTransfer& t) : transfer(t),
                                                                         messageProperties(transfer.getProperties<qpid::framing::MessageProperties>()),
                                                                         deliveryProperties(transfer.getProperties<qpid::framing::DeliveryProperties>())
    {}
  private:
    const qpid::broker::amqp_0_10::MessageTransfer& transfer;
    const qpid::framing::MessageProperties* messageProperties;
    const qpid::framing::DeliveryProperties* deliveryProperties;

    std::string getDestination() const
    {
        return transfer.getMethod<qpid::framing::MessageTransferBody>()->getDestination();
    }
};
}

Translation::Translation(const qpid::broker::Message& m, Broker* b) : original(m), broker(b) {}

boost::intrusive_ptr<const qpid::broker::amqp_0_10::MessageTransfer> Translation::getTransfer()
{
    boost::intrusive_ptr<const qpid::broker::amqp_0_10::MessageTransfer> t =
        boost::intrusive_ptr<const qpid::broker::amqp_0_10::MessageTransfer>(dynamic_cast<const qpid::broker::amqp_0_10::MessageTransfer*>(&original.getEncoding()));
    if (t) {
        return t;//no translation required
    } else {
        const Message* message = dynamic_cast<const Message*>(&original.getEncoding());
        if (message) {
            //translate 1.0 message into 0-10
            boost::intrusive_ptr<qpid::broker::amqp_0_10::MessageTransfer> transfer(new qpid::broker::amqp_0_10::MessageTransfer());
            qpid::framing::AMQFrame method((qpid::framing::MessageTransferBody(qpid::framing::ProtocolVersion(), EMPTY, 0, 0)));
            qpid::framing::AMQFrame header((qpid::framing::AMQHeaderBody()));
            qpid::framing::AMQFrame content((qpid::framing::AMQContentBody()));
            method.setEof(false);
            header.setBof(false);
            header.setEof(false);
            content.setBof(false);

            transfer->getFrames().append(method);
            transfer->getFrames().append(header);

            qpid::framing::MessageProperties* props =
                transfer->getFrames().getHeaders()->get<qpid::framing::MessageProperties>(true);

            if (message->isTypedBody()) {
                qpid::types::Variant body = message->getTypedBody();
                std::string& data = content.castBody<qpid::framing::AMQContentBody>()->getData();
                if (body.getType() == qpid::types::VAR_MAP) {
                    qpid::amqp_0_10::MapCodec::encode(body.asMap(), data);
                    props->setContentType(qpid::amqp_0_10::MapCodec::contentType);
                } else if (body.getType() == qpid::types::VAR_LIST) {
                    qpid::amqp_0_10::ListCodec::encode(body.asList(), data);
                    props->setContentType(qpid::amqp_0_10::ListCodec::contentType);
                } else if (body.getType() == qpid::types::VAR_STRING) {
                    data = body.getString();
                    if (body.getEncoding() == qpid::types::encodings::UTF8 || body.getEncoding() == qpid::types::encodings::ASCII) {
                        props->setContentType(TEXT_PLAIN);
                    }
                } else {
                    qpid::types::Variant::List container;
                    container.push_back(body);
                    qpid::amqp_0_10::ListCodec::encode(container, data);
                    props->setContentType(qpid::amqp_0_10::ListCodec::contentType);
                }
                transfer->getFrames().append(content);
                props->setContentLength(data.size());
            } else {
                qpid::amqp::CharSequence body = message->getBody();
                content.castBody<qpid::framing::AMQContentBody>()->getData().assign(body.data, body.size);
                transfer->getFrames().append(content);

                props->setContentLength(body.size);
            }

            qpid::amqp::MessageId mid = message->getMessageId();
            qpid::framing::Uuid uuid;
            switch (mid.type) {
              case qpid::amqp::MessageId::NONE:
                break;
              case qpid::amqp::MessageId::UUID:
              case qpid::amqp::MessageId::BYTES:
                if (mid.value.bytes.size == 0) break;
                if (setMessageId(*props, mid.value.bytes)) break;
              case qpid::amqp::MessageId::ULONG:
                QPID_LOG(info, "Skipping message id in translation from 1.0 to 0-10 as it is not a UUID");
                break;
            }

            qpid::amqp::MessageId cid = message->getCorrelationId();
            switch (cid.type) {
              case qpid::amqp::MessageId::NONE:
                break;
              case qpid::amqp::MessageId::UUID:
                assert(cid.value.bytes.size = 16);
                props->setCorrelationId(qpid::framing::Uuid(cid.value.bytes.data).str());
                break;
              case qpid::amqp::MessageId::BYTES:
                if (cid.value.bytes.size) {
                    props->setCorrelationId(translate(cid.value.bytes));
                }
                break;
              case qpid::amqp::MessageId::ULONG:
                props->setCorrelationId(boost::lexical_cast<std::string>(cid.value.ulong));
                break;
            }
            if (message->getReplyToAsCharSequence()) props->setReplyTo(translate(message->getReplyTo(), broker));
            if (message->getContentType()) props->setContentType(translate(message->getContentType()));
            if (message->getContentEncoding()) props->setContentEncoding(translate(message->getContentEncoding()));
            props->setUserId(message->getUserId());
            // TODO: FieldTable applicationHeaders;
            qpid::amqp::CharSequence ap = message->getApplicationProperties();
            if (ap) {
                qpid::amqp::Decoder d(ap.data, ap.size);
                qpid::amqp_0_10::translate(d.readMap(), props->getApplicationHeaders());
                std::string appid = props->getApplicationHeaders().getAsString(APP_ID);
                if (!appid.empty()) {
                    props->setAppId(appid);
                }
            }

            qpid::framing::DeliveryProperties* dp =
                transfer->getFrames().getHeaders()->get<qpid::framing::DeliveryProperties>(true);
            dp->setPriority(message->getPriority());
            if (message->isPersistent()) dp->setDeliveryMode(2);
            if (message->getRoutingKey().size()) {
                if (message->getRoutingKey().size() > std::numeric_limits<uint8_t>::max()) {
                    //have to truncate routing key as it is specified to be a str8
                    dp->setRoutingKey(message->getRoutingKey().substr(0,std::numeric_limits<uint8_t>::max()));
                } else {
                    dp->setRoutingKey(message->getRoutingKey());
                }
                props->getApplicationHeaders().setString(SUBJECT_KEY, message->getRoutingKey());
            }

            return transfer.get();
        } else {
            throw qpid::Exception("Could not write message data in AMQP 0-10 format");
        }
    }
}

void Translation::write(OutgoingFromQueue& out)
{
    const Message* message = dynamic_cast<const Message*>(original.getPersistentContext().get());
    //persistent context will contain any newly added annotations
    if (!message) message = dynamic_cast<const Message*>(&original.getEncoding());
    if (message) {
        //write annotations
        qpid::amqp::CharSequence deliveryAnnotations = message->getDeliveryAnnotations();
        qpid::amqp::CharSequence messageAnnotations = message->getMessageAnnotations();
        if (deliveryAnnotations.size) out.write(deliveryAnnotations.data, deliveryAnnotations.size);
        if (messageAnnotations.size) out.write(messageAnnotations.data, messageAnnotations.size);
        //write bare message
        qpid::amqp::CharSequence bareMessage = message->getBareMessage();
        if (bareMessage.size) out.write(bareMessage.data, bareMessage.size);
        //write footer:
        qpid::amqp::CharSequence footer = message->getFooter();
        if (footer.size) out.write(footer.data, footer.size);
    } else {
        const qpid::broker::amqp_0_10::MessageTransfer* transfer = dynamic_cast<const qpid::broker::amqp_0_10::MessageTransfer*>(&original.getEncoding());
        if (transfer) {
            Properties_0_10 properties(*transfer);
            qpid::types::Variant::Map applicationProperties;
            qpid::amqp_0_10::translate(properties.getApplicationProperties(), applicationProperties);
            if (properties.getContentType() == qpid::amqp_0_10::MapCodec::contentType) {
                qpid::types::Variant::Map content;
                qpid::amqp_0_10::MapCodec::decode(transfer->getContent(), content);
                size_t size = qpid::amqp::MessageEncoder::getEncodedSize(properties);
                size += qpid::amqp::MessageEncoder::getEncodedSize(applicationProperties, true) + 3;/*descriptor*/
                size += qpid::amqp::MessageEncoder::getEncodedSize(content, true) + 3/*descriptor*/;
                std::vector<char> buffer(size);
                qpid::amqp::MessageEncoder encoder(&buffer[0], buffer.size());
                encoder.writeProperties(properties);
                encoder.writeApplicationProperties(applicationProperties);
                encoder.writeMap(content, &qpid::amqp::message::AMQP_VALUE);
                out.write(&buffer[0], encoder.getPosition());
            } else if (properties.getContentType() == qpid::amqp_0_10::ListCodec::contentType) {
                qpid::types::Variant::List content;
                qpid::amqp_0_10::ListCodec::decode(transfer->getContent(), content);
                size_t size = qpid::amqp::MessageEncoder::getEncodedSize(properties);
                size += qpid::amqp::MessageEncoder::getEncodedSize(applicationProperties, true) + 3;/*descriptor*/
                size += qpid::amqp::MessageEncoder::getEncodedSize(content, true) + 3/*descriptor*/;
                std::vector<char> buffer(size);
                qpid::amqp::MessageEncoder encoder(&buffer[0], buffer.size());
                encoder.writeProperties(properties);
                encoder.writeApplicationProperties(applicationProperties);
                encoder.writeList(content, &qpid::amqp::message::AMQP_VALUE);
                out.write(&buffer[0], encoder.getPosition());
            } else {
                std::string content = transfer->getContent();
                size_t size = qpid::amqp::MessageEncoder::getEncodedSize(properties, applicationProperties, content);
                std::vector<char> buffer(size);
                qpid::amqp::MessageEncoder encoder(&buffer[0], buffer.size());
                encoder.writeProperties(properties);
                encoder.writeApplicationProperties(applicationProperties);
                if (content.size()) encoder.writeBinary(content, &qpid::amqp::message::DATA);
                out.write(&buffer[0], encoder.getPosition());
            }
        } else {
            QPID_LOG(error, "Could not write message data in AMQP 1.0 format");
        }
    }
}

}}} // namespace qpid::broker::amqp