added some support for session resuming (in client)
[gnutls:gnutls.git] / lib / gnutls.c
1 /*
2  *      Copyright (C) 2000 Nikos Mavroyanopoulos
3  *
4  * This file is part of GNUTLS.
5  *
6  * GNUTLS is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * GNUTLS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19  */
20
21 #include <defines.h>
22 #include "gnutls_int.h"
23 #include "gnutls_errors.h"
24 #include "debug.h"
25 #include "gnutls_compress.h"
26 #include "gnutls_plaintext.h"
27 #include "gnutls_cipher.h"
28 #include "gnutls_buffers.h"
29 #include "gnutls_handshake.h"
30 #include "gnutls_hash_int.h"
31 #include "gnutls_cipher_int.h"
32
33 GNUTLS_Version gnutls_get_current_version(GNUTLS_STATE state) {
34 GNUTLS_Version ver;
35         ver.local = state->connection_state.version.local;
36         ver.major = state->connection_state.version.major;
37         ver.minor = state->connection_state.version.minor;
38         return ver;
39 }
40
41 void gnutls_set_current_version(GNUTLS_STATE state, GNUTLS_Version version) {
42         state->connection_state.version.local = version.local;
43         state->connection_state.version.major = version.major;
44         state->connection_state.version.minor = version.minor;
45 }
46
47 int gnutls_is_secure_memory(const void* mem) {
48         return 0;
49 }
50
51 /* This function initializes the state to null (null encryption etc...) */
52 int gnutls_init(GNUTLS_STATE * state, ConnectionEnd con_end)
53 {
54         /* for gcrypt in order to be able to allocate memory */
55         gcry_set_allocation_handler(gnutls_malloc, secure_malloc,  gnutls_is_secure_memory, gnutls_realloc, free);
56
57         *state = gnutls_calloc(1, sizeof(GNUTLS_STATE_INT));
58         memset(*state, 0, sizeof(GNUTLS_STATE));
59         (*state)->security_parameters.entity = con_end;
60
61 /* Set the defaults (only to remind me that they should be allocated ) */
62         (*state)->security_parameters.bulk_cipher_algorithm = GNUTLS_NULL;
63         (*state)->security_parameters.mac_algorithm = GNUTLS_MAC_NULL;
64         (*state)->security_parameters.compression_algorithm = GNUTLS_COMPRESSION_NULL;
65
66         (*state)->connection_state.read_compression_state = NULL;
67         (*state)->connection_state.read_mac_secret = NULL;
68         (*state)->connection_state.write_compression_state = NULL;
69         (*state)->connection_state.write_mac_secret = NULL;
70
71         (*state)->cipher_specs.server_write_mac_secret = NULL;
72         (*state)->cipher_specs.client_write_mac_secret = NULL;
73         (*state)->cipher_specs.server_write_IV = NULL;
74         (*state)->cipher_specs.client_write_IV = NULL;
75         (*state)->cipher_specs.server_write_key = NULL;
76         (*state)->cipher_specs.client_write_key = NULL;
77
78         (*state)->gnutls_internals.buffer = NULL;
79         /* SSL3 stuff */
80         (*state)->gnutls_internals.hash_buffer = NULL;
81         
82         (*state)->gnutls_internals.buffer_handshake = NULL;
83         (*state)->gnutls_internals.resumable = RESUME_TRUE;
84
85         gnutls_set_current_version ( (*state), GNUTLS_TLS1); /* default */
86
87         (*state)->gnutls_internals.KEY = NULL;
88         (*state)->gnutls_internals.client_Y = NULL;
89         (*state)->gnutls_internals.client_p = NULL;
90         (*state)->gnutls_internals.client_g = NULL;
91         (*state)->gnutls_internals.dh_secret = NULL;
92         
93         (*state)->gnutls_internals.certificate_requested = 0;
94         (*state)->gnutls_internals.certificate_verify_needed = 0;
95
96         (*state)->gnutls_internals.MACAlgorithmPriority.algorithm_priority=NULL;
97         (*state)->gnutls_internals.MACAlgorithmPriority.algorithms=0;
98
99         (*state)->gnutls_internals.KXAlgorithmPriority.algorithm_priority=NULL;
100         (*state)->gnutls_internals.KXAlgorithmPriority.algorithms=0;
101
102         (*state)->gnutls_internals.BulkCipherAlgorithmPriority.algorithm_priority=NULL;
103         (*state)->gnutls_internals.BulkCipherAlgorithmPriority.algorithms=0;
104
105         (*state)->gnutls_internals.CompressionMethodPriority.algorithm_priority=NULL;
106         (*state)->gnutls_internals.CompressionMethodPriority.algorithms=0;
107
108         /* Set default priorities */
109         gnutls_set_cipher_priority( (*state), 2, GNUTLS_RIJNDAEL, GNUTLS_3DES);
110         gnutls_set_compression_priority( (*state), 1, GNUTLS_COMPRESSION_NULL);
111         gnutls_set_kx_priority( (*state), 2, GNUTLS_KX_DHE_DSS, GNUTLS_KX_DHE_RSA);
112         gnutls_set_mac_priority( (*state), 2, GNUTLS_MAC_SHA, GNUTLS_MAC_MD5);
113
114         (*state)->security_parameters.session_id_size = 0;
115         (*state)->gnutls_internals.resumed_security_parameters.session_id_size = 0;
116         (*state)->gnutls_internals.resumed = RESUME_FALSE;
117         return 0;
118 }
119
120 /* This function clears all buffers associated with the state. */
121 int gnutls_deinit(GNUTLS_STATE * state)
122 {
123         gnutls_free((*state)->connection_state.read_compression_state);
124         gnutls_free((*state)->connection_state.read_mac_secret);
125         gnutls_free((*state)->connection_state.write_compression_state);
126         gnutls_free((*state)->connection_state.write_mac_secret);
127
128         gnutls_free((*state)->gnutls_internals.buffer);
129         gnutls_free((*state)->gnutls_internals.buffer_handshake);
130
131         if ((*state)->connection_state.read_cipher_state != NULL)
132                 gnutls_cipher_deinit((*state)->connection_state.read_cipher_state);
133         if ((*state)->connection_state.write_cipher_state != NULL)
134                 gnutls_cipher_deinit((*state)->connection_state.write_cipher_state);
135
136         secure_free((*state)->cipher_specs.server_write_mac_secret);
137         secure_free((*state)->cipher_specs.client_write_mac_secret);
138         secure_free((*state)->cipher_specs.server_write_IV);
139         secure_free((*state)->cipher_specs.client_write_IV);
140         secure_free((*state)->cipher_specs.server_write_key);
141         secure_free((*state)->cipher_specs.client_write_key);
142
143         mpi_release((*state)->gnutls_internals.KEY);
144         mpi_release((*state)->gnutls_internals.client_Y);
145         mpi_release((*state)->gnutls_internals.client_p);
146         mpi_release((*state)->gnutls_internals.client_g);
147         mpi_release((*state)->gnutls_internals.dh_secret);
148
149         /* free priorities */
150         if ((*state)->gnutls_internals.MACAlgorithmPriority.algorithm_priority!=NULL)
151                 gnutls_free((*state)->gnutls_internals.MACAlgorithmPriority.algorithm_priority);
152         if ((*state)->gnutls_internals.KXAlgorithmPriority.algorithm_priority!=NULL)
153                 gnutls_free((*state)->gnutls_internals.KXAlgorithmPriority.algorithm_priority);
154         if ((*state)->gnutls_internals.BulkCipherAlgorithmPriority.algorithm_priority!=NULL)
155                 gnutls_free((*state)->gnutls_internals.BulkCipherAlgorithmPriority.algorithm_priority);
156
157
158         gnutls_free(*state);
159         return 0;
160 }
161
162
163 static void *_gnutls_cal_PRF_A( MACAlgorithm algorithm, void *secret, int secret_size, void *seed, int seed_size)
164 {
165         GNUTLS_MAC_HANDLE td1;
166
167         td1 = gnutls_hmac_init(algorithm, secret, secret_size);
168         gnutls_hmac(td1, seed, seed_size);
169         return gnutls_hmac_deinit(td1);
170 }
171
172
173 /* Produces "total_bytes" bytes using the hash algorithm specified.
174  * (used in the PRF function)
175  */
176 static svoid *gnutls_P_hash( MACAlgorithm algorithm, opaque * secret, int secret_size, opaque * seed, int seed_size, int total_bytes)
177 {
178
179         GNUTLS_MAC_HANDLE td2;
180         opaque *ret;
181         void *A, *Atmp;
182         int i = 0, times, how, blocksize, A_size;
183         void *final;
184
185         ret = secure_calloc(1, total_bytes);
186
187         blocksize = gnutls_hmac_get_algo_len(algorithm);
188         do {
189                 i += blocksize;
190         } while (i < total_bytes);
191
192         /* calculate A(0) */
193         A = gnutls_malloc(seed_size);
194         memmove( A, seed, seed_size);
195         A_size = seed_size;
196
197         times = i / blocksize;
198         for (i = 0; i < times; i++) {
199                 td2 = gnutls_hmac_init(algorithm, secret, secret_size);
200
201                 /* here we calculate A(i+1) */
202                 Atmp = _gnutls_cal_PRF_A( algorithm, secret, secret_size, A, A_size);
203                 A_size = blocksize;
204                 gnutls_free(A);
205                 A = Atmp;
206
207                 gnutls_hmac(td2, A, A_size);
208                 gnutls_hmac(td2, seed, seed_size);
209                 final = gnutls_hmac_deinit(td2);
210
211                 if ( (1+i) * blocksize < total_bytes) {
212                         how = blocksize;
213                 } else {
214                         how = total_bytes - (i) * blocksize;
215                 }
216
217                 if (how > 0) {
218                         memmove(&ret[i * blocksize], final, how);
219                 }
220                 gnutls_free(final);
221         }
222
223         return ret;
224 }
225
226
227 /* The PRF function expands a given secret 
228  * needed by the TLS specification
229  */
230 svoid *gnutls_PRF( opaque * secret, int secret_size, uint8 * label, int label_size, opaque * seed, int seed_size, int total_bytes)
231 {
232         int l_s, i, s_seed_size;
233         char *o1, *o2;
234         char *s1, *s2;
235         char *s_seed;
236
237         /* label+seed = s_seed */
238         s_seed_size = seed_size + label_size;
239         s_seed = gnutls_malloc(s_seed_size);
240         memmove(s_seed, label, label_size);
241         memmove(&s_seed[label_size], seed, seed_size);
242
243         l_s = secret_size / 2;
244         s1 = &secret[0];
245         s2 = &secret[l_s];
246
247         if (secret_size % 2 != 0) {
248                 l_s++;
249         }
250
251         o1 = gnutls_P_hash( GNUTLS_MAC_MD5, s1, l_s, s_seed, s_seed_size, total_bytes);
252         o2 = gnutls_P_hash( GNUTLS_MAC_SHA, s2, l_s, s_seed, s_seed_size, total_bytes);
253
254         gnutls_free(s_seed);
255
256         for (i = 0; i < total_bytes; i++) {
257                 o1[i] ^= o2[i];
258         }
259
260         secure_free(o2);
261
262         return o1;
263
264 }
265
266 /* This function is to be called after handshake, when master_secret,
267  *  client_random and server_random have been initialized. 
268  * This function creates the keys and stores them into pending state.
269  * (state->cipher_specs)
270  */
271 int _gnutls_set_keys(GNUTLS_STATE state)
272 {
273         char *key_block;
274         char keyexp[] = "key expansion";
275         char random[64];
276         int hash_size;
277         int IV_size;
278         int key_size;
279
280         hash_size = state->security_parameters.hash_size;
281         IV_size = state->security_parameters.IV_size;
282         key_size = state->security_parameters.key_material_length;
283
284         memmove(random, state->security_parameters.server_random, 32);
285         memmove(&random[32], state->security_parameters.client_random, 32);
286
287         if (_gnutls_version_ssl3(state->connection_state.version) == 0) { /* SSL 3 */
288                 key_block = gnutls_ssl3_generate_random( state->security_parameters.master_secret, 48, random, 64,
289                         2 * hash_size + 2 * key_size + 2 * IV_size);
290         } else { /* TLS 1.0 */
291                 key_block =
292                     gnutls_PRF( state->security_parameters.master_secret, 48,
293                                keyexp, strlen(keyexp), random, 64, 2 * hash_size + 2 * key_size + 2 * IV_size);
294         }
295
296         state->cipher_specs.client_write_mac_secret = secure_malloc(hash_size);
297         memmove(state->cipher_specs.client_write_mac_secret, &key_block[0], hash_size);
298
299         state->cipher_specs.server_write_mac_secret = secure_malloc(hash_size);
300         memmove(state->cipher_specs.server_write_mac_secret, &key_block[hash_size], hash_size);
301
302         state->cipher_specs.client_write_key = secure_malloc(key_size);
303         memmove(state->cipher_specs.client_write_key, &key_block[2 * hash_size], key_size);
304
305         state->cipher_specs.server_write_key = secure_malloc(key_size);
306         memmove(state->cipher_specs.server_write_key, &key_block[2 * hash_size + key_size], key_size);
307
308         state->cipher_specs.client_write_IV = secure_malloc(IV_size);
309         memmove(state->cipher_specs.client_write_IV, &key_block[2 * key_size + 2 * hash_size], IV_size);
310
311         state->cipher_specs.server_write_IV = secure_malloc(IV_size);
312         memmove(state->cipher_specs.server_write_IV, &key_block[2 * hash_size + 2 * key_size + IV_size], IV_size);
313
314         secure_free(key_block);
315         return 0;
316 }
317
318 int _gnutls_send_alert(int cd, GNUTLS_STATE state, AlertLevel level, AlertDescription desc)
319 {
320         uint8 data[2];
321
322         memmove(&data[0], &level, 1);
323         memmove(&data[1], &desc, 1);
324
325         return gnutls_send_int(cd, state, GNUTLS_ALERT, data, 2);
326
327 }
328
329 int gnutls_close(int cd, GNUTLS_STATE state)
330 {
331         int ret;
332
333         ret = _gnutls_send_alert(cd, state, GNUTLS_WARNING, GNUTLS_CLOSE_NOTIFY);
334
335         /* receive pending data or the closure alert */
336         gnutls_recv_int(cd, state, GNUTLS_ALERT, NULL, 0); 
337
338         state->gnutls_internals.valid_connection = VALID_FALSE;
339
340         return ret;
341 }
342
343 int gnutls_close_nowait(int cd, GNUTLS_STATE state)
344 {
345         int ret;
346
347         ret = _gnutls_send_alert(cd, state, GNUTLS_WARNING, GNUTLS_CLOSE_NOTIFY);
348
349         state->gnutls_internals.valid_connection = VALID_FALSE;
350
351         return ret;
352 }
353
354 /* This function behave exactly like write(). The only difference is 
355  * that it accepts, the gnutls_state and the ContentType of data to
356  * send (if called by the user the Content is specific)
357  * It is intended to transfer data, under the current state.    
358  */
359 #define MAX_ENC_LEN 16384
360 ssize_t gnutls_send_int(int cd, GNUTLS_STATE state, ContentType type, void *_data, size_t sizeofdata)
361 {
362         uint8 *cipher;
363         int i, err, cipher_size;
364         int ret = 0;
365         int iterations;
366         uint16 length;
367         int Size;
368         uint8 headers[5];
369         uint8 *data=_data;
370
371         if (sizeofdata == 0)
372                 return 0;
373         if (state->gnutls_internals.valid_connection == VALID_FALSE) {
374                 return GNUTLS_E_INVALID_SESSION;
375         }
376
377         if (sizeofdata < MAX_ENC_LEN) {
378                 iterations = 1;
379                 Size = sizeofdata;
380         } else {
381                 iterations = sizeofdata / MAX_ENC_LEN;
382                 Size = MAX_ENC_LEN;
383         }
384
385         headers[0]=type;
386         headers[1]=state->connection_state.version.major;
387         headers[2]=state->connection_state.version.minor;
388         
389         for (i = 0; i < iterations; i++) {
390                 cipher_size = _gnutls_encrypt( state, &data[i*Size], Size, &cipher, type);
391                 if (cipher_size<=0) return cipher_size;
392 #ifdef WORDS_BIGENDIAN
393                 length = cipher_size;
394 #else
395                 length = byteswap16(cipher_size);
396 #endif
397                 memmove( &headers[3], &length, sizeof(uint16));
398                 if (_gnutls_Write(cd, headers, sizeof(headers)) != sizeof(headers)) {
399                         state->gnutls_internals.valid_connection = VALID_FALSE;
400                         state->gnutls_internals.resumable = RESUME_FALSE;
401                         gnutls_assert();
402                         return GNUTLS_E_UNABLE_SEND_DATA;
403                 }
404                 if (_gnutls_Write(cd, cipher, cipher_size) != cipher_size) {
405                         state->gnutls_internals.valid_connection = VALID_FALSE;
406                         state->gnutls_internals.resumable = RESUME_FALSE;
407                         gnutls_assert();
408                         return GNUTLS_E_UNABLE_SEND_DATA;
409                 }
410                 state->connection_state.write_sequence_number++;
411         }
412                 /* rest data */
413         if (iterations > 1) {
414                 Size = sizeofdata % MAX_ENC_LEN;
415                 cipher_size = _gnutls_encrypt( state, &data[i*Size], Size, &cipher, type);
416                 if (cipher_size<=0) return cipher_size;
417 #ifdef WORDS_BIGENDIAN
418                 length = cipher_size;
419 #else
420                 length = byteswap16(cipher_size);
421 #endif
422                 memmove( &headers[3], &length, sizeof(uint16));
423                 if (_gnutls_Write(cd, headers, sizeof(headers)) != sizeof(headers)) {
424                         state->gnutls_internals.valid_connection = VALID_FALSE;
425                         state->gnutls_internals.resumable = RESUME_FALSE;
426                         gnutls_assert();
427                         return GNUTLS_E_UNABLE_SEND_DATA;
428                 }
429                 if (_gnutls_Write(cd, cipher, cipher_size) != cipher_size) {
430                         state->gnutls_internals.valid_connection = VALID_FALSE;
431                         state->gnutls_internals.resumable = RESUME_FALSE;
432                         gnutls_assert();
433                         return GNUTLS_E_UNABLE_SEND_DATA;
434                 }
435                 state->connection_state.write_sequence_number++;
436         }
437
438         ret += sizeofdata;
439
440         gnutls_free(cipher);
441
442         return ret;
443 }
444
445 /* This function is to be called if the handshake was successfully 
446  * completed. This sends a Change Cipher Spec packet to the peer.
447  */
448 ssize_t _gnutls_send_change_cipher_spec(int cd, GNUTLS_STATE state)
449 {
450         uint16 length;
451         int ret = 0, Size;
452         uint8 type=GNUTLS_CHANGE_CIPHER_SPEC;
453         char data[1] = { GNUTLS_TYPE_CHANGE_CIPHER_SPEC };
454         uint8 headers[5];
455
456         if (state->gnutls_internals.valid_connection == VALID_FALSE) {
457                 return GNUTLS_E_INVALID_SESSION;
458         }
459
460         headers[0] = type;
461         headers[1] = state->connection_state.version.major;
462         headers[2] = state->connection_state.version.minor;
463
464 #ifdef HANDSHAKE_DEBUG
465         fprintf(stderr, "Send Change Cipher Spec\n");
466 #endif
467
468 #ifdef WORDS_BIGENDIAN
469         length = (uint16)1;
470 #else
471         length = byteswap16((uint16)1);
472 #endif
473         memmove( &headers[3], &length, sizeof(uint16));
474         
475         if (_gnutls_Write(cd, headers, 5) != 5) {
476                 state->gnutls_internals.valid_connection = VALID_FALSE;
477                 state->gnutls_internals.resumable = RESUME_FALSE;
478                 gnutls_assert();
479                 return GNUTLS_E_UNABLE_SEND_DATA;
480         }
481
482         if (_gnutls_Write(cd, &data, 1) != 1) {
483                 state->gnutls_internals.valid_connection = VALID_FALSE;
484                 state->gnutls_internals.resumable = RESUME_FALSE;
485                 gnutls_assert();
486                 return GNUTLS_E_UNABLE_SEND_DATA;
487         }
488         ret += 1;
489
490         return ret;
491 }
492
493 /* This function behave exactly like read(). The only difference is 
494  * that it accepts, the gnutls_state and the ContentType of data to
495  * send (if called by the user the Content is specific)
496  * It is intended to receive data, under the current state.
497  */
498 #define MAX_RECV_SIZE 18432     /* 2^14+2048 */
499 ssize_t gnutls_recv_int(int cd, GNUTLS_STATE state, ContentType type, char *data, size_t sizeofdata)
500 {
501         uint8 *tmpdata;
502         int tmplen;
503         GNUTLS_Version version;
504         uint8 recv_type;
505         uint16 length;
506         uint8 *ciphertext;
507         int ret = 0;
508
509         /* If we have enough data in the cache do not bother receiving
510          * a new packet. (in order to flush the cache)
511          */
512         if ( (type == GNUTLS_APPLICATION_DATA || type == GNUTLS_HANDSHAKE) && gnutls_getDataBufferSize(type, state) > 0) {
513                 ret = gnutls_getDataFromBuffer(type, state, data, sizeofdata);
514                 return ret;
515         }
516
517         if (state->gnutls_internals.valid_connection == VALID_FALSE) {
518                 return GNUTLS_E_INVALID_SESSION;
519         }
520
521         if ( _gnutls_Read(cd, &recv_type, 1) != 1) {
522                 state->gnutls_internals.valid_connection = VALID_FALSE;
523                 state->gnutls_internals.resumable = RESUME_FALSE;
524                 gnutls_assert();
525                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
526         }
527
528         version.local = 0; /* TLS/SSL 3.0 */
529         
530         if (_gnutls_Read(cd, &version.major, 1) != 1) {
531                 state->gnutls_internals.valid_connection = VALID_FALSE;
532                 state->gnutls_internals.resumable = RESUME_FALSE;
533                 gnutls_assert();
534                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
535         }
536
537         if (_gnutls_Read(cd, &version.minor, 1) != 1) {
538                 state->gnutls_internals.valid_connection = VALID_FALSE;
539                 state->gnutls_internals.resumable = RESUME_FALSE;
540                 gnutls_assert();
541                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
542         }
543
544         if (_gnutls_version_is_supported(state, version) == 0) {
545 #ifdef DEBUG
546                 fprintf(stderr, "INVALID VERSION PACKET: %d.%d\n", version.major, version.minor);
547 #endif
548                 _gnutls_send_alert(cd, state, GNUTLS_FATAL, GNUTLS_PROTOCOL_VERSION);
549                 state->gnutls_internals.resumable = RESUME_FALSE;
550                 gnutls_assert();
551                 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
552         } else {
553                 gnutls_set_current_version(state, version);
554         }
555
556         if (_gnutls_Read(cd, &length, 2) != 2) {
557                 state->gnutls_internals.valid_connection = VALID_FALSE;
558                 state->gnutls_internals.resumable = RESUME_FALSE;
559                 gnutls_assert();
560                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
561         }
562 #ifndef WORDS_BIGENDIAN
563         length = byteswap16(length);
564 #endif
565
566 #ifdef HARD_DEBUG
567         fprintf(stderr, "Expected Packet[%d] %s(%d) with length: %d\n",
568                 (int) state->connection_state.read_sequence_number, _gnutls_packet2str(type), type, sizeofdata);
569         fprintf(stderr, "Received Packet[%d] %s(%d) with length: %d\n",
570                 (int) state->connection_state.read_sequence_number, _gnutls_packet2str(recv_type), recv_type, length);
571 #endif
572
573         if (length > MAX_RECV_SIZE) {
574 #ifdef DEBUG
575                 fprintf(stderr, "FATAL ERROR: Received packet with length: %d\n", length);
576 #endif
577                 _gnutls_send_alert(cd, state, GNUTLS_FATAL, GNUTLS_RECORD_OVERFLOW);
578                 state->gnutls_internals.valid_connection = VALID_FALSE;
579                 state->gnutls_internals.resumable = RESUME_FALSE;
580                 gnutls_assert();
581                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
582         }
583
584         ciphertext = gnutls_malloc(length);
585
586         /* read ciphertext */
587
588         ret = _gnutls_Read(cd, ciphertext, length);
589
590         if (ret != length) {
591 #ifdef DEBUG
592                 fprintf(stderr, "Received packet with length: %d\nExpected %d\n", ret, length);
593 #endif
594                 gnutls_free(ciphertext);
595                 state->gnutls_internals.valid_connection = VALID_FALSE;
596                 state->gnutls_internals.resumable = RESUME_FALSE;
597                 gnutls_assert();
598                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
599         }
600         
601         if (type == GNUTLS_CHANGE_CIPHER_SPEC && recv_type == GNUTLS_CHANGE_CIPHER_SPEC) {
602 #ifdef HARD_DEBUG
603                 fprintf(stderr, "Received Change Cipher Spec Packet\n");
604 #endif
605                 if (length!=1) {
606                         gnutls_assert();
607                         gnutls_free(ciphertext);
608                         return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
609                 }
610                 return 0;
611         }
612
613         tmplen = _gnutls_decrypt( state, ciphertext, length, &tmpdata, type);
614         if (tmplen < 0) {
615                 switch (tmplen) {
616                         case GNUTLS_E_MAC_FAILED:
617                                 _gnutls_send_alert(cd, state, GNUTLS_FATAL, GNUTLS_BAD_RECORD_MAC);
618                                 break;
619                         case GNUTLS_E_DECRYPTION_FAILED:
620                                 _gnutls_send_alert(cd, state, GNUTLS_FATAL, GNUTLS_DECRYPTION_FAILED);
621                                 break;
622                         case GNUTLS_E_DECOMPRESSION_FAILED:
623                                 _gnutls_send_alert(cd, state, GNUTLS_FATAL, GNUTLS_DECOMPRESSION_FAILURE);
624                                 break;
625                 }
626                 state->gnutls_internals.valid_connection = VALID_FALSE;
627                 state->gnutls_internals.resumable = RESUME_FALSE;
628                 gnutls_assert();
629                 gnutls_free(ciphertext);
630                 return tmplen;
631         }
632
633         gnutls_free(ciphertext);
634
635         if ( (recv_type == type) && (type == GNUTLS_APPLICATION_DATA || type == GNUTLS_HANDSHAKE)) {
636                 gnutls_insertDataBuffer(type, state, (void *) tmpdata, tmplen);
637         } else {
638                 switch (recv_type) {
639                 case GNUTLS_ALERT:
640 #ifdef HARD_DEBUG
641                         fprintf(stderr, "Alert[%d|%d] - %s - was received\n", tmpdata[0], tmpdata[1], _gnutls_alert2str((int)tmpdata[1]));
642 #endif
643                         state->gnutls_internals.last_alert = tmpdata[1];
644
645                         if (tmpdata[1] == GNUTLS_CLOSE_NOTIFY && tmpdata[0] != GNUTLS_FATAL) {
646
647                                 /* If we have been expecting for an alert do 
648                                  * not call close().
649                                  */
650                                 if (type != GNUTLS_ALERT)
651                                         gnutls_close_nowait(cd, state);
652
653                                 return GNUTLS_E_CLOSURE_ALERT_RECEIVED;
654                         } else {
655                                 if (tmpdata[0] == GNUTLS_FATAL) {
656                                         state->gnutls_internals.valid_connection = VALID_FALSE;
657                                         state->gnutls_internals.resumable = RESUME_FALSE;
658                                         
659                                         return GNUTLS_E_FATAL_ALERT_RECEIVED;
660                                 }
661                                 return GNUTLS_E_WARNING_ALERT_RECEIVED;
662                         }
663                         break;
664
665                 case GNUTLS_CHANGE_CIPHER_SPEC:
666                         /* this packet is now handled above */
667                         gnutls_assert();
668                         return GNUTLS_E_UNEXPECTED_PACKET;
669
670                 default:
671                         gnutls_assert();
672                         return GNUTLS_E_UNKNOWN_ERROR;
673                 }
674         }
675
676
677
678         /* Incread sequence number */
679         state->connection_state.read_sequence_number++;
680
681
682
683         /* Get Application data from buffer */
684         if ((type == GNUTLS_APPLICATION_DATA || type == GNUTLS_HANDSHAKE) && (recv_type == type)) {
685                 ret = gnutls_getDataFromBuffer(type, state, data, sizeofdata);
686                 gnutls_free(tmpdata);
687         } else {
688                 if (recv_type != type) {
689                         gnutls_assert();
690                         return GNUTLS_E_RECEIVED_BAD_MESSAGE;
691                 }
692                 gnutls_assert(); /* this shouldn't have happened */
693                 ret = GNUTLS_E_RECEIVED_BAD_MESSAGE;
694         }
695
696         return ret;
697 }
698