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