Added checking for maximum packet length.
[silc.git] / lib / silccore / silcpacket.h
1 /*
2
3   silcpacket.h 
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 /****h* silccore/Packet Protocol Interface
21  *
22  * DESCRIPTION
23  *
24  * Implementation of the packet routines for sending and receiving
25  * SILC Packets. These includes the data sending routines and data
26  * reading routines, encrypting and decrypting routines, packet assembling
27  * and packet parsing routines.
28  *
29  ***/
30
31 #ifndef SILCPACKET_H
32 #define SILCPACKET_H
33
34 /* Default byte size of the packet. */
35 #define SILC_PACKET_DEFAULT_SIZE SILC_SOCKET_BUF_SIZE
36
37 /* Header length without source and destination ID's. */
38 #define SILC_PACKET_HEADER_LEN 10
39
40 /* Minimum length of SILC Packet Header. This much is decrypted always
41    when packet is received to be able to get all the relevant data out
42    from the header. */
43 #define SILC_PACKET_MIN_HEADER_LEN 16
44
45 /* Maximum padding length */
46 #define SILC_PACKET_MAX_PADLEN 128
47
48 /* Default padding length */
49 #define SILC_PACKET_DEFAULT_PADLEN 16
50
51 /* Minimum packet length */
52 #define SILC_PACKET_MIN_LEN (SILC_PACKET_HEADER_LEN + 1)
53
54 /* Maximum packet length */
55 #define SILC_PACKET_MAX_LEN 0xffff
56
57 /* Maximum length of ID */
58 #define SILC_PACKET_MAX_ID_LEN 16
59
60 /****d* silccore/SilcPacketAPI/SilcPacketType
61  *
62  * NAME
63  * 
64  *    typedef unsigned char SilcPacketType;
65  *
66  * DESCRIPTION
67  *
68  *    SILC packet type definition and all the packet types.
69  *
70  * SOURCE
71  */
72 typedef unsigned char SilcPacketType;
73
74 /* SILC Packet types. */
75 #define SILC_PACKET_NONE                 0       /* NULL, never sent */
76 #define SILC_PACKET_DISCONNECT           1       /* Disconnection */
77 #define SILC_PACKET_SUCCESS              2       /* Success */
78 #define SILC_PACKET_FAILURE              3       /* Failure */
79 #define SILC_PACKET_REJECT               4       /* Rejected */
80 #define SILC_PACKET_NOTIFY               5       /* Notify message */
81 #define SILC_PACKET_ERROR                6       /* Error message */
82 #define SILC_PACKET_CHANNEL_MESSAGE      7       /* Message for channel */
83 #define SILC_PACKET_CHANNEL_KEY          8       /* Key of the channel */
84 #define SILC_PACKET_PRIVATE_MESSAGE      9       /* Private message */
85 #define SILC_PACKET_PRIVATE_MESSAGE_KEY  10      /* Private message key*/
86 #define SILC_PACKET_COMMAND              11      /* Command */
87 #define SILC_PACKET_COMMAND_REPLY        12      /* Reply to a command */
88 #define SILC_PACKET_KEY_EXCHANGE         13      /* Start of KE */
89 #define SILC_PACKET_KEY_EXCHANGE_1       14      /* KE1 */
90 #define SILC_PACKET_KEY_EXCHANGE_2       15      /* KE2 */
91 #define SILC_PACKET_CONNECTION_AUTH_REQUEST 16   /* Request of auth meth */
92 #define SILC_PACKET_CONNECTION_AUTH      17      /* Connectinon auth */
93 #define SILC_PACKET_NEW_ID               18      /* Sending new ID */
94 #define SILC_PACKET_NEW_CLIENT           19      /* Client registering */
95 #define SILC_PACKET_NEW_SERVER           20      /* Server registering */
96 #define SILC_PACKET_NEW_CHANNEL          21      /* Channel registering */
97 #define SILC_PACKET_REKEY                22      /* Re-key start */
98 #define SILC_PACKET_REKEY_DONE           23      /* Re-key done */
99 #define SILC_PACKET_HEARTBEAT            24      /* Heartbeat */
100 #define SILC_PACKET_KEY_AGREEMENT        25      /* Key Agreement request */
101 #define SILC_PACKET_RESUME_ROUTER        26      /* Backup router resume */
102 #define SILC_PACKET_FTP                  27      /* File Transfer */
103
104 #define SILC_PACKET_PRIVATE              200     /* Private range start  */
105 #define SILC_PACKET_MAX                  255     /* RESERVED */
106 /***/
107
108 /****d* silccore/SilcPacketAPI/SilcPacketVersion
109  *
110  * NAME
111  * 
112  *    typedef unsigned char SilcPacketVersion;
113  *
114  * DESCRIPTION
115  *
116  *    SILC packet version type definition.
117  *
118  ***/
119 typedef unsigned char SilcPacketVersion;
120
121 /****d* silccore/SilcPacketAPI/SilcPacketFlags
122  *
123  * NAME
124  * 
125  *    typedef unsigned char SilcPacketFlags;
126  *
127  * DESCRIPTION
128  *
129  *    SILC packet flags type definition and all the packet flags.
130  *
131  * SOURCE
132  */
133 typedef unsigned char SilcPacketFlags;
134
135 /* All defined packet flags */
136 #define SILC_PACKET_FLAG_NONE             0x00    /* No flags */
137 #define SILC_PACKET_FLAG_PRIVMSG_KEY      0x01    /* Private message key */
138 #define SILC_PACKET_FLAG_LIST             0x02    /* Packet is a list */
139 #define SILC_PACKET_FLAG_BROADCAST        0x04    /* Packet is a broadcast */
140 /***/
141
142 /* Rest of flags still available
143 #define SILC_PACKET_FLAG_XXX              0x08
144 #define SILC_PACKET_FLAG_XXX              0x10
145 #define SILC_PACKET_FLAG_XXX              0x20
146 #define SILC_PACKET_FLAG_XXX              0x40
147 #define SILC_PACKET_FLAG_XXX              0x80
148 */
149
150 /****s* silccore/SilcPacketAPI/SilcPacketContext
151  *
152  * NAME
153  * 
154  *    typedef struct { ... } SilcPacketContext;
155  *
156  * DESCRIPTION
157  *
158  *    In packet sending this is filled and sent to silc_packet_assemble 
159  *    which then uses it to assemble new packet. In packet reception pointer 
160  *    to this context is sent to silc_packet_parse which parses the packet 
161  *    and returns the relevant information to this structure. On packet 
162  *    reception returned ID's are always the hash values of the ID's from 
163  *    the packet. 
164  *
165  *    Short description of the fields following:
166  *
167  *    SilcBuffer buffer
168  *
169  *      The data buffer.
170  *
171  *    SilcPacketType type
172  *
173  *      Type of the packet. Types are defined below.
174  *
175  *    SilcPacketFlags flags
176  *
177  *      Packet flags. Flags are defined above.
178  *
179  *    unsigned char *src_id
180  *    SilcUInt8 src_id_len
181  *    unsigned char src_id_type
182  *
183  *      Source ID, its length and type. On packet reception retuned ID's
184  *      are always the hash values of the ID's from the packet.
185  *
186  *    unsigned char *dst_id;
187  *    SilcUInt8 dst_id_len;
188  *    unsigned char src_id_type;
189  *
190  *      Destination ID, its length and type. On packet reception retuned
191  *      ID's are always the hash values of the ID's from the packet.
192  *
193  *    SilcUInt16 truelen
194  *    SilcUInt8 padlen
195  *
196  *      The true lenght of the packet and the padded length of the packet.
197  *      These may be set by the caller before calling any of the 
198  *      silc_packet_* routines. If not provided the library will calculate
199  *      the values.
200  *
201  *    int users;
202  *
203  *      Reference counter for this context. The context is freed only 
204  *      after the reference counter hits zero. The counter is added
205  *      calling silc_packet_context_dup and decreased by calling the
206  *      silc_packet_context_free.
207  *
208  *    SilcUInt32 sequence;
209  *
210  *      Packet sequence number.
211  *
212  ***/
213 typedef struct {
214   SilcBuffer buffer;
215
216   SilcUInt16 truelen;
217   SilcPacketFlags flags;
218   SilcPacketType type;
219   SilcUInt8 padlen;
220
221   unsigned char *src_id;
222   SilcUInt8 src_id_len;
223   SilcUInt8 src_id_type;
224
225   unsigned char *dst_id;
226   SilcUInt8 dst_id_len;
227   SilcUInt8 dst_id_type;
228
229   int users;
230   bool long_pad;                /* Set to TRUE to use maximum padding
231                                    in packet (up to 256 bytes). */
232
233   SilcUInt32 sequence;
234 } SilcPacketContext;
235
236 /****s* silccore/SilcPacketAPI/SilcPacketParserContext
237  *
238  * NAME
239  * 
240  *    typedef struct { ... } SilcPacketParserContext;
241  *
242  * DESCRIPTION
243  *
244  *    This context is used in packet reception when the function
245  *    silc_packet_receive_process calls parser callback that performs
246  *    the actual packet decryption and parsing. This context is sent as
247  *    argument to the parser function. This context must be free'd by
248  *    the parser callback function.
249  *
250  *    Following description of the fields:
251  *
252  *    SilcPacketContext *packet
253  *
254  *      The actual packet received from the network. In this phase the
255  *      context is not parsed, only the packet->buffer is allocated and
256  *      it includes the raw packet data, which is encrypted.
257  *
258  *    bool normal
259  *
260  *      Indicates whether the received packet is normal or special packet.
261  *      If special the parsing process is special also.
262  *
263  *    SilcSocketConnection sock
264  *
265  *      The associated connection.
266  *
267  *    void *context
268  *
269  *      User context that is sent to the silc_packet_receive_process
270  *      function. This usually includes application and connection specific
271  *      data.
272  *
273  ***/
274 typedef struct {
275   SilcPacketContext *packet;
276   bool normal;
277   SilcSocketConnection sock;
278   void *context;
279 } SilcPacketParserContext;
280
281 /****f* silccore/SilcPacketAPI/SilcPacketParserCallback
282  *
283  * SYNOPSIS
284  *
285  *    typedef bool (*SilcPacketParserCallback)(SilcPacketParserContext 
286  *                                             *parse_context);
287  *
288  * DESCRIPTION
289  *
290  *    This callback is given to the silc_packet_receive_process function.
291  *    The callback is called by the library every time a packet is
292  *    received from the network. After the packet has been decrypted
293  *    and at least partially parsed it is passed to the application
294  *    for further parsing using this callback and the SilcPacketParserContext
295  *    context. The application receiving the SilcPacketParserContext
296  *    must free it.
297  *
298  *    This returns TRUE if the library should continue packet processing
299  *    (assuming there is more data to be processed), and FALSE if the
300  *    upper layer does not want the library to continue but to leave the
301  *    rest of the data is the packet queue untouched.  Application may
302  *    want to do this for example if the cipher is not ready before 
303  *    processing a certain packet.  In this case the application wants
304  *    to recall the processing function with the correct cipher.
305  *
306  ***/
307 typedef bool (*SilcPacketParserCallback)(SilcPacketParserContext 
308                                          *parse_context, void *context);
309
310 /* Macros */
311
312 /****d* silccore/SilcPacketAPI/SILC_PACKET_LENGTH
313  *
314  * NAME
315  * 
316  *    #define SILC_PACKET_LENGTH ...
317  *
318  * DESCRIPTION
319  *
320  *    Returns true length of the packet. This is primarily used by the
321  *    libary in packet parsing phase but the application may use it as
322  *    well if needed.
323  *
324  * SOURCE
325  */
326 #define SILC_PACKET_LENGTH(__packet, __ret_truelen, __ret_paddedlen)    \
327 do {                                                                    \
328   SILC_GET16_MSB((__ret_truelen), (__packet)->data);                    \
329   (__ret_paddedlen) = (__ret_truelen) + (__packet)->data[4];            \
330 } while(0)
331 /***/
332
333 /****d* silccore/SilcPacketAPI/SILC_PACKET_DATALEN
334  *
335  * NAME
336  * 
337  *    #define SILC_PACKET_DATALEN ...
338  *
339  * DESCRIPTION
340  *
341  *    Calculates the data length with given header length.  This macro
342  *    can be used to check whether the data_len with header_len exceeds
343  *    SILC_PACKET_MAX_LEN.  If it does, this returns the new data_len
344  *    so that the SILC_PACKET_MAX_LEN is not exceeded.  If the data_len
345  *    plus header_len fits SILC_PACKET_MAX_LEN the returned data length
346  *    is the data_len given as argument.  This macro can be used when
347  *    assembling packet.
348  *
349  * SOURCE
350  */
351 #define SILC_PACKET_DATALEN(data_len, header_len)                         \
352   ((data_len + header_len) > SILC_PACKET_MAX_LEN ?                        \
353    data_len - ((data_len + header_len) - SILC_PACKET_MAX_LEN) : data_len)
354 /***/
355
356 /****d* silccore/SilcPacketAPI/SILC_PACKET_PADLEN
357  *
358  * NAME
359  * 
360  *    #define SILC_PACKET_PADLEN ...
361  *
362  * DESCRIPTION
363  *
364  *    Returns the length of the padding in the packet. This is used
365  *    by various library routines to determine needed padding length.
366  *
367  * SOURCE
368  */
369 #define SILC_PACKET_PADLEN(__packetlen, __blocklen)             \
370   SILC_PACKET_DEFAULT_PADLEN - (__packetlen) %                  \
371     ((__blocklen) ? (__blocklen) : SILC_PACKET_DEFAULT_PADLEN)
372 /***/
373
374 /****d* silccore/SilcPacketAPI/SILC_PACKET_PADLEN_MAX
375  *
376  * NAME
377  * 
378  *    #define SILC_PACKET_PADLEN_MAX ...
379  *
380  * DESCRIPTION
381  *
382  *    Returns the length of the padding up to the maximum length, which
383  *    is 128 butes. This is used by various library routines to determine
384  *    needed padding length.
385  *
386  * SOURCE
387  */
388 #define SILC_PACKET_PADLEN_MAX(__packetlen)                             \
389   SILC_PACKET_MAX_PADLEN - (__packetlen) % SILC_PACKET_MAX_PADLEN
390 /***/
391
392 /* Prototypes */
393
394 /****f* silccore/SilcPacketAPI/silc_packet_send
395  *
396  * SYNOPSIS
397  *
398  *    int silc_packet_send(SilcSocketConnection sock, bool force_send);
399  *
400  * DESCRIPTION
401  *
402  *    Actually sends the packet. This flushes the connections outgoing data
403  *    buffer. If data is sent directly to the network this returns the bytes
404  *    written, if error occured this returns -1 and if the data could not
405  *    be written directly to the network at this time this returns -2, in
406  *    which case the data should be queued by the caller and sent at some
407  *    later time. If `force_send' is TRUE this attempts to write the data
408  *    directly to the network, if FALSE, this returns -2.
409  *
410  ***/
411 int silc_packet_send(SilcSocketConnection sock, bool force_send);
412
413 /****f* silccore/SilcPacketAPI/silc_packet_encrypt
414  *
415  * SYNOPSIS
416  *
417  *    void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac, 
418  *                             SilcBuffer buffer, SilcUInt32 len);
419  *
420  * DESCRIPTION
421  *
422  *    Encrypts a packet. This also creates HMAC of the packet before 
423  *    encryption and adds the HMAC at the end of the buffer. This assumes
424  *    that there is enough free space at the end of the buffer to add the
425  *    computed HMAC. This is the normal way of encrypting packets, if some
426  *    other process of HMAC computing and encryption is needed this function
427  *    cannot be used. 
428  *
429  ***/
430 void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac, SilcUInt32 sequence,
431                          SilcBuffer buffer, SilcUInt32 len);
432
433 /****f* silccore/SilcPacketAPI/silc_packet_assemble
434  *
435  * SYNOPSIS
436  *
437  *    void silc_packet_assemble(SilcPacketContext *ctx);
438  *
439  * DESCRIPTION
440  *
441  *    Assembles a new packet to be ready for send out. The buffer sent as
442  *    argument must include the data to be sent and it must not be encrypted. 
443  *    The packet also must have enough free space so that the SILC header
444  *    and padding maybe added to the packet. The packet is encrypted after 
445  *    this function has returned.
446  *
447  *    The buffer sent as argument should be something like following:
448  *
449  *    --------------------------------------------
450  *    | head             | data           | tail |
451  *    --------------------------------------------
452  *    ^                  ^
453  *    58 bytes           x bytes
454  *
455  *    So that the SILC header and 1 - 16 bytes of padding can fit to
456  *    the buffer. After assembly the buffer might look like this:
457  *
458  *    --------------------------------------------
459  *    | data                              |      |
460  *    --------------------------------------------
461  *    ^                                   ^
462  *    Start of assembled packet
463  *
464  *    Packet construct is as follows (* = won't be encrypted):
465  *
466  *    n bytes       SILC Header
467  *      2 bytes     Payload length  (*)
468  *      1 byte      Flags
469  *      1 byte      Packet type
470  *      2 bytes     Source ID Length
471  *      2 bytes     Destination ID Length
472  *      1 byte      Source ID Type
473  *      n bytes     Source ID
474  *      1 byte      Destination ID Type
475  *      n bytes     Destination ID
476  *
477  *    1 - 16 bytes    Padding
478  *
479  *    n bytes        Data payload
480  *
481  *    All fields in the packet will be authenticated by MAC. The MAC is
482  *    not computed here, it must be computed separately before encrypting
483  *    the packet.
484  *
485  ***/
486 void silc_packet_assemble(SilcPacketContext *ctx, SilcCipher cipher);
487
488 /****f* silccore/SilcPacketAPI/silc_packet_send_prepare
489  *
490  * SYNOPSIS
491  *
492  *    void silc_packet_send_prepare(SilcSocketConnection sock,
493  *                                  SilcUInt32 header_len,
494  *                                  SilcUInt32 padlen,
495  *                                  SilcUInt32 data_len);
496  *
497  * DESCRIPTION
498  *
499  *    Prepare outgoing data buffer for packet sending. This moves the data
500  *    area so that new packet may be added into it. If needed this allocates
501  *    more space to the buffer. This handles directly the connection's
502  *    outgoing buffer in SilcSocketConnection object.
503  *
504  ***/
505 void silc_packet_send_prepare(SilcSocketConnection sock,
506                               SilcUInt32 header_len,
507                               SilcUInt32 padlen,
508                               SilcUInt32 data_len);
509
510 /****f* silccore/SilcPacketAPI/silc_packet_receive
511  *
512  * SYNOPSIS
513  *
514  *    int silc_packet_receive(SilcSocketConnection sock);
515  *
516  * DESCRIPTION
517  *
518  *    Receives packet from network and reads the data into connection's
519  *    incoming data buffer. If the data was read directly this returns the
520  *    read bytes, if error occured this returns -1, if the data could not
521  *    be read directly at this time this returns -2 in which case the data
522  *    should be read again at some later time, or If EOF occured this returns
523  *    0.
524  *
525  ***/
526 int silc_packet_receive(SilcSocketConnection sock);
527
528 /****f* silccore/SilcPacketAPI/silc_packet_receive_process
529  *
530  * SYNOPSIS
531  *
532  *    bool silc_packet_receive_process(SilcSocketConnection sock,
533  *                                     bool local_is_router,
534  *                                     SilcCipher cipher, SilcHmac hmac,
535  *                                     SilcPacketParserCallback parser,
536  *                                     void *parser_context);
537  *
538  * DESCRIPTION
539  *
540  *    Processes and decrypts the incoming data, and calls parser callback
541  *    for each received packet that will handle the actual packet parsing.
542  *    If more than one packet was received this calls the parser multiple
543  *    times.  The parser callback will get context SilcPacketParserContext
544  *    that includes the packet and the `parser_context' sent to this
545  *    function. 
546  *
547  *    The `local_is_router' indicates whether the caller is router server
548  *    in which case the receiving process of a certain packet types may
549  *    be special.  Normal server and client must set it to FALSE.  The
550  *    SilcPacketParserContext will indicate also whether the received
551  *    packet was normal or special packet.
552  *
553  ***/
554 bool silc_packet_receive_process(SilcSocketConnection sock,
555                                  bool local_is_router,
556                                  SilcCipher cipher, SilcHmac hmac,
557                                  SilcUInt32 sequence,
558                                  SilcPacketParserCallback parser,
559                                  void *parser_context);
560
561 /****f* silccore/SilcPacketAPI/silc_packet_parse
562  *
563  * SYNOPSIS
564  *
565  *    SilcPacketType silc_packet_parse(SilcPacketContext *ctx);
566  *
567  * DESCRIPTION
568  *
569  *    Parses the packet. This is called when a whole packet is ready to be
570  *    parsed. The buffer sent must be already decrypted before calling this 
571  *    function. The len argument must be the true length of the packet. This 
572  *    function returns the type of the packet. The data section of the 
573  *    buffer is parsed, not head or tail sections.
574  *
575  ***/
576 SilcPacketType silc_packet_parse(SilcPacketContext *ctx, SilcCipher cipher);
577
578 /****f* silccore/SilcPacketAPI/silc_packet_parse_special
579  *
580  * SYNOPSIS
581  *
582  *    SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx);
583  *
584  * DESCRIPTION
585  *
586  *    Perform special SILC Packet header parsing. This is required to some
587  *    packet types that have the data payload encrypted with different key
588  *    than the header area plus padding of the packet. Hence, this parses
589  *    the header in a way that it does not take the data area into account
590  *    and parses the header and padding area only.
591  *
592  ***/
593 SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx,
594                                          SilcCipher cipher);
595
596 /****f* silccore/SilcPacketAPI/silc_packet_context_alloc
597  *
598  * SYNOPSIS
599  *
600  *    SilcPacketContext *silc_packet_context_alloc();
601  *
602  * DESCRIPTION
603  *
604  *    Allocates a packet context. Packet contexts are used when 
605  *    packets are assembled and parsed. The context is freed by the
606  *    silc_packet_context_free function.
607  *
608  ***/
609 SilcPacketContext *silc_packet_context_alloc(void);
610
611 /****f* silccore/SilcPacketAPI/silc_packet_context_dup
612  *
613  * SYNOPSIS
614  *
615  *    SilcPacketContext *silc_packet_context_dup(SilcPacketContext *ctx);
616  *
617  * DESCRIPTION
618  *
619  *    Duplicates the packet context. It actually does not duplicate
620  *    any data, instead a reference counter is increased.
621  *
622  ***/
623 SilcPacketContext *silc_packet_context_dup(SilcPacketContext *ctx);
624
625 /****f* silccore/SilcPacketAPI/silc_packet_context_free
626  *
627  * SYNOPSIS
628  *
629  *    void silc_packet_context_free(SilcPacketContext *ctx);
630  *
631  * DESCRIPTION
632  *
633  *    Frees the packet context. The context is actually freed when the
634  *    reference counter hits zero.
635  *
636  ***/
637 void silc_packet_context_free(SilcPacketContext *ctx);
638
639 #endif