Précédent   Forum du club des développeurs et IT Pro > C et C++ > C > Réseau
Réseau Forum d'entraide sur la programmation réseau en C
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse
 
Outils de la discussion
Publicité
'
Vieux 06/10/2008, 14h07   #21
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
bonjour
je n'avais effectivement pas mis de setsockopt. ce que j'ai fait...
seulement, quand je connecte deux clients en meme temps, ben le serveur ne recoi plus rien du tout .

je poste mon code si jamais j'ai fait une grosse boulette...
et je continue à chercher...

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/*CLIENT*/
 
#include "client_SSL.h"
#define CIPHER_LIST "ALL"
 
//////////////////////////////////////////////////////////////////
//								//
//			Fonction Principale			//
//								//
//////////////////////////////////////////////////////////////////
int main(argc,argv)
{          
int     err; 
 
 
 
int     verify_client = ON; /* To not verify a client certificate, set OFF */   
int     sock;         
struct sockaddr_in server_addr;     
char  *str;       
char    buf [100];         
char    hello[4096]; 
 
 
SSL_CTX         *ctx;       
SSL            *ssl;       
SSL_METHOD      *meth;      
X509            *server_cert;        
EVP_PKEY        *pkey; 
 
 
short int       s_port = 636;      
const char      *s_ipaddr = "10.102.13.114";      
 
FILE*fp_recu,*fp_enc,*fpin=NULL,*fpout=NULL,*fp,*fp_cle, *fp_emis;
int longueur=0;
 
int n=0,recp_fich;  
unsigned char *cipher=NULL,*plain=NULL;
int size=0,len=0,ks=0;
RSA *key=NULL;
long taille_fichier;
static int reconnect=0;
//int c;
  int i;
 
 /* while((c=getopt(argc,argv,"r"))!=-1){
      switch(c){
	case 'r':
          reconnect=1;
          break;break;
      }
}*/
  ////////////////////////////////////////////////////////////////
  /*INITIALIZATION*/
 
  /*message to send*/
  printf ("Message to be sent to the SSL server: ");          
  fgets (hello, 4096, stdin);       
 
  /* Load encryption & hashing algorithms for the SSL program */  
  SSL_library_init();     
 
  /* Load the error strings for SSL & CRYPTO APIs */      
  SSL_load_error_strings();      
 
  /* Create an SSL_METHOD structure (choose an SSL/TLS protocol version) */   
  meth = SSLv3_method();  
 
 
  /* Create an SSL_CTX structure */   
  ctx = SSL_CTX_new(meth);                                
  RETURN_NULL(ctx);   
 
 
  ////////////////////////////////////////////////////////////////  
  /*VERIFICATION*/
 
  if(verify_client == ON)         
      {               
      /* Load the client certificate into the SSL_CTX structure */               
      if (SSL_CTX_use_certificate_file(ctx, RSA_CLIENT_CERT, SSL_FILETYPE_PEM) <= 0) 
          {                   
          ERR_print_errors_fp(stderr);                        
          exit(1);            
          }               
 
      /* Load the private-key corresponding to the client certificate */          
      if (SSL_CTX_use_PrivateKey_file(ctx, RSA_CLIENT_KEY,SSL_FILETYPE_PEM) <= 0) 
          {                     
          ERR_print_errors_fp(stderr);                        
          exit(1);            
          }               
 
      /* Check if the client certificate and private-key matches */               
      if (!SSL_CTX_check_private_key(ctx)) 
          {                      
          fprintf(stderr,"Private key does not match the certificate public key\n");                    
          exit(1);            
          }   printf("Checking certificate and private key...\n");
      }       
 
 
  /* Load the RSA CA certificate into the SSL_CTX structure */        
  /* This will allow this client to verify the server's     */        
  /* certificate.                                           */ 
 
 
  if (!SSL_CTX_load_verify_locations(ctx, RSA_CLIENT_CA_CERT, NULL)) 
      {                
      ERR_print_errors_fp(stderr);                
      exit(1);    
      }         
 
  /* Set flag in context to require peer (server) certificate */        
  /* verification */         /*
  SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);         
  SSL_CTX_set_verify_depth(ctx,1);*/       
  printf("VERIFICATION OK!\n");
 
  if (SSL_CTX_set_cipher_list(ctx, CIPHER_LIST) != 1)
     {
     printf("Error setting cipher list (no valid ciphers)\n");
     }
 
  ////////////////////////////////////////////////////////////////
  /*SOCKET*/        
 
  /* Set up a TCP socket */       
  sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);              
  RETURN_ERR(sock, "socket");     
  memset (&server_addr, '\0', sizeof(server_addr));       
  server_addr.sin_family = AF_INET;  
  server_addr.sin_port = htons(s_port);       
 
  /* Server Port number */     
  server_addr.sin_addr.s_addr = inet_addr(s_ipaddr); 
 
  /* Server IP */      
 
  /* Establish a TCP/IP connection to the SSL client */           
  err = connect(sock, (struct sockaddr*) &server_addr, sizeof(server_addr));          
  RETURN_ERR(err, "connect");         
  printf("\n\n");
 
 
 
  ////////////////////////////////////////////////////////////////
  /*SSL*/
 
  /* An SSL structure is created */       
  ssl = SSL_new (ctx);    
  RETURN_NULL(ssl);       
 
  /* Assign the socket into the SSL structure (SSL and socket without BIO) */         
  SSL_set_fd(ssl, sock);  
 
  /* Perform SSL Handshake on the SSL client */       
  err = SSL_connect(ssl);         
  RETURN_SSL(err);        
 
  /* Informational output (optional) */       
  printf ("SSL connection using %s\n", SSL_get_cipher (ssl));     printf("\n\n");
 
  /* Get the server's certificate (optional) */       
  server_cert = SSL_get_peer_certificate (ssl);           
  if (server_cert != NULL)       
      {               
      printf ("Server certificate:\n"); 
      str = X509_NAME_oneline(X509_get_subject_name(server_cert),0,0);            
      RETURN_NULL(str);           
      printf ("\t subject: %s\n", str);           
      free (str);             
      str = X509_NAME_oneline(X509_get_issuer_name(server_cert),0,0);             
      RETURN_NULL(str);           
      printf ("\t issuer: %s\n", str);            
      free(str);              
      X509_free (server_cert); 
      }        
  else                
      {
      printf("The SSL server does not have certificate.\n");     }
 
  printf("\n\n");
 
 
  ////////////////////////////////////////////////////////////////
  /*-------- DATA EXCHANGE - send message and receive reply. -------*/        
  printf("\n************************************");
  printf("\nDATA EXCHANGE\n");
 
  /* Send data to the SSL server */   
  for(i = 0; i < 3; i++)
    {
 
    err = SSL_write(ssl, hello, strlen(hello));
 
    sleep(1);
    }   
 
  RETURN_SSL(err);     
 
  /* Receive data from the SSL server */      
 /* err = SSL_read(ssl, buf, sizeof(buf)-1);                        
  RETURN_SSL(err);    
  buf[err] = '\0';   
  printf ("Received %d chars:'%s'\n\n", err, buf); */
 
 
 
 
 
  printf("\nEND DATA EXCHANGE\n");
  printf("************************************\n");
 
 
  ////////////////////////////////////////////////////////////////
  /*--------------- SSL closure ---------------*/       
 
  /* Shutdown the client side of the SSL connection */         
  err = SSL_shutdown(ssl);        
  RETURN_SSL(err);         
 
  /* Terminate communication on a socket */        
  err = close(sock);         
  RETURN_ERR(err, "close");         
 
  /* Free the SSL structure */        
  SSL_free(ssl);         
 
  /* Free the SSL_CTX structure */        
  SSL_CTX_free(ctx);
 
  printf("Application terminate : good bye!\n");
 
}
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*SERVEUR*/
 
#include "serveur_SSL.h"
 
 
//////////////////////////////////////////////////////////////////
//								//
//			Fonction Principale			//
//								//
//////////////////////////////////////////////////////////////////
int main()
{    
 
 
  int     err;        
  int     verify_client = OFF; /* To verify a client certificate, set ON */       
  int     listen_sock;        
  int     sock;       
  struct sockaddr_in sa_serv;         
  struct sockaddr_in sa_cli;          
  size_t client_len;          
  char    *str;       
  char     buf[4096];     
  SSL_CTX         *ctx;        
  SSL            *ssl;       
  SSL_METHOD      *meth; 
  X509            *client_cert = NULL;    
  short int       s_port = 636;
 
 
  int address_size;
 
  FILE*fp,*fp_recu,*fpin,*fpout, *outfp, *infp, *decfp;
  int recp_fich=0,ks=0,longueur=0,n=0;
  unsigned char *cipher=NULL,*plain=NULL;
  int size=0,len=0;
  RSA *key=NULL;
  long taille_fichier;
 
  int mon_bool=TRUE;
  struct timeval tv;
 
 
  ////////////////////////////////////////////////////////////////
  /*Initialization*/
 
  /* Load encryption & hashing algorithms for the SSL program */  
  SSL_library_init();     
 
  /* Load the error strings for SSL & CRYPTO APIs */      
  SSL_load_error_strings();       
 
  /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */     
  meth = SSLv3_method();  
 
  /* Create a SSL_CTX structure */    
  ctx = SSL_CTX_new(meth);        
  if (!ctx) 
      {             
      ERR_print_errors_fp(stderr);            
      exit(1);        
      }       
 
  /* Load the server certificate into the SSL_CTX structure */       
  if (SSL_CTX_use_certificate_file(ctx, RSA_SERVER_CERT, SSL_FILETYPE_PEM) <= 0) 
      {                    
      ERR_print_errors_fp(stderr);                    
      exit(1);       
      }       
 
  /* Load the private-key corresponding to the server certificate */          
  if (SSL_CTX_use_PrivateKey_file(ctx, RSA_SERVER_KEY, SSL_FILETYPE_PEM) <= 0) 
      {               
      ERR_print_errors_fp(stderr);                
      exit(1);    
      }       
 
  /* Check if the server certificate and private-key matches */       
  if (!SSL_CTX_check_private_key(ctx)) 
      {                  
      fprintf(stderr,"Private key does not match the certificate public key\n");                  
      exit(1);    
      }      
 
  /*si on vérifie*/
  if(verify_client == ON)        
      {               
      /* Load the RSA CA certificate into the SSL_CTX structure */                
      if (!SSL_CTX_load_verify_locations(ctx, RSA_SERVER_CA_CERT, NULL)) 
          {                    
          ERR_print_errors_fp(stderr);                        
          exit(1);            
          }               
 
      /* Set to require peer (client) certificate verification */         
      SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);           
      /* Set the verification depth to 1 */               
      SSL_CTX_set_verify_depth(ctx,1);       
      }  
 
  printf("Initialization terminate\n\n");
 
  ////////////////////////////////////////////////////////////////
  /*SOCKET*/   
 
  /* Set up a TCP socket */       
  listen_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);        
  RETURN_ERR(listen_sock, "socket");          
  memset (&sa_serv, '\0', sizeof(sa_serv));       
  sa_serv.sin_family      = AF_INET;          
  sa_serv.sin_addr.s_addr = INADDR_ANY;       
  sa_serv.sin_port        = htons (s_port);     
 
  /* Server Port number */         
  err = bind(listen_sock, (struct sockaddr*)&sa_serv,sizeof(sa_serv));        
  RETURN_ERR(err, "bind");        
 
  /*setsockopt*/
  int bOptVal = 1;
  int bOptLen = sizeof(int);
  int iOptVal;
  int iOptLen = sizeof(int);
 
 
  if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptVal, bOptLen) != SO_ERROR) {
    printf("Set reuseaddr: ON\n");
  }
 
 
 
  /* Wait for an incoming TCP connection. */          
  err = listen(listen_sock, 5);                           
  RETURN_ERR(err, "listen");          
 
 
 
while(1)
  {
  /* Socket for a TCP/IP connection is created */ 
  printf("\nWAITING FOR CONNECTION\n\n");
  client_len = sizeof(sa_cli);    
  sock = accept(listen_sock, (struct sockaddr*)&sa_cli, &client_len);     
  RETURN_ERR(sock, "accept");         
  printf ("Connection from %lx, port %x\n", sa_cli.sin_addr.s_addr,sa_cli.sin_port);     
 
 
  ////////////////////////////////////////////////////////////////
  /*SSL*/      
 
  /* TCP connection is ready. */      
 
  /* A SSL structure is created */    
  ssl = SSL_new(ctx);     
  RETURN_NULL(ssl);       
 
  /* Assign the socket into the SSL structure (SSL and socket without BIO) */ 
  SSL_set_fd(ssl, sock);  
 
 
  /* Perform SSL Handshake on the SSL server */       
  err = SSL_accept(ssl);  
  RETURN_SSL(err);        
 
  /* Informational output (optional) */       
  printf("SSL connection using %s\n", SSL_get_cipher (ssl));    
 
  if (verify_client == ON)   
      {           
      /* Get the client's certificate (optional) */       
      client_cert = SSL_get_peer_certificate(ssl);        
      if (client_cert != NULL)            
          {               
          printf ("Client certificate:\n");                   
          str = X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0);                  
          RETURN_NULL(str);                   
          printf ("\t subject: %s\n", str);                   
          free (str);                 
          str = X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0);                   
          RETURN_NULL(str);                   
          printf ("\t issuer: %s\n", str);                    
          free (str);                 
          X509_free(client_cert);     
          }       
      else          
	  {          
          printf("The SSL client does not have certificate.\n");  
	  if (SSL_get_verify_result(ssl) != X509_V_OK) 
		{
		printf("client certificate verification failed!!!\n");
		tls_dump_verification_failure(SSL_get_verify_result(ssl));
		}
	  }
      }       
 
  ////////////////////////////////////////////////////////////////
  /*------- DATA EXCHANGE - Receive message and send reply. -------*/ 
 
  printf("\n************************************");
  printf("\nDATA EXCHANGE\n");
 
  while (mon_bool==TRUE)
      {
      fd_set readfs;
      tv.tv_sec = 5;
      tv.tv_usec = 0;
 
      FD_ZERO (&readfs);      /* clears readfs */
      FD_SET (sock, &readfs); /* adds a stream */
 
      int err = select (sock + 1, &readfs, NULL, NULL, &tv);
 
      switch (err)
          {
          case 0:
            /* timeout */
	    mon_bool=FALSE;
	    printf("time out\n");
            break;
 
          case -1:
            /* error */
            puts ("error\n");
	    mon_bool=FALSE;
            break;
 
          default:
          /* stream event */
 
          /* - data has been received */
 
          if (FD_ISSET (sock, &readfs))
              {
              err = SSL_read(ssl, buf, sizeof(buf));      
  	      RETURN_SSL(err);        
	      buf[err] = '\0';        
  	      if (err > 0)
                  {
                  /* process the received data */
		  printf ("Received %d chars:'%s'\n", err, buf); 
                  }
	      else
		  {
	          if (err==0)
		      {
		      mon_bool=FALSE;break;
		      }
		  }
              }
 
          /* - data has been sent */
 
          /* - an error has been received */
 
          }
   }
 
  /* Receive data from the SSL client */      
 /* err = SSL_read(ssl, buf, sizeof(buf));      
  RETURN_SSL(err);        buf[err] = '\0';        
  printf ("Received %d chars:'%s'\n", err, buf);  */
 
  /* Send data to the SSL client */   
/*  err = SSL_write(ssl, "This message is from the SSL server",strlen("This message is from the SSL server"));                 
  RETURN_SSL(err);        */
 
  mon_bool=TRUE;
  printf("\nEND DATA EXCHANGE\n");
  printf("************************************\n");
 
  ////////////////////////////////////////////////////////////////
  /*--------------- SSL closure ---------------*/     
 
  /* Shutdown this side (server) of the connection. */    
  err = SSL_shutdown(ssl);        
  RETURN_SSL(err);        
 
  /* Terminate communication on a socket */   
  err = close(sock);      
  RETURN_ERR(err, "close");      
  }
 
  /* Free the SSL structure */        
  SSL_free(ssl); 
 
  /* Free the SSL_CTX structure */   
  SSL_CTX_free(ctx); 
 
  printf("Application terminate : good bye!\n");
  close (listen_sock); 
  /*END*/
 
}
merci par avance pour votre aide..

[EDIT] en fin de compte, ca a l'air de fonctionner...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 07/10/2008, 09h52   #22
3DArchi
Rédacteur/Modérateur
 
Avatar de 3DArchi
 
Inscription : juin 2008
Messages : 7 631
Détails du profil
Informations forums :
Inscription : juin 2008
Messages : 7 631
Points : 12 159
Points : 12 159
Beaucoup de détails sont masqués par ton interface SSL.
Côté serveur: aïe: la boucle avec le listen puis la socket de réception est mal gérée à mon avis. En effet, dès que le premier listen réussi tu rentre dans ta boucle de réception. Cela empêche un second client de se connecter. Le schéma classique est:
-> un thread avec ta socket listen/accept.
-> un thread avec les sockets connectées (issues de l'accept) pour le traitement des messages.

Cependant, si tu veux rester sur un seul thread, cela devrait ressembler à quelque chose comme ça:
1/ Initialisation de ta socket d'écoute (mode non bloquant).
2/ listen sur cette socket
3/ boucle while(NonFini)
3.1/ Ajout de la socket d'écoute pour le select (je ne me souviens plus s'il faut la mettre dans le set de lecture ou d'écriture) puis de toute les sockets de connexions obtenus ensuite.
3.2/ Select
3.2.1/ Sortie du select sur timeout: traitement du timeout
3.2.2/ Sortie du select sur erreur: traitement de l'erreur
3.2.3/ Sortie du select sur un évènement socket:
3.2.3.1/ La socket d'écoute à déclencher la sortie: faire l'accept et rajouter la nouvelle socket dans l'ensemble adéquat pour le select
3.2.3.2/ sortie sur une des sockets de connexion: traiter la réception/envoi.
3DArchi est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 07/10/2008, 11h18   #23
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
je pense avoir fait comme tu m'as dit pour tout faire sur un thread (mon cerveau restant hermétique pour comprendre comment faire plusieurs thread mais je compte repotasser l'affaire dans l'aprem...)
et j'ai une erreur de segmentation sur cette ligne la...
je comprends pas pourquoi...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 07/10/2008, 11h28   #24
ram-0000
Rédacteur/Modérateur

 
Avatar de ram-0000
 
Homme Raymond
Inscription : mai 2007
Messages : 9 058
Détails du profil
Informations personnelles :
Nom : Homme Raymond
Localisation : France

Informations forums :
Inscription : mai 2007
Messages : 9 058
Points : 27 813
Points : 27 813
Bizarre parce que "fd_set readfs;" ne fait que allouer une variable locale. Tu dois avoir un problème ailleurs.
__________________
Raymond
Vous souhaitez participer à la rubrique Réseaux ? Contactez-moi

Cafuro Cafuro est un outil SNMP dont le but est d'aider les administrateurs système et réseau à configurer leurs équipements SNMP réseau.
e-verbe Un logiciel de conjugaison des verbes de la langue française.

Ma page personnelle sur DVP
.
ram-0000 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 07/10/2008, 11h36   #25
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
mea coulpa, l'erreur est sur :
Code :
FD_SET (sock, &readfs);
voila la version avec les changements, que j'espère que j'ai pas fait de boulette...
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*SERVEUR*/
 
#include "serveur_SSL.h"
 
 
//////////////////////////////////////////////////////////////////
//								//
//			Fonction Principale			//
//								//
//////////////////////////////////////////////////////////////////
int main()
{    
 
 
  int     err;        
  int     verify_client = OFF; /* To verify a client certificate, set ON */       
  int     listen_sock;        
  int     sock;       
  struct sockaddr_in sa_serv;         
  struct sockaddr_in sa_cli;          
  size_t client_len;          
  char    *str;       
  char     buf[4096];     
  SSL_CTX         *ctx;        
  SSL            *ssl;       
  SSL_METHOD      *meth; 
  X509            *client_cert = NULL;    
  short int       s_port = 636;
 
 
  int address_size;
 
  FILE*fp,*fp_recu,*fpin,*fpout, *outfp, *infp, *decfp;
  int recp_fich=0,ks=0,longueur=0,n=0;
  unsigned char *cipher=NULL,*plain=NULL;
  int size=0,len=0;
  RSA *key=NULL;
  long taille_fichier;
 
  int mon_bool=TRUE;
  struct timeval tv;
 
 
  ////////////////////////////////////////////////////////////////
  /*Initialization*/
 
  /* Load encryption & hashing algorithms for the SSL program */  
  SSL_library_init();     
 
  /* Load the error strings for SSL & CRYPTO APIs */      
  SSL_load_error_strings();       
 
  /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */     
  meth = SSLv3_method();  
 
  /* Create a SSL_CTX structure */    
  ctx = SSL_CTX_new(meth);        
  if (!ctx) 
      {             
      ERR_print_errors_fp(stderr);            
      exit(1);        
      }       
 
  /* Load the server certificate into the SSL_CTX structure */       
  if (SSL_CTX_use_certificate_file(ctx, RSA_SERVER_CERT, SSL_FILETYPE_PEM) <= 0) 
      {                    
      ERR_print_errors_fp(stderr);                    
      exit(1);       
      }       
 
  /* Load the private-key corresponding to the server certificate */          
  if (SSL_CTX_use_PrivateKey_file(ctx, RSA_SERVER_KEY, SSL_FILETYPE_PEM) <= 0) 
      {               
      ERR_print_errors_fp(stderr);                
      exit(1);    
      }       
 
  /* Check if the server certificate and private-key matches */       
  if (!SSL_CTX_check_private_key(ctx)) 
      {                  
      fprintf(stderr,"Private key does not match the certificate public key\n");                  
      exit(1);    
      }      
 
  /* Set the session id context*/
/*  SSL_CTX_set_session_id_context(ctx,
      (void*)&s_server_session_id_context,
      sizeof s_server_session_id_context); */
 
 
  /* if verify client */
  if(verify_client == ON)        
      {               
      /* Load the RSA CA certificate into the SSL_CTX structure */                
      if (!SSL_CTX_load_verify_locations(ctx, RSA_SERVER_CA_CERT, NULL)) 
          {                    
          ERR_print_errors_fp(stderr);                        
          exit(1);            
          }               
 
 
 
      /* Set to require peer (client) certificate verification */         
      SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);           
      /* Set the verification depth to 1 */               
      SSL_CTX_set_verify_depth(ctx,1);       
      }  
 
  printf("Initialization terminate\n\n");
 
  ////////////////////////////////////////////////////////////////
  /*SOCKET*/   
 
  /* Set up a TCP socket */       
  listen_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);        
  RETURN_ERR(listen_sock, "socket");          
  memset (&sa_serv, '\0', sizeof(sa_serv));       
  sa_serv.sin_family      = AF_INET;          
  sa_serv.sin_addr.s_addr = INADDR_ANY;       
  sa_serv.sin_port        = htons (s_port);     
 
  /* Server Port number */         
  err = bind(listen_sock, (struct sockaddr*)&sa_serv,sizeof(sa_serv));        
  RETURN_ERR(err, "bind");        
 
  /*setsockopt*/
  int bOptVal = 1;
  int bOptLen = sizeof(int);
  int iOptVal;
  int iOptLen = sizeof(int);
 
 
  if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptVal, bOptLen) != SO_ERROR) {
    printf("Set reuseaddr: ON\n");
  }
 
 
  /* Wait for an incoming TCP connection. */          
  err = listen(listen_sock, 5);                           
  RETURN_ERR(err, "listen");          
 
 
while(1)
  {
 
  while (mon_bool==TRUE)
      {
      fd_set readfs; 
      tv.tv_sec = 5;
      tv.tv_usec = 0;
 
      FD_ZERO (&readfs);      /* clears readfs */
      FD_SET (sock, &readfs); /* adds a stream */
 
      int err = select (sock + 1, &readfs, NULL, NULL, &tv);
 
      switch (err)
          {
          case 0:
            /* timeout */
	    mon_bool=FALSE;
	    printf("time out\n");
            break;
 
          case -1:
            /* error */
            puts ("error\n");
	    mon_bool=FALSE;
            break;
 
          default:
          /* stream event */
 
          /* - data has been received */
 
          if (FD_ISSET (sock, &readfs))
              {
             /* Socket for a TCP/IP connection is created */ 
  		printf("\nWAITING FOR CONNECTION\n\n");
 		 client_len = sizeof(sa_cli);    
 		 sock = accept(listen_sock, (struct sockaddr*)&sa_cli, &client_len);     
		  RETURN_ERR(sock, "accept");         
		  printf ("Connection from %lx, port %x\n", sa_cli.sin_addr.s_addr,sa_cli.sin_port);     
 
 
 		 ////////////////////////////////////////////////////////////////
 		 /*SSL*/      
 
 		 /* TCP connection is ready. */      
 
		  /* A SSL structure is created */    
		  ssl = SSL_new(ctx);     
		  RETURN_NULL(ssl);       
 
		  /* Assign the socket into the SSL structure (SSL and socket without BIO) */ 
 		 SSL_set_fd(ssl, sock);  
 
 
 		 /* Perform SSL Handshake on the SSL server */       
 		 err = SSL_accept(ssl);  
 		 RETURN_SSL(err);        
 
 		 /* Informational output (optional) */       
 		 printf("SSL connection using %s\n", SSL_get_cipher (ssl));    
 
 		 if (verify_client == ON)   
 		     {           
 		     /* Get the client's certificate (optional) */       
 		     client_cert = SSL_get_peer_certificate(ssl);        
 		     if (client_cert != NULL)            
 		         {               
 		         printf ("Client certificate:\n");                   
 		         str = X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0);                  
		          RETURN_NULL(str);                   
		          printf ("\t subject: %s\n", str);                   
  		         free (str);                 
     		        str = X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0);                   
		          RETURN_NULL(str);                   
  		        printf ("\t issuer: %s\n", str);                    
 		         free (str);                 
 		         X509_free(client_cert);     
 		         }       
 		     else          
			  {          
 	 	         printf("The SSL client does not have certificate.\n");  
			  if (SSL_get_verify_result(ssl) != X509_V_OK) 
				{
				printf("client certificate verification failed!!!\n");
				tls_dump_verification_failure(SSL_get_verify_result(ssl));
				}
			  }
 		     }       
 
		  ////////////////////////////////////////////////////////////////
		  /*------- DATA EXCHANGE - Receive message and send reply. -------*/ 
 
		  printf("\n************************************");
		  printf("\nDATA EXCHANGE\n");
 
 
 		err = SSL_read(ssl, buf, sizeof(buf));      
  			      RETURN_SSL(err);        
			      buf[err] = '\0';        
  			      if (err > 0)
  		                {
  		                /* process the received data */
				  printf ("Received %d chars:'%s'\n", err, buf); 
    		              }
			      else
				  {
			          if (err==0)
				      {
				      mon_bool=FALSE;break;
				      }
				  }
 		 /* Receive data from the SSL client */      
		 /* err = SSL_read(ssl, buf, sizeof(buf));      
		  RETURN_SSL(err);        buf[err] = '\0';        
		  printf ("Received %d chars:'%s'\n", err, buf);  */
 
 		 /* Send data to the SSL client */   
		/*  err = SSL_write(ssl, "This message is from the SSL server",strlen("This message is from the SSL 			server"));                 
 		 RETURN_SSL(err);        */
 
 		 mon_bool=TRUE;
 		 printf("\nEND DATA EXCHANGE\n");
 		 printf("************************************\n");
 
        		      }
 
    		      /* - data has been sent */
 
    		      /* - an error has been received */
 
    		      }
  		 }
 
  ////////////////////////////////////////////////////////////////
  /*--------------- SSL closure ---------------*/     
 
  /* Shutdown this side (server) of the connection. */    
  err = SSL_shutdown(ssl);        
  RETURN_SSL(err);        
 
  /* Terminate communication on a socket */   
  err = close(sock);      
  RETURN_ERR(err, "close");      
 
 
  /* Free the SSL structure */        
  SSL_free(ssl); 
}
  /* Free the SSL_CTX structure */   
  SSL_CTX_free(ctx); 
 
  printf("Application terminate : good bye!\n");
  close (listen_sock); 
  /*END*/
 
}
[EDIT] j'ai honte, c'est normal l'erreur, vu que je n'ai pas fait d'accept avant, il connait pas sock...
je rectifie ca de suite...

[EDIT 2 ] mais du coup j'ai un problème avec le select... ne faudrait il pas que je fasse l'accept avant quand meme??
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/10/2008, 15h06   #26
3DArchi
Rédacteur/Modérateur
 
Avatar de 3DArchi
 
Inscription : juin 2008
Messages : 7 631
Détails du profil
Informations forums :
Inscription : juin 2008
Messages : 7 631
Points : 12 159
Points : 12 159
Citation:
The parameter readfds identifies the sockets that are to be checked for readability. If the socket is currently in the listen state, it will be marked as readable if an incoming connection request has been received such that an accept is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading such that a call to recv or recvfrom is guaranteed not to block.
For connection-oriented sockets, readability can also indicate that a request to close the socket has been received from the peer. If the virtual circuit was closed gracefully, and all data was received, then a recv will return immediately with zero bytes read. If the virtual circuit was reset, then a recv will complete immediately with an error code such as WSAECONNRESET. The presence of OOB data will be checked if the socket option SO_OOBINLINE has been enabled (see setsockopt).
et
Citation:
The parameter writefds identifies the sockets that are to be checked for writability. If a socket is processing a connect call (nonblocking), a socket is writeable if the connection establishment successfully completes. If the socket is not processing a connect call, writability means a send or sendto are guaranteed to succeed. However, they can block on a blocking socket if the len parameter exceeds the amount of outgoing system buffer space available. It is not specified how long these guarantees can be assumed to be valid, particularly in a multithreaded environment.
Enfin:
Citation:
The parameter exceptfds identifies the sockets that are to be checked for the presence of OOB data or any exceptional error conditions.
3DArchi est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/10/2008, 15h32   #27
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
Bonjour

je suis repartie sur refaire un serveur en enlevant tout le ssl afin 'y voir plus clair...
du coup, je suis arrivée à ca :

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/* Program server */
 
#include <errno.h>
 
#include <stdlib.h>
 
#include <string.h>
 
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
 
#define FILED 5
#define T 1
#define F 0
 
/*constante*/
int port = 1234;
 
/*proto*/
void traiter_client(int sock);
 
 
//////////////////////////////////////////////////
//						//
//			MAIN			//
//						//
//////////////////////////////////////////////////
 
int main(int argc,char *argv[])
 
{
 
  /*déclaration*/
  struct sockaddr_in sin;
  struct sockaddr_in pin;
  int listen_sock;
  int sock;
  int address_size;
 
  int S_temp;
  fd_set liste_client[FILED]; 
 
  /*creation socket*/
  listen_sock = socket(PF_INET, SOCK_STREAM, 0);
  if (listen_sock ==-1)
    {
    perror("call to socket\n");
    exit(1);
    }
  printf("socket ok\n");
 
  /*initialization*/
  bzero(&sin,sizeof(sin));
  sin.sin_family=AF_INET;
  sin.sin_addr.s_addr=INADDR_ANY;
  sin.sin_port=htons(port);
 
  /*BIND*/
  if (bind(listen_sock, (struct sockaddr*)&sin, sizeof(sin))<0)
    {
    perror("call to bind\n");
    exit(-1);
    }
  printf("bind ok\n");
 
  /*setsockopt*/
  int bOptVal = 1;
  int bOptLen = sizeof(int);
  int iOptVal;
  int iOptLen = sizeof(int);
 
  if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptVal, bOptLen) != SO_ERROR) {
    printf("Set reuseaddr: ON\n");
  }
 
 
  /*LISTEN*/
  if (listen(listen_sock, FILED)<0)
    {
    perror("call to listen\n");
    exit(-2);
    }
 
  printf("waiting for connections...\n");
 
 
  /**/
  while(1)
    {
 
    FD_ZERO(liste_client); /*réinitialisation list of client*/
    FD_SET (listen_sock,liste_client); /*set with the socket*/
 
    /*select on the client list*/
    if ((select(FILED+1,liste_client, NULL, NULL, NULL))<0)
        {
        perror("call to select\n");
	}
 
    /*go to all client list*/
    for (S_temp=3; S_temp < FILED; S_temp++)
        {
	if (FD_ISSET(S_temp,liste_client))
		{
		/*if it is the connection socket*/
		if (S_temp==listen_sock)
			{
			/*accept the connection*/
			sock=accept(listen_sock, (struct sockaddr *)&pin,&address_size);
			if (sock<0)
				{
				perror("call to accept\n");
				exit(-3);
				}
			printf("connection socket n°%d is working\n",sock);
			FD_SET(sock,liste_client);
			}
		else {traiter_client(S_temp);}
		}
	}
 
 
    }
     /*close*/
    close(sock);
    close(listen_sock);
    exit(0);
 
}
 
 
//////////////////////////////////////////////////////////////////
//								//
//			traitement du client			//
//								//
//////////////////////////////////////////////////////////////////
void traiter_client(int sock)
{
 
  char buf[1024];
  int mon_bool=1;
 
  while (mon_bool==T)
      {
      int err = recv(sock, buf, sizeof(buf),0);            
      buf[err] = '\0';        
  	      if (err > 0)
                  {
                  /* process the received data */
		  printf ("Received %d chars:'%s'\n", err, buf); 
                  }
	      else
		  {
	          if (err==0)
		      {
		      mon_bool=F;
		      }
		  else
		      {
		      perror("call to receive\n");
		      exit(-5);
		      }
		  }
	}
  mon_bool=T;
  close(sock);
}


la buse en anglais se met au déchiffrement...

[EDIT] c y es, il fonctionne!
par contre quand je met deux clients, le premier arrivé, il m'affiche tout au fur et à mesure et pour le second, il doit mettre tout qq part et après il me rebalance tout...
Citation:
socket ok
bind ok
Set reuseaddr: ON
waiting for connections...
connection socket n°4 is working
Received 13 chars:'coucou cli 1
'
Received 13 chars:'coucou cli 1
'
Received 13 chars:'coucou cli 1
'
Received 13 chars:'coucou cli 1
'
Received 13 chars:'coucou cli 1
'
waiting for connections...
connection socket n°4 is working
Received 52 chars:'coucou cli 2
coucou cli 2
coucou cli 2
coucou cli 2
'
Received 13 chars:'coucou cli 2
'
waiting for connections...
que puis je faire pour que le serveur fasse tout en simultané...??

merci pour vos réponses../.
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/10/2008, 18h25   #28
Emmanuel Delahaye
Rédacteur
 
Avatar de Emmanuel Delahaye
 
Inscription : décembre 2003
Messages : 14 505
Détails du profil
Informations personnelles :
Âge : 56
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : décembre 2003
Messages : 14 505
Points : 19 321
Points : 19 321
Citation:
Envoyé par Bathou Voir le message
que puis je faire pour que le serveur fasse tout en simultané...
Ne pas boucler la fonction de traitement du client. Ici, tu fais de l'évènementiel, pas du multi-tâche...

Ceci fonctionne sous Windows (j'ai ouvert 3 clients Telnet). Non testé ailleurs, mais c'est censé fonctionner sous Linux. (en remettant un N° de port qui va bien)

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
 
/* Program server */
 
#ifdef __cplusplus
#error Be sure you are using a C compiler...
#endif
 
#if defined (WIN32) || defined (_WIN32)
 
#include <winsock2.h>
 
#elif defined (linux) || defined (_POSIX_VERSION) || defined (_POSIX2_C_VERSION)\
 || defined (_XOPEN_VERSION)
 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>             /* close */
 
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
 
#define closesocket(s) close (s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
 
#else
#error not defined for this platform
#endif
 
#include <stdio.h>
#include <stdlib.h>
 
/* macros ============================================================== */
/* constants =========================================================== */
 
/* constante */
#define port 23
 
/* types =============================================================== */
/* structures ========================================================== */
/* private data ======================================================== */
/* private functions =================================================== */
 
static int traiter_client (int sock_cli)
{
   int err = 0;
   char buf[1024];
 
   int n = recv (sock_cli, buf, sizeof (buf) - 1, 0);
 
   if (n > 0)
   {
      /* process the received data */
      buf[n] = '\0';
 
      printf ("Received %d chars:'%s' on socket %d\n", n, buf, sock_cli);
   }
   else
   {
      if (n == 0)
      {
         printf ("deconnexion socket %d\n", sock_cli);
      }
      else
      {
         printf ("receive error on socket %d\n", sock_cli);
      }
      err = 1;
   }
   return err;
}
 
static int get_cli_ndx (SOCKET a[], int n)
{
   int ndx = -1;
   int i;
   for (i = 0; i < n; i++)
   {
      if (a[i] == INVALID_SOCKET)
      {
         ndx = i;
         break;
      }
   }
   return ndx;
}
 
static int server (void)
{
   /* creation socket */
   SOCKET sock_srv = socket (PF_INET, SOCK_STREAM, 0);
   if (sock_srv == INVALID_SOCKET)
   {
      perror ("call to socket\n");
      exit (EXIT_FAILURE);
   }
   printf ("socket ok\n");
 
   /*initialization */
   struct sockaddr_in sin = { 0 };
 
   sin.sin_family = AF_INET;
   sin.sin_addr.s_addr = INADDR_ANY;
   sin.sin_port = htons (port);
 
    /*BIND*/ if (bind (sock_srv, (struct sockaddr *) &sin, sizeof (sin)) < 0)
   {
      perror ("call to bind\n");
      exit (-1);
   }
   printf ("bind ok\n");
 
   /* setsockopt */
   int bOptVal = 1;
   int bOptLen = sizeof (int);
 
   if (setsockopt
       (sock_srv, SOL_SOCKET, SO_REUSEADDR, (char *) &bOptVal,
        bOptLen) != SO_ERROR)
   {
      printf ("Set reuseaddr: ON\n");
   }
 
   /* LISTEN */
   if (listen (sock_srv, 5) < 0)
   {
      perror ("call to listen\n");
      exit (EXIT_FAILURE);
   }
 
   printf ("waiting for connections...\n");
 
   SOCKET a_cli[] = { INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET };
#define NB_CLI (sizeof a_cli/sizeof *a_cli)
 
   while (1)
   {
      fd_set inputs;
 
      /* compute the 1st parameter of select (ignored with Windows) */
      SOCKET sock_last = sock_srv;
 
      FD_ZERO (&inputs);        /*réinitialisation list of client */
      FD_SET (sock_srv, &inputs); /*set with the server socket (accept) */
 
      /* set clients (recv) */
      {
         size_t i;
 
         for (i = 0; i < NB_CLI; i++)
         {
            SOCKET sock_cli = a_cli[i];
 
            if (sock_cli != INVALID_SOCKET)
            {
               FD_SET (sock_cli, &inputs);
               if (sock_last < sock_cli)
               {
                  sock_last = sock_cli;
               }
            }
         }
      }
      sock_last++;
 
      /*select on the client list */
      if ((select (sock_last, &inputs, NULL, NULL, NULL)) < 0)
      {
         perror ("select error\n");
      }
      printf ("select()\n");
 
      if (FD_ISSET (sock_srv, &inputs))
      {
         /* accept the connection */
         struct sockaddr_in pin;
         int address_size;
         SOCKET sock_cli =
            accept (sock_srv, (struct sockaddr *) &pin, &address_size);
         if (sock_cli == INVALID_SOCKET)
         {
            perror ("call to accept\n");
            exit (EXIT_FAILURE);
         }
         printf ("A client is connected with socket %d\n", sock_cli);
         FD_SET (sock_cli, &inputs);
         {
            int i = get_cli_ndx (a_cli, NB_CLI);
 
            if (i != -1)
            {
               a_cli[i] = sock_cli;
            }
            else
            {
               closesocket (sock_cli);
            }
         }
      }
 
      /* check clients */
      {
         size_t i;
         for (i = 0; i < NB_CLI; i++)
         {
            SOCKET sock_cli = a_cli[i];
 
            if (sock_cli != INVALID_SOCKET)
            {
               if (FD_ISSET (sock_cli, &inputs))
               {
                  int err = traiter_client (sock_cli);
 
                  if (err)
                  {
                     closesocket (sock_cli);
                     a_cli[i] = INVALID_SOCKET;
                  }
               }
            }
         }
      }
   }
 
/* close clients */
   {
      size_t i;
      for (i = 0; i < NB_CLI; i++)
      {
         SOCKET sock_cli = a_cli[i];
 
         if (sock_cli != INVALID_SOCKET)
         {
            closesocket (sock_cli);
            a_cli[i] = INVALID_SOCKET;
         }
      }
   }
/* close server */
   closesocket (sock_srv);
   return 0;
}
 
/* entry point ========================================================= */
 
/* ---------------------------------------------------------------------
   --------------------------------------------------------------------- */
int main (void)
{
   int ret;
 
#if defined (WIN32) || defined (_WIN32)
   WSADATA wsa_data;
   int err = WSAStartup (MAKEWORD (2, 2), &wsa_data);
 
   if (!err)
   {
      puts ("WIN: winsock2: OK");
#else
   int err;
#endif
 
   server ();
 
#if defined (WIN32) || defined (_WIN32)
   WSACleanup ();
}
#endif
 
if (err)
{
   ret = EXIT_FAILURE;
}
else
{
   ret = EXIT_SUCCESS;
}
 
return ret;
}
__________________
Pas de Wi-Fi à la maison : CPL

Des infos sur la programmation et le langage C:
http://bien-programmer.blogspot.com/
http://www.bien-programmer.fr/
http://bien-programmer.forum-actif.net/forum.htm
Emmanuel Delahaye est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/10/2008, 18h28   #29
souviron34
Expert Confirmé Sénior
 
Inscription : janvier 2007
Messages : 9 590
Détails du profil
Informations personnelles :
Âge : 55

Informations forums :
Inscription : janvier 2007
Messages : 9 590
Points : 11 927
Points : 11 927
mettre un \n dans les printf, ou encore mieux un fprintf ( stderr , ..) (qui n'est pas bufferisé => synchrone)
__________________
"Un homme sage ne croit que la moitié de ce qu’il lit. Plus sage encore, il sait laquelle".

Consultant indépendant.
Architecture systèmes complexes. Programmation grosses applications critiques. Ergonomie.
C, Fortran, XWindow/Motif, Java

Je ne réponds pas aux MP techniques
souviron34 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 10h50   #30
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
rebonjour!
merci beaucoup pour votre aide ^^
j'ai juste une erreur de segmentation dont je n'arrive pas à me débarasser...
<...>
[EDIT]la buse a mis son cerveau en marche, j'ai rajouté ca avant le FD_ISSET
Code :
if (sock_cli !=INVALID_SOCKET){
et ça fonctionne nickel!

merci beaucoup!!

maintenant, je vais rajouter mon ssl dedans...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 13h26   #31
Emmanuel Delahaye
Rédacteur
 
Avatar de Emmanuel Delahaye
 
Inscription : décembre 2003
Messages : 14 505
Détails du profil
Informations personnelles :
Âge : 56
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : décembre 2003
Messages : 14 505
Points : 19 321
Points : 19 321
Citation:
Envoyé par Bathou Voir le message
maintenant, je vais rajouter mon ssl dedans..
Attention, as-tu bien remarqué la modif que j'ai faite autour de recv(), notamment le placement du 0.
__________________
Pas de Wi-Fi à la maison : CPL

Des infos sur la programmation et le langage C:
http://bien-programmer.blogspot.com/
http://www.bien-programmer.fr/
http://bien-programmer.forum-actif.net/forum.htm
Emmanuel Delahaye est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 14h46   #32
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
Citation:
Envoyé par Emmanuel Delahaye Voir le message
Attention, as-tu bien remarqué la modif que j'ai faite autour de recv(), notamment le placement du 0.
le zéro dans les () du recv...?? je crois que je le mettais par défaut...


grande question : j'ai juste rajouter mes headers d'openssl dans mon code
Code :
1
2
3
4
5
6
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h> 
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
et il me fait :
Citation:
call to accept
: Invalid argument
est ce qu'il y aurai une raison rationnelle à ca...?? parce que la, je ne le comprends pas le petit la...

[EDIT] bah j'ai rajouté d'autres headers et ça a l'air de fonctionner...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 15h01   #33
Emmanuel Delahaye
Rédacteur
 
Avatar de Emmanuel Delahaye
 
Inscription : décembre 2003
Messages : 14 505
Détails du profil
Informations personnelles :
Âge : 56
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : décembre 2003
Messages : 14 505
Points : 19 321
Points : 19 321
Citation:
Envoyé par Bathou Voir le message
le zéro dans les () du recv...?? je crois que je le mettais par défaut...
C'est bien le problème. Tu utilisais une valeur d'index qui pourrait être absurde (< 0)

Citation:
grande question : j'ai juste rajouter mes headers d'openssl dans mon code
Code :
1
2
3
4
5
6
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h> 
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
et il me fait :

est ce qu'il y aurai une raison rationnelle à ca...?? parce que la, je ne le comprends pas le petit la
Essaye de voir quel header provoque ce problème. Si il y en a un qui redéfinit accept(), c'est plutôt bizarre...
__________________
Pas de Wi-Fi à la maison : CPL

Des infos sur la programmation et le langage C:
http://bien-programmer.blogspot.com/
http://www.bien-programmer.fr/
http://bien-programmer.forum-actif.net/forum.htm
Emmanuel Delahaye est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 15h03   #34
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
Citation:
Envoyé par Emmanuel Delahaye Voir le message
C'est bien le problème. Tu utilisais une valeur d'index qui pourrait être absurde (< 0)
valeur d'index...??

[EDIT]ca fonctionnait... comprends pas...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 15h12   #35
Emmanuel Delahaye
Rédacteur
 
Avatar de Emmanuel Delahaye
 
Inscription : décembre 2003
Messages : 14 505
Détails du profil
Informations personnelles :
Âge : 56
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : décembre 2003
Messages : 14 505
Points : 19 321
Points : 19 321
Citation:
Envoyé par Bathou Voir le message
valeur d'index...??
Pour écrire une application réseau, il faut maitriser les bases du C. Tu devrais savoir ce qu'est un index (de tableau).

Pour placer le 0, tu écris dans la chaine, qui est un tableau, donc adressé par un index. L'index utilisé risquait d'être faux en cas d'erreur. (valeur hors limites < 0)
__________________
Pas de Wi-Fi à la maison : CPL

Des infos sur la programmation et le langage C:
http://bien-programmer.blogspot.com/
http://www.bien-programmer.fr/
http://bien-programmer.forum-actif.net/forum.htm
Emmanuel Delahaye est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 15h26   #36
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
ok j'avais raté un épisode merci (moi j'appelle ca un indice...)
par contre mes histoires d'header, c'est space... c'est jamais les memes qui ne fonctionnent pas...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 15h43   #37
Emmanuel Delahaye
Rédacteur
 
Avatar de Emmanuel Delahaye
 
Inscription : décembre 2003
Messages : 14 505
Détails du profil
Informations personnelles :
Âge : 56
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : décembre 2003
Messages : 14 505
Points : 19 321
Points : 19 321
Citation:
Envoyé par Bathou Voir le message
ok j'avais raté un épisode merci (moi j'appelle ca un indice...)
par contre mes histoires d'header, c'est space... c'est jamais les memes qui ne fonctionnent pas...
Oui. indice est correct (il est possible que 'index' soit le mot anglais de 'indice').
__________________
Pas de Wi-Fi à la maison : CPL

Des infos sur la programmation et le langage C:
http://bien-programmer.blogspot.com/
http://www.bien-programmer.fr/
http://bien-programmer.forum-actif.net/forum.htm
Emmanuel Delahaye est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 15h58   #38
Médinoc
Expert Confirmé Sénior
 
Avatar de Médinoc
 
Homme
Développeur informatique
Inscription : septembre 2005
Messages : 22 396
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 29
Localisation : France

Informations professionnelles :
Activité : Développeur informatique
Secteur : High Tech - Éditeur de logiciels

Informations forums :
Inscription : septembre 2005
Messages : 22 396
Points : 32 049
Points : 32 049
Envoyer un message via MSN à Médinoc
Ce que je sais, c'est que "indices" est une des formes plurielles acceptées pour "index".

Par contre, la version anglaise de Wikitionary considère "indice" au singulier comme du latin.
__________________
SVP, pas de questions techniques par MP. Surtout si je ne vous ai jamais parlé avant.

"Aw, come on, who would be so stupid as to insert a cast to make an error go away without actually fixing the error?"
Apparently everyone.
-- Raymond Chen.
Traduction obligatoire: "Oh, voyons, qui serait assez stupide pour mettre un cast pour faire disparaitre un message d'erreur sans vraiment corriger l'erreur?" - Apparemment, tout le monde. -- Raymond Chen.
Médinoc est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/10/2008, 17h13   #39
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21
bon, je comprends rien à mon programme...
les headers, c'est bon, il fonctionne avec mais après, je peux pas rajouter de code ssl, il me met toujours :
Citation:
call to accept
: Invalid argument
alors que ce que je veux rajouter :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
SSL_METHOD      *meth; 
    SSL_CTX         *ctx; 
 
/*SSL INITIALIZATION*/
  ////////////////////////////////////////////////////////////////
  /*Initialization*/
 
  /* Load encryption & hashing algorithms for the SSL program */  
  SSL_library_init();  
 
  /* Load the error strings for SSL & CRYPTO APIs */      
  SSL_load_error_strings();       
 /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */     
  meth = SSLv3_method();
n'influence a priori pas le accept...
je ne comprends pas...

actuelllement, c'est quand je rajoute le que ça marche plus...

si quelqu'un pouvait m'éclairer... parce que la...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/10/2008, 14h58   #40
Bathou
Membre à l'essai
 
Avatar de Bathou
 
Inscription : mars 2007
Messages : 175
Détails du profil
Informations personnelles :
Âge : 26

Informations forums :
Inscription : mars 2007
Messages : 175
Points : 21
Points : 21

bonjour!
alors ce matin, il acceptait que je rajoute mes lignes ssl... la nuit lui a porté conseil au petit??

bref, ça fonctionne quasiment...

j'ai juste un petit (lol) problème... c'est qu'à la réception le dernier client qui s'est connecté a une erreur sur sa socket et donc se ferme... je ne vois pas pourquoi...

voila, le code de mon serveur avec le ssl :
(a priori c'est pas du coté du client parce que mse clients sont tous les 3 les meme...)

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* Program server */
 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>   
 
 
 
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <netdb.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/des.h>
#include <openssl/blowfish.h>
 
 
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
 
#define closesocket(s) close (s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
 
 
#include <stdio.h>
#include <stdlib.h>
 
#include <string.h>
#include <errno.h>
 
/* macros ============================================================== */
#define RETURN_NULL(x) if ((x)==NULL) exit(1)
#define RETURN_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
#define RETURN_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(1); } 
/* constants =========================================================== */
 
/* constante */
#define port 1234
#define RSA_SERVER_CERT     "serveur_ssl_cert.pem"
#define RSA_SERVER_KEY          "serveur_ssl_priv_key.key" 
#define RSA_SERVER_CA_CERT "../cassl/cassl_cert.pem"
#define RSA_SERVER_CA_PATH   "bathou1" 
#define ON 1
#define OFF 0 
 
/* types =============================================================== */
/* structures ========================================================== */
typedef struct 
	{
	SOCKET sock1;
	SSL* ssl1;
	}client;
/* private data ======================================================== */
/* private functions =================================================== */
 
static int traiter_client (int sock_cli,SSL *ssl)
{
   int err = 0;
   char buf[1024];
 
   /*reception*/
  // int n = recv (sock_cli, buf, sizeof (buf) - 1, 0);
   int n = SSL_read(ssl, buf, sizeof(buf)-1);      
  	      //RETURN_SSL(err); 
   if (n > 0)
   {
      /* process the received data */
      buf[n] = '\0';
 
      printf ("Received %d chars:'%s' on socket %d\n", n, buf, sock_cli);
   }
   else /*error*/
   {
      if (n == 0)
      {
         printf ("deconnexion socket %d\n", sock_cli);
      }
      else
      {
         printf ("receive error on socket %d %d\n", sock_cli,n);
      }
      err = 1;
   }
   return err;
}
 
static int get_cli_ndx (client a[], int n)
{
   int ndx = -1;
   int i;
   for (i = 0; i < n; i++)
   {
      if ((a[i].sock1 == INVALID_SOCKET)||(a[i].ssl1 == NULL))
      {
         ndx = i;
         break;
      }
   }
   return ndx;
}
 
static int server (void)
{ SSL_METHOD      *meth; 
    SSL_CTX         *ctx; 
 int     verify_client = OFF;
 
  SSL            *ssl;       
 
  X509            *client_cert = NULL;    
 int err=0;
  char    *str;     
 
/*SSL INITIALIZATION*/
  ////////////////////////////////////////////////////////////////
  /*Initialization*/
 
  /* Load encryption & hashing algorithms for the SSL program */  
  SSL_library_init();  
 
  /* Load the error strings for SSL & CRYPTO APIs */      
  SSL_load_error_strings();       
 /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */     
  meth = SSLv3_method();  
 /* Create a SSL_CTX structure */    
  ctx = SSL_CTX_new(meth);        
  if (!ctx) 
      {             
      ERR_print_errors_fp(stderr);            
      exit(1);        
      }       
 
 /* Load the server certificate into the SSL_CTX structure */       
  if (SSL_CTX_use_certificate_file(ctx, RSA_SERVER_CERT, SSL_FILETYPE_PEM) <= 0) 
      {                    
      ERR_print_errors_fp(stderr);                    
      exit(1);       
      }       
 
  /* Load the private-key corresponding to the server certificate */          
  if (SSL_CTX_use_PrivateKey_file(ctx, RSA_SERVER_KEY, SSL_FILETYPE_PEM) <= 0) 
      {               
      ERR_print_errors_fp(stderr);                
      exit(1);    
      }       
 
  /* Check if the server certificate and private-key matches */       
  if (!SSL_CTX_check_private_key(ctx)) 
      {                  
      fprintf(stderr,"Private key does not match the certificate public key\n");                  
      exit(1);    
      }      
 
  /* Set the session id context*/
/*  SSL_CTX_set_session_id_context(ctx,
      (void*)&s_server_session_id_context,
      sizeof s_server_session_id_context); */
 
 
  /* if verify client certificate is on*/
  if(verify_client == ON)        
      {               
      /* Load the RSA CA certificate into the SSL_CTX structure */                
      if (!SSL_CTX_load_verify_locations(ctx, RSA_SERVER_CA_CERT, NULL)) 
          {                    
          ERR_print_errors_fp(stderr);                        
          exit(1);            
          }               
 
 
 
      /* Set to require peer (client) certificate verification */         
      SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);           
      /* Set the verification depth to 1 */               
      SSL_CTX_set_verify_depth(ctx,1);       
      }  
 
  printf("Initialization terminate\n\n");
 
 
///////////////////////////////////////////////////
   /* socket creation */
   SOCKET sock_srv = socket (PF_INET, SOCK_STREAM, 0);
   if (sock_srv == INVALID_SOCKET)
   {
      perror ("call to socket\n");
      exit (EXIT_FAILURE);
   }
   printf ("socket ok\n");
 
   /*initialization */
   struct sockaddr_in sin = { 0 };
 
   sin.sin_family = AF_INET;
   sin.sin_addr.s_addr = INADDR_ANY;
   sin.sin_port = htons (port);
 
   /*BIND*/ 
  int b=0;
b=bind (sock_srv, (struct sockaddr *) &sin, sizeof (sin));
   if ( b< 0)
   {
      perror ("call to bind\n");
      exit (-1);
   }
   printf ("bind ok\n");
 
   /* setsockopt */
   int bOptVal = 1;
   int bOptLen = sizeof (int);
 
   if (setsockopt
       (sock_srv, SOL_SOCKET, SO_REUSEADDR, (char *) &bOptVal,
        bOptLen) != SO_ERROR)
   {
      printf ("Set reuseaddr: ON\n");
   }
 
   /* LISTEN */
int l=0;
l=listen (sock_srv, 5);
   if ( l< 0)
   {
      perror ("call to listen\n");
      exit (EXIT_FAILURE);
   }
 
   printf ("waiting for connections...\n");
 
 
 
 #define NB_CLI 3
   client a_cli[NB_CLI] ;//= { INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET };
//#define NB_CLI (sizeof a_cli/sizeof *a_cli)
 
#define NB_CLI 3
int i;
for (i=0;i<=NB_CLI;i++)
{ a_cli[i].sock1=INVALID_SOCKET;
  a_cli[i].ssl1=NULL;}
 
   while (1)
   {
      //   printf ("waiting for connections...\n");
      fd_set inputs;
 
      /* compute the 1st parameter of select */
      SOCKET sock_last = sock_srv;
 
      FD_ZERO (&inputs);        /*réinitialization list of client */
      FD_SET (sock_srv, &inputs); /*set with the server socket (accept) */
 
      /* set clients (recv) */
      {
         size_t i;
 
         for (i = 0; i <= NB_CLI; i++)
         {
            SOCKET sock_cli = a_cli[i].sock1;
 
            if (sock_cli != INVALID_SOCKET)
            {
               FD_SET (sock_cli, &inputs);
               if (sock_last < sock_cli)
               {
                  sock_last = sock_cli;
               }
            }
         }
      }
      sock_last++;
 
      /*select on the client list */
      if ((select (sock_last, &inputs, NULL, NULL, NULL)) < 0)
      {
         perror ("select error\n");
      }
      printf ("select()\n");
 
      if (FD_ISSET (sock_srv, &inputs))
      {
         /* accept the connection */
         struct sockaddr_in pin;
         int address_size;
         SOCKET sock_cli = accept (sock_srv, (struct sockaddr *) &pin, &address_size);
         if (sock_cli == INVALID_SOCKET)
         {
            perror ("call to accept\n");
            exit (EXIT_FAILURE);
         }
         printf ("A client is connected with socket %d\n", sock_cli);
         FD_SET (sock_cli, &inputs);
	////////////////////////////////////////////////////////////////
        /*SSL*/      
 
        /* TCP connection is ready. */      
 
        /* A SSL structure is created */    
        ssl = SSL_new(ctx);     
        RETURN_NULL(ssl);       
 
        /* Assign the socket into the SSL structure (SSL and socket without BIO) */ 
 	SSL_set_fd(ssl, sock_cli);  
 
 
  	/* Perform SSL Handshake on the SSL server */       
  	err = SSL_accept(ssl);  
  		RETURN_SSL(err);        
 
  	/* Informational output (optional) */       
  	printf("SSL connection using %s\n", SSL_get_cipher (ssl));    
 
  	if (verify_client == ON)   
      		{           
      		/* Get the client's certificate (optional) */       
      		client_cert = SSL_get_peer_certificate(ssl);        
      		if (client_cert != NULL)            
          		{               
          		printf ("Client certificate:\n");                   
          		str = X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0);                  
          		RETURN_NULL(str);                   
          		printf ("\t subject: %s\n", str);                   
          		free (str);                 
          		str = X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0);                   
          		RETURN_NULL(str);                   
          		printf ("\t issuer: %s\n", str);                    
          		free (str);                 
          		X509_free(client_cert);     
          		}       
      		else          
	  		{
	  		/* we've got an error*/          
          		printf("The SSL client does not have certificate.\n");  
	  		if (SSL_get_verify_result(ssl) != X509_V_OK) 
				{
				printf("client certificate verification failed!!!\n");
				//tls_dump_verification_failure(SSL_get_verify_result(ssl));
				}
	  		}
      		}       
 
  	////////////////////////////////////////////////////////////////
         {
            int i = get_cli_ndx (a_cli, NB_CLI);
 
            if (i != -1)
            {
               a_cli[i].sock1 = sock_cli;
	       a_cli[i].ssl1 = ssl;
            }
            else
            {
               closesocket (sock_cli);
	  	/* Shutdown this side (server) of the connection. */    
  		err = SSL_shutdown(ssl);        
  		RETURN_SSL(err);        
//////////////////////////////////////////////////////////////////////////////////////////
            }
         }
      }
 
      /* check clients */
      {
         size_t i;
	 /*for all the clients*/
         for (i = 0; i <= NB_CLI; i++)
         {
            SOCKET sock_cli = a_cli[i].sock1;
	    SSL* ssl1=a_cli[i].ssl1;
 
	 if (sock_cli !=INVALID_SOCKET)
            {
            if (FD_ISSET (sock_cli, &inputs))
            {
               int err = traiter_client (sock_cli,ssl1);
 
               if (err)
               {  
                  closesocket (sock_cli); 
                  a_cli[i].sock1 = INVALID_SOCKET;
		  a_cli[i].ssl1 = NULL;
		  err = SSL_shutdown(ssl);        
  		  RETURN_SSL(err);    
               }
            }
	    }
         }
      }
   }
 
/* close clients */
   {
      size_t i;
      for (i = 0; i <= NB_CLI; i++)
      {
         SOCKET sock_cli = a_cli[i].sock1;
 
         if (sock_cli != INVALID_SOCKET)
         {
            closesocket (sock_cli);
            a_cli[i].sock1 = INVALID_SOCKET;
	    a_cli[i].ssl1 = NULL;
	    err = SSL_shutdown(ssl);        
	    RETURN_SSL(err);    
         }
      }
   }
/* close server */
 /* Free the SSL structure */        
  SSL_free(ssl); 
 
  /* Free the SSL_CTX structure */   
  SSL_CTX_free(ctx); 
   closesocket (sock_srv);
   return 0;
}
 
/* entry point ========================================================= */
 
/* ---------------------------------------------------------------------
   --------------------------------------------------------------------- */
int main (void)
{
   int ret;
 
 
   int err;
 
 
   server ();
 
 
if (err)
{
   ret = EXIT_FAILURE;
}
else
{
   ret = EXIT_SUCCESS;
}
 
return ret;
}
merci par avance pour votre aide...

[EDIT] en fait ca ne le fait que quand j'ai deux clients totalement identique à ce niveau la :

Code :
1
2
3
4
5
6
7
8
9
10
11
12
  /* Send data to the SSL server */   
  for(i = 0; i < 5; i++)
    {
    
    int err = SSL_write(ssl, hello, strlen(hello));
	if (err < 0)
        {
	perror("call to send\n");
	exit(-5);
	}
    sleep(1);
    }
client 1 : 2
client 2 : 5
client 3 : 10

et ça fonctionne... je ne comprends pas pourquoi ca ne fonctionnerai pas si client 1 et client 3 étaient tous les deux à 2...
Bathou est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse
Outils de la discussion

Navigation rapide


Fuseau horaire GMT +2. Il est actuellement 00h31.


 
 
 
 
Partenaires

Hébergement Web