Linux-libre 5.4.47-gnu
[librecmc/linux-libre.git] / net / dccp / feat.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  net/dccp/feat.c
4  *
5  *  Feature negotiation for the DCCP protocol (RFC 4340, section 6)
6  *
7  *  Copyright (c) 2008 Gerrit Renker <gerrit@erg.abdn.ac.uk>
8  *  Rewrote from scratch, some bits from earlier code by
9  *  Copyright (c) 2005 Andrea Bittau <a.bittau@cs.ucl.ac.uk>
10  *
11  *  ASSUMPTIONS
12  *  -----------
13  *  o Feature negotiation is coordinated with connection setup (as in TCP), wild
14  *    changes of parameters of an established connection are not supported.
15  *  o Changing non-negotiable (NN) values is supported in state OPEN/PARTOPEN.
16  *  o All currently known SP features have 1-byte quantities. If in the future
17  *    extensions of RFCs 4340..42 define features with item lengths larger than
18  *    one byte, a feature-specific extension of the code will be required.
19  */
20 #include <linux/module.h>
21 #include <linux/slab.h>
22 #include "ccid.h"
23 #include "feat.h"
24
25 /* feature-specific sysctls - initialised to the defaults from RFC 4340, 6.4 */
26 unsigned long   sysctl_dccp_sequence_window __read_mostly = 100;
27 int             sysctl_dccp_rx_ccid         __read_mostly = 2,
28                 sysctl_dccp_tx_ccid         __read_mostly = 2;
29
30 /*
31  * Feature activation handlers.
32  *
33  * These all use an u64 argument, to provide enough room for NN/SP features. At
34  * this stage the negotiated values have been checked to be within their range.
35  */
36 static int dccp_hdlr_ccid(struct sock *sk, u64 ccid, bool rx)
37 {
38         struct dccp_sock *dp = dccp_sk(sk);
39         struct ccid *new_ccid = ccid_new(ccid, sk, rx);
40
41         if (new_ccid == NULL)
42                 return -ENOMEM;
43
44         if (rx) {
45                 ccid_hc_rx_delete(dp->dccps_hc_rx_ccid, sk);
46                 dp->dccps_hc_rx_ccid = new_ccid;
47         } else {
48                 ccid_hc_tx_delete(dp->dccps_hc_tx_ccid, sk);
49                 dp->dccps_hc_tx_ccid = new_ccid;
50         }
51         return 0;
52 }
53
54 static int dccp_hdlr_seq_win(struct sock *sk, u64 seq_win, bool rx)
55 {
56         struct dccp_sock *dp = dccp_sk(sk);
57
58         if (rx) {
59                 dp->dccps_r_seq_win = seq_win;
60                 /* propagate changes to update SWL/SWH */
61                 dccp_update_gsr(sk, dp->dccps_gsr);
62         } else {
63                 dp->dccps_l_seq_win = seq_win;
64                 /* propagate changes to update AWL */
65                 dccp_update_gss(sk, dp->dccps_gss);
66         }
67         return 0;
68 }
69
70 static int dccp_hdlr_ack_ratio(struct sock *sk, u64 ratio, bool rx)
71 {
72         if (rx)
73                 dccp_sk(sk)->dccps_r_ack_ratio = ratio;
74         else
75                 dccp_sk(sk)->dccps_l_ack_ratio = ratio;
76         return 0;
77 }
78
79 static int dccp_hdlr_ackvec(struct sock *sk, u64 enable, bool rx)
80 {
81         struct dccp_sock *dp = dccp_sk(sk);
82
83         if (rx) {
84                 if (enable && dp->dccps_hc_rx_ackvec == NULL) {
85                         dp->dccps_hc_rx_ackvec = dccp_ackvec_alloc(gfp_any());
86                         if (dp->dccps_hc_rx_ackvec == NULL)
87                                 return -ENOMEM;
88                 } else if (!enable) {
89                         dccp_ackvec_free(dp->dccps_hc_rx_ackvec);
90                         dp->dccps_hc_rx_ackvec = NULL;
91                 }
92         }
93         return 0;
94 }
95
96 static int dccp_hdlr_ndp(struct sock *sk, u64 enable, bool rx)
97 {
98         if (!rx)
99                 dccp_sk(sk)->dccps_send_ndp_count = (enable > 0);
100         return 0;
101 }
102
103 /*
104  * Minimum Checksum Coverage is located at the RX side (9.2.1). This means that
105  * `rx' holds when the sending peer informs about his partial coverage via a
106  * ChangeR() option. In the other case, we are the sender and the receiver
107  * announces its coverage via ChangeL() options. The policy here is to honour
108  * such communication by enabling the corresponding partial coverage - but only
109  * if it has not been set manually before; the warning here means that all
110  * packets will be dropped.
111  */
112 static int dccp_hdlr_min_cscov(struct sock *sk, u64 cscov, bool rx)
113 {
114         struct dccp_sock *dp = dccp_sk(sk);
115
116         if (rx)
117                 dp->dccps_pcrlen = cscov;
118         else {
119                 if (dp->dccps_pcslen == 0)
120                         dp->dccps_pcslen = cscov;
121                 else if (cscov > dp->dccps_pcslen)
122                         DCCP_WARN("CsCov %u too small, peer requires >= %u\n",
123                                   dp->dccps_pcslen, (u8)cscov);
124         }
125         return 0;
126 }
127
128 static const struct {
129         u8                      feat_num;               /* DCCPF_xxx */
130         enum dccp_feat_type     rxtx;                   /* RX or TX  */
131         enum dccp_feat_type     reconciliation;         /* SP or NN  */
132         u8                      default_value;          /* as in 6.4 */
133         int (*activation_hdlr)(struct sock *sk, u64 val, bool rx);
134 /*
135  *    Lookup table for location and type of features (from RFC 4340/4342)
136  *  +--------------------------+----+-----+----+----+---------+-----------+
137  *  | Feature                  | Location | Reconc. | Initial |  Section  |
138  *  |                          | RX | TX  | SP | NN |  Value  | Reference |
139  *  +--------------------------+----+-----+----+----+---------+-----------+
140  *  | DCCPF_CCID               |    |  X  | X  |    |   2     | 10        |
141  *  | DCCPF_SHORT_SEQNOS       |    |  X  | X  |    |   0     |  7.6.1    |
142  *  | DCCPF_SEQUENCE_WINDOW    |    |  X  |    | X  | 100     |  7.5.2    |
143  *  | DCCPF_ECN_INCAPABLE      | X  |     | X  |    |   0     | 12.1      |
144  *  | DCCPF_ACK_RATIO          |    |  X  |    | X  |   2     | 11.3      |
145  *  | DCCPF_SEND_ACK_VECTOR    | X  |     | X  |    |   0     | 11.5      |
146  *  | DCCPF_SEND_NDP_COUNT     |    |  X  | X  |    |   0     |  7.7.2    |
147  *  | DCCPF_MIN_CSUM_COVER     | X  |     | X  |    |   0     |  9.2.1    |
148  *  | DCCPF_DATA_CHECKSUM      | X  |     | X  |    |   0     |  9.3.1    |
149  *  | DCCPF_SEND_LEV_RATE      | X  |     | X  |    |   0     | 4342/8.4  |
150  *  +--------------------------+----+-----+----+----+---------+-----------+
151  */
152 } dccp_feat_table[] = {
153         { DCCPF_CCID,            FEAT_AT_TX, FEAT_SP, 2,   dccp_hdlr_ccid     },
154         { DCCPF_SHORT_SEQNOS,    FEAT_AT_TX, FEAT_SP, 0,   NULL },
155         { DCCPF_SEQUENCE_WINDOW, FEAT_AT_TX, FEAT_NN, 100, dccp_hdlr_seq_win  },
156         { DCCPF_ECN_INCAPABLE,   FEAT_AT_RX, FEAT_SP, 0,   NULL },
157         { DCCPF_ACK_RATIO,       FEAT_AT_TX, FEAT_NN, 2,   dccp_hdlr_ack_ratio},
158         { DCCPF_SEND_ACK_VECTOR, FEAT_AT_RX, FEAT_SP, 0,   dccp_hdlr_ackvec   },
159         { DCCPF_SEND_NDP_COUNT,  FEAT_AT_TX, FEAT_SP, 0,   dccp_hdlr_ndp      },
160         { DCCPF_MIN_CSUM_COVER,  FEAT_AT_RX, FEAT_SP, 0,   dccp_hdlr_min_cscov},
161         { DCCPF_DATA_CHECKSUM,   FEAT_AT_RX, FEAT_SP, 0,   NULL },
162         { DCCPF_SEND_LEV_RATE,   FEAT_AT_RX, FEAT_SP, 0,   NULL },
163 };
164 #define DCCP_FEAT_SUPPORTED_MAX         ARRAY_SIZE(dccp_feat_table)
165
166 /**
167  * dccp_feat_index  -  Hash function to map feature number into array position
168  * Returns consecutive array index or -1 if the feature is not understood.
169  */
170 static int dccp_feat_index(u8 feat_num)
171 {
172         /* The first 9 entries are occupied by the types from RFC 4340, 6.4 */
173         if (feat_num > DCCPF_RESERVED && feat_num <= DCCPF_DATA_CHECKSUM)
174                 return feat_num - 1;
175
176         /*
177          * Other features: add cases for new feature types here after adding
178          * them to the above table.
179          */
180         switch (feat_num) {
181         case DCCPF_SEND_LEV_RATE:
182                         return DCCP_FEAT_SUPPORTED_MAX - 1;
183         }
184         return -1;
185 }
186
187 static u8 dccp_feat_type(u8 feat_num)
188 {
189         int idx = dccp_feat_index(feat_num);
190
191         if (idx < 0)
192                 return FEAT_UNKNOWN;
193         return dccp_feat_table[idx].reconciliation;
194 }
195
196 static int dccp_feat_default_value(u8 feat_num)
197 {
198         int idx = dccp_feat_index(feat_num);
199         /*
200          * There are no default values for unknown features, so encountering a
201          * negative index here indicates a serious problem somewhere else.
202          */
203         DCCP_BUG_ON(idx < 0);
204
205         return idx < 0 ? 0 : dccp_feat_table[idx].default_value;
206 }
207
208 /*
209  *      Debugging and verbose-printing section
210  */
211 static const char *dccp_feat_fname(const u8 feat)
212 {
213         static const char *const feature_names[] = {
214                 [DCCPF_RESERVED]        = "Reserved",
215                 [DCCPF_CCID]            = "CCID",
216                 [DCCPF_SHORT_SEQNOS]    = "Allow Short Seqnos",
217                 [DCCPF_SEQUENCE_WINDOW] = "Sequence Window",
218                 [DCCPF_ECN_INCAPABLE]   = "ECN Incapable",
219                 [DCCPF_ACK_RATIO]       = "Ack Ratio",
220                 [DCCPF_SEND_ACK_VECTOR] = "Send ACK Vector",
221                 [DCCPF_SEND_NDP_COUNT]  = "Send NDP Count",
222                 [DCCPF_MIN_CSUM_COVER]  = "Min. Csum Coverage",
223                 [DCCPF_DATA_CHECKSUM]   = "Send Data Checksum",
224         };
225         if (feat > DCCPF_DATA_CHECKSUM && feat < DCCPF_MIN_CCID_SPECIFIC)
226                 return feature_names[DCCPF_RESERVED];
227
228         if (feat ==  DCCPF_SEND_LEV_RATE)
229                 return "Send Loss Event Rate";
230         if (feat >= DCCPF_MIN_CCID_SPECIFIC)
231                 return "CCID-specific";
232
233         return feature_names[feat];
234 }
235
236 static const char *const dccp_feat_sname[] = {
237         "DEFAULT", "INITIALISING", "CHANGING", "UNSTABLE", "STABLE",
238 };
239
240 #ifdef CONFIG_IP_DCCP_DEBUG
241 static const char *dccp_feat_oname(const u8 opt)
242 {
243         switch (opt) {
244         case DCCPO_CHANGE_L:  return "Change_L";
245         case DCCPO_CONFIRM_L: return "Confirm_L";
246         case DCCPO_CHANGE_R:  return "Change_R";
247         case DCCPO_CONFIRM_R: return "Confirm_R";
248         }
249         return NULL;
250 }
251
252 static void dccp_feat_printval(u8 feat_num, dccp_feat_val const *val)
253 {
254         u8 i, type = dccp_feat_type(feat_num);
255
256         if (val == NULL || (type == FEAT_SP && val->sp.vec == NULL))
257                 dccp_pr_debug_cat("(NULL)");
258         else if (type == FEAT_SP)
259                 for (i = 0; i < val->sp.len; i++)
260                         dccp_pr_debug_cat("%s%u", i ? " " : "", val->sp.vec[i]);
261         else if (type == FEAT_NN)
262                 dccp_pr_debug_cat("%llu", (unsigned long long)val->nn);
263         else
264                 dccp_pr_debug_cat("unknown type %u", type);
265 }
266
267 static void dccp_feat_printvals(u8 feat_num, u8 *list, u8 len)
268 {
269         u8 type = dccp_feat_type(feat_num);
270         dccp_feat_val fval = { .sp.vec = list, .sp.len = len };
271
272         if (type == FEAT_NN)
273                 fval.nn = dccp_decode_value_var(list, len);
274         dccp_feat_printval(feat_num, &fval);
275 }
276
277 static void dccp_feat_print_entry(struct dccp_feat_entry const *entry)
278 {
279         dccp_debug("   * %s %s = ", entry->is_local ? "local" : "remote",
280                                     dccp_feat_fname(entry->feat_num));
281         dccp_feat_printval(entry->feat_num, &entry->val);
282         dccp_pr_debug_cat(", state=%s %s\n", dccp_feat_sname[entry->state],
283                           entry->needs_confirm ? "(Confirm pending)" : "");
284 }
285
286 #define dccp_feat_print_opt(opt, feat, val, len, mandatory)     do {          \
287         dccp_pr_debug("%s(%s, ", dccp_feat_oname(opt), dccp_feat_fname(feat));\
288         dccp_feat_printvals(feat, val, len);                                  \
289         dccp_pr_debug_cat(") %s\n", mandatory ? "!" : "");      } while (0)
290
291 #define dccp_feat_print_fnlist(fn_list)  {              \
292         const struct dccp_feat_entry *___entry;         \
293                                                         \
294         dccp_pr_debug("List Dump:\n");                  \
295         list_for_each_entry(___entry, fn_list, node)    \
296                 dccp_feat_print_entry(___entry);        \
297 }
298 #else   /* ! CONFIG_IP_DCCP_DEBUG */
299 #define dccp_feat_print_opt(opt, feat, val, len, mandatory)
300 #define dccp_feat_print_fnlist(fn_list)
301 #endif
302
303 static int __dccp_feat_activate(struct sock *sk, const int idx,
304                                 const bool is_local, dccp_feat_val const *fval)
305 {
306         bool rx;
307         u64 val;
308
309         if (idx < 0 || idx >= DCCP_FEAT_SUPPORTED_MAX)
310                 return -1;
311         if (dccp_feat_table[idx].activation_hdlr == NULL)
312                 return 0;
313
314         if (fval == NULL) {
315                 val = dccp_feat_table[idx].default_value;
316         } else if (dccp_feat_table[idx].reconciliation == FEAT_SP) {
317                 if (fval->sp.vec == NULL) {
318                         /*
319                          * This can happen when an empty Confirm is sent
320                          * for an SP (i.e. known) feature. In this case
321                          * we would be using the default anyway.
322                          */
323                         DCCP_CRIT("Feature #%d undefined: using default", idx);
324                         val = dccp_feat_table[idx].default_value;
325                 } else {
326                         val = fval->sp.vec[0];
327                 }
328         } else {
329                 val = fval->nn;
330         }
331
332         /* Location is RX if this is a local-RX or remote-TX feature */
333         rx = (is_local == (dccp_feat_table[idx].rxtx == FEAT_AT_RX));
334
335         dccp_debug("   -> activating %s %s, %sval=%llu\n", rx ? "RX" : "TX",
336                    dccp_feat_fname(dccp_feat_table[idx].feat_num),
337                    fval ? "" : "default ",  (unsigned long long)val);
338
339         return dccp_feat_table[idx].activation_hdlr(sk, val, rx);
340 }
341
342 /**
343  * dccp_feat_activate  -  Activate feature value on socket
344  * @sk: fully connected DCCP socket (after handshake is complete)
345  * @feat_num: feature to activate, one of %dccp_feature_numbers
346  * @local: whether local (1) or remote (0) @feat_num is meant
347  * @fval: the value (SP or NN) to activate, or NULL to use the default value
348  *
349  * For general use this function is preferable over __dccp_feat_activate().
350  */
351 static int dccp_feat_activate(struct sock *sk, u8 feat_num, bool local,
352                               dccp_feat_val const *fval)
353 {
354         return __dccp_feat_activate(sk, dccp_feat_index(feat_num), local, fval);
355 }
356
357 /* Test for "Req'd" feature (RFC 4340, 6.4) */
358 static inline int dccp_feat_must_be_understood(u8 feat_num)
359 {
360         return  feat_num == DCCPF_CCID || feat_num == DCCPF_SHORT_SEQNOS ||
361                 feat_num == DCCPF_SEQUENCE_WINDOW;
362 }
363
364 /* copy constructor, fval must not already contain allocated memory */
365 static int dccp_feat_clone_sp_val(dccp_feat_val *fval, u8 const *val, u8 len)
366 {
367         fval->sp.len = len;
368         if (fval->sp.len > 0) {
369                 fval->sp.vec = kmemdup(val, len, gfp_any());
370                 if (fval->sp.vec == NULL) {
371                         fval->sp.len = 0;
372                         return -ENOBUFS;
373                 }
374         }
375         return 0;
376 }
377
378 static void dccp_feat_val_destructor(u8 feat_num, dccp_feat_val *val)
379 {
380         if (unlikely(val == NULL))
381                 return;
382         if (dccp_feat_type(feat_num) == FEAT_SP)
383                 kfree(val->sp.vec);
384         memset(val, 0, sizeof(*val));
385 }
386
387 static struct dccp_feat_entry *
388               dccp_feat_clone_entry(struct dccp_feat_entry const *original)
389 {
390         struct dccp_feat_entry *new;
391         u8 type = dccp_feat_type(original->feat_num);
392
393         if (type == FEAT_UNKNOWN)
394                 return NULL;
395
396         new = kmemdup(original, sizeof(struct dccp_feat_entry), gfp_any());
397         if (new == NULL)
398                 return NULL;
399
400         if (type == FEAT_SP && dccp_feat_clone_sp_val(&new->val,
401                                                       original->val.sp.vec,
402                                                       original->val.sp.len)) {
403                 kfree(new);
404                 return NULL;
405         }
406         return new;
407 }
408
409 static void dccp_feat_entry_destructor(struct dccp_feat_entry *entry)
410 {
411         if (entry != NULL) {
412                 dccp_feat_val_destructor(entry->feat_num, &entry->val);
413                 kfree(entry);
414         }
415 }
416
417 /*
418  * List management functions
419  *
420  * Feature negotiation lists rely on and maintain the following invariants:
421  * - each feat_num in the list is known, i.e. we know its type and default value
422  * - each feat_num/is_local combination is unique (old entries are overwritten)
423  * - SP values are always freshly allocated
424  * - list is sorted in increasing order of feature number (faster lookup)
425  */
426 static struct dccp_feat_entry *dccp_feat_list_lookup(struct list_head *fn_list,
427                                                      u8 feat_num, bool is_local)
428 {
429         struct dccp_feat_entry *entry;
430
431         list_for_each_entry(entry, fn_list, node) {
432                 if (entry->feat_num == feat_num && entry->is_local == is_local)
433                         return entry;
434                 else if (entry->feat_num > feat_num)
435                         break;
436         }
437         return NULL;
438 }
439
440 /**
441  * dccp_feat_entry_new  -  Central list update routine (called by all others)
442  * @head:  list to add to
443  * @feat:  feature number
444  * @local: whether the local (1) or remote feature with number @feat is meant
445  *
446  * This is the only constructor and serves to ensure the above invariants.
447  */
448 static struct dccp_feat_entry *
449               dccp_feat_entry_new(struct list_head *head, u8 feat, bool local)
450 {
451         struct dccp_feat_entry *entry;
452
453         list_for_each_entry(entry, head, node)
454                 if (entry->feat_num == feat && entry->is_local == local) {
455                         dccp_feat_val_destructor(entry->feat_num, &entry->val);
456                         return entry;
457                 } else if (entry->feat_num > feat) {
458                         head = &entry->node;
459                         break;
460                 }
461
462         entry = kmalloc(sizeof(*entry), gfp_any());
463         if (entry != NULL) {
464                 entry->feat_num = feat;
465                 entry->is_local = local;
466                 list_add_tail(&entry->node, head);
467         }
468         return entry;
469 }
470
471 /**
472  * dccp_feat_push_change  -  Add/overwrite a Change option in the list
473  * @fn_list: feature-negotiation list to update
474  * @feat: one of %dccp_feature_numbers
475  * @local: whether local (1) or remote (0) @feat_num is meant
476  * @mandatory: whether to use Mandatory feature negotiation options
477  * @fval: pointer to NN/SP value to be inserted (will be copied)
478  */
479 static int dccp_feat_push_change(struct list_head *fn_list, u8 feat, u8 local,
480                                  u8 mandatory, dccp_feat_val *fval)
481 {
482         struct dccp_feat_entry *new = dccp_feat_entry_new(fn_list, feat, local);
483
484         if (new == NULL)
485                 return -ENOMEM;
486
487         new->feat_num        = feat;
488         new->is_local        = local;
489         new->state           = FEAT_INITIALISING;
490         new->needs_confirm   = false;
491         new->empty_confirm   = false;
492         new->val             = *fval;
493         new->needs_mandatory = mandatory;
494
495         return 0;
496 }
497
498 /**
499  * dccp_feat_push_confirm  -  Add a Confirm entry to the FN list
500  * @fn_list: feature-negotiation list to add to
501  * @feat: one of %dccp_feature_numbers
502  * @local: whether local (1) or remote (0) @feat_num is being confirmed
503  * @fval: pointer to NN/SP value to be inserted or NULL
504  *
505  * Returns 0 on success, a Reset code for further processing otherwise.
506  */
507 static int dccp_feat_push_confirm(struct list_head *fn_list, u8 feat, u8 local,
508                                   dccp_feat_val *fval)
509 {
510         struct dccp_feat_entry *new = dccp_feat_entry_new(fn_list, feat, local);
511
512         if (new == NULL)
513                 return DCCP_RESET_CODE_TOO_BUSY;
514
515         new->feat_num        = feat;
516         new->is_local        = local;
517         new->state           = FEAT_STABLE;     /* transition in 6.6.2 */
518         new->needs_confirm   = true;
519         new->empty_confirm   = (fval == NULL);
520         new->val.nn          = 0;               /* zeroes the whole structure */
521         if (!new->empty_confirm)
522                 new->val     = *fval;
523         new->needs_mandatory = false;
524
525         return 0;
526 }
527
528 static int dccp_push_empty_confirm(struct list_head *fn_list, u8 feat, u8 local)
529 {
530         return dccp_feat_push_confirm(fn_list, feat, local, NULL);
531 }
532
533 static inline void dccp_feat_list_pop(struct dccp_feat_entry *entry)
534 {
535         list_del(&entry->node);
536         dccp_feat_entry_destructor(entry);
537 }
538
539 void dccp_feat_list_purge(struct list_head *fn_list)
540 {
541         struct dccp_feat_entry *entry, *next;
542
543         list_for_each_entry_safe(entry, next, fn_list, node)
544                 dccp_feat_entry_destructor(entry);
545         INIT_LIST_HEAD(fn_list);
546 }
547 EXPORT_SYMBOL_GPL(dccp_feat_list_purge);
548
549 /* generate @to as full clone of @from - @to must not contain any nodes */
550 int dccp_feat_clone_list(struct list_head const *from, struct list_head *to)
551 {
552         struct dccp_feat_entry *entry, *new;
553
554         INIT_LIST_HEAD(to);
555         list_for_each_entry(entry, from, node) {
556                 new = dccp_feat_clone_entry(entry);
557                 if (new == NULL)
558                         goto cloning_failed;
559                 list_add_tail(&new->node, to);
560         }
561         return 0;
562
563 cloning_failed:
564         dccp_feat_list_purge(to);
565         return -ENOMEM;
566 }
567
568 /**
569  * dccp_feat_valid_nn_length  -  Enforce length constraints on NN options
570  * Length is between 0 and %DCCP_OPTVAL_MAXLEN. Used for outgoing packets only,
571  * incoming options are accepted as long as their values are valid.
572  */
573 static u8 dccp_feat_valid_nn_length(u8 feat_num)
574 {
575         if (feat_num == DCCPF_ACK_RATIO)        /* RFC 4340, 11.3 and 6.6.8 */
576                 return 2;
577         if (feat_num == DCCPF_SEQUENCE_WINDOW)  /* RFC 4340, 7.5.2 and 6.5  */
578                 return 6;
579         return 0;
580 }
581
582 static u8 dccp_feat_is_valid_nn_val(u8 feat_num, u64 val)
583 {
584         switch (feat_num) {
585         case DCCPF_ACK_RATIO:
586                 return val <= DCCPF_ACK_RATIO_MAX;
587         case DCCPF_SEQUENCE_WINDOW:
588                 return val >= DCCPF_SEQ_WMIN && val <= DCCPF_SEQ_WMAX;
589         }
590         return 0;       /* feature unknown - so we can't tell */
591 }
592
593 /* check that SP values are within the ranges defined in RFC 4340 */
594 static u8 dccp_feat_is_valid_sp_val(u8 feat_num, u8 val)
595 {
596         switch (feat_num) {
597         case DCCPF_CCID:
598                 return val == DCCPC_CCID2 || val == DCCPC_CCID3;
599         /* Type-check Boolean feature values: */
600         case DCCPF_SHORT_SEQNOS:
601         case DCCPF_ECN_INCAPABLE:
602         case DCCPF_SEND_ACK_VECTOR:
603         case DCCPF_SEND_NDP_COUNT:
604         case DCCPF_DATA_CHECKSUM:
605         case DCCPF_SEND_LEV_RATE:
606                 return val < 2;
607         case DCCPF_MIN_CSUM_COVER:
608                 return val < 16;
609         }
610         return 0;                       /* feature unknown */
611 }
612
613 static u8 dccp_feat_sp_list_ok(u8 feat_num, u8 const *sp_list, u8 sp_len)
614 {
615         if (sp_list == NULL || sp_len < 1)
616                 return 0;
617         while (sp_len--)
618                 if (!dccp_feat_is_valid_sp_val(feat_num, *sp_list++))
619                         return 0;
620         return 1;
621 }
622
623 /**
624  * dccp_feat_insert_opts  -  Generate FN options from current list state
625  * @skb: next sk_buff to be sent to the peer
626  * @dp: for client during handshake and general negotiation
627  * @dreq: used by the server only (all Changes/Confirms in LISTEN/RESPOND)
628  */
629 int dccp_feat_insert_opts(struct dccp_sock *dp, struct dccp_request_sock *dreq,
630                           struct sk_buff *skb)
631 {
632         struct list_head *fn = dreq ? &dreq->dreq_featneg : &dp->dccps_featneg;
633         struct dccp_feat_entry *pos, *next;
634         u8 opt, type, len, *ptr, nn_in_nbo[DCCP_OPTVAL_MAXLEN];
635         bool rpt;
636
637         /* put entries into @skb in the order they appear in the list */
638         list_for_each_entry_safe_reverse(pos, next, fn, node) {
639                 opt  = dccp_feat_genopt(pos);
640                 type = dccp_feat_type(pos->feat_num);
641                 rpt  = false;
642
643                 if (pos->empty_confirm) {
644                         len = 0;
645                         ptr = NULL;
646                 } else {
647                         if (type == FEAT_SP) {
648                                 len = pos->val.sp.len;
649                                 ptr = pos->val.sp.vec;
650                                 rpt = pos->needs_confirm;
651                         } else if (type == FEAT_NN) {
652                                 len = dccp_feat_valid_nn_length(pos->feat_num);
653                                 ptr = nn_in_nbo;
654                                 dccp_encode_value_var(pos->val.nn, ptr, len);
655                         } else {
656                                 DCCP_BUG("unknown feature %u", pos->feat_num);
657                                 return -1;
658                         }
659                 }
660                 dccp_feat_print_opt(opt, pos->feat_num, ptr, len, 0);
661
662                 if (dccp_insert_fn_opt(skb, opt, pos->feat_num, ptr, len, rpt))
663                         return -1;
664                 if (pos->needs_mandatory && dccp_insert_option_mandatory(skb))
665                         return -1;
666
667                 if (skb->sk->sk_state == DCCP_OPEN &&
668                     (opt == DCCPO_CONFIRM_R || opt == DCCPO_CONFIRM_L)) {
669                         /*
670                          * Confirms don't get retransmitted (6.6.3) once the
671                          * connection is in state OPEN
672                          */
673                         dccp_feat_list_pop(pos);
674                 } else {
675                         /*
676                          * Enter CHANGING after transmitting the Change
677                          * option (6.6.2).
678                          */
679                         if (pos->state == FEAT_INITIALISING)
680                                 pos->state = FEAT_CHANGING;
681                 }
682         }
683         return 0;
684 }
685
686 /**
687  * __feat_register_nn  -  Register new NN value on socket
688  * @fn: feature-negotiation list to register with
689  * @feat: an NN feature from %dccp_feature_numbers
690  * @mandatory: use Mandatory option if 1
691  * @nn_val: value to register (restricted to 4 bytes)
692  *
693  * Note that NN features are local by definition (RFC 4340, 6.3.2).
694  */
695 static int __feat_register_nn(struct list_head *fn, u8 feat,
696                               u8 mandatory, u64 nn_val)
697 {
698         dccp_feat_val fval = { .nn = nn_val };
699
700         if (dccp_feat_type(feat) != FEAT_NN ||
701             !dccp_feat_is_valid_nn_val(feat, nn_val))
702                 return -EINVAL;
703
704         /* Don't bother with default values, they will be activated anyway. */
705         if (nn_val - (u64)dccp_feat_default_value(feat) == 0)
706                 return 0;
707
708         return dccp_feat_push_change(fn, feat, 1, mandatory, &fval);
709 }
710
711 /**
712  * __feat_register_sp  -  Register new SP value/list on socket
713  * @fn: feature-negotiation list to register with
714  * @feat: an SP feature from %dccp_feature_numbers
715  * @is_local: whether the local (1) or the remote (0) @feat is meant
716  * @mandatory: use Mandatory option if 1
717  * @sp_val: SP value followed by optional preference list
718  * @sp_len: length of @sp_val in bytes
719  */
720 static int __feat_register_sp(struct list_head *fn, u8 feat, u8 is_local,
721                               u8 mandatory, u8 const *sp_val, u8 sp_len)
722 {
723         dccp_feat_val fval;
724
725         if (dccp_feat_type(feat) != FEAT_SP ||
726             !dccp_feat_sp_list_ok(feat, sp_val, sp_len))
727                 return -EINVAL;
728
729         /* Avoid negotiating alien CCIDs by only advertising supported ones */
730         if (feat == DCCPF_CCID && !ccid_support_check(sp_val, sp_len))
731                 return -EOPNOTSUPP;
732
733         if (dccp_feat_clone_sp_val(&fval, sp_val, sp_len))
734                 return -ENOMEM;
735
736         if (dccp_feat_push_change(fn, feat, is_local, mandatory, &fval)) {
737                 kfree(fval.sp.vec);
738                 return -ENOMEM;
739         }
740
741         return 0;
742 }
743
744 /**
745  * dccp_feat_register_sp  -  Register requests to change SP feature values
746  * @sk: client or listening socket
747  * @feat: one of %dccp_feature_numbers
748  * @is_local: whether the local (1) or remote (0) @feat is meant
749  * @list: array of preferred values, in descending order of preference
750  * @len: length of @list in bytes
751  */
752 int dccp_feat_register_sp(struct sock *sk, u8 feat, u8 is_local,
753                           u8 const *list, u8 len)
754 {        /* any changes must be registered before establishing the connection */
755         if (sk->sk_state != DCCP_CLOSED)
756                 return -EISCONN;
757         if (dccp_feat_type(feat) != FEAT_SP)
758                 return -EINVAL;
759         return __feat_register_sp(&dccp_sk(sk)->dccps_featneg, feat, is_local,
760                                   0, list, len);
761 }
762
763 /**
764  * dccp_feat_nn_get  -  Query current/pending value of NN feature
765  * @sk: DCCP socket of an established connection
766  * @feat: NN feature number from %dccp_feature_numbers
767  *
768  * For a known NN feature, returns value currently being negotiated, or
769  * current (confirmed) value if no negotiation is going on.
770  */
771 u64 dccp_feat_nn_get(struct sock *sk, u8 feat)
772 {
773         if (dccp_feat_type(feat) == FEAT_NN) {
774                 struct dccp_sock *dp = dccp_sk(sk);
775                 struct dccp_feat_entry *entry;
776
777                 entry = dccp_feat_list_lookup(&dp->dccps_featneg, feat, 1);
778                 if (entry != NULL)
779                         return entry->val.nn;
780
781                 switch (feat) {
782                 case DCCPF_ACK_RATIO:
783                         return dp->dccps_l_ack_ratio;
784                 case DCCPF_SEQUENCE_WINDOW:
785                         return dp->dccps_l_seq_win;
786                 }
787         }
788         DCCP_BUG("attempt to look up unsupported feature %u", feat);
789         return 0;
790 }
791 EXPORT_SYMBOL_GPL(dccp_feat_nn_get);
792
793 /**
794  * dccp_feat_signal_nn_change  -  Update NN values for an established connection
795  * @sk: DCCP socket of an established connection
796  * @feat: NN feature number from %dccp_feature_numbers
797  * @nn_val: the new value to use
798  *
799  * This function is used to communicate NN updates out-of-band.
800  */
801 int dccp_feat_signal_nn_change(struct sock *sk, u8 feat, u64 nn_val)
802 {
803         struct list_head *fn = &dccp_sk(sk)->dccps_featneg;
804         dccp_feat_val fval = { .nn = nn_val };
805         struct dccp_feat_entry *entry;
806
807         if (sk->sk_state != DCCP_OPEN && sk->sk_state != DCCP_PARTOPEN)
808                 return 0;
809
810         if (dccp_feat_type(feat) != FEAT_NN ||
811             !dccp_feat_is_valid_nn_val(feat, nn_val))
812                 return -EINVAL;
813
814         if (nn_val == dccp_feat_nn_get(sk, feat))
815                 return 0;       /* already set or negotiation under way */
816
817         entry = dccp_feat_list_lookup(fn, feat, 1);
818         if (entry != NULL) {
819                 dccp_pr_debug("Clobbering existing NN entry %llu -> %llu\n",
820                               (unsigned long long)entry->val.nn,
821                               (unsigned long long)nn_val);
822                 dccp_feat_list_pop(entry);
823         }
824
825         inet_csk_schedule_ack(sk);
826         return dccp_feat_push_change(fn, feat, 1, 0, &fval);
827 }
828 EXPORT_SYMBOL_GPL(dccp_feat_signal_nn_change);
829
830 /*
831  *      Tracking features whose value depend on the choice of CCID
832  *
833  * This is designed with an extension in mind so that a list walk could be done
834  * before activating any features. However, the existing framework was found to
835  * work satisfactorily up until now, the automatic verification is left open.
836  * When adding new CCIDs, add a corresponding dependency table here.
837  */
838 static const struct ccid_dependency *dccp_feat_ccid_deps(u8 ccid, bool is_local)
839 {
840         static const struct ccid_dependency ccid2_dependencies[2][2] = {
841                 /*
842                  * CCID2 mandates Ack Vectors (RFC 4341, 4.): as CCID is a TX
843                  * feature and Send Ack Vector is an RX feature, `is_local'
844                  * needs to be reversed.
845                  */
846                 {       /* Dependencies of the receiver-side (remote) CCID2 */
847                         {
848                                 .dependent_feat = DCCPF_SEND_ACK_VECTOR,
849                                 .is_local       = true,
850                                 .is_mandatory   = true,
851                                 .val            = 1
852                         },
853                         { 0, 0, 0, 0 }
854                 },
855                 {       /* Dependencies of the sender-side (local) CCID2 */
856                         {
857                                 .dependent_feat = DCCPF_SEND_ACK_VECTOR,
858                                 .is_local       = false,
859                                 .is_mandatory   = true,
860                                 .val            = 1
861                         },
862                         { 0, 0, 0, 0 }
863                 }
864         };
865         static const struct ccid_dependency ccid3_dependencies[2][5] = {
866                 {       /*
867                          * Dependencies of the receiver-side CCID3
868                          */
869                         {       /* locally disable Ack Vectors */
870                                 .dependent_feat = DCCPF_SEND_ACK_VECTOR,
871                                 .is_local       = true,
872                                 .is_mandatory   = false,
873                                 .val            = 0
874                         },
875                         {       /* see below why Send Loss Event Rate is on */
876                                 .dependent_feat = DCCPF_SEND_LEV_RATE,
877                                 .is_local       = true,
878                                 .is_mandatory   = true,
879                                 .val            = 1
880                         },
881                         {       /* NDP Count is needed as per RFC 4342, 6.1.1 */
882                                 .dependent_feat = DCCPF_SEND_NDP_COUNT,
883                                 .is_local       = false,
884                                 .is_mandatory   = true,
885                                 .val            = 1
886                         },
887                         { 0, 0, 0, 0 },
888                 },
889                 {       /*
890                          * CCID3 at the TX side: we request that the HC-receiver
891                          * will not send Ack Vectors (they will be ignored, so
892                          * Mandatory is not set); we enable Send Loss Event Rate
893                          * (Mandatory since the implementation does not support
894                          * the Loss Intervals option of RFC 4342, 8.6).
895                          * The last two options are for peer's information only.
896                         */
897                         {
898                                 .dependent_feat = DCCPF_SEND_ACK_VECTOR,
899                                 .is_local       = false,
900                                 .is_mandatory   = false,
901                                 .val            = 0
902                         },
903                         {
904                                 .dependent_feat = DCCPF_SEND_LEV_RATE,
905                                 .is_local       = false,
906                                 .is_mandatory   = true,
907                                 .val            = 1
908                         },
909                         {       /* this CCID does not support Ack Ratio */
910                                 .dependent_feat = DCCPF_ACK_RATIO,
911                                 .is_local       = true,
912                                 .is_mandatory   = false,
913                                 .val            = 0
914                         },
915                         {       /* tell receiver we are sending NDP counts */
916                                 .dependent_feat = DCCPF_SEND_NDP_COUNT,
917                                 .is_local       = true,
918                                 .is_mandatory   = false,
919                                 .val            = 1
920                         },
921                         { 0, 0, 0, 0 }
922                 }
923         };
924         switch (ccid) {
925         case DCCPC_CCID2:
926                 return ccid2_dependencies[is_local];
927         case DCCPC_CCID3:
928                 return ccid3_dependencies[is_local];
929         default:
930                 return NULL;
931         }
932 }
933
934 /**
935  * dccp_feat_propagate_ccid - Resolve dependencies of features on choice of CCID
936  * @fn: feature-negotiation list to update
937  * @id: CCID number to track
938  * @is_local: whether TX CCID (1) or RX CCID (0) is meant
939  *
940  * This function needs to be called after registering all other features.
941  */
942 static int dccp_feat_propagate_ccid(struct list_head *fn, u8 id, bool is_local)
943 {
944         const struct ccid_dependency *table = dccp_feat_ccid_deps(id, is_local);
945         int i, rc = (table == NULL);
946
947         for (i = 0; rc == 0 && table[i].dependent_feat != DCCPF_RESERVED; i++)
948                 if (dccp_feat_type(table[i].dependent_feat) == FEAT_SP)
949                         rc = __feat_register_sp(fn, table[i].dependent_feat,
950                                                     table[i].is_local,
951                                                     table[i].is_mandatory,
952                                                     &table[i].val, 1);
953                 else
954                         rc = __feat_register_nn(fn, table[i].dependent_feat,
955                                                     table[i].is_mandatory,
956                                                     table[i].val);
957         return rc;
958 }
959
960 /**
961  * dccp_feat_finalise_settings  -  Finalise settings before starting negotiation
962  * @dp: client or listening socket (settings will be inherited)
963  *
964  * This is called after all registrations (socket initialisation, sysctls, and
965  * sockopt calls), and before sending the first packet containing Change options
966  * (ie. client-Request or server-Response), to ensure internal consistency.
967  */
968 int dccp_feat_finalise_settings(struct dccp_sock *dp)
969 {
970         struct list_head *fn = &dp->dccps_featneg;
971         struct dccp_feat_entry *entry;
972         int i = 2, ccids[2] = { -1, -1 };
973
974         /*
975          * Propagating CCIDs:
976          * 1) not useful to propagate CCID settings if this host advertises more
977          *    than one CCID: the choice of CCID  may still change - if this is
978          *    the client, or if this is the server and the client sends
979          *    singleton CCID values.
980          * 2) since is that propagate_ccid changes the list, we defer changing
981          *    the sorted list until after the traversal.
982          */
983         list_for_each_entry(entry, fn, node)
984                 if (entry->feat_num == DCCPF_CCID && entry->val.sp.len == 1)
985                         ccids[entry->is_local] = entry->val.sp.vec[0];
986         while (i--)
987                 if (ccids[i] > 0 && dccp_feat_propagate_ccid(fn, ccids[i], i))
988                         return -1;
989         dccp_feat_print_fnlist(fn);
990         return 0;
991 }
992
993 /**
994  * dccp_feat_server_ccid_dependencies  -  Resolve CCID-dependent features
995  * It is the server which resolves the dependencies once the CCID has been
996  * fully negotiated. If no CCID has been negotiated, it uses the default CCID.
997  */
998 int dccp_feat_server_ccid_dependencies(struct dccp_request_sock *dreq)
999 {
1000         struct list_head *fn = &dreq->dreq_featneg;
1001         struct dccp_feat_entry *entry;
1002         u8 is_local, ccid;
1003
1004         for (is_local = 0; is_local <= 1; is_local++) {
1005                 entry = dccp_feat_list_lookup(fn, DCCPF_CCID, is_local);
1006
1007                 if (entry != NULL && !entry->empty_confirm)
1008                         ccid = entry->val.sp.vec[0];
1009                 else
1010                         ccid = dccp_feat_default_value(DCCPF_CCID);
1011
1012                 if (dccp_feat_propagate_ccid(fn, ccid, is_local))
1013                         return -1;
1014         }
1015         return 0;
1016 }
1017
1018 /* Select the first entry in @servlist that also occurs in @clilist (6.3.1) */
1019 static int dccp_feat_preflist_match(u8 *servlist, u8 slen, u8 *clilist, u8 clen)
1020 {
1021         u8 c, s;
1022
1023         for (s = 0; s < slen; s++)
1024                 for (c = 0; c < clen; c++)
1025                         if (servlist[s] == clilist[c])
1026                                 return servlist[s];
1027         return -1;
1028 }
1029
1030 /**
1031  * dccp_feat_prefer  -  Move preferred entry to the start of array
1032  * Reorder the @array_len elements in @array so that @preferred_value comes
1033  * first. Returns >0 to indicate that @preferred_value does occur in @array.
1034  */
1035 static u8 dccp_feat_prefer(u8 preferred_value, u8 *array, u8 array_len)
1036 {
1037         u8 i, does_occur = 0;
1038
1039         if (array != NULL) {
1040                 for (i = 0; i < array_len; i++)
1041                         if (array[i] == preferred_value) {
1042                                 array[i] = array[0];
1043                                 does_occur++;
1044                         }
1045                 if (does_occur)
1046                         array[0] = preferred_value;
1047         }
1048         return does_occur;
1049 }
1050
1051 /**
1052  * dccp_feat_reconcile  -  Reconcile SP preference lists
1053  *  @fv: SP list to reconcile into
1054  *  @arr: received SP preference list
1055  *  @len: length of @arr in bytes
1056  *  @is_server: whether this side is the server (and @fv is the server's list)
1057  *  @reorder: whether to reorder the list in @fv after reconciling with @arr
1058  * When successful, > 0 is returned and the reconciled list is in @fval.
1059  * A value of 0 means that negotiation failed (no shared entry).
1060  */
1061 static int dccp_feat_reconcile(dccp_feat_val *fv, u8 *arr, u8 len,
1062                                bool is_server, bool reorder)
1063 {
1064         int rc;
1065
1066         if (!fv->sp.vec || !arr) {
1067                 DCCP_CRIT("NULL feature value or array");
1068                 return 0;
1069         }
1070
1071         if (is_server)
1072                 rc = dccp_feat_preflist_match(fv->sp.vec, fv->sp.len, arr, len);
1073         else
1074                 rc = dccp_feat_preflist_match(arr, len, fv->sp.vec, fv->sp.len);
1075
1076         if (!reorder)
1077                 return rc;
1078         if (rc < 0)
1079                 return 0;
1080
1081         /*
1082          * Reorder list: used for activating features and in dccp_insert_fn_opt.
1083          */
1084         return dccp_feat_prefer(rc, fv->sp.vec, fv->sp.len);
1085 }
1086
1087 /**
1088  * dccp_feat_change_recv  -  Process incoming ChangeL/R options
1089  * @fn: feature-negotiation list to update
1090  * @is_mandatory: whether the Change was preceded by a Mandatory option
1091  * @opt: %DCCPO_CHANGE_L or %DCCPO_CHANGE_R
1092  * @feat: one of %dccp_feature_numbers
1093  * @val: NN value or SP value/preference list
1094  * @len: length of @val in bytes
1095  * @server: whether this node is the server (1) or the client (0)
1096  */
1097 static u8 dccp_feat_change_recv(struct list_head *fn, u8 is_mandatory, u8 opt,
1098                                 u8 feat, u8 *val, u8 len, const bool server)
1099 {
1100         u8 defval, type = dccp_feat_type(feat);
1101         const bool local = (opt == DCCPO_CHANGE_R);
1102         struct dccp_feat_entry *entry;
1103         dccp_feat_val fval;
1104
1105         if (len == 0 || type == FEAT_UNKNOWN)           /* 6.1 and 6.6.8 */
1106                 goto unknown_feature_or_value;
1107
1108         dccp_feat_print_opt(opt, feat, val, len, is_mandatory);
1109
1110         /*
1111          *      Negotiation of NN features: Change R is invalid, so there is no
1112          *      simultaneous negotiation; hence we do not look up in the list.
1113          */
1114         if (type == FEAT_NN) {
1115                 if (local || len > sizeof(fval.nn))
1116                         goto unknown_feature_or_value;
1117
1118                 /* 6.3.2: "The feature remote MUST accept any valid value..." */
1119                 fval.nn = dccp_decode_value_var(val, len);
1120                 if (!dccp_feat_is_valid_nn_val(feat, fval.nn))
1121                         goto unknown_feature_or_value;
1122
1123                 return dccp_feat_push_confirm(fn, feat, local, &fval);
1124         }
1125
1126         /*
1127          *      Unidirectional/simultaneous negotiation of SP features (6.3.1)
1128          */
1129         entry = dccp_feat_list_lookup(fn, feat, local);
1130         if (entry == NULL) {
1131                 /*
1132                  * No particular preferences have been registered. We deal with
1133                  * this situation by assuming that all valid values are equally
1134                  * acceptable, and apply the following checks:
1135                  * - if the peer's list is a singleton, we accept a valid value;
1136                  * - if we are the server, we first try to see if the peer (the
1137                  *   client) advertises the default value. If yes, we use it,
1138                  *   otherwise we accept the preferred value;
1139                  * - else if we are the client, we use the first list element.
1140                  */
1141                 if (dccp_feat_clone_sp_val(&fval, val, 1))
1142                         return DCCP_RESET_CODE_TOO_BUSY;
1143
1144                 if (len > 1 && server) {
1145                         defval = dccp_feat_default_value(feat);
1146                         if (dccp_feat_preflist_match(&defval, 1, val, len) > -1)
1147                                 fval.sp.vec[0] = defval;
1148                 } else if (!dccp_feat_is_valid_sp_val(feat, fval.sp.vec[0])) {
1149                         kfree(fval.sp.vec);
1150                         goto unknown_feature_or_value;
1151                 }
1152
1153                 /* Treat unsupported CCIDs like invalid values */
1154                 if (feat == DCCPF_CCID && !ccid_support_check(fval.sp.vec, 1)) {
1155                         kfree(fval.sp.vec);
1156                         goto not_valid_or_not_known;
1157                 }
1158
1159                 return dccp_feat_push_confirm(fn, feat, local, &fval);
1160
1161         } else if (entry->state == FEAT_UNSTABLE) {     /* 6.6.2 */
1162                 return 0;
1163         }
1164
1165         if (dccp_feat_reconcile(&entry->val, val, len, server, true)) {
1166                 entry->empty_confirm = false;
1167         } else if (is_mandatory) {
1168                 return DCCP_RESET_CODE_MANDATORY_ERROR;
1169         } else if (entry->state == FEAT_INITIALISING) {
1170                 /*
1171                  * Failed simultaneous negotiation (server only): try to `save'
1172                  * the connection by checking whether entry contains the default
1173                  * value for @feat. If yes, send an empty Confirm to signal that
1174                  * the received Change was not understood - which implies using
1175                  * the default value.
1176                  * If this also fails, we use Reset as the last resort.
1177                  */
1178                 WARN_ON(!server);
1179                 defval = dccp_feat_default_value(feat);
1180                 if (!dccp_feat_reconcile(&entry->val, &defval, 1, server, true))
1181                         return DCCP_RESET_CODE_OPTION_ERROR;
1182                 entry->empty_confirm = true;
1183         }
1184         entry->needs_confirm   = true;
1185         entry->needs_mandatory = false;
1186         entry->state           = FEAT_STABLE;
1187         return 0;
1188
1189 unknown_feature_or_value:
1190         if (!is_mandatory)
1191                 return dccp_push_empty_confirm(fn, feat, local);
1192
1193 not_valid_or_not_known:
1194         return is_mandatory ? DCCP_RESET_CODE_MANDATORY_ERROR
1195                             : DCCP_RESET_CODE_OPTION_ERROR;
1196 }
1197
1198 /**
1199  * dccp_feat_confirm_recv  -  Process received Confirm options
1200  * @fn: feature-negotiation list to update
1201  * @is_mandatory: whether @opt was preceded by a Mandatory option
1202  * @opt: %DCCPO_CONFIRM_L or %DCCPO_CONFIRM_R
1203  * @feat: one of %dccp_feature_numbers
1204  * @val: NN value or SP value/preference list
1205  * @len: length of @val in bytes
1206  * @server: whether this node is server (1) or client (0)
1207  */
1208 static u8 dccp_feat_confirm_recv(struct list_head *fn, u8 is_mandatory, u8 opt,
1209                                  u8 feat, u8 *val, u8 len, const bool server)
1210 {
1211         u8 *plist, plen, type = dccp_feat_type(feat);
1212         const bool local = (opt == DCCPO_CONFIRM_R);
1213         struct dccp_feat_entry *entry = dccp_feat_list_lookup(fn, feat, local);
1214
1215         dccp_feat_print_opt(opt, feat, val, len, is_mandatory);
1216
1217         if (entry == NULL) {    /* nothing queued: ignore or handle error */
1218                 if (is_mandatory && type == FEAT_UNKNOWN)
1219                         return DCCP_RESET_CODE_MANDATORY_ERROR;
1220
1221                 if (!local && type == FEAT_NN)          /* 6.3.2 */
1222                         goto confirmation_failed;
1223                 return 0;
1224         }
1225
1226         if (entry->state != FEAT_CHANGING)              /* 6.6.2 */
1227                 return 0;
1228
1229         if (len == 0) {
1230                 if (dccp_feat_must_be_understood(feat)) /* 6.6.7 */
1231                         goto confirmation_failed;
1232                 /*
1233                  * Empty Confirm during connection setup: this means reverting
1234                  * to the `old' value, which in this case is the default. Since
1235                  * we handle default values automatically when no other values
1236                  * have been set, we revert to the old value by removing this
1237                  * entry from the list.
1238                  */
1239                 dccp_feat_list_pop(entry);
1240                 return 0;
1241         }
1242
1243         if (type == FEAT_NN) {
1244                 if (len > sizeof(entry->val.nn))
1245                         goto confirmation_failed;
1246
1247                 if (entry->val.nn == dccp_decode_value_var(val, len))
1248                         goto confirmation_succeeded;
1249
1250                 DCCP_WARN("Bogus Confirm for non-existing value\n");
1251                 goto confirmation_failed;
1252         }
1253
1254         /*
1255          * Parsing SP Confirms: the first element of @val is the preferred
1256          * SP value which the peer confirms, the remainder depends on @len.
1257          * Note that only the confirmed value need to be a valid SP value.
1258          */
1259         if (!dccp_feat_is_valid_sp_val(feat, *val))
1260                 goto confirmation_failed;
1261
1262         if (len == 1) {         /* peer didn't supply a preference list */
1263                 plist = val;
1264                 plen  = len;
1265         } else {                /* preferred value + preference list */
1266                 plist = val + 1;
1267                 plen  = len - 1;
1268         }
1269
1270         /* Check whether the peer got the reconciliation right (6.6.8) */
1271         if (dccp_feat_reconcile(&entry->val, plist, plen, server, 0) != *val) {
1272                 DCCP_WARN("Confirm selected the wrong value %u\n", *val);
1273                 return DCCP_RESET_CODE_OPTION_ERROR;
1274         }
1275         entry->val.sp.vec[0] = *val;
1276
1277 confirmation_succeeded:
1278         entry->state = FEAT_STABLE;
1279         return 0;
1280
1281 confirmation_failed:
1282         DCCP_WARN("Confirmation failed\n");
1283         return is_mandatory ? DCCP_RESET_CODE_MANDATORY_ERROR
1284                             : DCCP_RESET_CODE_OPTION_ERROR;
1285 }
1286
1287 /**
1288  * dccp_feat_handle_nn_established  -  Fast-path reception of NN options
1289  * @sk:         socket of an established DCCP connection
1290  * @mandatory:  whether @opt was preceded by a Mandatory option
1291  * @opt:        %DCCPO_CHANGE_L | %DCCPO_CONFIRM_R (NN only)
1292  * @feat:       NN number, one of %dccp_feature_numbers
1293  * @val:        NN value
1294  * @len:        length of @val in bytes
1295  *
1296  * This function combines the functionality of change_recv/confirm_recv, with
1297  * the following differences (reset codes are the same):
1298  *    - cleanup after receiving the Confirm;
1299  *    - values are directly activated after successful parsing;
1300  *    - deliberately restricted to NN features.
1301  * The restriction to NN features is essential since SP features can have non-
1302  * predictable outcomes (depending on the remote configuration), and are inter-
1303  * dependent (CCIDs for instance cause further dependencies).
1304  */
1305 static u8 dccp_feat_handle_nn_established(struct sock *sk, u8 mandatory, u8 opt,
1306                                           u8 feat, u8 *val, u8 len)
1307 {
1308         struct list_head *fn = &dccp_sk(sk)->dccps_featneg;
1309         const bool local = (opt == DCCPO_CONFIRM_R);
1310         struct dccp_feat_entry *entry;
1311         u8 type = dccp_feat_type(feat);
1312         dccp_feat_val fval;
1313
1314         dccp_feat_print_opt(opt, feat, val, len, mandatory);
1315
1316         /* Ignore non-mandatory unknown and non-NN features */
1317         if (type == FEAT_UNKNOWN) {
1318                 if (local && !mandatory)
1319                         return 0;
1320                 goto fast_path_unknown;
1321         } else if (type != FEAT_NN) {
1322                 return 0;
1323         }
1324
1325         /*
1326          * We don't accept empty Confirms, since in fast-path feature
1327          * negotiation the values are enabled immediately after sending
1328          * the Change option.
1329          * Empty Changes on the other hand are invalid (RFC 4340, 6.1).
1330          */
1331         if (len == 0 || len > sizeof(fval.nn))
1332                 goto fast_path_unknown;
1333
1334         if (opt == DCCPO_CHANGE_L) {
1335                 fval.nn = dccp_decode_value_var(val, len);
1336                 if (!dccp_feat_is_valid_nn_val(feat, fval.nn))
1337                         goto fast_path_unknown;
1338
1339                 if (dccp_feat_push_confirm(fn, feat, local, &fval) ||
1340                     dccp_feat_activate(sk, feat, local, &fval))
1341                         return DCCP_RESET_CODE_TOO_BUSY;
1342
1343                 /* set the `Ack Pending' flag to piggyback a Confirm */
1344                 inet_csk_schedule_ack(sk);
1345
1346         } else if (opt == DCCPO_CONFIRM_R) {
1347                 entry = dccp_feat_list_lookup(fn, feat, local);
1348                 if (entry == NULL || entry->state != FEAT_CHANGING)
1349                         return 0;
1350
1351                 fval.nn = dccp_decode_value_var(val, len);
1352                 /*
1353                  * Just ignore a value that doesn't match our current value.
1354                  * If the option changes twice within two RTTs, then at least
1355                  * one CONFIRM will be received for the old value after a
1356                  * new CHANGE was sent.
1357                  */
1358                 if (fval.nn != entry->val.nn)
1359                         return 0;
1360
1361                 /* Only activate after receiving the Confirm option (6.6.1). */
1362                 dccp_feat_activate(sk, feat, local, &fval);
1363
1364                 /* It has been confirmed - so remove the entry */
1365                 dccp_feat_list_pop(entry);
1366
1367         } else {
1368                 DCCP_WARN("Received illegal option %u\n", opt);
1369                 goto fast_path_failed;
1370         }
1371         return 0;
1372
1373 fast_path_unknown:
1374         if (!mandatory)
1375                 return dccp_push_empty_confirm(fn, feat, local);
1376
1377 fast_path_failed:
1378         return mandatory ? DCCP_RESET_CODE_MANDATORY_ERROR
1379                          : DCCP_RESET_CODE_OPTION_ERROR;
1380 }
1381
1382 /**
1383  * dccp_feat_parse_options  -  Process Feature-Negotiation Options
1384  * @sk: for general use and used by the client during connection setup
1385  * @dreq: used by the server during connection setup
1386  * @mandatory: whether @opt was preceded by a Mandatory option
1387  * @opt: %DCCPO_CHANGE_L | %DCCPO_CHANGE_R | %DCCPO_CONFIRM_L | %DCCPO_CONFIRM_R
1388  * @feat: one of %dccp_feature_numbers
1389  * @val: value contents of @opt
1390  * @len: length of @val in bytes
1391  *
1392  * Returns 0 on success, a Reset code for ending the connection otherwise.
1393  */
1394 int dccp_feat_parse_options(struct sock *sk, struct dccp_request_sock *dreq,
1395                             u8 mandatory, u8 opt, u8 feat, u8 *val, u8 len)
1396 {
1397         struct dccp_sock *dp = dccp_sk(sk);
1398         struct list_head *fn = dreq ? &dreq->dreq_featneg : &dp->dccps_featneg;
1399         bool server = false;
1400
1401         switch (sk->sk_state) {
1402         /*
1403          *      Negotiation during connection setup
1404          */
1405         case DCCP_LISTEN:
1406                 server = true;                  /* fall through */
1407         case DCCP_REQUESTING:
1408                 switch (opt) {
1409                 case DCCPO_CHANGE_L:
1410                 case DCCPO_CHANGE_R:
1411                         return dccp_feat_change_recv(fn, mandatory, opt, feat,
1412                                                      val, len, server);
1413                 case DCCPO_CONFIRM_R:
1414                 case DCCPO_CONFIRM_L:
1415                         return dccp_feat_confirm_recv(fn, mandatory, opt, feat,
1416                                                       val, len, server);
1417                 }
1418                 break;
1419         /*
1420          *      Support for exchanging NN options on an established connection.
1421          */
1422         case DCCP_OPEN:
1423         case DCCP_PARTOPEN:
1424                 return dccp_feat_handle_nn_established(sk, mandatory, opt, feat,
1425                                                        val, len);
1426         }
1427         return 0;       /* ignore FN options in all other states */
1428 }
1429
1430 /**
1431  * dccp_feat_init  -  Seed feature negotiation with host-specific defaults
1432  * This initialises global defaults, depending on the value of the sysctls.
1433  * These can later be overridden by registering changes via setsockopt calls.
1434  * The last link in the chain is finalise_settings, to make sure that between
1435  * here and the start of actual feature negotiation no inconsistencies enter.
1436  *
1437  * All features not appearing below use either defaults or are otherwise
1438  * later adjusted through dccp_feat_finalise_settings().
1439  */
1440 int dccp_feat_init(struct sock *sk)
1441 {
1442         struct list_head *fn = &dccp_sk(sk)->dccps_featneg;
1443         u8 on = 1, off = 0;
1444         int rc;
1445         struct {
1446                 u8 *val;
1447                 u8 len;
1448         } tx, rx;
1449
1450         /* Non-negotiable (NN) features */
1451         rc = __feat_register_nn(fn, DCCPF_SEQUENCE_WINDOW, 0,
1452                                     sysctl_dccp_sequence_window);
1453         if (rc)
1454                 return rc;
1455
1456         /* Server-priority (SP) features */
1457
1458         /* Advertise that short seqnos are not supported (7.6.1) */
1459         rc = __feat_register_sp(fn, DCCPF_SHORT_SEQNOS, true, true, &off, 1);
1460         if (rc)
1461                 return rc;
1462
1463         /* RFC 4340 12.1: "If a DCCP is not ECN capable, ..." */
1464         rc = __feat_register_sp(fn, DCCPF_ECN_INCAPABLE, true, true, &on, 1);
1465         if (rc)
1466                 return rc;
1467
1468         /*
1469          * We advertise the available list of CCIDs and reorder according to
1470          * preferences, to avoid failure resulting from negotiating different
1471          * singleton values (which always leads to failure).
1472          * These settings can still (later) be overridden via sockopts.
1473          */
1474         if (ccid_get_builtin_ccids(&tx.val, &tx.len))
1475                 return -ENOBUFS;
1476         if (ccid_get_builtin_ccids(&rx.val, &rx.len)) {
1477                 kfree(tx.val);
1478                 return -ENOBUFS;
1479         }
1480
1481         if (!dccp_feat_prefer(sysctl_dccp_tx_ccid, tx.val, tx.len) ||
1482             !dccp_feat_prefer(sysctl_dccp_rx_ccid, rx.val, rx.len))
1483                 goto free_ccid_lists;
1484
1485         rc = __feat_register_sp(fn, DCCPF_CCID, true, false, tx.val, tx.len);
1486         if (rc)
1487                 goto free_ccid_lists;
1488
1489         rc = __feat_register_sp(fn, DCCPF_CCID, false, false, rx.val, rx.len);
1490
1491 free_ccid_lists:
1492         kfree(tx.val);
1493         kfree(rx.val);
1494         return rc;
1495 }
1496
1497 int dccp_feat_activate_values(struct sock *sk, struct list_head *fn_list)
1498 {
1499         struct dccp_sock *dp = dccp_sk(sk);
1500         struct dccp_feat_entry *cur, *next;
1501         int idx;
1502         dccp_feat_val *fvals[DCCP_FEAT_SUPPORTED_MAX][2] = {
1503                  [0 ... DCCP_FEAT_SUPPORTED_MAX-1] = { NULL, NULL }
1504         };
1505
1506         list_for_each_entry(cur, fn_list, node) {
1507                 /*
1508                  * An empty Confirm means that either an unknown feature type
1509                  * or an invalid value was present. In the first case there is
1510                  * nothing to activate, in the other the default value is used.
1511                  */
1512                 if (cur->empty_confirm)
1513                         continue;
1514
1515                 idx = dccp_feat_index(cur->feat_num);
1516                 if (idx < 0) {
1517                         DCCP_BUG("Unknown feature %u", cur->feat_num);
1518                         goto activation_failed;
1519                 }
1520                 if (cur->state != FEAT_STABLE) {
1521                         DCCP_CRIT("Negotiation of %s %s failed in state %s",
1522                                   cur->is_local ? "local" : "remote",
1523                                   dccp_feat_fname(cur->feat_num),
1524                                   dccp_feat_sname[cur->state]);
1525                         goto activation_failed;
1526                 }
1527                 fvals[idx][cur->is_local] = &cur->val;
1528         }
1529
1530         /*
1531          * Activate in decreasing order of index, so that the CCIDs are always
1532          * activated as the last feature. This avoids the case where a CCID
1533          * relies on the initialisation of one or more features that it depends
1534          * on (e.g. Send NDP Count, Send Ack Vector, and Ack Ratio features).
1535          */
1536         for (idx = DCCP_FEAT_SUPPORTED_MAX; --idx >= 0;)
1537                 if (__dccp_feat_activate(sk, idx, 0, fvals[idx][0]) ||
1538                     __dccp_feat_activate(sk, idx, 1, fvals[idx][1])) {
1539                         DCCP_CRIT("Could not activate %d", idx);
1540                         goto activation_failed;
1541                 }
1542
1543         /* Clean up Change options which have been confirmed already */
1544         list_for_each_entry_safe(cur, next, fn_list, node)
1545                 if (!cur->needs_confirm)
1546                         dccp_feat_list_pop(cur);
1547
1548         dccp_pr_debug("Activation OK\n");
1549         return 0;
1550
1551 activation_failed:
1552         /*
1553          * We clean up everything that may have been allocated, since
1554          * it is difficult to track at which stage negotiation failed.
1555          * This is ok, since all allocation functions below are robust
1556          * against NULL arguments.
1557          */
1558         ccid_hc_rx_delete(dp->dccps_hc_rx_ccid, sk);
1559         ccid_hc_tx_delete(dp->dccps_hc_tx_ccid, sk);
1560         dp->dccps_hc_rx_ccid = dp->dccps_hc_tx_ccid = NULL;
1561         dccp_ackvec_free(dp->dccps_hc_rx_ackvec);
1562         dp->dccps_hc_rx_ackvec = NULL;
1563         return -1;
1564 }