structure optimizations again.
[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 28
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  *    SilcUInt16 truelen
168  *
169  *      True length of the packet.  This may be set by the caller before
170  *      calling any of the silc_packet_* routines.  If not provided the
171  *      library will calculate the values.
172  *
173  *    SilcPacketFlags flags
174  *
175  *      Packet flags. Flags are defined above.
176  *
177  *    SilcPacketType type
178  *
179  *      Type of the packet. Types are defined below.
180  *
181  *    unsigned char *src_id
182  *    SilcUInt8 src_id_len
183  *    SilcUInt8 src_id_type
184  *
185  *      Source ID, its length and type. On packet reception retuned ID's
186  *      are always the hash values of the ID's from the packet.
187  *
188  *    unsigned char *dst_id;
189  *    SilcUInt8 dst_id_len;
190  *    SilcUInt8 src_id_type;
191  *
192  *      Destination ID, its length and type. On packet reception retuned
193  *      ID's are always the hash values of the ID's from the packet.
194  *
195  *    bool long_pad
196  * 
197  *      If set to TRUE the packet will include the maximum padding allowed
198  *      in SILC packet, which is 128 bytes.  If FALSE only the amount of
199  *      padding needed will be applied.
200  *
201  *    SilcUInt16 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  *    SilcUInt8 padlen
209  *
210  *      The padded length of the packet.  This may be set by the caller
211  *      before calling any of the silc_packet_* routines. If not provided
212  *      the library will calculate the values.
213  *
214  *    SilcUInt32 sequence;
215  *
216  *      Packet sequence number.  Set only when this context is a parsed
217  *      packet.
218  *
219  *    SilcBuffer buffer
220  *
221  *      The actual packet data.  Set only when this context is a parsed
222  *      packet.
223  *
224  ***/
225 typedef struct {
226   SilcUInt16 truelen;
227   SilcPacketFlags flags;
228   SilcPacketType type;
229
230   unsigned char *src_id;
231   unsigned char *dst_id;
232   unsigned int src_id_len : 5;
233   unsigned int src_id_type : 2;
234   unsigned int dst_id_len : 5;
235   unsigned int dst_id_type : 2;
236   unsigned int long_pad : 1;      /* Set when maximum padding in packet */
237   unsigned int users : 9;         /* Reference counter */
238   unsigned int padlen : 8;
239
240   SilcUInt32 sequence;
241   SilcBuffer buffer;
242 } SilcPacketContext;
243
244 /****s* silccore/SilcPacketAPI/SilcPacketParserContext
245  *
246  * NAME
247  * 
248  *    typedef struct { ... } SilcPacketParserContext;
249  *
250  * DESCRIPTION
251  *
252  *    This context is used in packet reception when the function
253  *    silc_packet_receive_process calls parser callback that performs
254  *    the actual packet decryption and parsing. This context is sent as
255  *    argument to the parser function. This context must be free'd by
256  *    the parser callback function.
257  *
258  *    Following description of the fields:
259  *
260  *    SilcPacketContext *packet
261  *
262  *      The actual packet received from the network. In this phase the
263  *      context is not parsed, only the packet->buffer is allocated and
264  *      it includes the raw packet data, which is encrypted.
265  *
266  *    bool normal
267  *
268  *      Indicates whether the received packet is normal or special packet.
269  *      If special the parsing process is special also.
270  *
271  *    SilcSocketConnection sock
272  *
273  *      The associated connection.
274  *
275  *    void *context
276  *
277  *      User context that is sent to the silc_packet_receive_process
278  *      function. This usually includes application and connection specific
279  *      data.
280  *
281  ***/
282 typedef struct {
283   SilcPacketContext *packet;
284   bool normal;
285   SilcSocketConnection sock;
286   void *context;
287 } SilcPacketParserContext;
288
289 /****f* silccore/SilcPacketAPI/SilcPacketParserCallback
290  *
291  * SYNOPSIS
292  *
293  *    typedef bool (*SilcPacketParserCallback)(SilcPacketParserContext 
294  *                                             *parse_context);
295  *
296  * DESCRIPTION
297  *
298  *    This callback is given to the silc_packet_receive_process function.
299  *    The callback is called by the library every time a packet is
300  *    received from the network. After the packet has been decrypted
301  *    and at least partially parsed it is passed to the application
302  *    for further parsing using this callback and the SilcPacketParserContext
303  *    context. The application receiving the SilcPacketParserContext
304  *    must free it.
305  *
306  *    This returns TRUE if the library should continue packet processing
307  *    (assuming there is more data to be processed), and FALSE if the
308  *    upper layer does not want the library to continue but to leave the
309  *    rest of the data is the packet queue untouched.  Application may
310  *    want to do this for example if the cipher is not ready before 
311  *    processing a certain packet.  In this case the application wants
312  *    to recall the processing function with the correct cipher.
313  *
314  ***/
315 typedef bool (*SilcPacketParserCallback)(SilcPacketParserContext 
316                                          *parse_context, void *context);
317
318 /* Macros */
319
320 /****d* silccore/SilcPacketAPI/SILC_PACKET_LENGTH
321  *
322  * NAME
323  * 
324  *    #define SILC_PACKET_LENGTH ...
325  *
326  * DESCRIPTION
327  *
328  *    Returns true length of the packet. This is primarily used by the
329  *    libary in packet parsing phase but the application may use it as
330  *    well if needed.
331  *
332  * SOURCE
333  */
334 #define SILC_PACKET_LENGTH(__packet, __ret_truelen, __ret_paddedlen)    \
335 do {                                                                    \
336   SILC_GET16_MSB((__ret_truelen), (__packet)->data);                    \
337   (__ret_paddedlen) = (__ret_truelen) + (__packet)->data[4];            \
338 } while(0)
339 /***/
340
341 /****d* silccore/SilcPacketAPI/SILC_PACKET_DATALEN
342  *
343  * NAME
344  * 
345  *    #define SILC_PACKET_DATALEN ...
346  *
347  * DESCRIPTION
348  *
349  *    Calculates the data length with given header length.  This macro
350  *    can be used to check whether the data_len with header_len exceeds
351  *    SILC_PACKET_MAX_LEN.  If it does, this returns the new data_len
352  *    so that the SILC_PACKET_MAX_LEN is not exceeded.  If the data_len
353  *    plus header_len fits SILC_PACKET_MAX_LEN the returned data length
354  *    is the data_len given as argument.  This macro can be used when
355  *    assembling packet.
356  *
357  * SOURCE
358  */
359 #define SILC_PACKET_DATALEN(data_len, header_len)                         \
360   ((data_len + header_len) > SILC_PACKET_MAX_LEN ?                        \
361    data_len - ((data_len + header_len) - SILC_PACKET_MAX_LEN) : data_len)
362 /***/
363
364 /****d* silccore/SilcPacketAPI/SILC_PACKET_PADLEN
365  *
366  * NAME
367  * 
368  *    #define SILC_PACKET_PADLEN ...
369  *
370  * DESCRIPTION
371  *
372  *    Returns the length of the padding in the packet. This is used
373  *    by various library routines to determine needed padding length.
374  *
375  * SOURCE
376  */
377 #define SILC_PACKET_PADLEN(__packetlen, __blocklen)             \
378   SILC_PACKET_DEFAULT_PADLEN - (__packetlen) %                  \
379     ((__blocklen) ? (__blocklen) : SILC_PACKET_DEFAULT_PADLEN)
380 /***/
381
382 /****d* silccore/SilcPacketAPI/SILC_PACKET_PADLEN_MAX
383  *
384  * NAME
385  * 
386  *    #define SILC_PACKET_PADLEN_MAX ...
387  *
388  * DESCRIPTION
389  *
390  *    Returns the length of the padding up to the maximum length, which
391  *    is 128 butes. This is used by various library routines to determine
392  *    needed padding length.
393  *
394  * SOURCE
395  */
396 #define SILC_PACKET_PADLEN_MAX(__packetlen)                             \
397   SILC_PACKET_MAX_PADLEN - (__packetlen) % SILC_PACKET_MAX_PADLEN
398 /***/
399
400 /* Prototypes */
401
402 /****f* silccore/SilcPacketAPI/silc_packet_send
403  *
404  * SYNOPSIS
405  *
406  *    int silc_packet_send(SilcSocketConnection sock, bool force_send);
407  *
408  * DESCRIPTION
409  *
410  *    Actually sends the packet. This flushes the connections outgoing data
411  *    buffer. If data is sent directly to the network this returns the bytes
412  *    written, if error occured this returns -1 and if the data could not
413  *    be written directly to the network at this time this returns -2, in
414  *    which case the data should be queued by the caller and sent at some
415  *    later time. If `force_send' is TRUE this attempts to write the data
416  *    directly to the network, if FALSE, this returns -2.
417  *
418  ***/
419 int silc_packet_send(SilcSocketConnection sock, bool force_send);
420
421 /****f* silccore/SilcPacketAPI/silc_packet_encrypt
422  *
423  * SYNOPSIS
424  *
425  *    void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac, 
426  *                             SilcBuffer buffer, SilcUInt32 len);
427  *
428  * DESCRIPTION
429  *
430  *    Encrypts a packet. This also creates HMAC of the packet before 
431  *    encryption and adds the HMAC at the end of the buffer. This assumes
432  *    that there is enough free space at the end of the buffer to add the
433  *    computed HMAC. This is the normal way of encrypting packets, if some
434  *    other process of HMAC computing and encryption is needed this function
435  *    cannot be used. 
436  *
437  ***/
438 void silc_packet_encrypt(SilcCipher cipher, SilcHmac hmac, SilcUInt32 sequence,
439                          SilcBuffer buffer, SilcUInt32 len);
440
441 /****f* silccore/SilcPacketAPI/silc_packet_assemble
442  *
443  * SYNOPSIS
444  *
445  *    bool silc_packet_assemble(SilcPacketContext *packet, SilcRng rng,
446  *                              SilcCipher cipher, SilcHmac hmac,
447  *                              SilcSocketConnection sock,
448  *                              const unsigned char *data, SilcUInt32 data_len,
449  *                              const SilcBuffer assembled_packet);
450  *
451  * DESCRIPTION
452  *
453  *    Assembles new packet to be ready for encrypting and sending out.
454  *    The `packet' is filled by caller to include the packet header specific
455  *    values.  This prepares the socket connection's `sock' outoing buffer
456  *    for sending data, and returns the assembled packet to the 
457  *    `assembled_packet' pointer sent by the caller.  The `assembled_packet'
458  *    is a reference to the socket connection's outgoing buffer.  The
459  *    returned packet can be encrypted, and then sent to network by calling
460  *    silc_packet_send function.  The `assembled_packet' may be freely
461  *    modified (like encrypted etc.) but it must not be freed, since it is
462  *    reference from `sock' outgoing buffer, and it is const.
463  *
464  ***/
465 bool silc_packet_assemble(SilcPacketContext *packet, SilcRng rng,
466                           SilcCipher cipher, SilcHmac hmac,
467                           SilcSocketConnection sock,
468                           const unsigned char *data, SilcUInt32 data_len,
469                           const SilcBuffer assembled_packet);
470
471 /****f* silccore/SilcPacketAPI/silc_packet_send_prepare
472  *
473  * SYNOPSIS
474  *
475  *    bool silc_packet_send_prepare(SilcSocketConnection sock,
476  *                                  SilcUInt32 header_len,
477  *                                  SilcUInt32 pad_len,
478  *                                  SilcUInt32 data_len,
479  *                                  SilcHmac hmac,
480  *                                  const SilcBuffer packet);
481  *
482  * DESCRIPTION
483  *
484  *    This function can be used to prepare the outgoing data buffer in
485  *    the socket connection specified by `sock' for packet sending.
486  *    This is used internally by packet sending routines, but application
487  *    may call this if it doesn't call silc_packet_assemble function.
488  *    If that function is called then application must not call this since
489  *    that function calls this internally.
490  *
491  *    This returns the prepared data area into the `packet' pointer provided
492  *    caller, which can be used then to add data to it, and later encrypt
493  *    it.  The `packet' includes reference to the socket connection's
494  *    outgoing buffer.  The `packet' may be freely modified (like 
495  *    encrypted etc.) but it must not be freed, since it is reference from 
496  *    `sock' outgoing buffer, and it is const.
497  *
498  ***/
499 bool silc_packet_send_prepare(SilcSocketConnection sock,
500                               SilcUInt32 header_len,
501                               SilcUInt32 pad_len,
502                               SilcUInt32 data_len,
503                               SilcHmac hmac,
504                               const SilcBuffer packet);
505
506 /****f* silccore/SilcPacketAPI/silc_packet_receive
507  *
508  * SYNOPSIS
509  *
510  *    int silc_packet_receive(SilcSocketConnection sock);
511  *
512  * DESCRIPTION
513  *
514  *    Receives packet from network and reads the data into connection's
515  *    incoming data buffer. If the data was read directly this returns the
516  *    read bytes, if error occured this returns -1, if the data could not
517  *    be read directly at this time this returns -2 in which case the data
518  *    should be read again at some later time, or If EOF occured this returns
519  *    0.
520  *
521  ***/
522 int silc_packet_receive(SilcSocketConnection sock);
523
524 /****f* silccore/SilcPacketAPI/silc_packet_receive_process
525  *
526  * SYNOPSIS
527  *
528  *    bool silc_packet_receive_process(SilcSocketConnection sock,
529  *                                     bool local_is_router,
530  *                                     SilcCipher cipher, SilcHmac hmac,
531  *                                     SilcPacketParserCallback parser,
532  *                                     void *parser_context);
533  *
534  * DESCRIPTION
535  *
536  *    Processes and decrypts the incoming data, and calls parser callback
537  *    for each received packet that will handle the actual packet parsing.
538  *    If more than one packet was received this calls the parser multiple
539  *    times.  The parser callback will get context SilcPacketParserContext
540  *    that includes the packet and the `parser_context' sent to this
541  *    function. 
542  *
543  *    The `local_is_router' indicates whether the caller is router server
544  *    in which case the receiving process of a certain packet types may
545  *    be special.  Normal server and client must set it to FALSE.  The
546  *    SilcPacketParserContext will indicate also whether the received
547  *    packet was normal or special packet.
548  *
549  ***/
550 bool silc_packet_receive_process(SilcSocketConnection sock,
551                                  bool local_is_router,
552                                  SilcCipher cipher, SilcHmac hmac,
553                                  SilcUInt32 sequence,
554                                  SilcPacketParserCallback parser,
555                                  void *parser_context);
556
557 /****f* silccore/SilcPacketAPI/silc_packet_parse
558  *
559  * SYNOPSIS
560  *
561  *    SilcPacketType silc_packet_parse(SilcPacketContext *ctx);
562  *
563  * DESCRIPTION
564  *
565  *    Parses the packet. This is called when a whole packet is ready to be
566  *    parsed. The buffer sent must be already decrypted before calling this 
567  *    function. The len argument must be the true length of the packet. This 
568  *    function returns the type of the packet. The data section of the 
569  *    buffer is parsed, not head or tail sections.
570  *
571  ***/
572 SilcPacketType silc_packet_parse(SilcPacketContext *ctx, SilcCipher cipher);
573
574 /****f* silccore/SilcPacketAPI/silc_packet_parse_special
575  *
576  * SYNOPSIS
577  *
578  *    SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx);
579  *
580  * DESCRIPTION
581  *
582  *    Perform special SILC Packet header parsing. This is required to some
583  *    packet types that have the data payload encrypted with different key
584  *    than the header area plus padding of the packet. Hence, this parses
585  *    the header in a way that it does not take the data area into account
586  *    and parses the header and padding area only.
587  *
588  ***/
589 SilcPacketType silc_packet_parse_special(SilcPacketContext *ctx,
590                                          SilcCipher cipher);
591
592 /****f* silccore/SilcPacketAPI/silc_packet_context_alloc
593  *
594  * SYNOPSIS
595  *
596  *    SilcPacketContext *silc_packet_context_alloc();
597  *
598  * DESCRIPTION
599  *
600  *    Allocates a packet context. Packet contexts are used when 
601  *    packets are assembled and parsed. The context is freed by the
602  *    silc_packet_context_free function.
603  *
604  ***/
605 SilcPacketContext *silc_packet_context_alloc(void);
606
607 /****f* silccore/SilcPacketAPI/silc_packet_context_dup
608  *
609  * SYNOPSIS
610  *
611  *    SilcPacketContext *silc_packet_context_dup(SilcPacketContext *ctx);
612  *
613  * DESCRIPTION
614  *
615  *    Duplicates the packet context. It actually does not duplicate
616  *    any data, instead a reference counter is increased.
617  *
618  ***/
619 SilcPacketContext *silc_packet_context_dup(SilcPacketContext *ctx);
620
621 /****f* silccore/SilcPacketAPI/silc_packet_context_free
622  *
623  * SYNOPSIS
624  *
625  *    void silc_packet_context_free(SilcPacketContext *ctx);
626  *
627  * DESCRIPTION
628  *
629  *    Frees the packet context. The context is actually freed when the
630  *    reference counter hits zero.
631  *
632  ***/
633 void silc_packet_context_free(SilcPacketContext *ctx);
634
635 #endif