e9acc9f759d22f8ee618a3bb1321f8d5cfcf3c6b
[cascardo/ovs.git] / datapath / conntrack.c
1 /*
2  * Copyright (c) 2015 Nicira, Inc.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * General Public License for more details.
12  */
13
14 #include <linux/kconfig.h>
15 #include <linux/version.h>
16
17 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
18
19 #include <linux/module.h>
20 #include <linux/openvswitch.h>
21 #include <net/ip.h>
22 #include <net/netfilter/nf_conntrack_core.h>
23 #include <net/netfilter/nf_conntrack_helper.h>
24 #include <net/netfilter/nf_conntrack_labels.h>
25 #include <net/netfilter/nf_conntrack_zones.h>
26 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
27
28 #include "datapath.h"
29 #include "conntrack.h"
30 #include "flow.h"
31 #include "flow_netlink.h"
32 #include "gso.h"
33
34 struct ovs_ct_len_tbl {
35         size_t maxlen;
36         size_t minlen;
37 };
38
39 /* Metadata mark for masked write to conntrack mark */
40 struct md_mark {
41         u32 value;
42         u32 mask;
43 };
44
45 /* Metadata label for masked write to conntrack label. */
46 struct md_labels {
47         struct ovs_key_ct_labels value;
48         struct ovs_key_ct_labels mask;
49 };
50
51 /* Conntrack action context for execution. */
52 struct ovs_conntrack_info {
53         struct nf_conntrack_helper *helper;
54         struct nf_conntrack_zone zone;
55         struct nf_conn *ct;
56         u8 commit : 1;
57         u16 family;
58         struct md_mark mark;
59         struct md_labels labels;
60 };
61
62 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
63
64 static u16 key_to_nfproto(const struct sw_flow_key *key)
65 {
66         switch (ntohs(key->eth.type)) {
67         case ETH_P_IP:
68                 return NFPROTO_IPV4;
69         case ETH_P_IPV6:
70                 return NFPROTO_IPV6;
71         default:
72                 return NFPROTO_UNSPEC;
73         }
74 }
75
76 /* Map SKB connection state into the values used by flow definition. */
77 static u8 ovs_ct_get_state(enum ip_conntrack_info ctinfo)
78 {
79         u8 ct_state = OVS_CS_F_TRACKED;
80
81         switch (ctinfo) {
82         case IP_CT_ESTABLISHED_REPLY:
83         case IP_CT_RELATED_REPLY:
84                 ct_state |= OVS_CS_F_REPLY_DIR;
85                 break;
86         default:
87                 break;
88         }
89
90         switch (ctinfo) {
91         case IP_CT_ESTABLISHED:
92         case IP_CT_ESTABLISHED_REPLY:
93                 ct_state |= OVS_CS_F_ESTABLISHED;
94                 break;
95         case IP_CT_RELATED:
96         case IP_CT_RELATED_REPLY:
97                 ct_state |= OVS_CS_F_RELATED;
98                 break;
99         case IP_CT_NEW:
100                 ct_state |= OVS_CS_F_NEW;
101                 break;
102         default:
103                 break;
104         }
105
106         return ct_state;
107 }
108
109 static u32 ovs_ct_get_mark(const struct nf_conn *ct)
110 {
111 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
112         return ct ? ct->mark : 0;
113 #else
114         return 0;
115 #endif
116 }
117
118 static void ovs_ct_get_labels(const struct nf_conn *ct,
119                               struct ovs_key_ct_labels *labels)
120 {
121         struct nf_conn_labels *cl = ct ? nf_ct_labels_find(ct) : NULL;
122
123         if (cl) {
124                 size_t len = cl->words * sizeof(long);
125
126                 if (len > OVS_CT_LABELS_LEN)
127                         len = OVS_CT_LABELS_LEN;
128                 else if (len < OVS_CT_LABELS_LEN)
129                         memset(labels, 0, OVS_CT_LABELS_LEN);
130                 memcpy(labels, cl->bits, len);
131         } else {
132                 memset(labels, 0, OVS_CT_LABELS_LEN);
133         }
134 }
135
136 static void __ovs_ct_update_key(struct sw_flow_key *key, u8 state,
137                                 const struct nf_conntrack_zone *zone,
138                                 const struct nf_conn *ct)
139 {
140         key->ct.state = state;
141         key->ct.zone = zone->id;
142         key->ct.mark = ovs_ct_get_mark(ct);
143         ovs_ct_get_labels(ct, &key->ct.labels);
144 }
145
146 /* Update 'key' based on skb->nfct. If 'post_ct' is true, then OVS has
147  * previously sent the packet to conntrack via the ct action.
148  */
149 static void ovs_ct_update_key(const struct sk_buff *skb,
150                               const struct ovs_conntrack_info *info,
151                               struct sw_flow_key *key, bool post_ct)
152 {
153         const struct nf_conntrack_zone *zone = &nf_ct_zone_dflt;
154         enum ip_conntrack_info ctinfo;
155         struct nf_conn *ct;
156         u8 state = 0;
157
158         ct = nf_ct_get(skb, &ctinfo);
159         if (ct) {
160                 state = ovs_ct_get_state(ctinfo);
161                 /* All unconfirmed entries are NEW connections. */
162                 if (!nf_ct_is_confirmed(ct))
163                         state |= OVS_CS_F_NEW;
164                 /* OVS persists the related flag for the duration of the
165                  * connection.
166                  */
167                 if (ct->master)
168                         state |= OVS_CS_F_RELATED;
169                 zone = nf_ct_zone(ct);
170         } else if (post_ct) {
171                 state = OVS_CS_F_TRACKED | OVS_CS_F_INVALID;
172                 if (info)
173                         zone = &info->zone;
174         }
175         __ovs_ct_update_key(key, state, zone, ct);
176 }
177
178 /* This is called to initialize CT key fields possibly coming in from the local
179  * stack.
180  */
181 void ovs_ct_fill_key(const struct sk_buff *skb, struct sw_flow_key *key)
182 {
183         ovs_ct_update_key(skb, NULL, key, false);
184 }
185
186 int ovs_ct_put_key(const struct sw_flow_key *key, struct sk_buff *skb)
187 {
188         if (nla_put_u32(skb, OVS_KEY_ATTR_CT_STATE, key->ct.state))
189                 return -EMSGSIZE;
190
191         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
192             nla_put_u16(skb, OVS_KEY_ATTR_CT_ZONE, key->ct.zone))
193                 return -EMSGSIZE;
194
195         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
196             nla_put_u32(skb, OVS_KEY_ATTR_CT_MARK, key->ct.mark))
197                 return -EMSGSIZE;
198
199         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
200             nla_put(skb, OVS_KEY_ATTR_CT_LABELS, sizeof(key->ct.labels),
201                     &key->ct.labels))
202                 return -EMSGSIZE;
203
204         return 0;
205 }
206
207 static int ovs_ct_set_mark(struct sk_buff *skb, struct sw_flow_key *key,
208                            u32 ct_mark, u32 mask)
209 {
210 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
211         enum ip_conntrack_info ctinfo;
212         struct nf_conn *ct;
213         u32 new_mark;
214
215         /* The connection could be invalid, in which case set_mark is no-op. */
216         ct = nf_ct_get(skb, &ctinfo);
217         if (!ct)
218                 return 0;
219
220         new_mark = ct_mark | (ct->mark & ~(mask));
221         if (ct->mark != new_mark) {
222                 ct->mark = new_mark;
223                 nf_conntrack_event_cache(IPCT_MARK, ct);
224                 key->ct.mark = new_mark;
225         }
226
227         return 0;
228 #else
229         return -ENOTSUPP;
230 #endif
231 }
232
233 static int ovs_ct_set_labels(struct sk_buff *skb, struct sw_flow_key *key,
234                              const struct ovs_key_ct_labels *labels,
235                              const struct ovs_key_ct_labels *mask)
236 {
237         enum ip_conntrack_info ctinfo;
238         struct nf_conn_labels *cl;
239         struct nf_conn *ct;
240         int err;
241
242         /* The connection could be invalid, in which case set_label is no-op.*/
243         ct = nf_ct_get(skb, &ctinfo);
244         if (!ct)
245                 return 0;
246
247         cl = nf_ct_labels_find(ct);
248         if (!cl) {
249                 nf_ct_labels_ext_add(ct);
250                 cl = nf_ct_labels_find(ct);
251         }
252         if (!cl || cl->words * sizeof(long) < OVS_CT_LABELS_LEN)
253                 return -ENOSPC;
254
255         err = nf_connlabels_replace(ct, (u32 *)labels, (u32 *)mask,
256                                     OVS_CT_LABELS_LEN / sizeof(u32));
257         if (err)
258                 return err;
259
260         ovs_ct_get_labels(ct, &key->ct.labels);
261         return 0;
262 }
263
264 /* 'skb' should already be pulled to nh_ofs. */
265 static int ovs_ct_helper(struct sk_buff *skb, u16 proto)
266 {
267         const struct nf_conntrack_helper *helper;
268         const struct nf_conn_help *help;
269         enum ip_conntrack_info ctinfo;
270         unsigned int protoff;
271         struct nf_conn *ct;
272
273         ct = nf_ct_get(skb, &ctinfo);
274         if (!ct || ctinfo == IP_CT_RELATED_REPLY)
275                 return NF_ACCEPT;
276
277         help = nfct_help(ct);
278         if (!help)
279                 return NF_ACCEPT;
280
281         helper = rcu_dereference(help->helper);
282         if (!helper)
283                 return NF_ACCEPT;
284
285         switch (proto) {
286         case NFPROTO_IPV4:
287                 protoff = ip_hdrlen(skb);
288                 break;
289         case NFPROTO_IPV6: {
290                 u8 nexthdr = ipv6_hdr(skb)->nexthdr;
291                 __be16 frag_off;
292                 int ofs;
293
294                 ofs = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr,
295                                        &frag_off);
296                 if (ofs < 0 || (frag_off & htons(~0x7)) != 0) {
297                         pr_debug("proto header not found\n");
298                         return NF_ACCEPT;
299                 }
300                 protoff = ofs;
301                 break;
302         }
303         default:
304                 WARN_ONCE(1, "helper invoked on non-IP family!");
305                 return NF_DROP;
306         }
307
308         return helper->help(skb, protoff, ct, ctinfo);
309 }
310
311 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
312  * value if 'skb' is freed.
313  */
314 static int handle_fragments(struct net *net, struct sw_flow_key *key,
315                             u16 zone, struct sk_buff *skb)
316 {
317         struct ovs_gso_cb ovs_cb = *OVS_GSO_CB(skb);
318         int err;
319
320         if (!skb->dev) {
321                 OVS_NLERR(true, "%s: skb has no dev; dropping", __func__);
322                 return -EINVAL;
323         }
324
325         if (key->eth.type == htons(ETH_P_IP)) {
326                 enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
327
328                 memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
329                 err = ip_defrag(net, skb, user);
330                 if (err)
331                         return err;
332
333                 ovs_cb.dp_cb.mru = IPCB(skb)->frag_max_size;
334 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
335         } else if (key->eth.type == htons(ETH_P_IPV6)) {
336                 enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
337
338                 skb_orphan(skb);
339                 memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
340                 err = nf_ct_frag6_gather(net, skb, user);
341                 if (err)
342                         return err;
343
344                 key->ip.proto = ipv6_hdr(skb)->nexthdr;
345                 ovs_cb.dp_cb.mru = IP6CB(skb)->frag_max_size;
346 #endif /* IP frag support */
347         } else {
348                 kfree_skb(skb);
349                 return -EPFNOSUPPORT;
350         }
351
352         key->ip.frag = OVS_FRAG_TYPE_NONE;
353         skb_clear_hash(skb);
354         skb->ignore_df = 1;
355         *OVS_GSO_CB(skb) = ovs_cb;
356
357         return 0;
358 }
359
360 static struct nf_conntrack_expect *
361 ovs_ct_expect_find(struct net *net, const struct nf_conntrack_zone *zone,
362                    u16 proto, const struct sk_buff *skb)
363 {
364         struct nf_conntrack_tuple tuple;
365
366         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), proto, net, &tuple))
367                 return NULL;
368         return __nf_ct_expect_find(net, zone, &tuple);
369 }
370
371 /* This replicates logic from nf_conntrack_core.c that is not exported. */
372 static enum ip_conntrack_info
373 ovs_ct_get_info(const struct nf_conntrack_tuple_hash *h)
374 {
375         const struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
376
377         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY)
378                 return IP_CT_ESTABLISHED_REPLY;
379         /* Once we've had two way comms, always ESTABLISHED. */
380         if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status))
381                 return IP_CT_ESTABLISHED;
382         if (test_bit(IPS_EXPECTED_BIT, &ct->status))
383                 return IP_CT_RELATED;
384         return IP_CT_NEW;
385 }
386
387 /* Find an existing connection which this packet belongs to without
388  * re-attributing statistics or modifying the connection state.  This allows an
389  * skb->nfct lost due to an upcall to be recovered during actions execution.
390  *
391  * Must be called with rcu_read_lock.
392  *
393  * On success, populates skb->nfct and skb->nfctinfo, and returns the
394  * connection.  Returns NULL if there is no existing entry.
395  */
396 static struct nf_conn *
397 ovs_ct_find_existing(struct net *net, const struct nf_conntrack_zone *zone,
398                      u8 l3num, struct sk_buff *skb)
399 {
400         struct nf_conntrack_l3proto *l3proto;
401         struct nf_conntrack_l4proto *l4proto;
402         struct nf_conntrack_tuple tuple;
403         struct nf_conntrack_tuple_hash *h;
404         enum ip_conntrack_info ctinfo;
405         struct nf_conn *ct;
406         unsigned int dataoff;
407         u8 protonum;
408
409         l3proto = __nf_ct_l3proto_find(l3num);
410         if (!l3proto) {
411                 pr_debug("ovs_ct_find_existing: Can't get l3proto\n");
412                 return NULL;
413         }
414         if (l3proto->get_l4proto(skb, skb_network_offset(skb), &dataoff,
415                                  &protonum) <= 0) {
416                 pr_debug("ovs_ct_find_existing: Can't get protonum\n");
417                 return NULL;
418         }
419         l4proto = __nf_ct_l4proto_find(l3num, protonum);
420         if (!l4proto) {
421                 pr_debug("ovs_ct_find_existing: Can't get l4proto\n");
422                 return NULL;
423         }
424         if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
425                              protonum, net, &tuple, l3proto, l4proto)) {
426                 pr_debug("ovs_ct_find_existing: Can't get tuple\n");
427                 return NULL;
428         }
429
430         /* look for tuple match */
431         h = nf_conntrack_find_get(net, zone, &tuple);
432         if (!h)
433                 return NULL;   /* Not found. */
434
435         ct = nf_ct_tuplehash_to_ctrack(h);
436
437         ctinfo = ovs_ct_get_info(h);
438         if (ctinfo == IP_CT_NEW) {
439                 /* This should not happen. */
440                 WARN_ONCE(1, "ovs_ct_find_existing: new packet for %p\n", ct);
441         }
442         skb->nfct = &ct->ct_general;
443         skb->nfctinfo = ctinfo;
444         return ct;
445 }
446
447 /* Determine whether skb->nfct is equal to the result of conntrack lookup. */
448 static bool skb_nfct_cached(struct net *net,
449                             const struct sw_flow_key *key,
450                             const struct ovs_conntrack_info *info,
451                             struct sk_buff *skb)
452 {
453         enum ip_conntrack_info ctinfo;
454         struct nf_conn *ct;
455
456         ct = nf_ct_get(skb, &ctinfo);
457         /* If no ct, check if we have evidence that an existing conntrack entry
458          * might be found for this skb.  This happens when we lose a skb->nfct
459          * due to an upcall.  If the connection was not confirmed, it is not
460          * cached and needs to be run through conntrack again.
461          */
462         if (!ct && key->ct.state & OVS_CS_F_TRACKED &&
463             !(key->ct.state & OVS_CS_F_INVALID) &&
464             key->ct.zone == info->zone.id)
465                 ct = ovs_ct_find_existing(net, &info->zone, info->family, skb);
466         if (!ct)
467                 return false;
468         if (!net_eq(net, read_pnet(&ct->ct_net)))
469                 return false;
470         if (!nf_ct_zone_equal_any(info->ct, nf_ct_zone(ct)))
471                 return false;
472         if (info->helper) {
473                 struct nf_conn_help *help;
474
475                 help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
476                 if (help && rcu_access_pointer(help->helper) != info->helper)
477                         return false;
478         }
479
480         return true;
481 }
482
483 /* Pass 'skb' through conntrack in 'net', using zone configured in 'info', if
484  * not done already.  Update key with new CT state after passing the packet
485  * through conntrack.
486  * Note that if the packet is deemed invalid by conntrack, skb->nfct will be
487  * set to NULL and 0 will be returned.
488  */
489 static int __ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
490                            const struct ovs_conntrack_info *info,
491                            struct sk_buff *skb)
492 {
493         /* If we are recirculating packets to match on conntrack fields and
494          * committing with a separate conntrack action,  then we don't need to
495          * actually run the packet through conntrack twice unless it's for a
496          * different zone.
497          */
498         if (!skb_nfct_cached(net, key, info, skb)) {
499                 struct nf_conn *tmpl = info->ct;
500
501                 /* Associate skb with specified zone. */
502                 if (tmpl) {
503                         if (skb->nfct)
504                                 nf_conntrack_put(skb->nfct);
505                         nf_conntrack_get(&tmpl->ct_general);
506                         skb->nfct = &tmpl->ct_general;
507                         skb->nfctinfo = IP_CT_NEW;
508                 }
509
510                 if (nf_conntrack_in(net, info->family, NF_INET_FORWARD,
511                                     skb) != NF_ACCEPT)
512                         return -ENOENT;
513
514                 ovs_ct_update_key(skb, info, key, true);
515
516                 if (ovs_ct_helper(skb, info->family) != NF_ACCEPT) {
517                         WARN_ONCE(1, "helper rejected packet");
518                         return -EINVAL;
519                 }
520         }
521
522         return 0;
523 }
524
525 /* Lookup connection and read fields into key. */
526 static int ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
527                          const struct ovs_conntrack_info *info,
528                          struct sk_buff *skb)
529 {
530         struct nf_conntrack_expect *exp;
531
532         /* If we pass an expected packet through nf_conntrack_in() the
533          * expectation is typically removed, but the packet could still be
534          * lost in upcall processing.  To prevent this from happening we
535          * perform an explicit expectation lookup.  Expected connections are
536          * always new, and will be passed through conntrack only when they are
537          * committed, as it is OK to remove the expectation at that time.
538          */
539         exp = ovs_ct_expect_find(net, &info->zone, info->family, skb);
540         if (exp) {
541                 u8 state;
542
543                 state = OVS_CS_F_TRACKED | OVS_CS_F_NEW | OVS_CS_F_RELATED;
544                 __ovs_ct_update_key(key, state, &info->zone, exp->master);
545         } else {
546                 int err;
547
548                 err = __ovs_ct_lookup(net, key, info, skb);
549                 if (err)
550                         return err;
551         }
552
553         return 0;
554 }
555
556 /* Lookup connection and confirm if unconfirmed. */
557 static int ovs_ct_commit(struct net *net, struct sw_flow_key *key,
558                          const struct ovs_conntrack_info *info,
559                          struct sk_buff *skb)
560 {
561         int err;
562
563         err = __ovs_ct_lookup(net, key, info, skb);
564         if (err)
565                 return err;
566         /* This is a no-op if the connection has already been confirmed. */
567         if (nf_conntrack_confirm(skb) != NF_ACCEPT)
568                 return -EINVAL;
569
570         return 0;
571 }
572
573 static bool labels_nonzero(const struct ovs_key_ct_labels *labels)
574 {
575         size_t i;
576
577         for (i = 0; i < sizeof(*labels); i++)
578                 if (labels->ct_labels[i])
579                         return true;
580
581         return false;
582 }
583
584 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
585  * value if 'skb' is freed.
586  */
587 int ovs_ct_execute(struct net *net, struct sk_buff *skb,
588                    struct sw_flow_key *key,
589                    const struct ovs_conntrack_info *info)
590 {
591         int nh_ofs;
592         int err;
593
594         /* The conntrack module expects to be working at L3. */
595         nh_ofs = skb_network_offset(skb);
596         skb_pull(skb, nh_ofs);
597
598         if (key->ip.frag != OVS_FRAG_TYPE_NONE) {
599                 err = handle_fragments(net, key, info->zone.id, skb);
600                 if (err)
601                         return err;
602         }
603
604         if (info->commit)
605                 err = ovs_ct_commit(net, key, info, skb);
606         else
607                 err = ovs_ct_lookup(net, key, info, skb);
608         if (err)
609                 goto err;
610
611         if (info->mark.mask) {
612                 err = ovs_ct_set_mark(skb, key, info->mark.value,
613                                       info->mark.mask);
614                 if (err)
615                         goto err;
616         }
617         if (labels_nonzero(&info->labels.mask))
618                 err = ovs_ct_set_labels(skb, key, &info->labels.value,
619                                         &info->labels.mask);
620 err:
621         skb_push(skb, nh_ofs);
622         if (err)
623                 kfree_skb(skb);
624         return err;
625 }
626
627 static int ovs_ct_add_helper(struct ovs_conntrack_info *info, const char *name,
628                              const struct sw_flow_key *key, bool log)
629 {
630         struct nf_conntrack_helper *helper;
631         struct nf_conn_help *help;
632
633         helper = nf_conntrack_helper_try_module_get(name, info->family,
634                                                     key->ip.proto);
635         if (!helper) {
636                 OVS_NLERR(log, "Unknown helper \"%s\"", name);
637                 return -EINVAL;
638         }
639
640         help = nf_ct_helper_ext_add(info->ct, helper, GFP_KERNEL);
641         if (!help) {
642                 module_put(helper->me);
643                 return -ENOMEM;
644         }
645
646         rcu_assign_pointer(help->helper, helper);
647         info->helper = helper;
648         return 0;
649 }
650
651 static const struct ovs_ct_len_tbl ovs_ct_attr_lens[OVS_CT_ATTR_MAX + 1] = {
652         [OVS_CT_ATTR_COMMIT]    = { .minlen = 0, .maxlen = 0 },
653         [OVS_CT_ATTR_ZONE]      = { .minlen = sizeof(u16),
654                                     .maxlen = sizeof(u16) },
655         [OVS_CT_ATTR_MARK]      = { .minlen = sizeof(struct md_mark),
656                                     .maxlen = sizeof(struct md_mark) },
657         [OVS_CT_ATTR_LABELS]    = { .minlen = sizeof(struct md_labels),
658                                     .maxlen = sizeof(struct md_labels) },
659         [OVS_CT_ATTR_HELPER]    = { .minlen = 1,
660                                     .maxlen = NF_CT_HELPER_NAME_LEN }
661 };
662
663 static int parse_ct(const struct nlattr *attr, struct ovs_conntrack_info *info,
664                     const char **helper, bool log)
665 {
666         struct nlattr *a;
667         int rem;
668
669         nla_for_each_nested(a, attr, rem) {
670                 int type = nla_type(a);
671                 int maxlen = ovs_ct_attr_lens[type].maxlen;
672                 int minlen = ovs_ct_attr_lens[type].minlen;
673
674                 if (type > OVS_CT_ATTR_MAX) {
675                         OVS_NLERR(log,
676                                   "Unknown conntrack attr (type=%d, max=%d)",
677                                   type, OVS_CT_ATTR_MAX);
678                         return -EINVAL;
679                 }
680                 if (nla_len(a) < minlen || nla_len(a) > maxlen) {
681                         OVS_NLERR(log,
682                                   "Conntrack attr type has unexpected length (type=%d, length=%d, expected=%d)",
683                                   type, nla_len(a), maxlen);
684                         return -EINVAL;
685                 }
686
687                 switch (type) {
688                 case OVS_CT_ATTR_COMMIT:
689                         info->commit = true;
690                         break;
691 #ifdef CONFIG_NF_CONNTRACK_ZONES
692                 case OVS_CT_ATTR_ZONE:
693                         info->zone.id = nla_get_u16(a);
694                         break;
695 #endif
696 #ifdef CONFIG_NF_CONNTRACK_MARK
697                 case OVS_CT_ATTR_MARK: {
698                         struct md_mark *mark = nla_data(a);
699
700                         if (!mark->mask) {
701                                 OVS_NLERR(log, "ct_mark mask cannot be 0");
702                                 return -EINVAL;
703                         }
704                         info->mark = *mark;
705                         break;
706                 }
707 #endif
708 #ifdef CONFIG_NF_CONNTRACK_LABELS
709                 case OVS_CT_ATTR_LABELS: {
710                         struct md_labels *labels = nla_data(a);
711
712                         if (!labels_nonzero(&labels->mask)) {
713                                 OVS_NLERR(log, "ct_labels mask cannot be 0");
714                                 return -EINVAL;
715                         }
716                         info->labels = *labels;
717                         break;
718                 }
719 #endif
720                 case OVS_CT_ATTR_HELPER:
721                         *helper = nla_data(a);
722                         if (!memchr(*helper, '\0', nla_len(a))) {
723                                 OVS_NLERR(log, "Invalid conntrack helper");
724                                 return -EINVAL;
725                         }
726                         break;
727                 default:
728                         OVS_NLERR(log, "Unknown conntrack attr (%d)",
729                                   type);
730                         return -EINVAL;
731                 }
732         }
733
734         if (rem > 0) {
735                 OVS_NLERR(log, "Conntrack attr has %d unknown bytes", rem);
736                 return -EINVAL;
737         }
738
739         return 0;
740 }
741
742 bool ovs_ct_verify(struct net *net, enum ovs_key_attr attr)
743 {
744         if (attr == OVS_KEY_ATTR_CT_STATE)
745                 return true;
746         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
747             attr == OVS_KEY_ATTR_CT_ZONE)
748                 return true;
749         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
750             attr == OVS_KEY_ATTR_CT_MARK)
751                 return true;
752         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
753             attr == OVS_KEY_ATTR_CT_LABELS) {
754                 struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
755
756                 return ovs_net->xt_label;
757         }
758
759         return false;
760 }
761
762 int ovs_ct_copy_action(struct net *net, const struct nlattr *attr,
763                        const struct sw_flow_key *key,
764                        struct sw_flow_actions **sfa,  bool log)
765 {
766         struct ovs_conntrack_info ct_info;
767         const char *helper = NULL;
768         u16 family;
769         int err;
770
771         family = key_to_nfproto(key);
772         if (family == NFPROTO_UNSPEC) {
773                 OVS_NLERR(log, "ct family unspecified");
774                 return -EINVAL;
775         }
776
777         memset(&ct_info, 0, sizeof(ct_info));
778         ct_info.family = family;
779
780         nf_ct_zone_init(&ct_info.zone, NF_CT_DEFAULT_ZONE_ID,
781                         NF_CT_DEFAULT_ZONE_DIR, 0);
782
783         err = parse_ct(attr, &ct_info, &helper, log);
784         if (err)
785                 return err;
786
787         /* Set up template for tracking connections in specific zones. */
788         ct_info.ct = nf_ct_tmpl_alloc(net, &ct_info.zone, GFP_KERNEL);
789         if (!ct_info.ct) {
790                 OVS_NLERR(log, "Failed to allocate conntrack template");
791                 return -ENOMEM;
792         }
793
794         __set_bit(IPS_CONFIRMED_BIT, &ct_info.ct->status);
795         nf_conntrack_get(&ct_info.ct->ct_general);
796
797         if (helper) {
798                 err = ovs_ct_add_helper(&ct_info, helper, key, log);
799                 if (err)
800                         goto err_free_ct;
801         }
802
803         err = ovs_nla_add_action(sfa, OVS_ACTION_ATTR_CT, &ct_info,
804                                  sizeof(ct_info), log);
805         if (err)
806                 goto err_free_ct;
807
808         return 0;
809 err_free_ct:
810         __ovs_ct_free_action(&ct_info);
811         return err;
812 }
813
814 int ovs_ct_action_to_attr(const struct ovs_conntrack_info *ct_info,
815                           struct sk_buff *skb)
816 {
817         struct nlattr *start;
818
819         start = nla_nest_start(skb, OVS_ACTION_ATTR_CT);
820         if (!start)
821                 return -EMSGSIZE;
822
823         if (ct_info->commit && nla_put_flag(skb, OVS_CT_ATTR_COMMIT))
824                 return -EMSGSIZE;
825         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
826             nla_put_u16(skb, OVS_CT_ATTR_ZONE, ct_info->zone.id))
827                 return -EMSGSIZE;
828         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) && ct_info->mark.mask &&
829             nla_put(skb, OVS_CT_ATTR_MARK, sizeof(ct_info->mark),
830                     &ct_info->mark))
831                 return -EMSGSIZE;
832         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
833             labels_nonzero(&ct_info->labels.mask) &&
834             nla_put(skb, OVS_CT_ATTR_LABELS, sizeof(ct_info->labels),
835                     &ct_info->labels))
836                 return -EMSGSIZE;
837         if (ct_info->helper) {
838                 if (nla_put_string(skb, OVS_CT_ATTR_HELPER,
839                                    ct_info->helper->name))
840                         return -EMSGSIZE;
841         }
842
843         nla_nest_end(skb, start);
844
845         return 0;
846 }
847
848 void ovs_ct_free_action(const struct nlattr *a)
849 {
850         struct ovs_conntrack_info *ct_info = nla_data(a);
851
852         __ovs_ct_free_action(ct_info);
853 }
854
855 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info)
856 {
857         if (ct_info->helper)
858                 module_put(ct_info->helper->me);
859         if (ct_info->ct)
860                 nf_ct_tmpl_free(ct_info->ct);
861 }
862
863 void ovs_ct_init(struct net *net)
864 {
865         unsigned int n_bits = sizeof(struct ovs_key_ct_labels) * BITS_PER_BYTE;
866         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
867
868         if (nf_connlabels_get(net, n_bits)) {
869                 ovs_net->xt_label = false;
870                 OVS_NLERR(true, "Failed to set connlabel length");
871         } else {
872                 ovs_net->xt_label = true;
873         }
874 }
875
876 void ovs_ct_exit(struct net *net)
877 {
878         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
879
880         if (ovs_net->xt_label)
881                 nf_connlabels_put(net);
882 }
883
884 #endif /* CONFIG_NF_CONNTRACK */