summaryrefslogtreecommitdiff
path: root/support/dktools/dk-recv.ctr
blob: c00d3c458cea1a1c12a5c5972dc33f619e79ee5b (plain)
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
%%	options

copyright owner	=	Dirk Krause
copyright year	=	2015-xxxx
license		=	bsd



%%	module

#include "dk4conf.h"

#if DK4_HAVE_MATH_H
#ifndef	MATH_H_INCLUDED
#include <math.h>
#define	MATH_H_INCLUDED 1
#endif
#endif

#if DK4_HAVE_ERRNO_H
#ifndef ERRNO_H_INCLUDED
#include <errno.h>
#define	ERRNO_H_INCLUDED 1
#endif
#endif

#if DK4_HAVE_IO_H
#ifndef IO_H_INCLUDED
#include <io.h>
#define	IO_H_INCLUDED 1
#endif
#endif

#if DK4_HAVE_FCNTL_H
#ifndef FCNTL_H_INCLUDED
#include <fcntl.h>
#define FCNTL_H_INCLUDED 1
#endif
#endif

#include "dk4sock.h"
#include "dk4socka.h"
#include "dk4fput.h"
#include "dk4vers.h"
#include "dk4aopt.h"
#include "dk4numco.h"
#include "dk4fopda.h"
#include "dk4isadm.h"
#include "dk4fdwre.h"
#include "dk4mpl.h"
#include "dk4mem.h"
#include "dk4mema.h"
#include "dk4strd.h"
#include "dk4pathd.h"



$!trace-include



/**	Default help text, shown if no localized help text is found.
*/
static const dkChar * const	dk_recv_help_text[] = {
$!text	macro=dkT

Receive data from a dk-send process.

dk-recv [<options>] <host> <port> [<file>]

Arguments:
host		Sender host to connect to (name or IP).
port		Port number to connect to.
file		Output file to create. Default: Write to standard output.

Options:
-t		Tell peer to start transmission.
-l <port>	Local port number to bind.
-c <int>	Timeout for connect attempt.

--help		Show this short help text.
--manual	*** SHOW FULL MANUAL. ***
--version	Show version information.
--license	Show license information.

$!end
};



/**	License text.
*/
static const dkChar * const	dk_recv_license_text[] = {
$!text	macro=dkT,preprocessor
This software uses code from the following projects, either directly or as
a library:

dktools		Dirk Krause's tools and libraries.
		See http://dktools.sourceforge.net/ for more information.
#if DK4_HAVE_ZLIB_H

zlib		Data compression library.
		See http://www.zlib.net/ for more information.
#endif
#if DK4_HAVE_BZLIB_H

bzip2		Data compression program and library.
		See http://www.bzip.org/ for more information.
#endif

All the licenses below apply to the program.
Licenses for used libraries are shown as found on my Scientific Linux 6.x
computer in the /usr/share/doc directory on 2015-04-01. Check the project
homepages of the used libraries for additional information and/or updated
license terms.


DK tools and libraries license
==============================
Copyright (c) 2015-2016, Dirk Krause
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of the Dirk Krause nor the names of contributors may be
  used to endorse or promote products derived from this software without
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.

IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if DK4_HAVE_ZLIB_H


Zlib license
============
(C) 1995-2004 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.

Jean-loup Gailly        Mark Adler
jloup@gzip.org          madler@alumni.caltech.edu
#endif
#if DK4_HAVE_BZLIB_H


Bzip2 and libbzip2 library license
==================================
This program, "bzip2", the associated library "libbzip2", and all
documentation, are copyright (C) 1996-2007 Julian R Seward.  All
rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. The origin of this software must not be misrepresented; you must 
   not claim that you wrote the original software.  If you use this 
   software in a product, an acknowledgment in the product 
   documentation would be appreciated but is not required.

3. Altered source versions must be plainly marked as such, and must
   not be misrepresented as being the original software.

4. The name of the author may not be used to endorse or promote 
   products derived from this software without specific prior written 
   permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Julian Seward, jseward@bzip.org
bzip2/libbzip2 version 1.0.5 of 10 December 2007
#endif

$!end
};



/**	Constant texts used by the program, not localized.
*/
static const dkChar * const	dk_recv_kwnl[] = {
$!string-table	macro=dkT
#
#	0	Program group name
#
dktools
#
#	1	Help file name
#
dk-recv.txt
#
#	2	String table file name
#
dk-recv.str
#
#	3	Path component separator for windows
#
\\
#
#	4	File open mode for binary writing
#
wb
$!end
};



/**	Constant texts used by the program, replaced by localized
	versions if found.
*/
static const dkChar * const	dk_recv_kw_def[] = {
$!string-table	macro=dkT
#
#	0 1	Error: Failed to set up / restore signal handlers!
#
Failed to set up signal handlers!
Failed to restore signal handlers!
#
#	2	File name "stdin" for error message
#
stdin
#
#	3	Error: Failed to close file!
#
Failed to close file!
#
#	4	Error: Timeout too large!
#
Timeout too large!
#
#	5	Error: Timeout must not be negative!
#
Timeout must not be negative!
#
#	6	Error: Timeout value not found!
#
Timeout value not found!
#
#	7	Error: Wrong number of arguments!
#
Wrong number of arguments!\n\thost port [filename]
#
#	8 9 10	Error: Interrupted by ... signal!
#
Interrupted by SIGINT signal!
Interrupted by SIGTERM signal!
Interrupted by SIGPIPE signal!
$!end
};



/**	Options used by the program.
*/
static const dk4_option_specification_t dk_recv_options[] = {

  /*	I am the last client, server can start transmissin now.
  */
  { dkT('t'),	dkT("transmission"),	DK4_OPT_ARG_NONE },

  /*	Bind a certain local port number.
  */
  { dkT('l'),	dkT("local-port"),	DK4_OPT_ARG_STRING },

  /*	Use a timeout when connecting to the server.
  */
  { dkT('c'),	dkT("connect-timeout"),	DK4_OPT_ARG_DOUBLE }
};



/**	Array of localized texts, loaded in the main() function.
	Usable as long as the app pointer below is usable.
*/
static const dkChar * const	*dk_recv_kw_loc	=	NULL;



/**	Local port number to use.
*/
static const dkChar		*dk_recv_portno	=	NULL;



/**	Application structure for diagnostics.
*/	
static	dk4_app_t	*app	= NULL;



/**	Number of elements in the dk_recv_options array.
*/
static const size_t dk_recv_sz_options =
sizeof(dk_recv_options)/sizeof(dk4_option_specification_t);



/**	Number of elements in the dk_recv_kw_def array.
*/
static const size_t	dk_recv_sz_def	=
sizeof(dk_recv_kw_def)/sizeof(DK4_PCDKCHAR) - 1;



/**	Number of elements in the dk_recv_kw_def array.
*/
static size_t	dk_recv_sz_loc	=
sizeof(dk_recv_kw_def)/sizeof(DK4_PCDKCHAR) - 1;



/**	Seconds for timeout.
*/
static long	dk_recv_timeout_secs	=	0L;



/**	Microseconds for timeout.
*/
static long	dk_recv_timeout_usecs	=	0L;



/**	Exit status code.
*/
static	int		 exval	= EXIT_FAILURE;



/**	Flag send to server: Start transmission immediately.
*/
static	unsigned char	 start_transmission = 0x00;



#ifdef SIGPIPE
/**	Indicator: SIGPIPE signal received.
*/
static
DK4_VOLATILE
dk4_sig_atomic_t	sig_had_pipe	=	0;
#endif

/**	Indicator: SIGINT signal received.
*/
static
DK4_VOLATILE
dk4_sig_atomic_t	sig_had_int	=	0;

/**	Indicator: SIGTERM signal received.
*/
static
DK4_VOLATILE
dk4_sig_atomic_t	sig_had_term	=	0;



/**	Pass a volatile pointer to an atomic integer.
	This function is necessary as some compilers mis-optimize
	direct access to volatile variables (at least if you believe
	one of the coding standards).
	@param	ptr	Address of atomic integer variable.
	@return	The unmodified pointer.
*/
static
DK4_VOLATILE
dk4_sig_atomic_t *
sig_pass_pointer(DK4_VOLATILE dk4_sig_atomic_t *ptr)
{
  return ptr;
}



#ifdef SIGPIPE
/**	Handler for SIGPIPE signal.
	@param	signo	Signal number (always SIGPIPE, ignored).
*/
static
void
sig_handler_pipe(int signo)
{
  *sig_pass_pointer(&sig_had_pipe) = 1;
}
#endif

/**	Handler for SIGINT signal.
	@param	signo	Signal number (always SIGINT, ignored).
*/
static
void
sig_handler_int(int signo)
{
  *sig_pass_pointer(&sig_had_int) = 1;
}

/**	Handler for SIGTERM signal.
	@param	signo	Signal number (always SIGTERM, ignored).
*/
static
void
sig_handler_term(int signo)
{
  *sig_pass_pointer(&sig_had_term) = 1;
}

/**	Read value from volatile atomic type.
	This function is necessary as some compilers mis-optimize
	direct access to volatile variables (at least if you believe
	one of the coding standards).
	@param	ap	Pointer to volatile atomic variable.
	@return	Contents of the variable.
*/
static
dk4_sig_atomic_t
sig_read_atomic(DK4_VOLATILE dk4_sig_atomic_t *ap)
{
  return (*ap);
}

/**	Check whether we can continue or if a signal was received.
	@param	check_pipe	Flag: Check for occured SIGPIPE signal too.
	@return	1 if the program can continue, 0 if a signal was received.
*/
static
int
sig_can_continue(int check_pipe)
{
  int		back = 1;
#ifdef SIGPIPE
  if (0 != check_pipe) {
    if (0 != sig_read_atomic(&sig_had_pipe)) { back = 0; }
  }
#endif
  if (0 != sig_read_atomic(&sig_had_int )) { back = 0; }
  if (0 != sig_read_atomic(&sig_had_term)) { back = 0; }
  return back;
}



#if 0

/*
	2016-01-02:
	Removed - replaced by sig_can_continue(1) - after profiling.
*/

/**	Check whether we can continue.
	@return	1 for yes, 0 for no.
*/
static
int
dk_recv_can_continue(void)
{
  int		back	=	1;
  if (0 == sig_can_continue(1)) {
    back = 0;
  }
  return back;
}

#endif
/* if 0 */



/**	Data buffer
*/
#if DK4_SIZEOF_SIZE_T > 2
static	char	 bu[1048576];
#else
static	char	 bu[16384];
#endif

/**	Run for hostname, port specification and real file name
	(wildcards * and ? resolved on Windows).
	@param	hostname	Host to connect to (name or address).
	@param	portspec	Port to connect to (number or service name).
	@param	filename	File name to write, may be NULL (stdout).
*/
static
void
dk_recv_run_with_real_file_name(
  const	dkChar	*hostname,
  const dkChar	*portspec,
  const	dkChar	*filename
)
{
#if 0
  /*	2016-01-06:
	Buffer size increased, do not use stack.
  */
  char			 bu[1460];			/* Data buffer */
#endif
  FILE			*fipo	= NULL;			/* Output file */
  size_t		 sz	= 0;			/* Buffer sizes */
  size_t		 wrb	= 0;			/* Bytes written */
  dk4_socket_t		 sock	= INVALID_SOCKET;	/* Client socket */
#if DK4_ON_WINDOWS
  int			 oldmode= _O_TEXT;		/* File mode stdout */
#endif
  int			 cc	= 1;			/* Flag: Can continue */
  int			 first	= 1;			/* Flag: First pass */
  int			 res	= 0;			/* Operation result */
  int			 we	= 0;			/* Flag: Write error */
  int			 tests	= 0;

  $? "+ dk_recv_run_with_real_file_name"
  /*	Check for signals.
  */
  if (0 == sig_can_continue(1)) {
    goto finished;
  }	$? ". no signals received yet"

  /*	Bring socket subsystem up (Windows).
  */
  if (DK4_SOCKET_RESULT_SUCCESS != dk4socket_up_app(app)) {
    /* ERROR: Failed to bring socket subsystem up, already reported */
    goto finished;
  }	$? ". socket subsystem up"

  /*	Open TCP client socket.
  */
  sock = dk4socket_tcp_client_for_host_service_app(
    hostname, portspec, dk_recv_portno,
    dk_recv_timeout_secs, dk_recv_timeout_usecs, app
  );
  if (INVALID_SOCKET == sock) {
    /* ERROR: Failed to create socket, already reported */
    goto tcpip_down;
  }	$? ". socket created"
  if (0 == sig_can_continue(1)) {
    goto close_socket;
  }	$? ". no signal yet"

  /*	Send start-of-transmission byte and shutdown socket for writing.
  */
  sz = 1;
  res = dk4socket_send_app(sock, &start_transmission, &sz, 0, 0L, 0L, app);
  if (DK4_SOCKET_RESULT_SUCCESS != res) {
    goto close_socket;
  }	$? ". initial byte sent"
  if (0 == sig_can_continue(1)) {
    goto close_socket;
  }	$? ". no signal yet"
  res = dk4socket_shutdown_app(sock, DK4_SOCKET_SHUT_WRITE, app);
  if (DK4_SOCKET_RESULT_SUCCESS != res) {
    goto close_socket;
  }	$? ". shut down for writing"
  if (0 == sig_can_continue(1)) {
    goto close_socket;
  }	$? ". no signal yet"

  /*	Indicate success so far.
  */
  exval = EXIT_SUCCESS;

  /*	Now receive data.
  */
  do {
    if (0 != sig_can_continue(1)) {	$? ". can continue"
      sz = sizeof(bu);
      res = dk4socket_recv_app(sock, bu, &sz, 0, 0L, 0L, app);
      if (DK4_SOCKET_RESULT_SUCCESS == res) {
        if (0 < sz) {			$? ". %u bytes found", (unsigned)sz
	  if (0 != sig_can_continue(1)) {
            if (0 != first) {		$? ". first data packet"
	      first = 0;
	      if (NULL != filename) {	$? ". have file name"
	        tests = DK4_FOPEN_SC_USER;
	        if (0 != dk4isadmin()) { tests = DK4_FOPEN_SC_PRIVILEGED; }
	        fipo = dk4fopen_app(filename, dk_recv_kwnl[4], tests, app);
	        if (NULL == fipo) {	$? "! failed to open file"
	          exval = EXIT_FAILURE;
	        }
	      } else {			$? ". no file name, use stdout"
	        /* MODE FOR WINDOWS */
#if DK4_ON_WINDOWS
	        oldmode = _setmode(_fileno(stdout), _O_BINARY);
#endif
	        fipo = stdout;
	      }
	    }
	    if (NULL != fipo) {		$? ". have output file"
	      if (0 == we) {		$? ". no write error yet"
	        errno = 0;		$? ". size %u", (unsigned)sz
	        wrb = fwrite(bu, 1, sz, fipo);
	        if (wrb != sz) {	$? "! write error"
	          we = 1;
	          exval = EXIT_FAILURE;
	          /* ERROR: Write attempt failed */
		  dk4fd_write_error_msg(
		    app,
		    ((filename) ? (filename) : (dk_recv_kw_def[2])),
		    errno
		  );
	        }
	      }
	    }
	  } else {	$? "! signal"
	    cc = -1;
	  }
        } else {	$? ". no more data available"
          cc = 0;
        }
      } else {		$? "! failed to receive data"
        cc = -1;
      }
    } else {		$? "! signal"
      cc = -1;
    }
  } while (1 == cc);

  /*	Cleanup
  */
  if (0 == first) {			$? ". must clean up"
    if (NULL != filename) {		$? ". have file name"
      if (NULL != fipo) {		$? ". have file"
        if (0 != fclose(fipo)) {	$? "! failed to close file"
	  /* ERROR: Failed to close file */
	  dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 3);
	  exval = EXIT_FAILURE;
	}
      }
    } else {				$? ". no file name"
      if (0 != fflush(stdout)) {	$? "! failed to flush stdout"
        exval = EXIT_FAILURE;
      }
#if DK4_ON_WINDOWS
      _setmode(_fileno(stdout), oldmode);
#endif
    }
  }

  /*	Close socket if open.
  */
  close_socket:
  if (INVALID_SOCKET != sock) {		$? ". close socket"
    dk4socket_close_app(sock, app);
  }

  /*	Shut socket subsystem down (Windows).
  */
  tcpip_down:
  dk4socket_down_app(app);		$? ". TCP/IP subsystem down"

  finished: ;
  $? "- dk_recv_run_with_real_file_name"
}



#if DK4_ON_WINDOWS
/**	Expand file name and run for host, port and file name.
	@param	hostname	Host name or address to connect to.
	@param	portspec	Remote port to connect to.
	@param	filename	File name pattern to expand.
*/
static
void
dk_recv_expand_file_name(
  const	dkChar	*hostname,
  const dkChar	*portspec,
  const	dkChar	*filename
)
{
  dkChar		 buf[DK4_MAX_PATH];
  dk4_dir_t		*fne;
  const	dkChar		*pt;
  const dkChar		*fn;
  size_t		 szbuf;
  int			 copied;

  fne = dk4app_fne_open(filename, app);
  if (NULL != fne) {
    fn = dk4dir_next_file(fne);
    if (NULL != fn) {
      pt = dk4dir_get_path(fne);
      if (NULL == dk4dir_next_file(fne)) {
        if (NULL != pt) {
	  szbuf = DK4_SIZEOF(buf, dkChar);
	  copied = 0;
	  if (0 != dk4str_cpy_s(buf, szbuf, pt, NULL)) {
	    if (0 != dk4str_cat_s(buf, szbuf, dk_recv_kwnl[3], NULL)) {
	      if (0 != dk4str_cat_s(buf, szbuf, fn, NULL)) {
	        copied = 1;
		dk_recv_run_with_real_file_name(hostname, portspec, buf);
	      }
	    }
	  }
	  if (0 == copied) {
	    /* ERROR: Path too long */
	    dk4app_log_base3(app, DK4_LL_ERROR, 100, 105, filename);
	  }
	} else {
	  dk_recv_run_with_real_file_name(hostname, portspec, fn);
	}
      } else {
        /* ERROR: Not a unique file name */
	dk4app_log_base3(app, DK4_LL_ERROR, 100, 106, filename);
      }
    } else {
      /* ERROR: No such file */
      dk4app_log_base3(app, DK4_LL_ERROR, 100, 107, filename);
    }
    dk4dir_close(fne);
  }
}
#endif



/**	Run for given host, port and file name.
	@param	hostname	Host name or address to connect to.
	@param	portspec	Remote port to connect to.
	@param	filename	File name to write to, may be NULL (stdout).
*/
static
void
dk_recv_run_for_arguments(
  const	dkChar	*hostname,
  const dkChar	*portspec,
  const	dkChar	*filename
)
{
#if DK4_ON_WINDOWS
  if (0 != dk4path_must_expand(filename)) {
    dk_recv_expand_file_name(hostname, portspec, filename);
  } else {
#endif
    dk_recv_run_with_real_file_name(hostname, portspec, filename);
#if DK4_ON_WINDOWS
  }
#endif
}



/**	Process options, retrieve command line arguments and run
	for given host, port and optionally file name.
*/
static
void
dk_recv_normal_run(void)
{
  double		 timeout;
  double		 d1;
  double		 d2;
  int	 		 xargc;
  int			 canrun;
  $? "+ dk_recv_normal_run"
  canrun = 1;
  /*	Timeout specified?
  */
  if (0 != dk4app_opt_is_set_short(app, dkT('t'), NULL)) {
    start_transmission = 0x01;
  }
  /*	Local port number specified?
  */
  if (0 != dk4app_opt_is_set_short(app, dkT('l'), NULL)) {
    dk_recv_portno = dk4app_opt_get_string_ptr_short(app, dkT('l'), NULL);
  }
  /*	Connection timeout specified?
  */
  if (0 != dk4app_opt_is_set_short(app, dkT('c'), NULL)) {
    if (0 != dk4app_opt_get_double_short(&timeout, app, dkT('c'), NULL)) {
      if (0.0 <= timeout) {
        d1 = floor(timeout);
	d2 = timeout - d1;
	d2 = 1000000.0 * d2;
	if ((double)(LONG_MAX) >= d1) {
	  dk_recv_timeout_secs  = (long)d1;
	  dk_recv_timeout_usecs = (long)d2;
	} else {
	  canrun = 0;
	  /* ERROR: Timeout too large */
          dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 4);
	}
      } else {
        /* Warning: Can not use a negative timeout */
	dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_WARNING, 5);
      }
    } else {
      canrun = 0;
      /* No timeout value found ! */
      dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 6);
    }
  }
  if (0 != canrun) {
    xargc = dk4app_get_argc(app);
    switch (xargc) {
      case 2: {
        dk_recv_run_for_arguments(
          dk4app_get_argv(app, 0),
	  dk4app_get_argv(app, 1),
	  NULL
        );
      } break;
      case 3: {
        dk_recv_run_for_arguments(
          dk4app_get_argv(app, 0),
	  dk4app_get_argv(app, 1),
	  dk4app_get_argv(app, 2)
        );
      } break;
      default : {
        /* ERROR: Wrong number of arguments */
	dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 7);
      } break;
    }
  }
  $? "- dk_recv_normal_run"
}



#if	DK4_HAVE_SIGACTION
/**	Set signal handlers and run.
*/
static
void
dk_recv_run_with_signal_handlers(void)
{
#ifdef SIGPIPE
  struct sigaction opipe;
#endif
  struct sigaction oint;
#ifdef SIGPIPE
  struct sigaction npipe;
#endif
  struct sigaction nint;
  struct sigaction oterm;
  struct sigaction nterm;
  int	 success = 0;

#ifdef SIGPIPE
  /*	Set up signal handling for SIGPIPE.
  */
  DK4_MEMRES(&npipe, sizeof(npipe));
  npipe.sa_handler = sig_handler_pipe;
  npipe.sa_flags = 0;
  if (0 != sigemptyset(&npipe.sa_mask)) {
    /* ERROR: Failed to set up masked signal set for SIGPIPE */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto finished;
  }
  if (0 != sigaddset(&npipe.sa_mask, SIGPIPE)) {
    /* ERROR: Failed to set up masked signal set for SIGPIPE */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto finished;
  }
  if (0 != sigaction(SIGPIPE, &npipe, &opipe)) {
    /* ERROR: Failed to set up signal handler for SIGPIPE */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto finished;
  }
#endif

  /*	Set up signal handling for SIGINT.
  */
  DK4_MEMRES(&nint, sizeof(nint));
  nint.sa_handler = sig_handler_int;
  nint.sa_flags = 0;
  if (0 != sigemptyset(&nint.sa_mask)) {
    /* ERROR: Failed to set up masked signal set for SIGINT */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto restore_old_pipe;
  }
  if (0 != sigaddset(&nint.sa_mask, SIGINT)) {
    /* ERROR: Failed to set up masked signal set for SIGINT */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto restore_old_pipe;
  }
  if (0 != sigaction(SIGINT, &nint, &oint)) {
    /* ERROR: Failed to set up signal handler for SIGINT */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto restore_old_pipe;
  }

  /*	Set up signal handling for SIGTERM
  */
  DK4_MEMRES(&nterm, sizeof(nterm));
  nterm.sa_handler = sig_handler_term;
  nterm.sa_flags = 0;
  if (0 != sigemptyset(&nterm.sa_mask)) {
    /* ERROR: Failed to set up masked signal set for SIGTERM */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto restore_old_int;
  }
  if (0 != sigaddset(&nterm.sa_mask, SIGTERM)) {
    /* ERROR: Failed to set up masked signal set for SIGTERM */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto restore_old_int;
  }
  if (0 != sigaction(SIGTERM, &nterm, &oterm)) {
    /* ERROR: Failed to set up signal handler for SIGTERM */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 0);
    goto restore_old_int;
  }

  success = 1;
  dk_recv_normal_run();

  /*	Restore signal handling for SIGTERM.
  */
  if (0 != sigaction(SIGTERM, &oterm, NULL)) {
    /* ERROR: Failed to restore old SIGTERM settings */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 1);
    success = 0;
  }

  /*	Restore signal handling for SIGINT.
  */
  restore_old_int:
  if (0 != sigaction(SIGINT, &oint, NULL)) {
    /* ERROR: Failed to restore old SIGPIPE settings */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 1);
    success = 0;
  }

#ifdef SIGPIPE
  /*	Restore signal handling for SIGPIPE.
  */
  restore_old_pipe:
  if (0 != sigaction(SIGPIPE, &opipe, NULL)) {
    /* ERROR: Failed to restore old SIGPIPE settings */
    dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 1);
    success = 0;
  }
#endif

  /*	Set exit status code if error occured.
  */
  finished:
  if (0 == success) { exval = EXIT_FAILURE; }
}
#else
#if	DK4_HAVE_SIGSET
/**	Set signal handlers and run.
*/
static
void
dk_recv_run_with_signal_handlers(void)
{
#ifdef SIGPIPE
  dk4_sig_handler_t	*oldpipe = NULL;
#endif
  dk4_sig_handler_t	*oldint  = NULL;
  dk4_sig_handler_t	*oldterm = NULL;

#ifdef SIGPIPE
  oldpipe = sigset(SIGPIPE, sig_handler_pipe);
#endif
  oldint  = sigset(SIGINT,  sig_handler_int);
  oldterm = sigset(SIGTERM, sig_handler_term);
  dk_recv_normal_run();
  sigset(SIGTERM, oldterm);
  sigset(SIGINT,  oldint);
#ifdef SIGPIPE
  sigset(SIGPIPE, oldpipe);
#endif
}
#else
#if	DK4_HAVE_SIGNAL
/**	Set signal handlers and run.
*/
static
void
dk_recv_run_with_signal_handlers(void)
{
#ifdef SIGPIPE
  dk4_sig_handler_t	*oldpipe = NULL;
#endif
  dk4_sig_handler_t	*oldint  = NULL;
  dk4_sig_handler_t	*oldterm = NULL;

#ifdef SIGPIPE
  oldpipe = signal(SIGPIPE, sig_handler_pipe);
#endif
  oldint  = signal(SIGINT,  sig_handler_int);
  oldterm = signal(SIGTERM, sig_handler_term);
  dk_recv_normal_run();
  signal(SIGTERM, oldterm);
  signal(SIGINT,  oldint);
#ifdef SIGPIPE
  signal(SIGPIPE, oldpipe);
#endif
}
#else
/**	Set signal handlers and run.
*/
static
void
dk_recv_run_with_signal_handlers(void)
{
  dk_recv_normal_run();
}
#endif
#endif
#endif



/**	Main function.
	@param	argc	Number of command line arguments.
	@param	argv	Command line arguments array.
	@return	0 on success, all other values indicate errors.
*/
#if DK4_CHAR_SIZE > 1
int wmain(int argc, wchar_t *argv[])
#else
int main(int argc, char *argv[])
#endif
{
  $!trace-init dk-recv.deb
  $? "+ main"
  dk4fput_initialize_stderr();
  app = dk4app_open_cmd(
    argc, argv, dk_recv_options, dk_recv_sz_options,
    dk_recv_kwnl[0], DKT_VERSION_DK,
    dk_recv_kwnl[1], dk_recv_help_text, dk_recv_license_text
  );
  if (NULL != app) {					$? ". app"
    dk_recv_sz_loc = dk4app_string_table_size(dk_recv_kw_def);
    dk_recv_kw_loc = dk4app_string_table(app, dk_recv_kwnl[2], dk_recv_kw_def);
    dk_recv_sz_loc = dk4app_string_table_size(dk_recv_kw_loc);
    if (0 != dk4app_can_run_normally(app)) {
      dk_recv_run_with_signal_handlers();
    } else {
      if (0 != dk4app_help_version_license(app)) {
        exval = EXIT_SUCCESS;
      }
    }
    if (0 != sig_read_atomic(&sig_had_int )) {
      /* Interrupted by SIGINT */
      dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 8);
    }
    if (0 != sig_read_atomic(&sig_had_term)) {
      /* Interrupted by SIGTERM */
      dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 9);
    }
#if defined(SIGPIPE)
    if (0 != sig_read_atomic(&sig_had_pipe)) {
      /* Interrupted by SIGPIPE */
      dk4app_log_1(app, dk_recv_kw_loc, dk_recv_sz_loc, DK4_LL_ERROR, 10);
    }
#endif
    dk4app_close(app); app = NULL;
  } else {						$? "! app"
  }
  fflush(stderr);
  dk4fput_cleanup_stderr();
  if (0 != sig_read_atomic(&sig_had_int )) {
    exval = EXIT_FAILURE;
  }
  if (0 != sig_read_atomic(&sig_had_term)) {
    exval = EXIT_FAILURE;
  }
#if defined(SIGPIPE)
  if (0 != sig_read_atomic(&sig_had_pipe)) {
    exval = EXIT_FAILURE;
  }
#endif
  $? "- main %d", exval
  $!trace-end
  exit(exval); return exval;
}