-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinject.c
2472 lines (2140 loc) · 71.5 KB
/
inject.c
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Injecteur HTTP simple (C) 2000-2011 Willy Tarreau <[email protected]>
* Utilisation et redistribution soumises a la licence GPL.
*
* Compilation :
* gcc -O2 -o inject inject.c -lm # par défaut
* gcc -O2 -DNO_SD -o inject inject.c # désactive sdht (pas besoin de libm)
* gcc -O2 -DDONT_ANALYSE_HTTP_HEADERS -o inject inject.c -lm # désactive parseur HTTP
*
* 2000/11/18 : correction du SEGV.
* 2000/11/21 : grand nettoyage de l'automate et correction de nombreux bugs.
* 2000/11/22 : ajout des time-outs, erreurs, temps par hit et par page.
* 2000/11/22 : limitation du nombre de sockets simultanées par client.
* 2000/11/24 : correction du bug infame lie a la limitation du nombre de FD.
* 2001/02/26 : ajout du "User-Agent" et du "Connection: close". Acceptation
* des cookies sans "path=/"
* TODO: gérer le referer, et controler la longueur des cookies lors des remplacements.
* 2001/03/02 : ajout de headers personnalisés
* 2001/08/07 : heure de demarrage dans les logs, affichage toutes les secondes.
* correction d'un bug sur l'allocation des variables
* 2001/08/09 : Affinage du delai d'affichage des stats à la milliseconde. Ce
* temps devient paramétrable par l'option "-w".
* Le démarrage en douceur fonctionne bien, même pour des petits délais.
* Le temps cumulé affiché est désormais "-1" tant que l'injection n'a pas
* pu démarrer.
* 2001/08/10 : correction de l'arret premature et ajout de la ligne de commande dans les logs.
* 2002/02/04 : correction d'un nouveau bug dans la gestion des headers, et affinage de la
* gestion mémoire pour tenter de faire tenir plus d'utilisateurs.
* Il faudrait refaire la partie serveur (voir haproxy) pour libérer les headers
* aussitôt que possible, et lire les data à la volée.
* 2004/05/14 : ajout de l'option '-a' pour afficher la date absolue.
* 2004/09/26 : passage en mode multi-processus
* 2005/01/10 : affichage des moyenne et ecart-type des temps de réponse
* 2005/01/19 : Ne plus démarrer un client si pas assez de FD.
* Synthèse des statistiques avant affichage final.
* 2005/08/09 : ajout des options -H, -T, -G, -P pour faire le scénario en ligne de commande.
* 2005/10/09 : correction du nom 'host' si utilisation de -G.
*
* Remarque : le champ "variables" HTTP peut contenir 2 "%s" qui seront remplacés par l'id du client
* et son mot de passe (=id)
*
* Obs : parfois l'injecteur se bloque vers le serveur sizesrv, s'il y a peu
* de clients. strace montre que c'est parce qu'un connect() n'aboutit
* pas. C'est maintenant rattrapé par le timeout. Sans doute une table
* de sockets qui se fige quelque part, ou un bug sur l'OS :-(
* Voir la trace à la fin de ce fichier.
*
* TODO :
* - réécrire en gérant des files d'attente suivant l'état des clients.
* - gérer les unités d'affichage
*
* Détail des affichages :
* time delta clients hits ^hits hits/s ^h/s bytes ^bytes kB/s last errs tout htime ptime
*
* - time est le nombre de millisecondes écoulées depuis le début du test
* - delta est le temps en millisecondes depuis le dernier affichage
* - clients est le nombre total de clients ayant déroulé un scénario (avec ou sans erreurs)
* - hits est le nombre total de hits réussis (=sans erreur) depuis le début du test
* - ^hits est le nombre de hits réussis depuis le dernier affichage
* - hits/s est le nombre moyen de hits par seconde depuis le début du test
* - ^h/s est le nombre moyen de hits par seconde depuis le dernier affichage
* - bytes est le nombre total d'octets lus depuis le début du test
* - ^bytes est le nombre d'octets recus depuis le dernier affichage
* - kB/s est le débit moyen depuis le début du test, en kilooctets par seconde
* - ^k/s est le débit moyen depuis le dernier affichage, en ko/s
* - errs est le nombre d'erreurs (déconnexions ...) depuis le début du test
* - tout est le nombre de timeouts depuis le début du test
* - htime donne l'évolution du temps moyen d'un hit (en ms)
* - ptime donne l'évolution du temps moyen de chargement d'une page avec tous ses objets (en ms)
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <sys/resource.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <math.h>
#ifndef TCP_NODELAY
#define TCP_NODELAY 1
#endif
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#ifndef MSG_MORE
#define MSG_MORE 0
#endif
#ifdef ENABLE_SPLICE
#ifndef F_SETPIPE_SZ
#define F_SETPIPE_SZ (1024 + 7)
#endif
#ifndef __NR_splice
#if defined(__x86_64__)
#define __NR_splice 275
#define __NR_tee 276
#define __NR_vmsplice 278
#elif defined (__i386__)
#define __NR_splice 313
#define __NR_tee 315
#define __NR_vmsplice 316
#elif defined (__arm__)
#define __NR_splice 340
#define __NR_tee 342
#define __NR_vmsplice 343
#endif /* $arch */
#endif /* __NR_splice */
#ifndef SPLICE_F_NONBLOCK
#define SPLICE_F_MOVE 1
#define SPLICE_F_NONBLOCK 2
#define SPLICE_F_MORE 4
#ifndef _syscall4
#define _syscall4(tr, nr, t1, n1, t2, n2, t3, n3, t4, n4) \
inline tr nr(t1 n1, t2 n2, t3 n3, t4 n4) { \
return syscall(__NR_##nr, n1, n2, n3, n4); \
}
#endif
#ifndef _syscall6
#define _syscall6(tr, nr, t1, n1, t2, n2, t3, n3, t4, n4, t5, n5, t6, n6) \
inline tr nr(t1 n1, t2 n2, t3 n3, t4 n4, t5 n5, t6 n6) { \
return syscall(__NR_##nr, n1, n2, n3, n4, n5, n6); \
}
#endif
static _syscall6(int, splice, int, fdin, loff_t *, off_in, int, fdout, loff_t *, off_out, size_t, len, unsigned long, flags);
static _syscall4(long, vmsplice, int, fd, const struct iovec *, iov, unsigned long, nr_segs, unsigned int, flags);
static _syscall4(long, tee, int, fd_in, int, fd_out, size_t, len, unsigned int, flags);
#endif
#endif
#define METH_NONE 0
#define METH_GET 1
#define METH_POST 2
#define STATUS_RUN 1
#define STATUS_THINK 2
#define STATUS_ERROR 3
#define OBJ_STNEW -1
#define OBJ_STTERM -2
#define BUFSIZE 4096
#define TRASHSIZE 65536
/* this reduces the number of calls to select() by choosing appropriate
* sheduler precision in milliseconds. It should be near the minimum
* time that is needed by select() to collect all events. All timeouts
* are rounded up by adding this value prior to pass it to select().
*/
// 100 HZ
//#define SCHEDULER_RESOLUTION 9
// 250 HZ
//#define SCHEDULER_RESOLUTION 3
// trade off CPU for better accuracy
#define SCHEDULER_RESOLUTION 0
/* show stats this every millisecond, 0 to disable */
#define STATTIME 1000
/* sur combien de bits code-t-on la taille d'un entier (ex: 32bits -> 5) */
#define INTBITS 5
#define USER_AGENT "Mozilla/4.0.(compatible; MSIE 4.01; Windows)"
#define MINTIME(old, new) (((new)<0)?(old):(((old)<0||(new)<(old))?(new):(old)))
#define SETNOW(a) (*a=now)
/*
* Gcc >= 3 provides the ability for the programme to give hints to the
* compiler about what branch of an if is most likely to be taken. This
* helps the compiler produce the most compact critical paths, which is
* generally better for the cache and to reduce the number of jumps.
*/
#if !defined(likely)
#if __GNUC__ < 3
#define __builtin_expect(x,y) (x)
#define likely(x) (x)
#define unlikely(x) (x)
#elif __GNUC__ < 4
/* gcc 3.x does the best job at this */
#define likely(x) (__builtin_expect((x) != 0, 1))
#define unlikely(x) (__builtin_expect((x) != 0, 0))
#else
/* GCC 4.x is stupid, it performs the comparison then compares it to 1,
* so we cheat in a dirty way to prevent it from doing this. This will
* only work with ints and booleans though.
*/
#define likely(x) (x)
#define unlikely(x) (__builtin_expect((unsigned long)(x), 0))
#endif
#endif
/* a local IP addresses list */
struct local_ip {
struct in_addr addr;
u_int16_t *freeports; /* ports in host byte order */
int size; /* number of allocatable ports + 1 */
int reserved; /* # of reserved ports (preallocated) */
int get, put; /* indexes of where to get and put a free port. Empty if get == put */
struct local_ip *next;
};
/* un objet dont le fd est -1 est inactif */
struct pageobj {
struct pageobj *next;
struct page *page;
struct sockaddr_in addr;
u_int16_t local_port; /* local port in host byte order. 0 if not assigned. */
int fd;
char *buf;
char *read;
char meth;
char *uri;
char *vars;
char *host;
struct timeval starttime;
};
struct page {
struct page *next;
struct pageobj *objects;
struct pageobj *objecttostart;
struct client *client;
struct timeval begin;
int actobj;
int objleft;
int thinktime;
int status;
int dataread;
};
struct client {
struct client *next;
struct timeval nextevent;
struct timeval expire;
struct page *current;
struct scnpage *pages;
struct local_ip *addr; /* NULL if automatically assigned */
char *username;
char *password;
char *cookie;
int status;
int dataread;
int hits;
};
struct scnobj {
struct sockaddr_in addr;
char meth;
char *host;
char *uri;
char *vars;
struct scnobj *next;
};
struct scnpage {
int thinktime;
char *name;
struct scnobj *objects;
struct scnpage *next;
} *firstscnpage = NULL;
struct scnpage *curscnpage = NULL;
struct scnobj *curscnobj = NULL;
char curscnhost[64]="host not set !";
struct client *clients = NULL;
char *global_headers = NULL;
unsigned long int arg_nbclients=0;
unsigned long int nbclients=0;
unsigned int arg_maxobj = 8;
unsigned long int arg_maxiter=0;
int arg_nbprocs = 1;
int arg_slowstart = 0;
int arg_stepsize = 1; /* #of clients to add every <arg_slowstart> */
int arg_stattime = STATTIME;
int arg_maxsock = 1000;
char *arg_scnfile = NULL;
char *arg_sourceaddr = NULL;
int arg_random_delay = 0;
int arg_random_distance = 0;
int arg_fast_connect = 0;
int arg_fast_close = 0;
int arg_use_splice = 0;
int arg_regular_time = 0;
static int arg_timeout = 0;
static int arg_log = 0, arg_abs_time = 0;
static int arg_maxtime = 0;
static int arg_nbpages, arg_thinktime;
static char *arg_geturl = NULL;
int active_thread = 0;
static struct timeval now={0,0};
static struct timeval ramp_start={0,0};
static int one = 1;
static int zero = 0;
int nbconn=0;
int nbactconn=0;
int clientid=0;
int nbactcli=0;
int ramp_step=0;
/* set to the local_ip list if required */
static struct local_ip *local_ip_list = NULL;
static struct local_ip *next_ip = NULL;
/* stats[0] = global. stats[x]=per thread */
struct stats {
unsigned long long int totalread;
unsigned long int totalhits;
unsigned long int aborted;
unsigned long int totalerr;
unsigned long int totaltout;
unsigned long int iterations;
unsigned long int stat_hits;
unsigned long int stat_ptime, stat_pages;
unsigned long int nbconn, nbcli;
double moy_htime, moy_sdhtime, moy_ptime;
double tot_htime, tot_sqhtime; /* utilisés pour le calcul de l'écart-type */
} *stats = NULL;
char trash[TRASHSIZE];
static struct timeval starttime = {0,0};
static struct timeval stoptime = {0,0};
const struct linger nolinger = { .l_onoff = 1, .l_linger = 0 };
int master_pipe[2]; /* pipe used by splice() */
int pipe_count = 0;
int dev_null_fd=0;
int pipesize = TRASHSIZE;
int maxfd = 0;
int thr = 0;
int stopnow = 0;
static struct pageobj **fdtab;
fd_set *ReadEvent,
*WriteEvent,
*StaticReadEvent,
*StaticWriteEvent;
void **pool_pageobj = NULL,
**pool_buffer = NULL,
**pool_page = NULL,
**pool_client = NULL,
**pool_str = NULL,
**pool_vars = NULL;
char *cmd_line; /* this contain the original command line for repporting */
/***** prototypes **********************************************/
void destroyclient(struct client *client, struct client *prev);
int EventRead(int fd);
int EventWrite(int fd);
/****************************************************/
/****** gestion mémoire *******/
#define sizeof_pageobj (sizeof(struct pageobj))
#define sizeof_buffer (BUFSIZE)
#define sizeof_page (sizeof(struct page))
#define sizeof_client (sizeof(struct client))
#define sizeof_str (2048)
#define sizeof_vars (2048)
#define MEM_OPTIM
#ifdef MEM_OPTIM
/*
Returns a pointer to type <type> taken from the
pool <pool_type> or dynamically allocated. In the
first case, <pool_type> is updated to point to the
next element in the list.
*/
#define alloc_pool(type) ({ \
void *p; \
if ((p = pool_##type) == NULL) \
p = malloc(sizeof_##type); \
else { \
pool_##type = *(void **)pool_##type; \
} \
p; \
})
/*
Puts a memory area back to the corresponding pool.
Items are chained directly through a pointer that
is written in the beginning of the memory area, so
there's no need for any carrier cells. This implies
that each memory area is at least as big as one
pointer.
*/
#define free_pool(type, ptr) ({ \
*(void **)ptr = (void *)pool_##type; \
pool_##type = (void *)ptr; \
})
#else
#define alloc_pool(type) (calloc(1,sizeof_##type));
#define free_pool(type, ptr) (free(ptr));
#endif
/***************** libtools ************************/
/* Arreter avec un ABORT apres avoir affiche un message d'erreur sur STDERR.
* Cette fonction est de type int pour pouvoir etre inseree dans une expression.
* Elle ne retourne jamais.
*/
int Abort(char *fmt, ...) {
va_list argp;
struct timeval tv;
struct tm *tm;
va_start(argp, fmt);
gettimeofday(&tv, NULL);
tm=localtime(&tv.tv_sec);
fprintf(stderr, "[ABT] %03d %02d%02d%02d pid=%d, cause=",
tm->tm_yday, tm->tm_hour, tm->tm_min, tm->tm_sec, getpid());
vfprintf(stderr, fmt, argp);
fflush(stderr);
va_end(argp);
abort();
return 0; // juste pour eviter un warning a la compilation
}
/* sets <tv> to the current time */
static inline struct timeval *tv_now(struct timeval *tv) {
if (tv)
gettimeofday(tv, NULL);
return tv;
}
/* adds <ms> ms to <from>, set the result to <tv> and returns a pointer <tv> */
static inline struct timeval *tv_delayfrom(struct timeval *tv, struct timeval *from, int ms) {
if (!tv || !from)
return NULL;
tv->tv_usec = from->tv_usec + (ms%1000)*1000;
tv->tv_sec = from->tv_sec + (ms/1000);
while (tv->tv_usec >= 1000000) {
tv->tv_usec -= 1000000;
tv->tv_sec++;
}
return tv;
}
/* compares <tv1> and <tv2> : returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2 */
static inline int tv_cmp(struct timeval *tv1, struct timeval *tv2) {
if (tv1->tv_sec > tv2->tv_sec)
return 1;
else if (tv1->tv_sec < tv2->tv_sec)
return -1;
else if (tv1->tv_usec > tv2->tv_usec)
return 1;
else if (tv1->tv_usec < tv2->tv_usec)
return -1;
else return 0;
}
/*
* compares <tv1> and <tv2> modulo 1ms: returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2
*/
static inline int tv_cmp_ms(struct timeval *tv1, struct timeval *tv2) {
if (tv1->tv_sec == tv2->tv_sec) {
if (tv1->tv_usec >= tv2->tv_usec + 1000)
return 1;
else if (tv2->tv_usec >= tv1->tv_usec + 1000)
return -1;
else
return 0;
}
else if ((tv1->tv_sec > tv2->tv_sec + 1) ||
((tv1->tv_sec == tv2->tv_sec + 1) && (tv1->tv_usec + 1000000 >= tv2->tv_usec + 1000)))
return 1;
else if ((tv2->tv_sec > tv1->tv_sec + 1) ||
((tv2->tv_sec == tv1->tv_sec + 1) && (tv2->tv_usec + 1000000 >= tv1->tv_usec + 1000)))
return -1;
else
return 0;
}
/* returns the absolute difference, in ms, between tv1 and tv2 */
unsigned long tv_delta(struct timeval *tv1, struct timeval *tv2) {
int cmp;
unsigned long ret;
cmp=tv_cmp(tv1, tv2);
if (!cmp)
return 0; /* same dates, null diff */
else if (cmp<0) {
struct timeval *tmp=tv1;
tv1=tv2;
tv2=tmp;
}
ret=(tv1->tv_sec - tv2->tv_sec)*1000;
if (tv1->tv_usec > tv2->tv_usec)
ret+=(tv1->tv_usec - tv2->tv_usec)/1000;
else
ret-=(tv2->tv_usec - tv1->tv_usec)/1000;
return (unsigned long) ret;
}
/* returns the remaining time between tv1=now and event=tv2
if tv2 is passed, 0 is returned.
*/
static inline unsigned long tv_remain(struct timeval *tv1, struct timeval *tv2) {
int cmp;
unsigned long ret;
cmp=tv_cmp_ms(tv1, tv2);
if (cmp >= 0)
return 0; /* event elapsed */
ret=(tv2->tv_sec - tv1->tv_sec)*1000;
if (tv2->tv_usec > tv1->tv_usec)
ret+=(tv2->tv_usec - tv1->tv_usec)/1000;
else
ret-=(tv1->tv_usec - tv2->tv_usec)/1000;
return (unsigned long) ret;
}
/* retourne un pointeur sur une structure de type sockaddr_in remplie d'après
la chaine <str> entrée au format "123.123.123.123:12345". */
struct sockaddr_in *str2sa(char *str) {
static struct sockaddr_in sa;
char *c;
int port;
bzero(&sa, sizeof(sa));
str=strdup(str);
if ((c=strrchr(str,':')) != NULL) {
*c++=0;
port=atol(c);
}
else
port=0;
if (!inet_aton(str, &sa.sin_addr)) {
struct hostent *he;
if ((he = gethostbyname(str)) == NULL)
fprintf(stderr,"[NetTools] Invalid server name: %s\n",str);
else
sa.sin_addr = *(struct in_addr *) *(he->h_addr_list);
}
sa.sin_port=htons(port);
sa.sin_family=AF_INET;
free(str);
return &sa;
}
/* crée un objet pour une page :
methode = { METH_GET | METH_POST }
addr = ADRESSE:PORT
uri = "/accesi/ia10.html" par exemple
vars = "codcli1=truc&codcli2=truc2" ou NULL
page = page web de rattachement
Toutes les chaines sont réallouées dynamiquement (strdup).
*/
static inline struct pageobj *newobj(char methode, char *host, struct sockaddr_in *addr, char *uri, char *vars, struct page *page) {
struct pageobj *obj;
// obj=(struct pageobj *)calloc(1, sizeof(struct pageobj));
obj = alloc_pool(pageobj);
// memset(obj, 0, sizeof_pageobj);
memset(&obj->starttime, 0, sizeof(struct timeval));
memcpy(&obj->addr, addr, sizeof(obj->addr));
obj->fd = OBJ_STNEW; /* fd non ouvert */
obj->meth = methode;
obj->uri = uri;
obj->host = host;
if (vars) {
//fprintf(stderr, "%s, %d\n", vars, strlen(vars));
obj->vars = (char *)alloc_pool(vars);
strcpy(obj->vars, vars);
}
else
obj->vars = NULL;
obj->next = NULL;
obj->buf = NULL;
obj->page = page;
// obj->read = obj->buf = (char *)malloc(BUFSIZE);
// obj->read = obj->buf = (char *)alloc_pool(buffer);
return obj;
}
/* crée une page pour un client existant. Les username et password du client doivent exister */
struct page *newpage(struct scnpage *scn, struct client *client) {
struct page *page;
struct pageobj **obj;
struct scnobj *scnobj;
char variables[sizeof_str];
// page=(struct page *)calloc(1, sizeof(struct page));
page=(struct page *)alloc_pool(page);
memset(page, 0, sizeof_page);
page->client = client;
page->thinktime = scn->thinktime;
if (arg_random_delay)
page->thinktime += random() % (1+scn->thinktime/10) - scn->thinktime/20;
obj = &(page->objects);
for (scnobj = scn->objects; scnobj; scnobj = scnobj->next) {
if ((scnobj->vars != NULL) && (client != NULL) &&
(client->username != NULL) && (client->password != NULL)) {
sprintf(variables, scnobj->vars, client->username, client->password);
*obj = newobj(scnobj->meth, scnobj->host, &scnobj->addr, scnobj->uri, variables, page);
}
else
*obj = newobj(scnobj->meth, scnobj->host, &scnobj->addr, scnobj->uri, NULL, page);
obj=&((*obj)->next);
}
page->objecttostart = page->objects;
return page;
}
/* finds an IP with at least <nbports> free ports. Returns a pointer to the
* structure with the pre-reserved ports, or NULL if not found.
*/
static inline struct local_ip *get_free_ip(int nbports) {
struct local_ip *orig = next_ip;
do {
if (!next_ip)
next_ip = local_ip_list;
if (next_ip->size - next_ip->reserved >= nbports) {
next_ip->reserved += nbports;
orig = next_ip;
next_ip = next_ip->next;
return orig;
}
next_ip = next_ip->next;
} while (next_ip != orig);
return NULL;
}
/* frees the ip */
static inline void put_free_ip(struct local_ip *ip, int nbports) {
ip->reserved -= nbports;
}
/* returns a free port from the ip address <ip>, or 0 if none or if <ip> is NULL.
* The port is in host byte order.
*/
static inline u_int16_t get_free_port(struct local_ip *ip, int offset) {
u_int16_t port;
if (!ip)
return 0;
//fprintf(stderr,"%s:%d - entering\n", __FUNCTION__, __LINE__);
port = 0;
if (ip->get != ip->put) {
port = ip->freeports[ip->get++] + offset;
if (ip->get >= ip->size)
ip->get = 0;
}
//fprintf(stderr,"%s:%d - leaving : %d\n", __FUNCTION__, __LINE__, port);
return port;
}
/* frees the host byte order port <p> into the <ip> list. Does nothing if
* called with port 0, or NULL ip.
*/
static inline void put_free_port(struct local_ip *ip, u_int16_t p, int offset) {
if (!p || !ip)
return;
//fprintf(stderr,"%s:%d - entering with %d,%d\n", __FUNCTION__, __LINE__, p, offset);
ip->freeports[ip->put++] = p - offset;
if (ip->put >= ip->size)
ip->put = 0;
//fprintf(stderr,"%s:%d - leaving\n", __FUNCTION__, __LINE__);
}
/* tente de rajouter les fetchs non initiés pour une page donnée.
renvoie 0 si le client a été supprimé suite à une erreur.
renvoie 1 si le fetch a correctement été initié, et 2 s'il a échoué (manque de ressources)
*/
/*static inline*/ int continue_fetch(struct page *page) {
struct pageobj *obj;
int attempts = 0;
while ((obj = page->objecttostart) != NULL) {
int fd;
obj->local_port = 0;
if (unlikely(nbconn+arg_maxobj >= arg_maxsock || page->actobj >= arg_maxobj)) {
/* on ne peut pas démarrer le fetch tout de suite */
/* ce n'est pas de la faute du serveur en face, donc on reporte le timeout */
if (arg_timeout > 0)
tv_delayfrom(&page->client->expire, &now, arg_timeout);
return 2;
}
if ((page->begin.tv_sec | page->begin.tv_usec) == 0)
SETNOW(&page->begin);
retry:
if (unlikely((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)) {
// fprintf(stderr, "impossible de créer une socket, destruction du client.\n");
// destroyclient(page->client, NULL); /* renvoie un pointeur sur le suivant */
// return 0; /* killed client */
return 2;
}
if (page->client->addr) {
if ((obj->local_port = get_free_port(page->client->addr, thr-1)) != 0) {
struct sockaddr_in local_addr;
local_addr.sin_addr = page->client->addr->addr;
local_addr.sin_port = htons(obj->local_port);
local_addr.sin_family = AF_INET;
/* if bind fails, let the system do its own work */
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)) == -1 ||
bind(fd, (struct sockaddr *)&local_addr, sizeof local_addr) == -1) {
put_free_port(page->client->addr, obj->local_port, thr-1);
obj->local_port = 0;
}
if (arg_random_distance) {
/* set a pseudo-random TTL depending only on the source /24 network */
unsigned int ttl = ntohl(*(uint32_t *)&local_addr.sin_addr);
ttl &= -64;
ttl ^= 0x12345678;
ttl ^= ttl << 13;
ttl ^= ttl >> 17;
ttl ^= ttl << 5;
while (ttl >= 64) {
ttl = (ttl & 0x3f) + (ttl >> 6);
}
ttl += 64;
setsockopt(fd, IPPROTO_IP, IP_TTL, (char *) &ttl, sizeof(ttl));
}
}
}
fcntl(fd, F_SETFL, O_NONBLOCK);
#ifdef TCP_QUICKACK
/* we don't want quick ACKs there */
if (arg_fast_connect)
setsockopt(fd, SOL_TCP, TCP_QUICKACK, (char *) &zero, sizeof(zero));
#endif
if (unlikely((connect(fd, (struct sockaddr *)&obj->addr, sizeof(obj->addr)) == -1) && (errno != EINPROGRESS))) {
if (errno == EAGAIN || errno == EADDRNOTAVAIL) { /* plus de ports en local -> réessayer plus tard */
put_free_port(page->client->addr, obj->local_port, thr-1);
obj->local_port = 0;
close(fd);
if (attempts++ < 10)
goto retry;
return 2;
}
else if (errno != EALREADY && errno != EISCONN) {
// fprintf(stderr,"impossible de faire le connect() pour le fd %d, errno ) %d. destruction du client.\n",
// fd, errno);
put_free_port(page->client->addr, obj->local_port, thr-1);
obj->local_port = 0;
close(fd);
return 2;
/* ne pas renouveler le client, sinon on risque une récursivité ! */
//destroyclient(page->client, NULL); /* renvoie un pointeur sur le suivant */
//return 0; /* killed client */
}
/* else connection delayed or accepted */
}
else {
obj->fd = fd;
nbconn++;
page->actobj++;
SETNOW(&obj->starttime);
fdtab[fd]=obj;
FD_SET(fd, StaticWriteEvent);
if (fd+1 > maxfd)
maxfd = fd+1;
}
page->objecttostart = obj->next;
attempts = 0;
}
return 1; /* ok */
}
/* démarre un client. Si une erreur se produit lors du démarrage, alors
les ressources sont libérées et le client est détruit.
retourne 0 si le client a été détruit.
*/
int start_client(struct client *cli) {
struct page *page;
struct pageobj *obj;
cli->status = STATUS_RUN;
if (arg_timeout > 0)
tv_delayfrom(&cli->expire, &now, arg_timeout);
if (arg_regular_time) {
/* will be needed later to compute next start time */
cli->nextevent = now;
// it's important to get the real time and not the cycle time if we
// want to spread the load
//tv_now(&cli->nextevent);
}
if ((page = cli->current) == NULL) /* fin des pages pour ce client */
return 1;
/* initie autant de fetches que possible pour cette page */
if (continue_fetch(page) == 0)
return 0; /* client détruit */
/* on va terminer de compter les objets pour savoir combien il en reste */
obj = page->objecttostart;
page->objleft = page->actobj;
while (obj != NULL) {
page->objleft++;
obj = obj->next;
}
//SETNOW(&page->begin);
/* le client est (re)démarré */
return 1;
}
/* retourne 0 si le client a du être détruit. */
int newclient(char *username, char *password) {
struct client *newclient;
// newclient=(struct client*)calloc(1, sizeof(struct client));
newclient=(struct client*)alloc_pool(client);
memset(newclient, 0, sizeof_client);
//fprintf(stderr,"client calloc %p\n", newclient);
if (username != NULL)
newclient->username=strdup(username);
if (password != NULL)
newclient->password=strdup(password);
newclient->addr = NULL;
if (local_ip_list)
newclient->addr = get_free_ip(arg_maxobj);
newclient->pages = firstscnpage;
newclient->current = newpage(newclient->pages, newclient);
nbactcli++;
newclient->next = clients;
return start_client(clients = newclient);
}
/* retourne 0 si le client a été détruit */
static inline int onemoreclient() {
char uname[32];
sprintf(uname, "%d", clientid++);
/* on entre dans le scheduler directement à partir de ce client */
if (newclient(uname, uname) == 0)
return 0;
stats[thr].iterations++;
return 1;
}
void destroypage(struct page *page) {
struct pageobj *obj, *nextobj;
obj=page->objects;
while (obj) {
int fd = obj->fd;
nextobj = obj->next;
if (fd > 0) {
put_free_port(page->client->addr, obj->local_port, thr-1);
obj->local_port = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER,
(struct linger *) &nolinger, sizeof(struct linger));
close(fd);
nbconn--;
stats[thr].aborted++;
if (!FD_ISSET(fd, StaticWriteEvent) && FD_ISSET(fd, StaticReadEvent))
/* the connect() succeeded */
nbactconn--;
fdtab[fd] = NULL;
FD_CLR(fd, StaticReadEvent);
FD_CLR(fd, StaticWriteEvent);
if (maxfd == fd+1) { /* recompute maxfd */
while ((maxfd-1 >= 0) && (fdtab[maxfd-1] == NULL))
maxfd--;
}
}
if (obj->vars)
free_pool(vars, obj->vars);
if (obj->buf)
free_pool(buffer, obj->buf);
free_pool(pageobj, obj);
obj=nextobj;
}
free_pool(page, page);
}
/* detruit le client, libère ses fd encore ouverts, décompte le nombre de connexions
associées, et décrémente le nombre de clients actifs */
void destroyclient(struct client *client, struct client *prev) {
if (client->current) {
destroypage(client->current);
}
if (clients == client)
clients = clients->next;
else {
if ((prev != NULL) &&
(prev->next == client)) { /* si on connait le précédent dans la liste, on y va directement */
}
else {
prev = clients;
while (prev->next != client) {
prev = prev->next;
if (prev == NULL)
abort(); /* ca ne doit jamais arriver */
}
}
prev->next = client->next;
}
if (client->addr)
put_free_ip(client->addr, arg_maxobj);
if (client->cookie)
free(client->cookie);
if (client->password)
free(client->password);
if (client->username)
free(client->username);
free_pool(client, client);
nbactcli--;
/* dynamically compute the number of clients if the step size is > 1 */
if (arg_slowstart && arg_stepsize > 1 && nbclients < ramp_step + arg_stepsize) {
nbclients = arg_stepsize * 10 * tv_remain(&ramp_start, &now) / arg_slowstart;
if (nbclients >= arg_stepsize)
nbclients = arg_stepsize;
nbclients += ramp_step;
if (nbclients < 1)
nbclients = 1;
}
while (nbactcli < nbclients) {
if ((arg_maxiter > 0) && (stats[thr].iterations >= arg_maxiter)) {
if (nbactcli == 0)
stopnow = 1;
break;
}
else if (onemoreclient() == 0) {
break; /* si ret==0, plus possible d'injecter à cause d'erreurs */
}
}
return;
}