summaryrefslogtreecommitdiff
path: root/core/qws/transferserver.cpp
authorkergoth <kergoth>2003-05-08 16:48:20 (UTC)
committer kergoth <kergoth>2003-05-08 16:48:20 (UTC)
commit7d24cfad2a564436950b5f42e74c0bd51481f5a9 (patch) (unidiff)
treebc55466250fd15014a35a9c13f0538893b2245fc /core/qws/transferserver.cpp
parent0cb4111d34d9fe96731f48983e1ff2e67262db02 (diff)
downloadopie-7d24cfad2a564436950b5f42e74c0bd51481f5a9.zip
opie-7d24cfad2a564436950b5f42e74c0bd51481f5a9.tar.gz
opie-7d24cfad2a564436950b5f42e74c0bd51481f5a9.tar.bz2
Start work on a new launcher. This commit is simply a minimal Opie QWS server.
Diffstat (limited to 'core/qws/transferserver.cpp') (more/less context) (ignore whitespace changes)
-rw-r--r--core/qws/transferserver.cpp1424
1 files changed, 1424 insertions, 0 deletions
diff --git a/core/qws/transferserver.cpp b/core/qws/transferserver.cpp
new file mode 100644
index 0000000..0337a94
--- a/dev/null
+++ b/core/qws/transferserver.cpp
@@ -0,0 +1,1424 @@
1/**********************************************************************
2** Copyright (C) 2000-2002 Trolltech AS. All rights reserved.
3**
4** This file is part of the Qtopia Environment.
5**
6** This file may be distributed and/or modified under the terms of the
7** GNU General Public License version 2 as published by the Free Software
8** Foundation and appearing in the file LICENSE.GPL included in the
9** packaging of this file.
10**
11** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
12** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
13**
14** See http://www.trolltech.com/gpl/ for GPL licensing information.
15**
16** Contact info@trolltech.com if any conditions of this licensing are
17** not clear to you.
18**
19**********************************************************************/
20#define _XOPEN_SOURCE
21#include <pwd.h>
22#include <sys/types.h>
23#include <unistd.h>
24#include <stdlib.h>
25#include <time.h>
26#include <shadow.h>
27
28/* we need the _OS_LINUX stuff first ! */
29#include <qglobal.h>
30
31#ifndef _OS_LINUX_
32
33extern "C"
34{
35#include <uuid/uuid.h>
36#define UUID_H_INCLUDED
37}
38
39#endif // not defined linux
40
41#if defined(_OS_LINUX_)
42#include <shadow.h>
43#endif
44
45#include <qdir.h>
46#include <qfile.h>
47#include <qtextstream.h>
48#include <qdatastream.h>
49#include <qmessagebox.h>
50#include <qstringlist.h>
51#include <qfileinfo.h>
52#include <qregexp.h>
53//#include <qpe/qcopchannel_qws.h>
54#include <qpe/process.h>
55#include <qpe/global.h>
56#include <qpe/config.h>
57#include <qpe/contact.h>
58#include <qpe/quuid.h>
59#include <qpe/version.h>
60#include <qpe/qcopenvelope_qws.h>
61
62#include "transferserver.h"
63#include <opie/oprocess.h>
64
65const int block_size = 51200;
66
67TransferServer::TransferServer( Q_UINT16 port, QObject *parent ,
68 const char* name )
69 : QServerSocket( port, 1, parent, name )
70{
71 if ( !ok() )
72 qWarning( "Failed to bind to port %d", port );
73}
74
75TransferServer::~TransferServer()
76{
77}
78
79void TransferServer::newConnection( int socket )
80{
81 (void) new ServerPI( socket, this );
82}
83
84/*
85 * small class in anonymous namespace
86 * to generate a QUUid for us
87 */
88namespace
89{
90struct UidGen
91{
92 QString uuid();
93};
94#if !defined(_OS_LINUX_)
95
96QString UidGen::uuid()
97{
98 uuid_t uuid;
99 uuid_generate( uuid );
100 return QUUid( uuid ).toString();
101}
102#else
103/*
104* linux got a /proc/sys/kernel/random/uuid file
105* it'll generate the uuids for us
106*/
107QString UidGen::uuid()
108{
109 QFile file( "/proc/sys/kernel/random/uuid" );
110 if (!file.open(IO_ReadOnly ) )
111 return QString::null;
112
113 QTextStream stream(&file);
114
115 return "{" + stream.read().stripWhiteSpace() + "}";
116}
117#endif
118}
119
120QString SyncAuthentication::serverId()
121{
122 Config cfg("Security");
123 cfg.setGroup("Sync");
124 QString r = cfg.readEntry("serverid");
125 if ( r.isEmpty() ) {
126 UidGen gen;
127 r = gen.uuid();
128 cfg.writeEntry("serverid", r );
129 }
130 return r;
131}
132
133QString SyncAuthentication::ownerName()
134{
135 QString vfilename = Global::applicationFileName("addressbook",
136 "businesscard.vcf");
137 if (QFile::exists(vfilename)) {
138 Contact c;
139 c = Contact::readVCard( vfilename )[0];
140 return c.fullName();
141 }
142
143 return "";
144}
145
146QString SyncAuthentication::loginName()
147{
148 struct passwd *pw;
149 pw = getpwuid( geteuid() );
150 return QString::fromLocal8Bit( pw->pw_name );
151}
152
153int SyncAuthentication::isAuthorized(QHostAddress peeraddress)
154{
155 Config cfg("Security");
156 cfg.setGroup("Sync");
157 // QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0");
158 uint auth_peer = cfg.readNumEntry("auth_peer", 0xc0a80100);
159
160 // QHostAddress allowed;
161 // allowed.setAddress(allowedstr);
162 // uint auth_peer = allowed.ip4Addr();
163 uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits", 24);
164 uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined
165 ? 0xffffffff : (((1 << auth_peer_bits) - 1) << (32 - auth_peer_bits));
166 return (peeraddress.ip4Addr() & mask) == auth_peer;
167}
168
169bool SyncAuthentication::checkUser( const QString& user )
170{
171 if ( user.isEmpty() )
172 return FALSE;
173 QString euser = loginName();
174 return user == euser;
175}
176
177bool SyncAuthentication::checkPassword( const QString& password )
178{
179#ifdef ALLOW_UNIX_USER_FTP
180 // First, check system password...
181
182 struct passwd *pw = 0;
183 struct spwd *spw = 0;
184
185 pw = getpwuid( geteuid() );
186 spw = getspnam( pw->pw_name );
187
188 QString cpwd = QString::fromLocal8Bit( pw->pw_passwd );
189 if ( cpwd == "x" && spw )
190 cpwd = QString::fromLocal8Bit( spw->sp_pwdp );
191
192 // Note: some systems use more than crypt for passwords.
193 QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) );
194 if ( cpwd == cpassword )
195 return TRUE;
196#endif
197
198 static int lastdenial = 0;
199 static int denials = 0;
200 int now = time(0);
201
202 // Detect old Qtopia Desktop (no password)
203 if ( password.isEmpty() ) {
204 if ( denials < 1 || now > lastdenial + 600 ) {
205 QMessageBox::warning( 0, tr("Sync Connection"),
206 tr("<p>An unauthorized system is requesting access to this device."
207 "<p>If you are using a version of Qtopia Desktop older than 1.5.1, "
208 "please upgrade."),
209 tr("Deny") );
210 denials++;
211 lastdenial = now;
212 }
213 return FALSE;
214 }
215
216 // Second, check sync password...
217 QString pass = password.left(6);
218 /* old QtopiaDesktops are sending
219 * rootme newer versions got a Qtopia
220 * prefixed. Qtopia prefix will suceed
221 * until the sync software syncs up
222 * FIXME
223 */
224 if ( pass == "rootme" || pass == "Qtopia") {
225
226 QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), "qp" ) );
227 Config cfg("Security");
228 cfg.setGroup("Sync");
229 QString pwds = cfg.readEntry("Passwords");
230 if ( QStringList::split(QChar(' '), pwds).contains(cpassword) )
231 return TRUE;
232
233 // Unrecognized system. Be careful...
234
235 if ( (denials > 2 && now < lastdenial + 600)
236 || QMessageBox::warning(0, tr("Sync Connection"),
237 tr("<p>An unrecognized system is requesting access to this device."
238 "<p>If you have just initiated a Sync for the first time, this is normal."),
239 tr("Allow"), tr("Deny"), 0, 1, 1 ) == 1 ) {
240 denials++;
241 lastdenial = now;
242 return FALSE;
243 }
244 else {
245 denials = 0;
246 cfg.writeEntry("Passwords", pwds + " " + cpassword);
247 return TRUE;
248 }
249 }
250
251 return FALSE;
252}
253
254ServerPI::ServerPI( int socket, QObject *parent , const char* name )
255 : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 )
256{
257 state = Connected;
258
259 setSocket( socket );
260
261 peerport = peerPort();
262 peeraddress = peerAddress();
263
264#ifndef INSECURE
265
266 if ( !SyncAuthentication::isAuthorized(peeraddress) ) {
267 state = Forbidden;
268 startTimer( 0 );
269 }
270 else
271#endif
272 {
273 connect( this, SIGNAL( readyRead() ), SLOT( read() ) );
274 connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) );
275
276 passiv = FALSE;
277 for ( int i = 0; i < 4; i++ )
278 wait[i] = FALSE;
279
280 send( "220 Qtopia " QPE_VERSION " FTP Server" );
281 state = Wait_USER;
282
283 dtp = new ServerDTP( this );
284 connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) );
285 connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) );
286 connect( dtp, SIGNAL( error( int ) ), SLOT( dtpError( int ) ) );
287
288
289 directory = QDir::currentDirPath();
290
291 static int p = 1024;
292
293 while ( !serversocket || !serversocket->ok() ) {
294 delete serversocket;
295 serversocket = new ServerSocket( ++p, this );
296 }
297 connect( serversocket, SIGNAL( newIncomming( int ) ),
298 SLOT( newConnection( int ) ) );
299 }
300}
301
302ServerPI::~ServerPI()
303{
304}
305
306void ServerPI::connectionClosed()
307{
308 // qDebug( "Debug: Connection closed" );
309 delete this;
310}
311
312void ServerPI::send( const QString& msg )
313{
314 QTextStream os( this );
315 os << msg << endl;
316 //qDebug( "Reply: %s", msg.latin1() );
317}
318
319void ServerPI::read()
320{
321 while ( canReadLine() )
322 process( readLine().stripWhiteSpace() );
323}
324
325bool ServerPI::checkReadFile( const QString& file )
326{
327 QString filename;
328
329 if ( file[0] != "/" )
330 filename = directory.path() + "/" + file;
331 else
332 filename = file;
333
334 QFileInfo fi( filename );
335 return ( fi.exists() && fi.isReadable() );
336}
337
338bool ServerPI::checkWriteFile( const QString& file )
339{
340 QString filename;
341
342 if ( file[0] != "/" )
343 filename = directory.path() + "/" + file;
344 else
345 filename = file;
346
347 QFileInfo fi( filename );
348
349 if ( fi.exists() )
350 if ( !QFile( filename ).remove() )
351 return FALSE;
352 return TRUE;
353}
354
355void ServerPI::process( const QString& message )
356{
357 //qDebug( "Command: %s", message.latin1() );
358
359 // split message using "," as separator
360 QStringList msg = QStringList::split( " ", message );
361 if ( msg.isEmpty() )
362 return ;
363
364 // command token
365 QString cmd = msg[0].upper();
366
367 // argument token
368 QString arg;
369 if ( msg.count() >= 2 )
370 arg = msg[1];
371
372 // full argument string
373 QString args;
374 if ( msg.count() >= 2 ) {
375 QStringList copy( msg );
376 // FIXME: for Qt3
377 // copy.pop_front()
378 copy.remove( copy.begin() );
379 args = copy.join( " " );
380 }
381
382 //qDebug( "args: %s", args.latin1() );
383
384 // we always respond to QUIT, regardless of state
385 if ( cmd == "QUIT" ) {
386 send( "211 Good bye!" );
387 delete this;
388 return ;
389 }
390
391 // connected to client
392 if ( Connected == state )
393 return ;
394
395 // waiting for user name
396 if ( Wait_USER == state ) {
397
398 if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) {
399 send( "530 Please login with USER and PASS" );
400 return ;
401 }
402 send( "331 User name ok, need password" );
403 state = Wait_PASS;
404 return ;
405 }
406
407 // waiting for password
408 if ( Wait_PASS == state ) {
409
410 if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) {
411 send( "530 Please login with USER and PASS" );
412 return ;
413 }
414 send( "230 User logged in, proceed" );
415 state = Ready;
416 return ;
417 }
418
419 // ACCESS CONTROL COMMANDS
420
421
422 // account (ACCT)
423 if ( cmd == "ACCT" ) {
424 // even wu-ftp does not support it
425 send( "502 Command not implemented" );
426 }
427
428 // change working directory (CWD)
429 else if ( cmd == "CWD" ) {
430
431 if ( !args.isEmpty() ) {
432 if ( directory.cd( args, TRUE ) )
433 send( "250 Requested file action okay, completed" );
434 else
435 send( "550 Requested action not taken" );
436 }
437 else
438 send( "500 Syntax error, command unrecognized" );
439 }
440
441 // change to parent directory (CDUP)
442 else if ( cmd == "CDUP" ) {
443 if ( directory.cdUp() )
444 send( "250 Requested file action okay, completed" );
445 else
446 send( "550 Requested action not taken" );
447 }
448
449 // structure mount (SMNT)
450 else if ( cmd == "SMNT" ) {
451 // even wu-ftp does not support it
452 send( "502 Command not implemented" );
453 }
454
455 // reinitialize (REIN)
456 else if ( cmd == "REIN" ) {
457 // even wu-ftp does not support it
458 send( "502 Command not implemented" );
459 }
460
461
462 // TRANSFER PARAMETER COMMANDS
463
464
465 // data port (PORT)
466 else if ( cmd == "PORT" ) {
467 if ( parsePort( arg ) )
468 send( "200 Command okay" );
469 else
470 send( "500 Syntax error, command unrecognized" );
471 }
472
473 // passive (PASV)
474 else if ( cmd == "PASV" ) {
475 passiv = TRUE;
476 send( "227 Entering Passive Mode ("
477 + address().toString().replace( QRegExp( "\\." ), "," ) + ","
478 + QString::number( ( serversocket->port() ) >> 8 ) + ","
479 + QString::number( ( serversocket->port() ) & 0xFF ) + ")" );
480 }
481
482 // representation type (TYPE)
483 else if ( cmd == "TYPE" ) {
484 if ( arg.upper() == "A" || arg.upper() == "I" )
485 send( "200 Command okay" );
486 else
487 send( "504 Command not implemented for that parameter" );
488 }
489
490 // file structure (STRU)
491 else if ( cmd == "STRU" ) {
492 if ( arg.upper() == "F" )
493 send( "200 Command okay" );
494 else
495 send( "504 Command not implemented for that parameter" );
496 }
497
498 // transfer mode (MODE)
499 else if ( cmd == "MODE" ) {
500 if ( arg.upper() == "S" )
501 send( "200 Command okay" );
502 else
503 send( "504 Command not implemented for that parameter" );
504 }
505
506
507 // FTP SERVICE COMMANDS
508
509
510 // retrieve (RETR)
511 else if ( cmd == "RETR" )
512 if ( !args.isEmpty() && checkReadFile( absFilePath( args ) )
513 || backupRestoreGzip( absFilePath( args ) ) ) {
514 send( "150 File status okay" );
515 sendFile( absFilePath( args ) );
516 }
517 else {
518 qDebug("550 Requested action not taken");
519 send( "550 Requested action not taken" );
520 }
521
522 // store (STOR)
523 else if ( cmd == "STOR" )
524 if ( !args.isEmpty() && checkWriteFile( absFilePath( args ) ) ) {
525 send( "150 File status okay" );
526 retrieveFile( absFilePath( args ) );
527 }
528 else
529 send( "550 Requested action not taken" );
530
531 // store unique (STOU)
532 else if ( cmd == "STOU" ) {
533 send( "502 Command not implemented" );
534 }
535
536 // append (APPE)
537 else if ( cmd == "APPE" ) {
538 send( "502 Command not implemented" );
539 }
540
541 // allocate (ALLO)
542 else if ( cmd == "ALLO" ) {
543 send( "200 Command okay" );
544 }
545
546 // restart (REST)
547 else if ( cmd == "REST" ) {
548 send( "502 Command not implemented" );
549 }
550
551 // rename from (RNFR)
552 else if ( cmd == "RNFR" ) {
553 renameFrom = QString::null;
554 if ( args.isEmpty() )
555 send( "500 Syntax error, command unrecognized" );
556 else {
557 QFile file( absFilePath( args ) );
558 if ( file.exists() ) {
559 send( "350 File exists, ready for destination name" );
560 renameFrom = absFilePath( args );
561 }
562 else
563 send( "550 Requested action not taken" );
564 }
565 }
566
567 // rename to (RNTO)
568 else if ( cmd == "RNTO" ) {
569 if ( lastCommand != "RNFR" )
570 send( "503 Bad sequence of commands" );
571 else if ( args.isEmpty() )
572 send( "500 Syntax error, command unrecognized" );
573 else {
574 QDir dir( absFilePath( args ) );
575 if ( dir.rename( renameFrom, absFilePath( args ), TRUE ) )
576 send( "250 Requested file action okay, completed." );
577 else
578 send( "550 Requested action not taken" );
579 }
580 }
581
582 // abort (ABOR)
583 else if ( cmd.contains( "ABOR" ) ) {
584 dtp->close();
585 if ( dtp->dtpMode() != ServerDTP::Idle )
586 send( "426 Connection closed; transfer aborted" );
587 else
588 send( "226 Closing data connection" );
589 }
590
591 // delete (DELE)
592 else if ( cmd == "DELE" ) {
593 if ( args.isEmpty() )
594 send( "500 Syntax error, command unrecognized" );
595 else {
596 QFile file( absFilePath( args ) ) ;
597 if ( file.remove() ) {
598 send( "250 Requested file action okay, completed" );
599 QCopEnvelope e("QPE/System", "linkChanged(QString)" );
600 e << file.name();
601 }
602 else {
603 send( "550 Requested action not taken" );
604 }
605 }
606 }
607
608 // remove directory (RMD)
609 else if ( cmd == "RMD" ) {
610 if ( args.isEmpty() )
611 send( "500 Syntax error, command unrecognized" );
612 else {
613 QDir dir;
614 if ( dir.rmdir( absFilePath( args ), TRUE ) )
615 send( "250 Requested file action okay, completed" );
616 else
617 send( "550 Requested action not taken" );
618 }
619 }
620
621 // make directory (MKD)
622 else if ( cmd == "MKD" ) {
623 if ( args.isEmpty() ) {
624 qDebug(" Error: no arg");
625 send( "500 Syntax error, command unrecognized" );
626 }
627 else {
628 QDir dir;
629 if ( dir.mkdir( absFilePath( args ), TRUE ) )
630 send( "250 Requested file action okay, completed." );
631 else
632 send( "550 Requested action not taken" );
633 }
634 }
635
636 // print working directory (PWD)
637 else if ( cmd == "PWD" ) {
638 send( "257 \"" + directory.path() + "\"" );
639 }
640
641 // list (LIST)
642 else if ( cmd == "LIST" ) {
643 if ( sendList( absFilePath( args ) ) )
644 send( "150 File status okay" );
645 else
646 send( "500 Syntax error, command unrecognized" );
647 }
648
649 // size (SIZE)
650 else if ( cmd == "SIZE" ) {
651 QString filePath = absFilePath( args );
652 QFileInfo fi( filePath );
653 bool gzipfile = backupRestoreGzip( filePath );
654 if ( !fi.exists() && !gzipfile )
655 send( "500 Syntax error, command unrecognized" );
656 else {
657 if ( !gzipfile )
658 send( "213 " + QString::number( fi.size() ) );
659 else {
660 Process duproc( QString("du") );
661 duproc.addArgument("-s");
662 QString in, out;
663 if ( !duproc.exec(in, out) ) {
664 qDebug("du process failed; just sending back 1K");
665 send( "213 1024");
666 }
667 else {
668 QString size = out.left( out.find("\t") );
669 int guess = size.toInt() / 5;
670 if ( filePath.contains("doc") )
671 guess *= 1000;
672 qDebug("sending back gzip guess of %d", guess);
673 send( "213 " + QString::number(guess) );
674 }
675 }
676 }
677 }
678 // name list (NLST)
679 else if ( cmd == "NLST" ) {
680 send( "502 Command not implemented" );
681 }
682
683 // site parameters (SITE)
684 else if ( cmd == "SITE" ) {
685 send( "502 Command not implemented" );
686 }
687
688 // system (SYST)
689 else if ( cmd == "SYST" ) {
690 send( "215 UNIX Type: L8" );
691 }
692
693 // status (STAT)
694 else if ( cmd == "STAT" ) {
695 send( "502 Command not implemented" );
696 }
697
698 // help (HELP )
699 else if ( cmd == "HELP" ) {
700 send( "502 Command not implemented" );
701 }
702
703 // noop (NOOP)
704 else if ( cmd == "NOOP" ) {
705 send( "200 Command okay" );
706 }
707
708 // not implemented
709 else
710 send( "502 Command not implemented" );
711
712 lastCommand = cmd;
713}
714
715bool ServerPI::backupRestoreGzip( const QString &file )
716{
717 return (file.find( "backup" ) != -1 &&
718 file.findRev( ".tgz" ) == (int)file.length() - 4 );
719}
720
721bool ServerPI::backupRestoreGzip( const QString &file, QStringList &targets )
722{
723 if ( file.find( "backup" ) != -1 &&
724 file.findRev( ".tgz" ) == (int)file.length() - 4 ) {
725 QFileInfo info( file );
726 targets = info.dirPath( TRUE );
727 qDebug("ServerPI::backupRestoreGzip for %s = %s", file.latin1(),
728 targets.join(" ").latin1() );
729 return true;
730 }
731 return false;
732}
733
734void ServerPI::sendFile( const QString& file )
735{
736 if ( passiv ) {
737 wait[SendFile] = TRUE;
738 waitfile = file;
739 if ( waitsocket )
740 newConnection( waitsocket );
741 }
742 else {
743 QStringList targets;
744 if ( backupRestoreGzip( file, targets ) )
745 dtp->sendGzipFile( file, targets, peeraddress, peerport );
746 else
747 dtp->sendFile( file, peeraddress, peerport );
748 }
749}
750
751void ServerPI::retrieveFile( const QString& file )
752{
753 if ( passiv ) {
754 wait[RetrieveFile] = TRUE;
755 waitfile = file;
756 if ( waitsocket )
757 newConnection( waitsocket );
758 }
759 else {
760 QStringList targets;
761 if ( backupRestoreGzip( file, targets ) )
762 dtp->retrieveGzipFile( file, peeraddress, peerport );
763 else
764 dtp->retrieveFile( file, peeraddress, peerport );
765 }
766}
767
768bool ServerPI::parsePort( const QString& pp )
769{
770 QStringList p = QStringList::split( ",", pp );
771 if ( p.count() != 6 )
772 return FALSE;
773
774 // h1,h2,h3,h4,p1,p2
775 peeraddress = QHostAddress( ( p[0].toInt() << 24 ) + ( p[1].toInt() << 16 ) +
776 ( p[2].toInt() << 8 ) + p[3].toInt() );
777 peerport = ( p[4].toInt() << 8 ) + p[5].toInt();
778 return TRUE;
779}
780
781void ServerPI::dtpCompleted()
782{
783 send( "226 Closing data connection, file transfer successful" );
784 if ( dtp->dtpMode() == ServerDTP::RetrieveFile ) {
785 QString fn = dtp->fileName();
786 if ( fn.right(8) == ".desktop" && fn.find("/Documents/") >= 0 ) {
787 QCopEnvelope e("QPE/System", "linkChanged(QString)" );
788 e << fn;
789 }
790 }
791 waitsocket = 0;
792 dtp->close();
793}
794
795void ServerPI::dtpFailed()
796{
797 dtp->close();
798 waitsocket = 0;
799 send( "451 Requested action aborted: local error in processing" );
800}
801
802void ServerPI::dtpError( int )
803{
804 dtp->close();
805 waitsocket = 0;
806 send( "451 Requested action aborted: local error in processing" );
807}
808
809bool ServerPI::sendList( const QString& arg )
810{
811 QByteArray listing;
812 QBuffer buffer( listing );
813
814 if ( !buffer.open( IO_WriteOnly ) )
815 return FALSE;
816
817 QTextStream ts( &buffer );
818 QString fn = arg;
819
820 if ( fn.isEmpty() )
821 fn = directory.path();
822
823 QFileInfo fi( fn );
824 if ( !fi.exists() )
825 return FALSE;
826
827 // return file listing
828 if ( fi.isFile() ) {
829 ts << fileListing( &fi ) << endl;
830 }
831
832 // return directory listing
833 else if ( fi.isDir() ) {
834 QDir dir( fn );
835 const QFileInfoList *list = dir.entryInfoList( QDir::All | QDir::Hidden );
836
837 QFileInfoListIterator it( *list );
838 QFileInfo *info;
839
840 unsigned long total = 0;
841 while ( ( info = it.current() ) ) {
842 if ( info->fileName() != "." && info->fileName() != ".." )
843 total += info->size();
844 ++it;
845 }
846
847 ts << "total " << QString::number( total / 1024 ) << endl;
848
849 it.toFirst();
850 while ( ( info = it.current() ) ) {
851 if ( info->fileName() == "." || info->fileName() == ".." ) {
852 ++it;
853 continue;
854 }
855 ts << fileListing( info ) << endl;
856 ++it;
857 }
858 }
859
860 if ( passiv ) {
861 waitarray = buffer.buffer();
862 wait[SendByteArray] = TRUE;
863 if ( waitsocket )
864 newConnection( waitsocket );
865 }
866 else
867 dtp->sendByteArray( buffer.buffer(), peeraddress, peerport );
868 return TRUE;
869}
870
871QString ServerPI::fileListing( QFileInfo *info )
872{
873 if ( !info )
874 return QString::null;
875 QString s;
876
877 // type char
878 if ( info->isDir() )
879 s += "d";
880 else if ( info->isSymLink() )
881 s += "l";
882 else
883 s += "-";
884
885 // permisson string
886 s += permissionString( info ) + " ";
887
888 // number of hardlinks
889 int subdirs = 1;
890
891 if ( info->isDir() )
892 subdirs = 2;
893 // FIXME : this is to slow
894 //if ( info->isDir() )
895 //subdirs = QDir( info->absFilePath() ).entryList( QDir::Dirs ).count();
896
897 s += QString::number( subdirs ).rightJustify( 3, ' ', TRUE ) + " ";
898
899 // owner
900 s += info->owner().leftJustify( 8, ' ', TRUE ) + " ";
901
902 // group
903 s += info->group().leftJustify( 8, ' ', TRUE ) + " ";
904
905 // file size in bytes
906 s += QString::number( info->size() ).rightJustify( 9, ' ', TRUE ) + " ";
907
908 // last modified date
909 QDate date = info->lastModified().date();
910 QTime time = info->lastModified().time();
911 s += date.monthName( date.month() ) + " "
912 + QString::number( date.day() ).rightJustify( 2, ' ', TRUE ) + " "
913 + QString::number( time.hour() ).rightJustify( 2, '0', TRUE ) + ":"
914 + QString::number( time.minute() ).rightJustify( 2, '0', TRUE ) + " ";
915
916 // file name
917 s += info->fileName();
918
919 return s;
920}
921
922QString ServerPI::permissionString( QFileInfo *info )
923{
924 if ( !info )
925 return QString( "---------" );
926 QString s;
927
928 // user
929 if ( info->permission( QFileInfo::ReadUser ) )
930 s += "r";
931 else
932 s += "-";
933 if ( info->permission( QFileInfo::WriteUser ) )
934 s += "w";
935 else
936 s += "-";
937 if ( info->permission( QFileInfo::ExeUser ) )
938 s += "x";
939 else
940 s += "-";
941
942 // group
943 if ( info->permission( QFileInfo::ReadGroup ) )
944 s += "r";
945 else
946 s += "-";
947 if ( info->permission( QFileInfo::WriteGroup ) )
948 s += "w";
949 else
950 s += "-";
951 if ( info->permission( QFileInfo::ExeGroup ) )
952 s += "x";
953 else
954 s += "-";
955
956 // exec
957 if ( info->permission( QFileInfo::ReadOther ) )
958 s += "r";
959 else
960 s += "-";
961 if ( info->permission( QFileInfo::WriteOther ) )
962 s += "w";
963 else
964 s += "-";
965 if ( info->permission( QFileInfo::ExeOther ) )
966 s += "x";
967 else
968 s += "-";
969
970 return s;
971}
972
973void ServerPI::newConnection( int socket )
974{
975 //qDebug( "New incomming connection" );
976
977 if ( !passiv )
978 return ;
979
980 if ( wait[SendFile] ) {
981 QStringList targets;
982 if ( backupRestoreGzip( waitfile, targets ) )
983 dtp->sendGzipFile( waitfile, targets );
984 else
985 dtp->sendFile( waitfile );
986 dtp->setSocket( socket );
987 }
988 else if ( wait[RetrieveFile] ) {
989 qDebug("check retrieve file");
990 if ( backupRestoreGzip( waitfile ) )
991 dtp->retrieveGzipFile( waitfile );
992 else
993 dtp->retrieveFile( waitfile );
994 dtp->setSocket( socket );
995 }
996 else if ( wait[SendByteArray] ) {
997 dtp->sendByteArray( waitarray );
998 dtp->setSocket( socket );
999 }
1000 else if ( wait[RetrieveByteArray] ) {
1001 qDebug("retrieve byte array");
1002 dtp->retrieveByteArray();
1003 dtp->setSocket( socket );
1004 }
1005 else
1006 waitsocket = socket;
1007
1008 for ( int i = 0; i < 4; i++ )
1009 wait[i] = FALSE;
1010}
1011
1012QString ServerPI::absFilePath( const QString& file )
1013{
1014 if ( file.isEmpty() )
1015 return file;
1016
1017 QString filepath( file );
1018 if ( file[0] != "/" )
1019 filepath = directory.path() + "/" + file;
1020
1021 return filepath;
1022}
1023
1024
1025void ServerPI::timerEvent( QTimerEvent * )
1026{
1027 connectionClosed();
1028}
1029
1030
1031ServerDTP::ServerDTP( QObject *parent, const char* name)
1032 : QSocket( parent, name ), mode( Idle ), createTargzProc( 0 ),
1033 retrieveTargzProc( 0 ), gzipProc( 0 )
1034{
1035
1036 connect( this, SIGNAL( connected() ), SLOT( connected() ) );
1037 connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) );
1038 connect( this, SIGNAL( bytesWritten( int ) ), SLOT( bytesWritten( int ) ) );
1039 connect( this, SIGNAL( readyRead() ), SLOT( readyRead() ) );
1040
1041 gzipProc = new OProcess( this, "gzipProc" );
1042
1043 createTargzProc = new OProcess( QString("tar"), this, "createTargzProc");
1044 createTargzProc->setWorkingDirectory( QDir::rootDirPath() );
1045 connect( createTargzProc, SIGNAL( processExited(OProcess *) ), SLOT( targzDone() ) );
1046
1047 QStringList args = "tar";
1048 args += "-xv";
1049 retrieveTargzProc = new OProcess( args, this, "retrieveTargzProc" );
1050 retrieveTargzProc->setWorkingDirectory( QDir::rootDirPath() );
1051 connect( retrieveTargzProc, SIGNAL( processExited(OProcess *) ),
1052 SIGNAL( completed() ) );
1053 connect( retrieveTargzProc, SIGNAL( processExited(OProcess *) ),
1054 SLOT( extractTarDone() ) );
1055}
1056
1057ServerDTP::~ServerDTP()
1058{
1059 buf.close();
1060 file.close();
1061 createTargzProc->kill();
1062}
1063
1064void ServerDTP::extractTarDone()
1065{
1066 qDebug("extract done");
1067#ifndef QT_NO_COP
1068
1069 QCopEnvelope e( "QPE/Desktop", "restoreDone(QString)" );
1070 e << file.name();
1071#endif
1072}
1073
1074void ServerDTP::connected()
1075{
1076 // send file mode
1077 switch ( mode ) {
1078 case SendFile :
1079 if ( !file.exists() || !file.open( IO_ReadOnly) ) {
1080 emit failed();
1081 mode = Idle;
1082 return ;
1083 }
1084
1085 //qDebug( "Debug: Sending file '%s'", file.name().latin1() );
1086
1087 bytes_written = 0;
1088 if ( file.size() == 0 ) {
1089 //make sure it doesn't hang on empty files
1090 file.close();
1091 emit completed();
1092 mode = Idle;
1093 }
1094 else {
1095
1096 if ( !file.atEnd() ) {
1097 QCString s;
1098 s.resize( block_size );
1099 int bytes = file.readBlock( s.data(), block_size );
1100 writeBlock( s.data(), bytes );
1101 }
1102 }
1103 break;
1104 case SendGzipFile:
1105 if ( createTargzProc->isRunning() ) {
1106 // SHOULDN'T GET HERE, BUT DOING A SAFETY CHECK ANYWAY
1107 qWarning("Previous tar --gzip process is still running; killing it...");
1108 createTargzProc->kill();
1109 }
1110
1111 bytes_written = 0;
1112 qDebug("==>start send tar process");
1113 if ( !createTargzProc->start(OProcess::NotifyOnExit, OProcess::Stdout) )
1114 qWarning("Error starting %s or %s",
1115 createTargzProc->args()[0].data(),
1116 gzipProc->args()[0].data());
1117 break;
1118 case SendBuffer:
1119 if ( !buf.open( IO_ReadOnly) ) {
1120 emit failed();
1121 mode = Idle;
1122 return ;
1123 }
1124
1125 // qDebug( "Debug: Sending byte array" );
1126 bytes_written = 0;
1127 while ( !buf.atEnd() )
1128 putch( buf.getch() );
1129 buf.close();
1130 break;
1131 case RetrieveFile:
1132 // retrieve file mode
1133 if ( file.exists() && !file.remove() ) {
1134 emit failed();
1135 mode = Idle;
1136 return ;
1137 }
1138
1139 if ( !file.open( IO_WriteOnly) ) {
1140 emit failed();
1141 mode = Idle;
1142 return ;
1143 }
1144 // qDebug( "Debug: Retrieving file %s", file.name().latin1() );
1145 break;
1146 case RetrieveGzipFile:
1147 qDebug("=-> starting tar process to receive .tgz file");
1148 break;
1149 case RetrieveBuffer:
1150 // retrieve buffer mode
1151 if ( !buf.open( IO_WriteOnly) ) {
1152 emit failed();
1153 mode = Idle;
1154 return ;
1155 }
1156 // qDebug( "Debug: Retrieving byte array" );
1157 break;
1158 case Idle:
1159 qDebug("connection established but mode set to Idle; BUG!");
1160 break;
1161 }
1162}
1163
1164void ServerDTP::connectionClosed()
1165{
1166 //qDebug( "Debug: Data connection closed %ld bytes written", bytes_written );
1167
1168 // send file mode
1169 if ( SendFile == mode ) {
1170 if ( bytes_written == file.size() )
1171 emit completed();
1172 else
1173 emit failed();
1174 }
1175
1176 // send buffer mode
1177 else if ( SendBuffer == mode ) {
1178 if ( bytes_written == buf.size() )
1179 emit completed();
1180 else
1181 emit failed();
1182 }
1183
1184 // retrieve file mode
1185 else if ( RetrieveFile == mode ) {
1186 file.close();
1187 emit completed();
1188 }
1189
1190 else if ( RetrieveGzipFile == mode ) {
1191 qDebug("Done writing ungzip file; closing input");
1192 gzipProc->flushStdin();
1193 gzipProc->closeStdin();
1194 }
1195
1196 // retrieve buffer mode
1197 else if ( RetrieveBuffer == mode ) {
1198 buf.close();
1199 emit completed();
1200 }
1201
1202 mode = Idle;
1203}
1204
1205void ServerDTP::bytesWritten( int bytes )
1206{
1207 bytes_written += bytes;
1208
1209 // send file mode
1210 if ( SendFile == mode ) {
1211
1212 if ( bytes_written == file.size() ) {
1213 // qDebug( "Debug: Sending complete: %d bytes", file.size() );
1214 file.close();
1215 emit completed();
1216 mode = Idle;
1217 }
1218 else if ( !file.atEnd() ) {
1219 QCString s;
1220 s.resize( block_size );
1221 int bytes = file.readBlock( s.data(), block_size );
1222 writeBlock( s.data(), bytes );
1223 }
1224 }
1225
1226 // send buffer mode
1227 if ( SendBuffer == mode ) {
1228
1229 if ( bytes_written == buf.size() ) {
1230 // qDebug( "Debug: Sending complete: %d bytes", buf.size() );
1231 emit completed();
1232 mode = Idle;
1233 }
1234 }
1235}
1236
1237void ServerDTP::readyRead()
1238{
1239 // retrieve file mode
1240 if ( RetrieveFile == mode ) {
1241 QCString s;
1242 s.resize( bytesAvailable() );
1243 readBlock( s.data(), bytesAvailable() );
1244 file.writeBlock( s.data(), s.size() );
1245 }
1246 else if ( RetrieveGzipFile == mode ) {
1247 if ( !gzipProc->isRunning() )
1248 gzipProc->start(OProcess::NotifyOnExit, (OProcess::Communication) ( OProcess::Stdin | OProcess::Stdout ));
1249
1250 QByteArray s;
1251 s.resize( bytesAvailable() );
1252 readBlock( s.data(), bytesAvailable() );
1253 gzipProc->writeStdin( s.data(), s.size() );
1254 qDebug("wrote %d bytes to ungzip ", s.size() );
1255 }
1256 // retrieve buffer mode
1257 else if ( RetrieveBuffer == mode ) {
1258 QCString s;
1259 s.resize( bytesAvailable() );
1260 readBlock( s.data(), bytesAvailable() );
1261 buf.writeBlock( s.data(), s.size() );
1262 }
1263}
1264
1265void ServerDTP::writeTargzBlock(OProcess *, char *buffer, int buflen)
1266{
1267 writeBlock( buffer, buflen );
1268 qDebug("writeTargzBlock %d", buflen);
1269 if ( !createTargzProc->isRunning() ) {
1270 qDebug("tar and gzip done");
1271 emit completed();
1272 mode = Idle;
1273 disconnect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int ) ),
1274 this, SLOT( writeTargzBlock(OProcess *, char *, int) ) );
1275 }
1276}
1277
1278void ServerDTP::targzDone()
1279{
1280 //qDebug("targz done");
1281 disconnect( createTargzProc, SIGNAL( receivedStdout(OProcess *, char *, int) ),
1282 this, SLOT( gzipTarBlock(OProcess *, char *, int) ) );
1283 gzipProc->closeStdin();
1284}
1285
1286void ServerDTP::gzipTarBlock(OProcess *, char *buffer, int buflen)
1287{
1288 //qDebug("gzipTarBlock");
1289 if ( !gzipProc->isRunning() ) {
1290 //qDebug("auto start gzip proc");
1291 gzipProc->start(OProcess::NotifyOnExit, (OProcess::Communication) ( OProcess::Stdin | OProcess::Stdout ));
1292 }
1293 gzipProc->writeStdin( buffer, buflen );
1294}
1295
1296void ServerDTP::sendFile( const QString fn, const QHostAddress& host, Q_UINT16 port )
1297{
1298 file.setName( fn );
1299 mode = SendFile;
1300 connectToHost( host.toString(), port );
1301}
1302
1303void ServerDTP::sendFile( const QString fn )
1304{
1305 file.setName( fn );
1306 mode = SendFile;
1307}
1308
1309void ServerDTP::sendGzipFile( const QString &fn,
1310 const QStringList &archiveTargets,
1311 const QHostAddress& host, Q_UINT16 port )
1312{
1313 sendGzipFile( fn, archiveTargets );
1314 connectToHost( host.toString(), port );
1315}
1316
1317void ServerDTP::sendGzipFile( const QString &fn,
1318 const QStringList &archiveTargets )
1319{
1320 mode = SendGzipFile;
1321 file.setName( fn );
1322
1323 QStringList args = "tar";
1324 args += "-cv";
1325 args += archiveTargets;
1326 qDebug("sendGzipFile %s", args.join(" ").latin1() );
1327 createTargzProc->clearArguments( );
1328 *createTargzProc << args;
1329 connect( createTargzProc,
1330 SIGNAL( receivedStdout(OProcess *, char *, int) ), SLOT( gzipTarBlock(OProcess *, char *, int) ) );
1331
1332 gzipProc->clearArguments( );
1333 *gzipProc << "gzip";
1334 connect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int) ),
1335 SLOT( writeTargzBlock(OProcess *, char *, int) ) );
1336}
1337
1338void ServerDTP::gunzipDone()
1339{
1340 qDebug("gunzipDone");
1341 disconnect( gzipProc, SIGNAL( processExited() ),
1342 this, SLOT( gunzipDone() ) );
1343 retrieveTargzProc->closeStdin();
1344 disconnect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int) ),
1345 this, SLOT( tarExtractBlock(OProcess *, char *, int) ) );
1346}
1347
1348void ServerDTP::tarExtractBlock(OProcess *, char *buffer, int buflen)
1349{
1350 qDebug("tarExtractBlock");
1351 if ( !retrieveTargzProc->isRunning() ) {
1352 qDebug("auto start ungzip proc");
1353 if ( !retrieveTargzProc->start(OProcess::NotifyOnExit, OProcess::Stdin) )
1354 qWarning(" failed to start tar -x process");
1355 }
1356 retrieveTargzProc->writeStdin( buffer, buflen );
1357}
1358
1359
1360void ServerDTP::retrieveFile( const QString fn, const QHostAddress& host, Q_UINT16 port )
1361{
1362 file.setName( fn );
1363 mode = RetrieveFile;
1364 connectToHost( host.toString(), port );
1365}
1366
1367void ServerDTP::retrieveFile( const QString fn )
1368{
1369 file.setName( fn );
1370 mode = RetrieveFile;
1371}
1372
1373void ServerDTP::retrieveGzipFile( const QString &fn )
1374{
1375 qDebug("retrieveGzipFile %s", fn.latin1());
1376 file.setName( fn );
1377 mode = RetrieveGzipFile;
1378
1379 gzipProc->clearArguments();
1380 *gzipProc << "gunzip";
1381 connect( gzipProc, SIGNAL( readyReadStdout() ),
1382 SLOT( tarExtractBlock() ) );
1383 connect( gzipProc, SIGNAL( processExited() ),
1384 SLOT( gunzipDone() ) );
1385}
1386
1387void ServerDTP::retrieveGzipFile( const QString &fn, const QHostAddress& host, Q_UINT16 port )
1388{
1389 retrieveGzipFile( fn );
1390 connectToHost( host.toString(), port );
1391}
1392
1393void ServerDTP::sendByteArray( const QByteArray& array, const QHostAddress& host, Q_UINT16 port )
1394{
1395 buf.setBuffer( array );
1396 mode = SendBuffer;
1397 connectToHost( host.toString(), port );
1398}
1399
1400void ServerDTP::sendByteArray( const QByteArray& array )
1401{
1402 buf.setBuffer( array );
1403 mode = SendBuffer;
1404}
1405
1406void ServerDTP::retrieveByteArray( const QHostAddress& host, Q_UINT16 port )
1407{
1408 buf.setBuffer( QByteArray() );
1409 mode = RetrieveBuffer;
1410 connectToHost( host.toString(), port );
1411}
1412
1413void ServerDTP::retrieveByteArray()
1414{
1415 buf.setBuffer( QByteArray() );
1416 mode = RetrieveBuffer;
1417}
1418
1419void ServerDTP::setSocket( int socket )
1420{
1421 QSocket::setSocket( socket );
1422 connected();
1423}
1424