File: tftpd.c

package info (click to toggle)
atftp 0.7.dfsg-11
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 1,136 kB
  • sloc: ansic: 6,651; sh: 4,107; makefile: 83
file content (1219 lines) | stat: -rw-r--r-- 42,045 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
/* hey emacs! -*- Mode: C; c-file-style: "k&r"; indent-tabs-mode: nil -*- */
/*
 * tftpd.c
 *    main server file
 *
 * $Id: tftpd.c,v 1.61 2004/02/27 02:05:26 jp Exp $
 *
 * Copyright (c) 2000 Jean-Pierre Lefebvre <helix@step.polymtl.ca>
 *                and Remi Lefebvre <remi@debian.org>
 *
 * atftp is free software; you can redistribute them and/or modify them
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <getopt.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h> 
#include <pthread.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#ifdef HAVE_WRAP
#include <tcpd.h>
#endif
#include "tftpd.h"
#include "tftp_io.h"
#include "tftp_def.h"
#include "logger.h"
#include "options.h"
#include "stats.h"
#ifdef HAVE_PCRE
#include "tftpd_pcre.h"
#endif
#ifdef HAVE_MTFTP
#include "tftpd_mtftp.h"
#endif

#undef RATE_CONTROL

/*
 * Global variables set by main when starting. Read-only for threads
 */
int tftpd_max_thread = 100;     /* number of concurent thread allowed */
int tftpd_timeout = 300;        /* number of second of inactivity
                                   before exiting */
char directory[MAXLEN] = "/srv/tftp/";
int retry_timeout = S_TIMEOUT;

int on = 1;
int listen_local = 0;

int tftpd_daemon = 0;           /* By default we are started by inetd */
int tftpd_daemon_no_fork = 0;   /* For who want a false daemon mode */
short tftpd_port = 0;           /* Port atftpd listen to */
char tftpd_addr[MAXLEN] = "";   /* IP address atftpd binds to */

int tftpd_cancel = 0;           /* When true, thread must exit. pthread
                                   cancellation point are not used because
                                   thread id are not tracked. */
char *pidfile = NULL;           /* File to write own's pid */

pthread_t main_thread_id;

/*
 * Multicast related. These reflect option from command line
 * argument --mcast-ttl, --mcast-port and  --mcast-addr
 */
int mcast_ttl = 1;
char mcast_addr[MAXLEN] = "239.255.0.0-255";
char mcast_port[MAXLEN] = "1758";

/*
 * "logging level" is the maximum error level that will get logged.
 *  This can be increased with the -v switch.
 */
int logging_level = LOG_NOTICE;
char *log_file = NULL;

/* logging level as requested by libwrap */
#ifdef HAVE_WRAP
int allow_severity = LOG_NOTICE;
int deny_severity = LOG_NOTICE;
#endif

/* user ID and group ID when running as a daemon */
char user_name[MAXLEN] = "nobody";
char group_name[MAXLEN] = "nogroup";

/* For special uses, disable source port checking */
int source_port_checking = 1;

/* Special feature to make the server switch to new client as soon as
   the current client timeout in multicast mode */
int mcast_switch_client = 0;

int trace = 0;

#ifdef HAVE_PCRE
/* Use for PCRE file name substitution */
tftpd_pcre_self_t *pcre_top = NULL;
char *pcre_file;
#endif

#ifdef HAVE_MTFTP
/* mtftp options */
struct mtftp_data *mtftp_data = NULL;
char mtftp_file[MAXLEN] = "";
int mtftp_sport = 75;
#endif

#ifdef RATE_CONTROL
int rate = 0;
#endif

/*
 * We need a lock on stdin from the time we notice fresh data coming from
 * stdin to the time the freshly created server thread as read it.
 */
pthread_mutex_t stdin_mutex = PTHREAD_MUTEX_INITIALIZER;

/*
 * Function defined in this file
 */
void *tftpd_receive_request(void *);
void signal_handler(int signal);
int tftpd_cmd_line_options(int argc, char **argv);
void tftpd_log_options(void);
int tftpd_pid_file(char *file, int action);
void tftpd_usage(void);

/*
 * Main thread. Do required initialisation and then go through a loop
 * listening for client requests. When a request arrives, we allocate
 * memory for a thread data structure and start a thread to serve the
 * new client. If theres no activity for more than 'tftpd_timeout'
 * seconds, we exit and tftpd must be respawned by inetd.
 */
int main(int argc, char **argv)
{
     fd_set rfds;               /* for select */
     struct timeval tv;         /* for select */
     int run = 1;               /* while (run) loop */
     struct thread_data *new;   /* for allocation of new thread_data */
     int sockfd;                /* used in daemon mode */
     struct sockaddr_storage sa; /* used in daemon mode */
     struct passwd *user;
     struct group *group;
     pthread_t tid;

#ifdef HAVE_MTFTP
     pthread_t mtftp_thread;
#endif

#ifdef RATE_CONTROL
     struct timeval current_time = {0, 0}; /* For rate control */
     long long current = 0L;
     struct timeval previous_time = {0, 0};
     long long previous = 0L;
     int rcvbuf;                /* size of input socket buffer */
#endif
     int one = 1;               /* for setsockopt() */

     /*
      * Parse command line options. We parse before verifying
      * if we are running on a tty or not to make it possible to
      * verify the command line arguments
      */
     if (tftpd_cmd_line_options(argc, argv) == ERR)
          exit(1);

     /*
      * Can't be started from the prompt without explicitely specifying 
      * the --daemon option.
      */
     if (isatty(0) && !(tftpd_daemon))
     {
          tftpd_usage();
          exit(1);
     }

     /* Using syslog facilties through a wrapper. This call divert logs
      * to a file as specified or to syslog if no file specified. Specifying
      * /dev/stderr or /dev/stdout will work if the server is started in
      * daemon mode.
      */
     open_logger("atftpd", log_file, logging_level);
     logger(LOG_NOTICE, "Advanced Trivial FTP server started (%s)", VERSION);

#ifdef HAVE_PCRE
     /*  */
     if (pcre_file)
     {
          if ((pcre_top = tftpd_pcre_open(pcre_file)) == NULL)
               logger(LOG_WARNING, "Failed to initialise PCRE, continuing anyway.");
     }
#endif

#ifdef RATE_CONTROL
     /* Some tuning */
     rcvbuf = 128;
     if (setsockopt(0, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) == 0)
     {
          logger(LOG_WARNING, "Failed to set socket option: %s", strerror(errno));
     }
     logger(LOG_DEBUG, "Receive socket buffer set to %d bytes", rcvbuf);
#endif

     /*
      * If tftpd is run in daemon mode ...
      */
     if (tftpd_daemon)
     {
          /* daemonize here */
          if (!tftpd_daemon_no_fork)
          {
               if (daemon(0, 0) == -1)
                    exit(2);
          }

          /* find the port; initialise sockaddr_storage structure */
          if (strlen(tftpd_addr) > 0 || tftpd_port == 0)
          {
               struct addrinfo hints, *result;
               int err;

               /* look up the service and host */
               memset(&hints, 0, sizeof(hints));
               hints.ai_socktype = SOCK_DGRAM;
               hints.ai_flags = AI_NUMERICHOST;
               err = getaddrinfo(tftpd_addr, tftpd_port ? NULL : "tftp",
                                 &hints, &result);
               if (err == EAI_SERVICE)
               {
                    logger(LOG_ERR, "atftpd: udp/tftp, unknown service");
                    exit(1);
               }
               if (err || sockaddr_set_addrinfo(&sa, result))
               {
                    logger(LOG_ERR, "atftpd: invalid IP address %s", tftpd_addr);
                    exit(1);
               }

               if (!tftpd_port)
                    tftpd_port = sockaddr_get_port(&sa);
               else {
                    sa.ss_family = AF_INET;
                    sockaddr_set_port(&sa, tftpd_port);
               }

               freeaddrinfo(result);
          }

          if (strlen(tftpd_addr) == 0)
          {
               memset(&sa, 0, sizeof(sa));
               sa.ss_family = AF_INET;
          }
          sockaddr_set_port(&sa, tftpd_port);

          /* open the socket */
          if ((sockfd = socket(sa.ss_family, SOCK_DGRAM, 0)) == 0)
          {
               logger(LOG_ERR, "atftpd: can't open socket");
               exit(1);
          }
          /* bind the socket to the desired address and port  */
          if (bind(sockfd, (struct sockaddr*)&sa, sizeof(sa)) < 0)
          {
               logger(LOG_ERR, "atftpd: can't bind port %s:%d/udp",
                      tftpd_addr, tftpd_port);
               exit(1);
          }
          /*
           * dup sockfd on 0 only, not 1,2 like inetd do to allow
           * logging to stderr in pseudo daemon mode (--daemon --no-fork)
           */
          dup2(sockfd, 0);
          close(sockfd);

          /* release priviliedge */
          user = getpwnam(user_name);
          group = getgrnam(group_name);
          if (!user || !group)
          {
               logger(LOG_ERR,
                      "atftpd: can't change identity to %s.%s, exiting.",
                      user_name, group_name);
               exit(1);
          }

          /* write our pid in the specified file before changing user*/
          if (pidfile)
          {
               if (tftpd_pid_file(pidfile, 1) != OK)
                    exit(1);
               /* to be able to remove it later */
               chown(pidfile, user->pw_uid, group->gr_gid);
          }

          setgid(group->gr_gid);
          setuid(user->pw_uid);

          /* Reopen log file now that we changed user, and that we've
           * open and dup2 the socket. */
          open_logger("atftpd", log_file, logging_level);
     }

#if defined(SOL_IP) && defined(IP_PKTINFO)
     /* We need to retieve some information from incomming packets */
     if (setsockopt(0, SOL_IP, IP_PKTINFO, &one, sizeof(one)) != 0)
     {
          logger(LOG_WARNING, "Failed to set socket option: %s", strerror(errno));
     }
#endif

     /* save main thread ID for proper signal handling */
     main_thread_id = pthread_self();

     /* Register signal handler. */
     signal(SIGINT, signal_handler);
     signal(SIGTERM, signal_handler);

     /* print summary of options */
     tftpd_log_options();

     /* start collecting stats */
     stats_start();

#ifdef HAVE_MTFTP
     /* start mtftp server thread */
     if (strlen(mtftp_file) > 0)
     {
          if (!tftpd_daemon)
               logger(LOG_ERR, "Can't start mtftp server, use --deamon");
          else
          {
               if ((mtftp_data = tftpd_mtftp_init(mtftp_file)) == NULL)
                    logger(LOG_ERR, "Failled initialise mtftp");
               else
               {
                    mtftp_data->server_port = mtftp_sport;
                    mtftp_data->mcast_ttl = mcast_ttl;
                    mtftp_data->timeout = retry_timeout;
                    mtftp_data->checkport = source_port_checking;
                    mtftp_data->trace = trace;
                    /* Start server thread. */
                    if (pthread_create(&mtftp_thread, NULL, tftpd_mtftp_server,
                                       (void *)mtftp_data) != 0)
                    {
                         logger(LOG_ERR, "Failed to start mtftp server thread");
                         tftpd_mtftp_clean(mtftp_data);
                         mtftp_data = NULL;
                    } 
              }
          }
     }
#endif

     /* Wait for read or write request and exit if timeout. */
     while (run)
     {
          /*
           * inetd dups the socket file descriptor to 0, 1 and 2 so we can
           * use any of those as the socket fd. We use 0. stdout and stderr
           * may not be used to print messages.
           */
          FD_ZERO(&rfds);
          FD_SET(0, &rfds);
          tv.tv_sec = tftpd_timeout;
          tv.tv_usec = 0;

          /* We need to lock stdin, and release it when the thread
             is done reading the request. */
          pthread_mutex_lock(&stdin_mutex);

#ifdef RATE_CONTROL          
          /* if we want to implement rate control, we sleep some time here
             so we cannot exceed the allowed thread/sec. */
          if (rate > 0)
          {
               gettimeofday(&current_time, NULL);
               current = (long long)current_time.tv_sec*1000000L + current_time.tv_usec;
               logger(LOG_DEBUG, "time from previous request: %Ld", current - previous);
               if ((current - previous) < (60L*1000000L / (long long)rate))
               {
                    logger(LOG_DEBUG, "will sleep for rate control (%Ld)",
                           (60L*1000000L / (long long)rate) - (current - previous));
                    usleep((60L*1000000L / (long long)rate) - (current - previous));
               }
          }
#endif

          /* A timeout of 0 is interpreted as infinity. Wait for incomming
             packets */
          if (!tftpd_cancel)
          {
               int rv;

               if ((tftpd_timeout == 0) || (tftpd_daemon))
                    rv = select(FD_SETSIZE, &rfds, NULL, NULL, NULL);
               else
                    rv = select(FD_SETSIZE, &rfds, NULL, NULL, &tv);
               if (rv < 0) {
                    logger(LOG_ERR, "%s: %d: select: %s",
                           __FILE__, __LINE__, strerror(errno));
                    /* Clear the bits, they are undefined! */
                    FD_ZERO(&rfds);
	       }
          }

#ifdef RATE_CONTROL
          /* get the time we receive this packet */
          if (rate > 0)
          {
               gettimeofday(&previous_time, NULL);
               previous = (long long)previous_time.tv_sec*1000000L +
                    previous_time.tv_usec;
          }
#endif

          if (FD_ISSET(0, &rfds) && (!tftpd_cancel))
          {
               /* Allocate memory for thread_data structure. */
               if ((new = calloc(1, sizeof(struct thread_data))) == NULL)
               {
                    logger(LOG_ERR, "%s: %d: Memory allocation failed",
                           __FILE__, __LINE__);
                    exit(1);
               }

               /*
                * Initialisation of thread_data structure.
                */
               pthread_mutex_init(&new->client_mutex, NULL);
               new->sockfd = 0;

               /* Allocate data buffer for tftp transfer. */
               if ((new->data_buffer = malloc((size_t)SEGSIZE + 4)) == NULL)
               {
                    logger(LOG_ERR, "%s: %d: Memory allocation failed",
                           __FILE__, __LINE__);
                    exit(1);
               }
               new->data_buffer_size = SEGSIZE + 4;

               /* Allocate memory for tftp option structure. */
               if ((new->tftp_options = 
                    malloc(sizeof(tftp_default_options))) == NULL)
               {
                    logger(LOG_ERR, "%s: %d: Memory allocation failed",
                           __FILE__, __LINE__);
                    exit(1);
               }

               /* Copy default options. */
               memcpy(new->tftp_options, tftp_default_options,
                      sizeof(tftp_default_options));

               /* default timeout */
               new->timeout = retry_timeout;

               /* wheter we check source port or not */
               new->checkport = source_port_checking;

               /* other options */
               new->mcast_switch_client = mcast_switch_client;
               new->trace = trace;

               /* default ttl for multicast */
               new->mcast_ttl = mcast_ttl;

               /* Allocate memory for a client structure. */
               if ((new->client_info =
                    calloc(1, sizeof(struct client_info))) == NULL)
               {
                    logger(LOG_ERR, "%s: %d: Memory allocation failed",
                           __FILE__, __LINE__);
                    exit(1);
               }
               new->client_info->done = 0;
               new->client_info->next = NULL;
               
               /* Start a new server thread. */
               if (pthread_create(&tid, NULL, tftpd_receive_request,
                                  (void *)new) != 0)
               {
                    logger(LOG_ERR, "Failed to start new thread");
                    free(new);
                    pthread_mutex_unlock(&stdin_mutex);
               }
          }
          else
          {
               pthread_mutex_unlock(&stdin_mutex);
               
               /* Either select return after timeout of we've been killed. In the first case
                  we wait for server thread to finish, in the other we kill them */
               if (tftpd_cancel)
                    tftpd_list_kill_threads();

               while (tftpd_list_num_of_thread() != 0)
                    sleep(1);

               run = 0;
               if (tftpd_daemon || (tftpd_timeout == 0))
                    logger(LOG_NOTICE, "atftpd terminating");
               else
                    logger(LOG_NOTICE,
                           "atftpd terminating after %d seconds",
                           tftpd_timeout);
          }
     }

     /* close all open file descriptors */
     close(0);
     close(1);
     close(2);

#ifdef HAVE_MTFTP
     /*  stop the mtftp threads */
     if (mtftp_data)
     {
          /* kill mtftp serving thread */
          tftpd_mtftp_kill_threads(mtftp_data);
          /* kill mtftp main thread */
          pthread_kill(mtftp_thread, SIGTERM);
          pthread_join(mtftp_thread, NULL);
     }
#endif

     /* stop collecting stats and print them*/
     stats_end();
     stats_print();
     
#ifdef HAVE_PCRE
     /* remove allocated memory for tftpd_pcre */
     if (pcre_top)
          tftpd_pcre_close(pcre_top);
#endif

     /* some cleaning */
     if (log_file)
          free(log_file);
#ifdef HAVE_PCRE
     if (pcre_file)
          free(pcre_file);
#endif

     /* remove PID file */
     if (pidfile)
          tftpd_pid_file(pidfile, 0);

     logger(LOG_NOTICE, "Main thread exiting");
     close_logger();
     exit(0);
}

/* 
 * This function handles the initial connection with a client. It reads
 * the request from stdin and then release the stdin_mutex, so the main
 * thread may listen for new clients. After that, we process options and
 * call the sending or receiving function.
 *
 * arg is a thread_data structure pointer for that thread.
 */
void *tftpd_receive_request(void *arg)
{
     struct thread_data *data = (struct thread_data *)arg;
     
     int retval;                /* hold return value for testing */
     int data_size;             /* returned size by recvfrom */
     char string[MAXLEN];       /* hold the string we pass to the logger */
     int num_of_threads;
     int abort = 0;             /* 1 if we need to abort because the maximum
                                   number of threads have been reached*/ 
     struct sockaddr_storage to; /* destination of client's packet */
     socklen_t len = sizeof(to);

     char addr_str[SOCKADDR_PRINT_ADDR_LEN];

     /* Detach ourself. That way the main thread does not have to
      * wait for us with pthread_join. */
     data->tid = pthread_self();
     pthread_detach(data->tid);

     /* Read the first packet from stdin. */
     data_size = data->data_buffer_size;     
     retval = tftp_get_packet(0, -1, NULL, &data->client_info->client, NULL,
                              &to, data->timeout, &data_size,
                              data->data_buffer);
     if (retval == ERR) {
          logger(LOG_NOTICE, "Invalid request in 1st packet");
          abort = 1;
     }

     /* now unlock stdin */
     pthread_mutex_unlock(&stdin_mutex);

     /* Verify the number of threads */
     if ((num_of_threads = tftpd_list_num_of_thread()) >= tftpd_max_thread)
     {
          logger(LOG_INFO, "Maximum number of threads reached: %d",
                 num_of_threads);
          abort = 1;
     }

#ifdef HAVE_WRAP
     if (!abort)
     {
          /* Verify the client has access. We don't look for the name but
             rely only on the IP address for that. */
          sockaddr_print_addr(&data->client_info->client,
                              addr_str, sizeof(addr_str));
          if (hosts_ctl("in.tftpd", STRING_UNKNOWN, addr_str,
                        STRING_UNKNOWN) == 0)
          {
               logger(LOG_ERR, "Connection refused from %s", addr_str);
               abort = 1;
          }
     }
#endif

     /* Add this new thread structure to the list. */
     if (!abort)
          stats_new_thread(tftpd_list_add(data));

     /* if the maximum number of thread is reached, too bad we abort. */
     if (abort)
          stats_abort_locked();
     else
     {
          /* open a socket for client communication */
          data->sockfd = socket(data->client_info->client.ss_family,
                                SOCK_DGRAM, 0);
          /*memset(&to, 0, sizeof(to));*/
          /* PSz 11 Aug 2011  http://bugs.debian.org/613582
           * Do not nullify "to", preserve IP address from tftp_get_packet().
           * Only set port to 0, as we used to in v6.
           * (Why set ss_family, was not it right already??)
           */
          to.ss_family = data->client_info->client.ss_family;
          sockaddr_set_port(&to, 0);
          /* Force socket to listen on local address. Do not listen on broadcast address 255.255.255.255. 
             If the socket listens on the broadcast address, Linux tells the remote client the port
             is unreachable. This happens even if SO_BROADCAST is set in setsockopt for this socket.
             I was unable to find a kernel option or /proc/sys flag to make the kernel pay attention to 
             these requests, so the workaround is to force listening on the local address. */
          if (listen_local == 1)
          { 
               logger(LOG_INFO, "forcing socket to listen on local address");
               if (setsockopt(data->sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) != 0) {
                  logger(LOG_ERR, "setsockopt: %s", strerror(errno));
               }
          }
          else
          {
               logger(LOG_INFO, "socket may listen on any address, including broadcast");
          }

          if (data->sockfd > 0)
          {
               /* bind the socket to the interface */
               if (bind(data->sockfd, (struct sockaddr *)&to, len) == -1)
               {
                    logger(LOG_ERR, "bind: %s", strerror(errno));
                    retval = ABORT;
               }
               /* read back assigned port */
               len = sizeof(to);
               if (getsockname(data->sockfd, (struct sockaddr *)&to, &len) == -1)
               {
                    logger(LOG_ERR, "getsockname: %s", strerror(errno));
                    retval = ABORT;
               }
               /* connect the socket, faster for kernel operation */
               /* this is not a good idea on FreeBSD, because sendto() cannot
                  be used on a connected datagram socket */
#if !defined(__FreeBSD_kernel__)
               if (connect(data->sockfd,
                           (struct sockaddr *)&data->client_info->client,
                           sizeof(data->client_info->client)) == -1)
               {
                    logger(LOG_ERR, "connect: %s", strerror(errno));
                    retval = ABORT;
               }
#endif
               logger(LOG_DEBUG, "Creating new socket: %s:%d",
                      sockaddr_print_addr(&to, addr_str, sizeof(addr_str)),
                      sockaddr_get_port(&to));
               
               /* read options from request */
               opt_parse_request(data->data_buffer, data_size,
                                 data->tftp_options);
               opt_request_to_string(data->tftp_options, string, MAXLEN);
          }
          else
          {
               retval = ABORT;
          }

          /* Analyse the request. */
          switch (retval)
          {
          case GET_RRQ:
               logger(LOG_NOTICE, "Serving %s to %s:%d",
                      data->tftp_options[OPT_FILENAME].value,
                      sockaddr_print_addr(&data->client_info->client,
                                          addr_str, sizeof(addr_str)),
                      sockaddr_get_port(&data->client_info->client));
               if (data->trace)
                    logger(LOG_DEBUG, "received RRQ <%s>", string);
               if (tftpd_send_file(data) == OK)
                    stats_send_locked();
               else
                    stats_err_locked();
               break;
          case GET_WRQ:
               logger(LOG_NOTICE, "Fetching from %s to %s",
                      sockaddr_print_addr(&data->client_info->client,
                                          addr_str, sizeof(addr_str)),
                      data->tftp_options[OPT_FILENAME].value);
               if (data->trace)
                    logger(LOG_DEBUG, "received WRQ <%s>", string);
               if (tftpd_receive_file(data) == OK)
                    stats_recv_locked();
               else
                    stats_err_locked();
               break;
          case ERR:
               logger(LOG_ERR, "Error from tftp_get_packet");
               tftp_send_error(data->sockfd, &data->client_info->client,
                               EUNDEF, data->data_buffer, data->data_buffer_size);
               if (data->trace)
                    logger(LOG_DEBUG, "sent ERROR <code: %d, msg: %s>", EUNDEF,
                           tftp_errmsg[EUNDEF]);
               stats_err_locked();
               break;
          case ABORT:
               if (data->trace)
                    logger(LOG_ERR, "thread aborting");
               stats_err_locked();
               break;
          default:
               logger(LOG_NOTICE, "Invalid request <%d> from %s",
                      retval,
                      sockaddr_print_addr(&data->client_info->client,
                                          addr_str, sizeof(addr_str)));
               tftp_send_error(data->sockfd, &data->client_info->client,
                               EBADOP, data->data_buffer, data->data_buffer_size);
               if (data->trace)
                    logger(LOG_DEBUG, "sent ERROR <code: %d, msg: %s>", EBADOP,
                           tftp_errmsg[EBADOP]);
               stats_err_locked();
          }
     }  

     /* make sure all data is sent to the network */
     if (data->sockfd)
     {
          fsync(data->sockfd);
          close(data->sockfd);
     }

     /* update stats */
     stats_thread_usage_locked();

     /* Remove the thread_data structure from the list, if it as been
        added. */
     if (!abort)
          tftpd_list_remove(data);

     /* Free memory. */
     if (data->data_buffer)
          free(data->data_buffer);

     free(data->tftp_options);

     /* if the thread had reserverd a multicast IP/Port, deallocate it */
     if (data->mc_port != 0)
          tftpd_mcast_free_tid(data->mc_addr, data->mc_port);

     /* this function take care of freeing allocated memory by other threads */
     tftpd_clientlist_free(data);

     /* free the thread structure */
     free(data);    

     logger(LOG_INFO, "Server thread exiting");
     pthread_exit(NULL);
}

/*
 * If we receive signals, we must exit in a clean way. This means
 * sending an ERROR packet to all clients to terminate the connection.
 */
void signal_handler(int signal)
{
     /* Any thread may receive the signal, always make sure the main thread receive it
        and cancel other threads itself. However, if tftpd_cancel already set, just
        ignore the signal since the master thread as already got the signal. */
     if (pthread_self() != main_thread_id)
     {
          if (tftpd_cancel == 0)
          {
               logger(LOG_ERR, "Forwarding signal to main thread");
               pthread_kill(main_thread_id, signal);
          }
          return;
     }

     /* Only signals for the main thread get there */
     switch (signal)
     {
     case SIGINT:
          logger(LOG_ERR, "SIGINT received, stopping threads and exiting.");
          tftpd_cancel = 1;
          break;
     case SIGTERM:
          logger(LOG_ERR, "SIGTERM received, stopping threads and exiting.");
          tftpd_cancel = 1;
          break;
     default:
          logger(LOG_WARNING, "Signal %d received, ignoring.", signal);
          break;
     }
}

#define OPT_RATE       'R'
#define OPT_MCAST_TTL  '0'
#define OPT_MCAST_ADDR '1'
#define OPT_MCAST_PORT '2'
#define OPT_PCRE       '3'
#define OPT_PCRE_TEST  '4'
#define OPT_PORT_CHECK '5'
#define OPT_MCAST_SWITCH '6'
#define OPT_MTFTP      '7'
#define OPT_MTFTP_PORT '8'
#define OPT_TRACE      '9'

/*
 * Parse the command line using the standard getopt function.
 */
int tftpd_cmd_line_options(int argc, char **argv)
{
     int c;
     char *tmp;
#ifdef HAVE_PCRE
     char string[MAXLEN], out[MAXLEN];
#endif
     static struct option options[] = {
          { "tftpd-timeout", 1, NULL, 't' },
          { "retry-timeout", 1, NULL, 'r' },
          { "maxthread", 1, NULL, 'm' },
#ifdef RATE_CONTROL
          { "rate", 1, NULL, OPT_RATE },
#endif
          { "verbose", 2, NULL, 'v' },
          { "trace", 0, NULL, OPT_TRACE },
          { "no-timeout", 0, NULL, 'T' },
          { "no-tsize", 0, NULL, 'S' },
          { "no-blksize", 0, NULL, 'B' },
          { "no-multicast", 0, NULL, 'M' },
          { "logfile", 1, NULL, 'L' },
          { "pidfile", 1, NULL, 'I'},
          { "listen-local", 0, NULL, 'F'},
          { "daemon", 0, NULL, 'D' },
          { "no-fork", 0, NULL, 'N'},
          { "user", 1, NULL, 'U'},
          { "group", 1, NULL, 'G'},
          { "port", 1, NULL, 'P' },
          { "bind-address", 1, NULL, 'A'},
          { "mcast-ttl", 1, NULL, OPT_MCAST_TTL },
          { "mcast_ttl", 1, NULL, OPT_MCAST_TTL },
          { "mcast-addr", 1, NULL, OPT_MCAST_ADDR },
          { "mcast_addr", 1, NULL, OPT_MCAST_ADDR },
          { "mcast-port", 1, NULL, OPT_MCAST_PORT },
          { "mcast_port", 1, NULL, OPT_MCAST_PORT },
#ifdef HAVE_PCRE
          { "pcre", 1, NULL, OPT_PCRE },
          { "pcre-test", 1, NULL, OPT_PCRE_TEST },
#endif
#ifdef HAVE_MTFTP
          { "mtftp", 1, NULL, OPT_MTFTP },
          { "mtftp-port", 1, NULL, OPT_MTFTP_PORT },
#endif
          { "no-source-port-checking", 0, NULL, OPT_PORT_CHECK },
          { "mcast-switch-client", 0, NULL, OPT_MCAST_SWITCH },
          { "version", 0, NULL, 'V' },
          { "help", 0, NULL, 'h' },
          { 0, 0, 0, 0 }
     };
     
     while ((c = getopt_long(argc, argv, "t:r:m:v::Vh",
                             options, NULL)) != EOF)
     {
          switch (c)
          {
          case 't':
               tftpd_timeout = atoi(optarg);
               break;
          case 'r':
               retry_timeout = atoi(optarg);
               break;
          case 'm':
               tftpd_max_thread = atoi(optarg);
               break;
#ifdef RATE_CONTROL
          case OPT_RATE:
               rate = atoi(optarg);
               break;
#endif
          case 'v':
               if (optarg)
                    logging_level = atoi(optarg);
               else
                    logging_level++;
#ifdef HAVE_WRAP
               allow_severity = logging_level;
               deny_severity = logging_level;
#endif
               break;
          case OPT_TRACE:
               trace = 1;
               break;
          case 'T':
               tftp_default_options[OPT_TIMEOUT].enabled = 0;
               break;
          case 'S':
               tftp_default_options[OPT_TSIZE].enabled = 0;
               break;
          case 'B':
               tftp_default_options[OPT_BLKSIZE].enabled = 0;
               break;
          case 'M':
               tftp_default_options[OPT_MULTICAST].enabled = 0;
               break;
          case 'L':
               log_file = strdup(optarg);
               break;
          case 'I':
               pidfile = strdup(optarg);
               break;
          case 'F':
               listen_local = 1;
               break;
          case 'D':
               tftpd_daemon = 1;
               break;
          case 'N':
               tftpd_daemon_no_fork = 1;
               break;
          case 'U':
               tmp = strtok(optarg, ".");
               if (tmp != NULL)
                    Strncpy(user_name, tmp, MAXLEN);
               tmp = strtok(NULL, "");
               if (tmp != NULL)
                    Strncpy(group_name, optarg, MAXLEN);
               break;
          case 'G':
               Strncpy(group_name, optarg, MAXLEN);
               break;
          case 'P':
               tftpd_port = (short)atoi(optarg);
               break;
          case 'A': 
               Strncpy(tftpd_addr, optarg, MAXLEN);
               break;
          case OPT_MCAST_TTL:
               mcast_ttl = atoi(optarg);
               break;
          case OPT_MCAST_ADDR:
               Strncpy(mcast_addr, optarg, MAXLEN);
               break;
          case '2':
               Strncpy(mcast_port, optarg, MAXLEN);
               break;
#ifdef HAVE_PCRE
          case OPT_PCRE:
               pcre_file = strdup(optarg);
               break;
          case OPT_PCRE_TEST:
               /* test the pattern file */
               if ((pcre_top = tftpd_pcre_open(optarg)) == NULL)
               {
                    fprintf(stderr, "Failed to initialise PCRE with file %s", optarg);
                    exit(1);
               }
               /* run test */
               while (1)
               {
                    if (isatty(0))
                         printf("> ");
                    if (fgets(string, MAXLEN, stdin) == NULL)
                    {
                         tftpd_pcre_close(pcre_top);
                         exit(0);
                    }
                    /* exit on empty line */
                    if (string[0] == '\n')
                    {
                         tftpd_pcre_close(pcre_top);
                         exit(0);
                    }
                    /* remove \n from input */
                    string[strlen(string) - 1] = '\0';
                    /* do the substitution */
                    if (tftpd_pcre_sub(pcre_top, out, MAXLEN, string) < 0)
                         printf("Substitution: \"%s\" -> \"\"\n", string);
                    else
                         printf("Substitution: \"%s\" -> \"%s\"\n", string, out);
               }
#endif
          case OPT_PORT_CHECK:
               source_port_checking = 0;
               break;
          case OPT_MCAST_SWITCH:
               mcast_switch_client = 1;
               break;
#ifdef HAVE_MTFTP
          case OPT_MTFTP:
               Strncpy(mtftp_file, optarg, MAXLEN);         
               break;
          case OPT_MTFTP_PORT:
               mtftp_sport = atoi(optarg);
               break;
#endif
          case 'V':
               printf("atftp-%s (server)\n", VERSION);
               exit(0);
          case 'h':
               tftpd_usage();
               exit(0);
          case '?':
               exit(1);
               break;
          }
     }
          
     /* verify that only one arguement is left */
     if (optind < argc)
          Strncpy(directory, argv[optind], MAXLEN);
     /* make sure the last caracter is a / */
     if (directory[strlen(directory)] != '/')
          strcat(directory, "/");
     /* build multicast address/port range */
     if (tftpd_mcast_parse_opt(mcast_addr, mcast_port) != OK)
          exit(1);
     return OK;
}

/*
 * Output option to the syslog.
 */
void tftpd_log_options(void)
{
     if (tftpd_daemon == 1)
     {
          logger(LOG_INFO, "  running in daemon mode on port %d", tftpd_port);
          if (strlen(tftpd_addr) > 0)
               logger(LOG_INFO, "  bound to IP address %s only", tftpd_addr);
     }
     else
          logger(LOG_INFO, "  started by inetd");
     logger(LOG_INFO, "  logging level: %d", logging_level);
     if (trace)
          logger(LOG_INFO, "     trace enabled");
     logger(LOG_INFO, "  directory: %s", directory);
     logger(LOG_INFO, "  user: %s.%s", user_name, group_name);
     logger(LOG_INFO, "  log file: %s", (log_file==NULL) ? "syslog":log_file);
     if (pidfile)
          logger(LOG_INFO, "  pid file: %s", pidfile);
     if (listen_local == 1)
          logger(LOG_INFO, "  forcing to listen on local interfaces: on.");
     else
          logger(LOG_INFO, "  not forcing to listen on local interfaces.");
     if (tftpd_daemon == 1)
          logger(LOG_INFO, "  server timeout: Not used");
     else
          logger(LOG_INFO, "  server timeout: %d", tftpd_timeout);
     logger(LOG_INFO, "  tftp retry timeout: %d", retry_timeout);
     logger(LOG_INFO, "  maximum number of thread: %d", tftpd_max_thread);
#ifdef RATE_CONTROL
     if (rate > 0)
          logger(LOG_INFO, "  request per minute limit: %d", rate);
     else
          logger(LOG_INFO, "  request per minute limit: ---");
#endif
     logger(LOG_INFO, "  option timeout:   %s",
            tftp_default_options[OPT_TIMEOUT].enabled ? "enabled":"disabled");
     logger(LOG_INFO, "  option tzise:     %s",
            tftp_default_options[OPT_TSIZE].enabled ? "enabled":"disabled");
     logger(LOG_INFO, "  option blksize:   %s",
            tftp_default_options[OPT_BLKSIZE].enabled ? "enabled":"disabled");
     logger(LOG_INFO, "  option multicast: %s",
            tftp_default_options[OPT_MULTICAST].enabled ? "enabled":"disabled");
     logger(LOG_INFO, "     address range: %s", mcast_addr);
     logger(LOG_INFO, "     port range:    %s", mcast_port);
#ifdef HAVE_PCRE
     if (pcre_top)
          logger(LOG_INFO, "  PCRE: using file: %s", pcre_file);
#endif
#ifdef HAVE_MTFTP
     if (strcmp(mtftp_file, "") != 0)
     {
          logger(LOG_INFO, "  mtftp: using file: %s", mtftp_file);
          logger(LOG_INFO, "  mtftp: listenning on port %d", mtftp_sport);
     }
#endif
     if (mcast_switch_client)
          logger(LOG_INFO, "  --mcast-switch-client turned on");
     if (!source_port_checking)
          logger(LOG_INFO, "  --no-source-port-checking turned on");
}

/* 
 *
 */
int tftpd_pid_file(char *file, int action)
{
     FILE *fp;
     pid_t pid;

     if (action)
     {
          /* check if file exist */
          if ((fp = fopen(file, "r")) != NULL)
          {
               logger(LOG_NOTICE, "pid file already exist, overwriting");
               fclose(fp);
          }
          /* open file for writing */
          if ((fp = fopen(file, "w")) == NULL)
          {
               logger(LOG_ERR, "error writing PID to file %s\n", file);
               return ERR;
          }
          /* write it */
          pid = getpid();     
          fprintf(fp, "%d\n", pid);
          fclose(fp);
          return OK;
     }
     else
     {
          /* unlink the pid file */
          if (unlink(file) == -1)
               logger(LOG_ERR, "unlink: %s", strerror(errno));
          return OK;
     }
}

/*
 * Show a nice usage...
 */
void tftpd_usage(void)
{
     printf("Usage: tftpd [options] [directory]\n"
            " [options] may be:\n"
            "  -t, --tftpd-timeout <value>: number of second of inactivity"
            " before exiting\n"
            "  -r, --retry-timeout <value>: time to wait a reply before"
            " retransmition\n"
            "  -m, --maxthread <value>    : number of concurrent thread"
            " allowed\n"
#ifdef RATE_CONTROL
            "  --rate <value>             : number of request per minute limit\n"
#endif
            "  -v, --verbose [value]      : increase or set the level of"
            " output messages\n"
            "  --trace                    : log all sent and received packets\n"
            "  --no-timeout               : disable 'timeout' from RFC2349\n"
            "  --no-tsize                 : disable 'tsize' from RFC2349\n"
            "  --no-blksize               : disable 'blksize' from RFC2348\n"
            "  --no-multicast             : disable 'multicast' from RFC2090\n"
            "  --logfile <file>           : logfile to log logs to ;-)\n"
            "  --pidfile <file>           : write PID to this file\n"
            "  --listen-local             : force listen on local network address\n"
            "  --daemon                   : run atftpd standalone (no inetd)\n"
            "  --no-fork                  : run as a daemon, don't fork\n"
            "  --user <user[.group]>      : default is nobody\n"
            "  --group <group>            : default is nogroup\n"
            "  --port <port>              : port on which atftp listen\n"
            "  --bind-address <IP>        : local address atftpd listen to\n"
            "  --mcast-ttl                : ttl to used for multicast\n"
            "  --mcast-addr <address list>: list/range of IP address to use\n"
            "  --mcast-port <port range>  : ports to use for multicast"
            " transfer\n"
#ifdef HAVE_PCRE
            "  --pcre <file>              : use this file for pattern replacement\n"
            "  --pcre-test <file>         : just test pattern file, not starting server\n"
#endif
#ifdef HAVE_MTFTP
            "  --mtftp <file>             : mtftp configuration file\n"
            "  --mtftp-port <port>        : port mtftp will listen\n"
#endif
            "  --no-source-port-checking  : violate RFC, see man page\n"
            "  --mcast-switch-client      : switch client on first timeout, see man page\n"
            "  -V, --version              : print version information\n"
            "  -h, --help                 : print this help\n"
            "\n"
            " [directory] must be a world readable/writable directories.\n"
            " By default /tftpboot is assumed."
            "\n");
}