Debian Codegraph @

hfaxd/FileTransfer.c++

raw
1 /* $Id$ */
2 /*
3 * Copyright (c) 1995-1996 Sam Leffler
4 * Copyright (c) 1995-1996 Silicon Graphics, Inc.
5 * HylaFAX is a trademark of Silicon Graphics
6 *
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
14 *
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18 *
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 * OF THIS SOFTWARE.
25 */
26
27 /*
28 * File transfer commands.
29 */
30 #include "HylaFAXServer.h"
31 #include "Sys.h"
32 #include "config.h"
33 #include "zlib.h"
34 #include "tiffio.h"
35
36 #include <ctype.h>
37 #include <limits.h>
38 #ifdef HAVE_STDINT_H
39 #include <stdint.h>
40 #endif
41
42 #ifndef CHAR_BIT
43 #ifdef NBBY
44 #define CHAR_BIT NBBY
45 #else
46 #define CHAR_BIT 8
47 #endif
48 #endif /* CHAR_BIT */
49
50
51 #ifdef NEED_TIFFDIRENTRY
52 /*
53 * we don't pass these to libtiff anywhere, but HylaFAX uses it to keep track
54 * of the info it has read from the TIFFGetField functions when constructin
55 * and writing a single-directory TIFF FILE read from an existing TIFF fax.
56 */
57 typedef struct {
58 uint16 tdir_tag;
59 uint16 tdir_type; /* data type */
60 uint32 tdir_count; /* number of items; length in spec */
61 uint32 tdir_offset; /* byte offset to field data */
62 } TIFFDirEntry;
63 #endif
64
65
66 static struct {
67 const char* name; // protocol token name
68 bool supported; // true if format is supported
69 const char* suffix; // file suffix
70 const char* help; // help string for HELP FORM command
71 FaxSendOp op; // associated FaxSendOp value
72 } formats[] = {
73 { "TIFF", true, "tif", "Tagged Image File Format, Class F only", FaxRequest::send_tiff },
74 { "PS", true, "ps", "Adobe PostScript", FaxRequest::send_postscript },
75 { "PCL", true, "pcl", "HP Printer Control Language (PCL)", FaxRequest::send_pcl},
76 { "PDF", true, "pdf", "Adobe Portable Document Format", FaxRequest::send_pdf}
77 };
78
79 static const char* typenames[] = { "ASCII", "EBCDIC", "Image", "Local" };
80 static const char* strunames[] = { "File", "Record", "Page", "TIFF" };
81 static const char* modenames[] = { "Stream", "Block", "Compressed", "ZIP" };
82
83 #define N(a) (sizeof (a) / sizeof (a[0]))
84
85
86 static bool
87 isTIFF(const TIFFHeader& h)
88 {
89 if (h.tiff_magic != TIFF_BIGENDIAN && h.tiff_magic != TIFF_LITTLEENDIAN)
90 return (false);
91 union {
92 int32 i;
93 char c[4];
94 } u;
95 u.i = 1;
96 uint16 version = h.tiff_version;
97 // byte swap version stamp if opposite byte order
98 if ((u.c[0] == 0) ^ (h.tiff_magic == TIFF_BIGENDIAN))
99 TIFFSwabShort(&version);
100 return (version == TIFF_VERSION);
101 }
102
103
104 /*
105 * Record a file transfer in the log file.
106 */
107 void
108 HylaFAXServer::logTransfer(const char* direction,
109 const SpoolDir& sd, const char* pathname, time_t start)
110 {
111 time_t now = Sys::now();
112 time_t xferfaxtime = now - start;
113 if (xferfaxtime == 0)
114 xferfaxtime++;
115 const char* filename = strrchr(pathname, '/');
116 fxStr msg(fxStr::format("%.24s\t%lu\t%s\t%lu\t%s/%s\t%s\t%s\n"
117 , ctime(&now)
118 , (u_long) xferfaxtime
119 , (const char*) remotehost
120 , (u_long) byte_count
121 , sd.pathname, filename ? filename+1 : pathname
122 , direction
123 , (const char*) the_user
124 ));
125 (void) Sys::write(xferfaxlog, msg, msg.length());
126 }
127
128 bool
129 HylaFAXServer::restartSend(FILE* fd, off_t marker)
130 {
131 if (type == TYPE_A) { // restart based on line count
132 int c;
133 while ((c = getc(fd)) != EOF)
134 if (c == '\n' && --marker == 0)
135 return (true);
136 return (false);
137 } else // restart based on file offset
138 return (lseek(fileno(fd), marker, SEEK_SET) == marker);
139 }
140
141 /*
142 * RETRieve a file.
143 */
144 void
145 HylaFAXServer::retrieveCmd(const char* name)
146 {
147 struct stat sb;
148 SpoolDir* sd = fileAccess(name, R_OK, sb);
149 if (sd) {
150 FILE* fd = fopen(name, "r");
151 if (fd != NULL) {
152 if (restart_point && !restartSend(fd, restart_point)) {
153 perror_reply(550, name, errno);
154 } else {
155 time_t start_time = Sys::now();
156 int code;
157 FILE* dout = openDataConn("w", code);
158 if (dout != NULL) {
159 file_size = sb.st_size;
160 reply(code, "%s for %s (%lu bytes).",
161 dataConnMsg(code), name, (u_long) file_size);
162 if (sendData(fd, dout))
163 reply(226, "Transfer complete.");
164 if (TRACE(OUTXFERS) && xferfaxlog != -1)
165 logTransfer("o", *sd, name, start_time);
166 closeDataConn(dout);
167 }
168 }
169 fclose(fd);
170 } else if (errno != 0)
171 perror_reply(550, name, errno);
172 else
173 reply(550, "%s: Cannot open file.", name);
174 }
175 }
176
177 /*
178 * TIFF Directory Template used in returning
179 * a single IFD/image from a TIFF file.
180 */
181 typedef struct {
182 TIFFDirEntry SubFileType;
183 TIFFDirEntry ImageWidth;
184 TIFFDirEntry ImageLength;
185 TIFFDirEntry BitsPerSample;
186 TIFFDirEntry Compression;
187 TIFFDirEntry Photometric;
188 TIFFDirEntry FillOrder;
189 TIFFDirEntry StripOffsets;
190 TIFFDirEntry Orientation;
191 TIFFDirEntry SamplesPerPixel;
192 TIFFDirEntry RowsPerStrip;
193 TIFFDirEntry StripByteCounts;
194 TIFFDirEntry XResolution;
195 TIFFDirEntry YResolution;
196 TIFFDirEntry Options; // T4 or T6
197 TIFFDirEntry ResolutionUnit;
198 TIFFDirEntry PageNumber;
199 TIFFDirEntry BadFaxLines;
200 TIFFDirEntry CleanFaxData;
201 TIFFDirEntry ConsecutiveBadFaxLines;
202 uint32 link; // offset to next directory
203 uint32 xres[2]; // X resolution indirect value
204 uint32 yres[2]; // Y resolution indirect value
205 } DirTemplate;
206
207 /*
208 * RETrieve one Page from a file. For now the
209 * file must be a TIFF image; we might try to
210 * handle PostScript at a later time (but don't
211 * hold your breath as there's not much reason).
212 */
213 void
214 HylaFAXServer::retrievePageCmd(const char* name)
215 {
216 TIFF* tif = cachedTIFF;
217 if (tif != NULL && streq(name, TIFFFileName(tif))) {
218 /*
219 * Reuse the cached open file. If no directory
220 * has been specified with a REST command then
221 * return the next consecutive directory in the file.
222 */
223 if (restart_point == 0) // advance to next directory
224 restart_point = TIFFCurrentDirectory(tif)+1;
225 } else {
226 if (tif) // close cached handle
227 TIFFClose(tif), cachedTIFF = NULL;
228 tif = openTIFF(name);
229 }
230 if (tif != NULL) {
231 if (restart_point && !TIFFSetDirectory(tif, (tdir_t) restart_point)) {
232 reply(550, "%s: Unable to access directory %lu.",
233 name, (u_long) restart_point);
234 } else {
235 time_t start_time = Sys::now();
236 int code;
237 FILE* dout = openDataConn("w", code);
238 if (dout != NULL) {
239 /*
240 * Calculate "file size" by totalling up the
241 * amount of image data and then adding in
242 * the expected data for the TIFF headers.
243 */
244 tiff_bytecount_t* sb;
245 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &sb);
246 file_size = sizeof (DirTemplate) +
247 sizeof (TIFFHeader) + sizeof (uint16);
248 for (tstrip_t s = 0, ns = TIFFNumberOfStrips(tif); s < ns; s++)
249 file_size += sb[s];
250 reply(code, "%s for %s (%lu bytes).",
251 dataConnMsg(code), name, (u_long) file_size);
252 if (sendTIFFData(tif, dout))
253 reply(226, "Transfer complete.");
254 if (TRACE(OUTXFERS) && xferfaxlog != -1) {
255 struct stat sb;
256 SpoolDir* sd = fileAccess(name, R_OK, sb);
257 logTransfer("o", *sd, name, start_time);
258 }
259 closeDataConn(dout);
260 }
261 }
262 cachedTIFF = tif;
263 }
264 }
265
266 /*
267 * Open a file that is expected to hold a TIFF image.
268 */
269 TIFF*
270 HylaFAXServer::openTIFF(const char* name)
271 {
272 struct stat sb;
273 SpoolDir* sd = fileAccess(name, R_OK, sb);
274 if (sd) {
275 int fd = Sys::open(name, O_RDONLY);
276 if (fd >= 0) {
277 union {
278 char buf[512];
279 TIFFHeader h;
280 } b;
281 ssize_t cc = Sys::read(fd, (char*) &b, sizeof (b));
282 if (cc > (ssize_t)sizeof (b.h) && b.h.tiff_version == TIFF_VERSION &&
283 (b.h.tiff_magic == TIFF_BIGENDIAN ||
284 b.h.tiff_magic == TIFF_LITTLEENDIAN)) {
285 (void) lseek(fd, 0L, SEEK_SET); // rewind
286 TIFF* tif = TIFFFdOpen(fd, name, "r");
287 if (tif != NULL)
288 return (tif);
289 else
290 reply(550, "%s: Incomplete or invalid TIFF file.", name);
291 } else
292 reply(550, "%s: Not a TIFF file.", name);
293 Sys::close(fd);
294 } else if (errno != 0)
295 perror_reply(550, name, errno);
296 else
297 reply(550, "%s: Cannot open file.", name);
298 }
299 return (NULL);
300 }
301
302 /*
303 * Tranfer the current directory's contents of "tif" to "fdout".
304 */
305 bool
306 HylaFAXServer::sendTIFFData(TIFF* tif, FILE* fdout)
307 {
308 state |= S_TRANSFER;
309 if (setjmp(urgcatch) != 0) {
310 state &= ~S_TRANSFER;
311 return (false);
312 }
313 #define PACK(a,b) (((a)<<8)|(b))
314 switch (PACK(type,mode)) {
315 case PACK(TYPE_I,MODE_S):
316 case PACK(TYPE_L,MODE_S):
317 if (sendTIFFHeader(tif, fileno(fdout)) &&
318 sendITIFFData(tif, fileno(fdout))) {
319 state &= ~S_TRANSFER;
320 return (true);
321 }
322 break;
323 default:
324 reply(550, "TYPE %s, MODE %s not implemented."
325 , typenames[type]
326 , modenames[mode]
327 );
328 break;
329 }
330 #undef PACK
331 state &= ~S_TRANSFER;
332 return (false);
333 }
334
335 static void
336 getLong(TIFF* tif, TIFFDirEntry& de)
337 {
338 TIFFGetField(tif, de.tdir_tag, &de.tdir_offset);
339 }
340 static void
341 getShort(TIFF* tif, TIFFDirEntry& de)
342 {
343 uint16 v;
344 TIFFGetField(tif, de.tdir_tag, &v);
345 de.tdir_offset = (uint32) v;
346 }
347
348 /*
349 * Send a TIFF header and IFD for the current directory
350 * in the open TIFF file. The image data is expected to
351 * immediately follow this information (i.e. the value of
352 * the StripByteOffsets tag is setup to point to the offset
353 * immediately after this data) and it is assumed that
354 * all image data is concatenated into a single strip.
355 */
356 bool
357 HylaFAXServer::sendTIFFHeader(TIFF* tif, int fdout)
358 {
359 static DirTemplate templ = {
360 #define TIFFdiroff(v) \
361 (uint32) (sizeof (TIFFHeader) + sizeof (uint16) + \
362 (intptr_t) &(((DirTemplate*) 0)->v))
363 { TIFFTAG_SUBFILETYPE, TIFF_LONG, 1 },
364 { TIFFTAG_IMAGEWIDTH, TIFF_LONG, 1 },
365 { TIFFTAG_IMAGELENGTH, TIFF_LONG, 1 },
366 { TIFFTAG_BITSPERSAMPLE, TIFF_SHORT, 1, 1 },
367 { TIFFTAG_COMPRESSION, TIFF_SHORT, 1 },
368 { TIFFTAG_PHOTOMETRIC, TIFF_SHORT, 1 },
369 { TIFFTAG_FILLORDER, TIFF_SHORT, 1 },
370 { TIFFTAG_STRIPOFFSETS, TIFF_LONG, 1, TIFFdiroff(yres[2]) },
371 { TIFFTAG_ORIENTATION, TIFF_SHORT, 1 },
372 { TIFFTAG_SAMPLESPERPIXEL, TIFF_SHORT, 1, 1 },
373 { TIFFTAG_ROWSPERSTRIP, TIFF_LONG, 1, (uint32) -1 },
374 { TIFFTAG_STRIPBYTECOUNTS, TIFF_LONG, 1 },
375 { TIFFTAG_XRESOLUTION, TIFF_RATIONAL, 1, TIFFdiroff(xres[0]) },
376 { TIFFTAG_YRESOLUTION, TIFF_RATIONAL, 1, TIFFdiroff(yres[0]) },
377 { TIFFTAG_GROUP3OPTIONS, TIFF_LONG, 1 },
378 { TIFFTAG_RESOLUTIONUNIT, TIFF_SHORT, 1 },
379 { TIFFTAG_PAGENUMBER, TIFF_SHORT, 2 },
380 { TIFFTAG_BADFAXLINES, TIFF_LONG, 1 },
381 { TIFFTAG_CLEANFAXDATA, TIFF_SHORT, 1 },
382 { TIFFTAG_CONSECUTIVEBADFAXLINES,TIFF_LONG, 1 },
383 0, // next directory
384 { 0, 1 }, { 0, 1 }, // x+y resolutions
385 };
386 #define NTAGS ((TIFFdiroff(link)-TIFFdiroff(SubFileType)) / sizeof (TIFFDirEntry))
387 /*
388 * Construct the TIFF header for this IFD using
389 * the preconstructed template above. We extract
390 * the necessary information from the open TIFF file.
391 * In case it's not obvious, this code assumes a lot
392 * of things about the contents of the TIFF file.
393 */
394 struct {
395 TIFFHeader h;
396 uint16 dircount;
397 u_char dirstuff[sizeof (templ)];
398 } buf;
399 union { int32 i; char c[4]; } u; u.i = 1;
400 buf.h.tiff_magic = (u.c[0] == 0 ? TIFF_BIGENDIAN : TIFF_LITTLEENDIAN);
401 buf.h.tiff_version = TIFF_VERSION;
402 buf.h.tiff_diroff = sizeof (TIFFHeader);
403 buf.dircount = (uint16) NTAGS;
404 getLong(tif, templ.SubFileType);
405 getLong(tif, templ.ImageWidth);
406 getLong(tif, templ.ImageLength);
407 getShort(tif, templ.Compression);
408 getShort(tif, templ.Photometric);
409 getShort(tif, templ.FillOrder);
410 getShort(tif, templ.Orientation);
411 templ.StripByteCounts.tdir_offset = (uint32) file_size - sizeof (buf);
412 float res;
413 TIFFGetField(tif, TIFFTAG_XRESOLUTION, &res);
414 templ.xres[0] = (uint32) res;
415 TIFFGetField(tif, TIFFTAG_YRESOLUTION, &res);
416 templ.yres[0] = (uint32) res;
417 if (templ.Compression.tdir_offset == COMPRESSION_CCITTFAX3) {
418 templ.Options.tdir_tag = TIFFTAG_GROUP3OPTIONS;
419 getLong(tif, templ.Options);
420 } else if (templ.Compression.tdir_offset == COMPRESSION_CCITTFAX4) {
421 templ.Options.tdir_tag = TIFFTAG_GROUP4OPTIONS;
422 getLong(tif, templ.Options);
423 }
424 getShort(tif, templ.ResolutionUnit);
425 TIFFGetField(tif, TIFFTAG_PAGENUMBER, &templ.PageNumber.tdir_offset);
426 getLong(tif, templ.BadFaxLines);
427 getShort(tif, templ.CleanFaxData);
428 getLong(tif, templ.ConsecutiveBadFaxLines);
429 if (buf.h.tiff_magic == TIFF_BIGENDIAN) {
430 TIFFDirEntry* dp = &templ.SubFileType;
431 for (u_int i = 0; i < NTAGS; i++) {
432 if (dp->tdir_type == TIFF_SHORT)
433 dp->tdir_offset <<= 16;
434 dp++;
435 }
436 }
437 memcpy(buf.dirstuff, &templ, sizeof (templ));
438 if (write(fdout, (const char*) &buf, sizeof (buf)) != sizeof (buf)) {
439 perror_reply(426, "Data connection", errno);
440 return (false);
441 } else {
442 byte_count += sizeof (buf);
443 return (true);
444 }
445 #undef NTAGS
446 #undef offsetof
447 }
448
449 /*
450 * Send the raw image data for the current directory
451 * in the open TIFF file. If multiple strips are
452 * present in the file they are concatenated w/o
453 * consideration for any padding that might be present
454 * or might be needed.
455 */
456 bool
457 HylaFAXServer::sendITIFFData(TIFF* tif, int fdout)
458 {
459 tiff_bytecount_t* sb;
460 (void) TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &sb);
461 tdata_t buf = _TIFFmalloc(sb[0]);
462 tsize_t bsize = sb[0];
463 for (tstrip_t s = 0, ns = TIFFNumberOfStrips(tif); s < ns; s++) {
464 tsize_t cc = sb[s];
465 if (cc > bsize) {
466 buf = _TIFFrealloc(buf, cc);
467 bsize = cc;
468 }
469 if (buf == NULL) {
470 reply(551, "Error allocating intermediate buffer");
471 return (false);
472 }
473 if (TIFFReadRawStrip(tif, s, buf, cc) != cc) {
474 reply(551, "Error reading input file at strip %u", s);
475 goto bad;
476 }
477 if (write(fdout, buf, (u_int) cc) != cc) {
478 perror_reply(426, "Data connection", errno);
479 goto bad;
480 }
481 byte_count += cc;
482 }
483 _TIFFfree(buf);
484 return (true);
485 bad:
486 _TIFFfree(buf);
487 return (false);
488 }
489
490 const char*
491 HylaFAXServer::dataConnMsg(int code)
492 {
493 return (code == 125 ?
494 "Using existing data connection" : "Opening new data connection");
495 }
496
497 void
498 HylaFAXServer::closeDataConn(FILE* fd)
499 {
500 fclose(fd);
501 data = -1;
502 pdata = -1;
503 }
504
505 /*
506 * STORe a file.
507 */
508 void
509 HylaFAXServer::storeCmd(const char* name, const char* mode)
510 {
511 struct stat sb;
512 SpoolDir* sd = fileAccess(name, W_OK, sb);
513 if (sd) {
514 // check filename for magic characters
515 for (const char* cp = name; *cp; cp++)
516 if (isspace(*cp) || !isgraph(*cp)) {
517 reply(553, "Bad filename; includes invalid character.");
518 return;
519 }
520 mode_t omask = umask(027);
521 FILE* fout = fopen(name, restart_point ? "r+w" : mode);
522 if (fout != NULL) {
523 setFileOwner(name);
524 if (restart_point &&
525 lseek(fileno(fout), restart_point, SEEK_SET) != restart_point)
526 perror_reply(550, name, errno);
527 else {
528 time_t start_time = Sys::now();
529 int code;
530 FILE* din = openDataConn("r", code);
531 if (din != NULL) {
532 reply(code, "%s for %s.", dataConnMsg(code), name);
533 file_size = -1;
534 if (recvData(din, fout))
535 reply(226, "Transfer complete.");
536 if (TRACE(INXFERS) && xferfaxlog != -1)
537 logTransfer("i", *sd, name, start_time);
538 closeDataConn(din);
539 }
540 }
541 fclose(fout);
542 } else
543 perror_reply(553, name, errno);
544 (void) umask(omask);
545 }
546 }
547
548 /*
549 * STOU (STOre Unique) file.
550 * STOT (STOre unique Temporary) file.
551 *
552 * STOT differs from STOU in that files created with STOT
553 * are automatically unlinked when the process terminates
554 * while files created with STOU are not. STOT is intended
555 * for clients creating documents that are to be sent and
556 * then expunged. STOU is for documents that are intended
557 * be shared across multiple sessions.
558 */
559 void
560 HylaFAXServer::storeUniqueCmd(bool isTemp)
561 {
562 fxStr emsg;
563 u_int seqnum = getDocumentNumber(emsg);
564 if (seqnum != (u_int) -1) {
565 fxStr filename = fxStr::format("/%s/doc%u.%s"
566 , isTemp ? FAX_TMPDIR : FAX_DOCDIR
567 , seqnum
568 , formats[form].suffix
569 );
570 FILE* fout = fopen(filename, "w");
571 if (fout != NULL) {
572 setFileOwner(filename);
573 FileCache::chmod(filename, 0640); // sync cache
574 if (isTemp)
575 tempFiles.append(filename);
576 time_t start_time = Sys::now();
577 int code;
578 FILE* din = openDataConn("r", code);
579 if (din != NULL) {
580 reply(code, "FILE: %s (%s).", (const char*) filename,
581 dataConnMsg(code));
582 file_size = -1;
583 if (recvData(din, fout))
584 reply(226, "Transfer complete (FILE: %s).",
585 (const char*) filename);
586 if (TRACE(INXFERS) && xferfaxlog != -1)
587 logTransfer("i"
588 , *dirLookup(isTemp ? "/" FAX_TMPDIR : "/" FAX_DOCDIR)
589 , filename
590 , start_time
591 );
592 closeDataConn(din);
593 }
594 fclose(fout);
595 } else
596 perror_reply(553, filename, errno);
597 } else
598 reply(553, "%s", (const char*)emsg);
599 }
600
601 /*
602 * Tranfer the contents of "fdin" to "fdout".
603 */
604 bool
605 HylaFAXServer::sendData(FILE* fdin, FILE* fdout)
606 {
607 state |= S_TRANSFER;
608 if (setjmp(urgcatch) != 0) {
609 state &= ~S_TRANSFER;
610 return (false);
611 }
612 #define PACK(a,b) (((a)<<8)|(b))
613 switch (PACK(type,mode)) {
614 case PACK(TYPE_I,MODE_S):
615 case PACK(TYPE_L,MODE_S):
616 if (sendIData(fileno(fdin), fileno(fdout))) {
617 state &= ~S_TRANSFER;
618 return (true);
619 }
620 break;
621 case PACK(TYPE_I,MODE_Z):
622 case PACK(TYPE_L,MODE_Z):
623 if (sendZData(fileno(fdin), fileno(fdout))) {
624 state &= ~S_TRANSFER;
625 return (true);
626 }
627 break;
628 case PACK(TYPE_A,MODE_S):
629 for (;;) {
630 int c = getc(fdin);
631 if (c == EOF) {
632 fflush(fdout);
633 if (ferror(fdout)) {
634 perror_reply(426, "Data Connection", errno);
635 break;
636 }
637 if (ferror(fdin)) {
638 perror_reply(551, "Error on input file", errno);
639 break;
640 }
641 state &= ~S_TRANSFER;
642 return (true);
643 }
644 byte_count++;
645 if (c == '\n') { // \n -> \r\n
646 if (ferror(fdout)) { // check at the end of each line
647 perror_reply(426, "Data connection", errno);
648 break;
649 }
650 putc('\r', fdout);
651 }
652 putc(c, fdout);
653 }
654 break;
655 default:
656 reply(550, "TYPE %s, MODE %s not implemented."
657 , typenames[type]
658 , modenames[mode]
659 );
660 break;
661 }
662 #undef PACK
663 state &= ~S_TRANSFER;
664 return (false);
665 }
666
667 bool
668 HylaFAXServer::sendIData(int fdin, int fdout)
669 {
670 char buf[16*1024];
671 for (;;) {
672 int cc = read(fdin, buf, sizeof (buf));
673 if (cc == 0)
674 return (true);
675 if (cc < 0) {
676 perror_reply(551, "Error reading input file", errno);
677 break;
678 }
679 if (write(fdout, buf, cc) != cc) {
680 perror_reply(426, "Data connection", errno);
681 break;
682 }
683 byte_count += cc;
684 }
685 return (false);
686 }
687
688 bool
689 HylaFAXServer::sendZData(int fdin, int fdout)
690 {
691 z_stream zstream;
692 zstream.zalloc = NULL;
693 zstream.zfree = NULL;
694 zstream.opaque = NULL;
695 zstream.data_type = Z_BINARY;
696 if (deflateInit(&zstream, Z_DEFAULT_COMPRESSION) == Z_OK) {
697 char obuf[16*1024];
698 zstream.next_out = (Bytef*) obuf;
699 zstream.avail_out = sizeof (obuf);
700
701 int cc;
702 for (;;) {
703 char buf[16*1024];
704 cc = read(fdin, buf, sizeof (buf));
705 if (cc == 0)
706 break;
707 if (cc < 0) {
708 perror_reply(551, "Error reading input file", errno);
709 goto bad;
710 }
711 zstream.next_in = (Bytef*) buf;
712 zstream.avail_in = cc;
713 do {
714 if (deflate(&zstream, Z_NO_FLUSH) != Z_OK) {
715 reply(452, "Compressor error: %s", zstream.msg);
716 goto bad;
717 }
718 if (zstream.avail_out == 0) {
719 if (write(fdout, obuf, sizeof (obuf)) != sizeof (obuf)) {
720 perror_reply(426, "Data connection", errno);
721 goto bad;
722 }
723 byte_count += sizeof (obuf);
724 zstream.next_out = (Bytef*) obuf;
725 zstream.avail_out = sizeof (obuf);
726 }
727 } while (zstream.avail_in > 0);
728 }
729 int state;
730 do {
731 switch (state = deflate(&zstream, Z_FINISH)) {
732 case Z_STREAM_END:
733 case Z_OK:
734 if (zstream.avail_out != sizeof (obuf)) {
735 cc = sizeof (obuf) - zstream.avail_out;
736 if (write(fdout, obuf, cc) != cc) {
737 perror_reply(426, "Data connection", errno);
738 goto bad;
739 }
740 byte_count += cc;
741 zstream.next_out = (Bytef*) obuf;
742 zstream.avail_out = sizeof (obuf);
743 }
744 break;
745 default:
746 reply(426, "Compressor error: %s", zstream.msg);
747 goto bad;
748 }
749 } while (state != Z_STREAM_END);
750 deflateEnd(&zstream);
751 return (true);
752 bad:
753 deflateEnd(&zstream);
754 } else
755 reply(452, "Can not initialize compression library: %s", zstream.msg);
756 return (false);
757 }
758
759 /*
760 * Transfer data from peer to file.
761 */
762 bool
763 HylaFAXServer::recvData(FILE* fdin, FILE* fdout)
764 {
765 state |= S_TRANSFER;
766 if (setjmp(urgcatch) != 0) {
767 state &= ~S_TRANSFER;
768 return (false);
769 }
770 #define PACK(a,b) (((a)<<8)|(b))
771 switch (PACK(type,mode)) {
772 case PACK(TYPE_I,MODE_S):
773 case PACK(TYPE_L,MODE_S):
774 if (recvIData(fileno(fdin), fileno(fdout))) {
775 state &= ~S_TRANSFER;
776 return (true);
777 }
778 break;
779 case PACK(TYPE_I,MODE_Z):
780 case PACK(TYPE_L,MODE_Z):
781 if (recvZData(fileno(fdin), fileno(fdout))) {
782 state &= ~S_TRANSFER;
783 return (true);
784 }
785 break;
786 case PACK(TYPE_A,MODE_S):
787 for (;;) {
788 int c = getc(fdin);
789 if (c == EOF) {
790 fflush(fdout);
791 if (ferror(fdin)) {
792 perror_reply(426, "Data Connection", errno);
793 break;
794 }
795 if (ferror(fdout)) {
796 perror_reply(452, "Error writing output file", errno);
797 break;
798 }
799 state &= ~S_TRANSFER;
800 return (true);
801 }
802 byte_count++;
803 if (c == '\r') { // \r\n -> \n
804 if (ferror(fdout)) { // check at the end of each line
805 perror_reply(452, "Error writing output file", errno);
806 break;
807 }
808 c = getc(fdin);
809 if (c != '\n') {
810 putc('\r', fdout);
811 if (c == EOF)
812 continue;
813 }
814 byte_count++;
815 }
816 putc(c, fdout);
817 }
818 break;
819 default:
820 reply(550, "TYPE %s, MODE %s not implemented."
821 , typenames[type]
822 , modenames[mode]
823 );
824 break;
825 }
826 #undef PACK
827 state &= ~S_TRANSFER;
828 return (false);
829 }
830
831 bool
832 HylaFAXServer::recvIData(int fdin, int fdout)
833 {
834 char buf[16*1024]; // XXX better if page-aligned
835 for (;;) {
836 int cc = read(fdin, buf, sizeof (buf));
837 if (cc == 0)
838 return (true);
839 if (cc < 0) {
840 perror_reply(426, "Data Connection", errno);
841 break;
842 }
843 if (write(fdout, buf, cc) != cc) {
844 perror_reply(452, "Error writing output file", errno);
845 break;
846 }
847 byte_count += cc;
848 }
849 return (false);
850 }
851
852 bool
853 HylaFAXServer::recvZData(int fdin, int fdout)
854 {
855 z_stream zstream;
856 zstream.zalloc = NULL;
857 zstream.zfree = NULL;
858 zstream.opaque = NULL;
859 zstream.data_type = Z_BINARY;
860 if (inflateInit(&zstream) == Z_OK) {
861 char obuf[16*1024];
862 zstream.next_out = (Bytef*) obuf;
863 zstream.avail_out = sizeof (obuf);
864 for (;;) {
865 char buf[16*1024];
866 int cc = read(fdin, buf, sizeof (buf));
867 if (cc == 0) {
868 size_t occ = sizeof (obuf) - zstream.avail_out;
869 if (occ > 0 && write(fdout, obuf, occ) != (ssize_t)occ) {
870 perror_reply(452, "Error writing output file", errno);
871 break;
872 }
873 (void) inflateEnd(&zstream);
874 return (true);
875 }
876 if (cc < 0) {
877 perror_reply(426, "Data Connection", errno);
878 break;
879 }
880 byte_count += cc;
881 zstream.next_in = (Bytef*) buf;
882 zstream.avail_in = cc;
883 do {
884 int state = inflate(&zstream, Z_PARTIAL_FLUSH);
885 if (state == Z_STREAM_END)
886 break;
887 if (state != Z_OK) {
888 reply(452, "Decoding error: %s", zstream.msg);
889 goto bad;
890 }
891 size_t occ = sizeof (obuf) - zstream.avail_out;
892 if (write(fdout, obuf, occ) != (ssize_t)occ) {
893 perror_reply(452, "Error writing output file", errno);
894 goto bad;
895 }
896 zstream.next_out = (Bytef*) obuf;
897 zstream.avail_out = sizeof (obuf);
898 } while (zstream.avail_in > 0);
899 }
900 bad:
901 (void) inflateEnd(&zstream);
902 } else
903 reply(452, "Can not initialize decoder: %s", zstream.msg);
904 return (false);
905 }
906
907 void
908 HylaFAXServer::formHelpCmd(void)
909 {
910 lreply(211, "Supported file formats:");
911 for (u_int i = 0, n = N(formats); i < n; i++)
912 lreply(211, "%8s%s %s"
913 , formats[i].name
914 , formats[i].supported ? " " : "*"
915 , formats[i].help
916 );
917 reply(211, "Formats marked with a * are not supported.");
918 }
919
920 void
921 HylaFAXServer::formCmd(const char* name)
922 {
923 fxStr f(name);
924 f.raisecase();
925 for (u_int i = 0, n = N(formats); i < n; i++)
926 if (f == formats[i].name) {
927 if (formats[i].supported) {
928 form = i;
929 reply(200, "Format set to %s.", (const char*) f);
930 } else
931 reply(504, "Format %s not supported.", (const char*) f);
932 return;
933 }
934 reply(504, "Unknown format %s.", name);
935 }
936
937 /*
938 * This is used to identify a submitted document type when the client
939 * specified the default (Postscript, legacy) or did not make a specification.
940 * If the file extension is not unknown, or or is Postscript, we'll check
941 * it, otherwise we'll trust it.
942 */
943 bool
944 HylaFAXServer::docType(const char* docname, FaxSendOp& op)
945 {
946 op = FaxRequest::send_unknown;
947
948 fxStr file(docname);
949 u_int d = file.nextR(file.length(), '.');
950 if (strcmp(docname+d, "ps") != 0) {
951 /*
952 * Since it's not Postscript, let's look for it in ourlist of
953 * supported formats.
954 */
955 for (u_int i = 0, n = N(formats); i < n; i++) {
956 if (strcmp(docname+d, formats[i].suffix) == 0 && formats[i].supported) {
957 op = formats[i].op;
958 return (true);
959 }
960 }
961 }
962
963 /*
964 * The file extension is either Postscript (which is default on old
965 * clients, so no guarantee) or un-recognized, so let's take a peek
966 * and see if we can figure it out.
967 * XXX: Should we rename it if we find it successful?
968 */
969 int fd = Sys::open(docname, O_RDONLY);
970 if (fd >= 0) {
971 struct stat sb;
972 if (FileCache::lookup(docname, sb) && S_ISREG(sb.st_mode)) {
973 union {
974 char buf[512];
975 TIFFHeader h;
976 } b;
977 ssize_t cc = Sys::read(fd, (char*) &b, sizeof (b));
978 if (cc > 2 && b.buf[0] == '%' && b.buf[1] == '!')
979 op = FaxRequest::send_postscript;
980 else if (cc > 2 && b.buf[0] == '%' && b.buf[1] == 'P') {
981 logDebug("What we have here is a PDF file");
982 op = FaxRequest::send_pdf;
983 } else if (cc > 2 && b.buf[0] == 0x1b && (b.buf[1] == 'E' || b.buf[1] == '%' || b.buf[1] == '&' || b.buf[1] == '*')) {
984 logDebug("What we have here is a PCL file");
985 op = FaxRequest::send_pcl;
986 } else if (cc > (ssize_t)sizeof (b.h) && isTIFF(b.h))
987 op = FaxRequest::send_tiff;
988 else if (cc > 3 && b.buf[0] == '@' && b.buf[1] == 'P' && b.buf[2] == 'J' && b.buf[3] == 'L') {
989 logDebug("PJL is unsupported");
990 op = FaxRequest::send_unknown;
991 }
992 else
993 op = FaxRequest::send_data;
994 }
995 Sys::close(fd);
996 }
997 if (op == FaxRequest::send_unknown)
998 logError("Don't know what file");
999
1000 return (op != FaxRequest::send_unknown);
1001 }
1002 #undef N
1003
1004 void
1005 HylaFAXServer::typeCmd(const char* name)
1006 {
1007 if (strcasecmp(name, "I") == 0)
1008 type = TYPE_I;
1009 else if (strcasecmp(name, "A") == 0)
1010 type = TYPE_A;
1011 else if (strcasecmp(name, "L") == 0)
1012 type = TYPE_L;
1013 else {
1014 reply(504, "Type %s not supported.", name);
1015 return;
1016 }
1017 reply(200, "Type set to %s.", typenames[type]);
1018 }
1019
1020 void
1021 HylaFAXServer::modeCmd(const char* name)
1022 {
1023 if (strcasecmp(name, "S") == 0)
1024 mode = MODE_S;
1025 else if (strcasecmp(name, "Z") == 0)
1026 mode = MODE_Z;
1027 else {
1028 reply(504, "Mode %s not supported.", name);
1029 return;
1030 }
1031 reply(200, "Mode set to %s.", modenames[mode]);
1032 }
1033
1034 void
1035 HylaFAXServer::struCmd(const char* name)
1036 {
1037 if (strcasecmp(name, "F") == 0)
1038 stru = STRU_F;
1039 else if (strcasecmp(name, "T") == 0)
1040 stru = STRU_T;
1041 else {
1042 reply(504, "Structure %s not supported.", name);
1043 return;
1044 }
1045 reply(200, "Structure set to %s.", strunames[stru]);
1046 }
1047
1048 void
1049 HylaFAXServer::printTransferStatus(FILE* fd)
1050 {
1051 if (restart_point)
1052 fprintf(fd, " Data transfer restart pending at %lu\r\n",
1053 (u_long) restart_point);
1054 fprintf(fd, " TYPE: %s", typenames[type]);
1055 if (type == TYPE_L)
1056 fprintf(fd, " %d", CHAR_BIT);
1057 fprintf(fd, "; STRU: %s; MODE: %s; FORM: %s\r\n"
1058 , strunames[stru]
1059 , modenames[mode]
1060 , formats[form].name
1061 );
1062 }