• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • tdeio/tdeio
 

tdeio/tdeio

  • tdeio
  • tdeio
job.cpp
1 /* This file is part of the KDE libraries
2  Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
3  David Faure <faure@kde.org>
4  Waldo Bastian <bastian@kde.org>
5 
6  This library is free software; you can redistribute it and/or
7  modify it under the terms of the GNU Library General Public
8  License as published by the Free Software Foundation; either
9  version 2 of the License, or (at your option) any later version.
10 
11  This library is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  Library General Public License for more details.
15 
16  You should have received a copy of the GNU Library General Public License
17  along with this library; see the file COPYING.LIB. If not, write to
18  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  Boston, MA 02110-1301, USA.
20 */
21 
22 #include "tdeio/job.h"
23 
24 #include <config.h>
25 
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <sys/stat.h>
29 
30 #include <assert.h>
31 
32 #include <signal.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <time.h>
36 #include <unistd.h>
37 extern "C" {
38 #include <pwd.h>
39 #include <grp.h>
40 }
41 #include <tqtimer.h>
42 #include <tqfile.h>
43 
44 #include <tdeapplication.h>
45 #include <tdeglobal.h>
46 #include <tdelocale.h>
47 #include <ksimpleconfig.h>
48 #include <kdebug.h>
49 #include <kdialog.h>
50 #include <tdemessagebox.h>
51 #include <kdatastream.h>
52 #include <tdemainwindow.h>
53 #include <kde_file.h>
54 
55 #include <errno.h>
56 
57 #include "kmimetype.h"
58 #include "slave.h"
59 #include "scheduler.h"
60 #include "kdirwatch.h"
61 #include "kmimemagic.h"
62 #include "kprotocolinfo.h"
63 #include "tdeprotocolmanager.h"
64 
65 #include "tdeio/observer.h"
66 
67 #include "kssl/ksslcsessioncache.h"
68 
69 #include <kdirnotify_stub.h>
70 #include <tdetempfile.h>
71 #include <dcopclient.h>
72 
73 #ifdef Q_OS_UNIX
74 #include <utime.h>
75 #endif
76 #if defined Q_WS_X11
77 #include <netwm.h>
78 #include <fixx11h.h>
79 #endif
80 
81 using namespace TDEIO;
82 template class TQPtrList<TDEIO::Job>;
83 
84 //this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
85 #define REPORT_TIMEOUT 200
86 
87 #define KIO_ARGS TQByteArray packedArgs; TQDataStream stream( packedArgs, IO_WriteOnly ); stream
88 
89 class Job::JobPrivate
90 {
91 public:
92  JobPrivate() : m_autoErrorHandling( false ), m_autoWarningHandling( true ),
93  m_interactive( true ), m_parentJob( 0L ), m_extraFlags(0),
94  m_processedSize(0), m_userTimestamp(0)
95  {}
96 
97  bool m_autoErrorHandling;
98  bool m_autoWarningHandling;
99  bool m_interactive;
100  TQGuardedPtr<TQWidget> m_errorParentWidget;
101  // Maybe we could use the TQObject parent/child mechanism instead
102  // (requires a new ctor, and moving the ctor code to some init()).
103  Job* m_parentJob;
104  int m_extraFlags;
105  TDEIO::filesize_t m_processedSize;
106  unsigned long m_userTimestamp;
107 };
108 
109 Job::Job(bool showProgressInfo) : TQObject(0, "job"), m_error(0), m_percent(0)
110  , m_progressId(0), m_speedTimer(0), d( new JobPrivate )
111 {
112  // All jobs delete themselves after emiting 'result'.
113 
114  // Notify the UI Server and get a progress id
115  if ( showProgressInfo )
116  {
117  m_progressId = Observer::self()->newJob( this, true );
118  addMetaData("progress-id", TQString::number(m_progressId));
119  //kdDebug(7007) << "Created job " << this << " with progress info -- m_progressId=" << m_progressId << endl;
120  // Connect global progress info signals
121  connect( this, TQT_SIGNAL( percent( TDEIO::Job*, unsigned long ) ),
122  Observer::self(), TQT_SLOT( slotPercent( TDEIO::Job*, unsigned long ) ) );
123  connect( this, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString & ) ),
124  Observer::self(), TQT_SLOT( slotInfoMessage( TDEIO::Job*, const TQString & ) ) );
125  connect( this, TQT_SIGNAL( totalSize( TDEIO::Job*, TDEIO::filesize_t ) ),
126  Observer::self(), TQT_SLOT( slotTotalSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
127  connect( this, TQT_SIGNAL( processedSize( TDEIO::Job*, TDEIO::filesize_t ) ),
128  Observer::self(), TQT_SLOT( slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
129  connect( this, TQT_SIGNAL( speed( TDEIO::Job*, unsigned long ) ),
130  Observer::self(), TQT_SLOT( slotSpeed( TDEIO::Job*, unsigned long ) ) );
131  }
132  // Don't exit while this job is running
133  if (kapp)
134  kapp->ref();
135  if (kapp)
136  updateUserTimestamp( kapp->userTimestamp());
137 }
138 
139 Job::~Job()
140 {
141  delete m_speedTimer;
142  delete d;
143  if (kapp)
144  kapp->deref();
145 }
146 
147 int& Job::extraFlags()
148 {
149  return d->m_extraFlags;
150 }
151 
152 void Job::setProcessedSize(TDEIO::filesize_t size)
153 {
154  d->m_processedSize = size;
155 }
156 
157 TDEIO::filesize_t Job::getProcessedSize()
158 {
159  return d->m_processedSize;
160 }
161 
162 void Job::addSubjob(Job *job, bool inheritMetaData)
163 {
164  //kdDebug(7007) << "addSubjob(" << job << ") this = " << this << endl;
165  subjobs.append(job);
166 
167  connect( job, TQT_SIGNAL(result(TDEIO::Job*)),
168  TQT_SLOT(slotResult(TDEIO::Job*)) );
169 
170  // Forward information from that subjob.
171  connect( job, TQT_SIGNAL(speed( TDEIO::Job*, unsigned long )),
172  TQT_SLOT(slotSpeed(TDEIO::Job*, unsigned long)) );
173 
174  connect( job, TQT_SIGNAL(infoMessage( TDEIO::Job*, const TQString & )),
175  TQT_SLOT(slotInfoMessage(TDEIO::Job*, const TQString &)) );
176 
177  if (inheritMetaData)
178  job->mergeMetaData(m_outgoingMetaData);
179 
180  job->setWindow( m_window );
181  job->updateUserTimestamp( d->m_userTimestamp );
182 }
183 
184 void Job::removeSubjob( Job *job )
185 {
186  removeSubjob( job, false, true );
187 }
188 
189 void Job::removeSubjob( Job *job, bool mergeMetaData, bool emitResultIfLast )
190 {
191  //kdDebug(7007) << "removeSubjob(" << job << ") this = " << this << " subjobs = " << subjobs.count() << endl;
192  // Merge metadata from subjob
193  if ( mergeMetaData )
194  m_incomingMetaData += job->metaData();
195  subjobs.remove(job);
196  if ( subjobs.isEmpty() && emitResultIfLast )
197  emitResult();
198 }
199 
200 void Job::emitPercent( TDEIO::filesize_t processedSize, TDEIO::filesize_t totalSize )
201 {
202  // calculate percents
203  unsigned long ipercent = m_percent;
204 
205  if ( totalSize == 0 )
206  m_percent = 100;
207  else
208  m_percent = (unsigned long)(( (float)(processedSize) / (float)(totalSize) ) * 100.0);
209 
210  if ( m_percent != ipercent || m_percent == 100 /* for those buggy total sizes that grow */ ) {
211  emit percent( this, m_percent );
212  //kdDebug(7007) << "Job::emitPercent - percent = " << (unsigned int) m_percent << endl;
213  }
214 }
215 
216 void Job::emitSpeed( unsigned long bytes_per_second )
217 {
218  //kdDebug(7007) << "Job " << this << " emitSpeed " << bytes_per_second << endl;
219  if ( !m_speedTimer )
220  {
221  m_speedTimer = new TQTimer();
222  connect( m_speedTimer, TQT_SIGNAL( timeout() ), TQT_SLOT( slotSpeedTimeout() ) );
223  }
224  emit speed( this, bytes_per_second );
225  m_speedTimer->start( 5000 ); // 5 seconds interval should be enough
226 }
227 
228 void Job::emitResult()
229 {
230  // If we are displaying a progress dialog, remove it first.
231  if ( m_progressId ) // Did we get an ID from the observer ?
232  Observer::self()->jobFinished( m_progressId );
233  if ( m_error && d->m_interactive && d->m_autoErrorHandling )
234  showErrorDialog( d->m_errorParentWidget );
235  emit result(this);
236  deleteLater();
237 }
238 
239 void Job::kill( bool quietly )
240 {
241  kdDebug(7007) << "Job::kill this=" << this << " " << className() << " m_progressId=" << m_progressId << " quietly=" << quietly << endl;
242  // kill all subjobs, without triggering their result slot
243  TQPtrListIterator<Job> it( subjobs );
244  for ( ; it.current() ; ++it )
245  (*it)->kill( true );
246  subjobs.clear();
247 
248  if ( ! quietly ) {
249  m_error = ERR_USER_CANCELED;
250  emit canceled( this ); // Not very useful (deprecated)
251  emitResult();
252  } else
253  {
254  if ( m_progressId ) // in both cases we want to hide the progress window
255  Observer::self()->jobFinished( m_progressId );
256  deleteLater();
257  }
258 }
259 
260 void Job::slotResult( Job *job )
261 {
262  // Did job have an error ?
263  if ( job->error() && !m_error )
264  {
265  // Store it in the parent only if first error
266  m_error = job->error();
267  m_errorText = job->errorText();
268  }
269  removeSubjob(job);
270 }
271 
272 void Job::slotSpeed( TDEIO::Job*, unsigned long speed )
273 {
274  //kdDebug(7007) << "Job::slotSpeed " << speed << endl;
275  emitSpeed( speed );
276 }
277 
278 void Job::slotInfoMessage( TDEIO::Job*, const TQString & msg )
279 {
280  emit infoMessage( this, msg );
281 }
282 
283 void Job::slotSpeedTimeout()
284 {
285  //kdDebug(7007) << "slotSpeedTimeout()" << endl;
286  // send 0 and stop the timer
287  // timer will be restarted only when we receive another speed event
288  emit speed( this, 0 );
289  m_speedTimer->stop();
290 }
291 
292 //Job::errorString is implemented in global.cpp
293 
294 void Job::showErrorDialog( TQWidget * parent )
295 {
296  //kdDebug(7007) << "Job::showErrorDialog parent=" << parent << endl;
297  kapp->enableStyles();
298  // Show a message box, except for "user canceled" or "no content"
299  if ( (m_error != ERR_USER_CANCELED) && (m_error != ERR_NO_CONTENT) ) {
300  //old plain error message
301  //kdDebug(7007) << "Default language: " << TDEGlobal::locale()->defaultLanguage() << endl;
302  if ( 1 )
303  KMessageBox::queuedMessageBox( parent, KMessageBox::Error, errorString() );
304 #if 0
305  } else {
306  TQStringList errors = detailedErrorStrings();
307  TQString caption, err, detail;
308  TQStringList::const_iterator it = errors.begin();
309  if ( it != errors.end() )
310  caption = *(it++);
311  if ( it != errors.end() )
312  err = *(it++);
313  if ( it != errors.end() )
314  detail = *it;
315  KMessageBox::queuedDetailedError( parent, err, detail, caption );
316  }
317 #endif
318  }
319 }
320 
321 void Job::setAutoErrorHandlingEnabled( bool enable, TQWidget *parentWidget )
322 {
323  d->m_autoErrorHandling = enable;
324  d->m_errorParentWidget = parentWidget;
325 }
326 
327 bool Job::isAutoErrorHandlingEnabled() const
328 {
329  return d->m_autoErrorHandling;
330 }
331 
332 void Job::setAutoWarningHandlingEnabled( bool enable )
333 {
334  d->m_autoWarningHandling = enable;
335 }
336 
337 bool Job::isAutoWarningHandlingEnabled() const
338 {
339  return d->m_autoWarningHandling;
340 }
341 
342 void Job::setInteractive(bool enable)
343 {
344  d->m_interactive = enable;
345 }
346 
347 bool Job::isInteractive() const
348 {
349  return d->m_interactive;
350 }
351 
352 void Job::setWindow(TQWidget *window)
353 {
354  m_window = window;
355  TDEIO::Scheduler::registerWindow(window);
356 }
357 
358 TQWidget *Job::window() const
359 {
360  return m_window;
361 }
362 
363 void Job::updateUserTimestamp( unsigned long time )
364 {
365 #if defined Q_WS_X11
366  if( d->m_userTimestamp == 0 || NET::timestampCompare( time, d->m_userTimestamp ) > 0 )
367  d->m_userTimestamp = time;
368 #endif
369 }
370 
371 unsigned long Job::userTimestamp() const
372 {
373  return d->m_userTimestamp;
374 }
375 
376 void Job::setParentJob(Job* job)
377 {
378  Q_ASSERT(d->m_parentJob == 0L);
379  Q_ASSERT(job);
380  d->m_parentJob = job;
381 }
382 
383 Job* Job::parentJob() const
384 {
385  return d->m_parentJob;
386 }
387 
388 MetaData Job::metaData() const
389 {
390  return m_incomingMetaData;
391 }
392 
393 TQString Job::queryMetaData(const TQString &key)
394 {
395  if (!m_incomingMetaData.contains(key))
396  return TQString::null;
397  return m_incomingMetaData[key];
398 }
399 
400 void Job::setMetaData( const TDEIO::MetaData &_metaData)
401 {
402  m_outgoingMetaData = _metaData;
403 }
404 
405 void Job::addMetaData( const TQString &key, const TQString &value)
406 {
407  m_outgoingMetaData.insert(key, value);
408 }
409 
410 void Job::addMetaData( const TQMap<TQString,TQString> &values)
411 {
412  TQMapConstIterator<TQString,TQString> it = values.begin();
413  for(;it != values.end(); ++it)
414  m_outgoingMetaData.insert(it.key(), it.data());
415 }
416 
417 void Job::mergeMetaData( const TQMap<TQString,TQString> &values)
418 {
419  TQMapConstIterator<TQString,TQString> it = values.begin();
420  for(;it != values.end(); ++it)
421  m_outgoingMetaData.insert(it.key(), it.data(), false);
422 }
423 
424 MetaData Job::outgoingMetaData() const
425 {
426  return m_outgoingMetaData;
427 }
428 
429 
430 SimpleJob::SimpleJob(const KURL& url, int command, const TQByteArray &packedArgs,
431  bool showProgressInfo )
432  : Job(showProgressInfo), m_slave(0), m_packedArgs(packedArgs),
433  m_url(url), m_command(command), m_totalSize(0)
434 {
435  if (m_url.hasSubURL())
436  {
437  KURL::List list = KURL::split(m_url);
438  KURL::List::Iterator it = list.fromLast();
439  list.remove(it);
440  m_subUrl = KURL::join(list);
441  //kdDebug(7007) << "New URL = " << m_url.url() << endl;
442  //kdDebug(7007) << "Sub URL = " << m_subUrl.url() << endl;
443  }
444 
445  Scheduler::doJob(this);
446 
447  if (!m_url.isValid())
448  {
449  kdDebug() << "ERR_MALFORMED_URL" << endl;
450  m_error = ERR_MALFORMED_URL;
451  m_errorText = m_url.url();
452  TQTimer::singleShot(0, this, TQT_SLOT(slotFinished()) );
453  return;
454  }
455 }
456 
457 void SimpleJob::kill( bool quietly )
458 {
459  Scheduler::cancelJob( this ); // deletes the slave if not 0
460  m_slave = 0; // -> set to 0
461  Job::kill( quietly );
462 }
463 
464 void SimpleJob::putOnHold()
465 {
466  Q_ASSERT( m_slave );
467  if ( m_slave )
468  {
469  Scheduler::putSlaveOnHold(this, m_url);
470  m_slave = 0;
471  }
472  kill(true);
473 }
474 
475 void SimpleJob::removeOnHold()
476 {
477  Scheduler::removeSlaveOnHold();
478 }
479 
480 SimpleJob::~SimpleJob()
481 {
482  if (m_slave) // was running
483  {
484  kdDebug(7007) << "SimpleJob::~SimpleJob: Killing running job in destructor!" << endl;
485 #if 0
486  m_slave->kill();
487  Scheduler::jobFinished( this, m_slave ); // deletes the slave
488 #endif
489  Scheduler::cancelJob( this );
490  m_slave = 0; // -> set to 0
491  }
492 }
493 
494 void SimpleJob::start(Slave *slave)
495 {
496  m_slave = slave;
497 
498  connect( m_slave, TQT_SIGNAL( error( int , const TQString & ) ),
499  TQT_SLOT( slotError( int , const TQString & ) ) );
500 
501  connect( m_slave, TQT_SIGNAL( warning( const TQString & ) ),
502  TQT_SLOT( slotWarning( const TQString & ) ) );
503 
504  connect( m_slave, TQT_SIGNAL( infoMessage( const TQString & ) ),
505  TQT_SLOT( slotInfoMessage( const TQString & ) ) );
506 
507  connect( m_slave, TQT_SIGNAL( connected() ),
508  TQT_SLOT( slotConnected() ) );
509 
510  connect( m_slave, TQT_SIGNAL( finished() ),
511  TQT_SLOT( slotFinished() ) );
512 
513  if ((extraFlags() & EF_TransferJobDataSent) == 0)
514  {
515  connect( m_slave, TQT_SIGNAL( totalSize( TDEIO::filesize_t ) ),
516  TQT_SLOT( slotTotalSize( TDEIO::filesize_t ) ) );
517 
518  connect( m_slave, TQT_SIGNAL( processedSize( TDEIO::filesize_t ) ),
519  TQT_SLOT( slotProcessedSize( TDEIO::filesize_t ) ) );
520 
521  connect( m_slave, TQT_SIGNAL( speed( unsigned long ) ),
522  TQT_SLOT( slotSpeed( unsigned long ) ) );
523  }
524 
525  connect( slave, TQT_SIGNAL( needProgressId() ),
526  TQT_SLOT( slotNeedProgressId() ) );
527 
528  connect( slave, TQT_SIGNAL(metaData( const TDEIO::MetaData& ) ),
529  TQT_SLOT( slotMetaData( const TDEIO::MetaData& ) ) );
530 
531  if (m_window)
532  {
533  TQString id;
534  addMetaData("window-id", id.setNum((ulong)m_window->winId()));
535  }
536  if (userTimestamp())
537  {
538  TQString id;
539  addMetaData("user-timestamp", id.setNum(userTimestamp()));
540  }
541 
542  TQString sslSession = KSSLCSessionCache::getSessionForURL(m_url);
543  if ( !sslSession.isNull() )
544  {
545  addMetaData("ssl_session_id", sslSession);
546  }
547 
548  if (!isInteractive())
549  {
550  addMetaData("no-auth-prompt", "true");
551  }
552 
553  if (!m_outgoingMetaData.isEmpty())
554  {
555  KIO_ARGS << m_outgoingMetaData;
556  slave->send( CMD_META_DATA, packedArgs );
557  }
558 
559  if (!m_subUrl.isEmpty())
560  {
561  KIO_ARGS << m_subUrl;
562  m_slave->send( CMD_SUBURL, packedArgs );
563  }
564 
565  m_slave->send( m_command, m_packedArgs );
566 }
567 
568 void SimpleJob::slaveDone()
569 {
570  if (!m_slave) return;
571  disconnect(m_slave); // Remove all signals between slave and job
572  Scheduler::jobFinished( this, m_slave );
573  m_slave = 0;
574 }
575 
576 void SimpleJob::slotFinished( )
577 {
578  // Return slave to the scheduler
579  slaveDone();
580 
581  if (subjobs.isEmpty())
582  {
583  if ( !m_error && (m_command == CMD_MKDIR || m_command == CMD_RENAME ) )
584  {
585  KDirNotify_stub allDirNotify( "*", "KDirNotify*" );
586  if ( m_command == CMD_MKDIR )
587  {
588  KURL urlDir( url() );
589  urlDir.setPath( urlDir.directory() );
590  allDirNotify.FilesAdded( urlDir );
591  }
592  else /*if ( m_command == CMD_RENAME )*/
593  {
594  KURL src, dst;
595  TQDataStream str( m_packedArgs, IO_ReadOnly );
596  str >> src >> dst;
597  if ( src.directory() == dst.directory() ) // For the user, moving isn't renaming. Only renaming is.
598  allDirNotify.FileRenamed( src, dst );
599  }
600  }
601  emitResult();
602  }
603 }
604 
605 void SimpleJob::slotError( int error, const TQString & errorText )
606 {
607  m_error = error;
608  m_errorText = errorText;
609  if ((m_error == ERR_UNKNOWN_HOST) && m_url.host().isEmpty())
610  m_errorText = TQString::null;
611  // error terminates the job
612  slotFinished();
613 }
614 
615 void SimpleJob::slotWarning( const TQString & errorText )
616 {
617  TQGuardedPtr<SimpleJob> guard( this );
618  if (isInteractive() && isAutoWarningHandlingEnabled())
619  {
620  static uint msgBoxDisplayed = 0;
621  if ( msgBoxDisplayed == 0 ) // don't bomb the user with message boxes, only one at a time
622  {
623  msgBoxDisplayed++;
624  KMessageBox::information( 0L, errorText );
625  msgBoxDisplayed--;
626  }
627  // otherwise just discard it.
628  }
629 
630  if ( !guard.isNull() )
631  emit warning( this, errorText );
632 }
633 
634 void SimpleJob::slotInfoMessage( const TQString & msg )
635 {
636  emit infoMessage( this, msg );
637 }
638 
639 void SimpleJob::slotConnected()
640 {
641  emit connected( this );
642 }
643 
644 void SimpleJob::slotNeedProgressId()
645 {
646  if ( !m_progressId )
647  m_progressId = Observer::self()->newJob( this, false );
648  m_slave->setProgressId( m_progressId );
649 }
650 
651 void SimpleJob::slotTotalSize( TDEIO::filesize_t size )
652 {
653  if (size > m_totalSize)
654  {
655  m_totalSize = size;
656  emit totalSize( this, size );
657  }
658 }
659 
660 void SimpleJob::slotProcessedSize( TDEIO::filesize_t size )
661 {
662  //kdDebug(7007) << "SimpleJob::slotProcessedSize " << TDEIO::number(size) << endl;
663  setProcessedSize(size);
664  emit processedSize( this, size );
665  if ( size > m_totalSize ) {
666  slotTotalSize(size); // safety
667  }
668  emitPercent( size, m_totalSize );
669 }
670 
671 void SimpleJob::slotSpeed( unsigned long speed )
672 {
673  //kdDebug(7007) << "SimpleJob::slotSpeed( " << speed << " )" << endl;
674  emitSpeed( speed );
675 }
676 
677 void SimpleJob::slotMetaData( const TDEIO::MetaData &_metaData)
678 {
679  m_incomingMetaData += _metaData;
680 }
681 
682 void SimpleJob::storeSSLSessionFromJob(const KURL &m_redirectionURL) {
683  TQString sslSession = queryMetaData("ssl_session_id");
684 
685  if ( !sslSession.isNull() ) {
686  const KURL &queryURL = m_redirectionURL.isEmpty()?m_url:m_redirectionURL;
687  KSSLCSessionCache::putSessionForURL(queryURL, sslSession);
688  }
689 }
690 
692 MkdirJob::MkdirJob( const KURL& url, int command,
693  const TQByteArray &packedArgs, bool showProgressInfo )
694  : SimpleJob(url, command, packedArgs, showProgressInfo)
695 {
696 }
697 
698 void MkdirJob::start(Slave *slave)
699 {
700  connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
701  TQT_SLOT( slotRedirection(const KURL &) ) );
702 
703  SimpleJob::start(slave);
704 }
705 
706 // Slave got a redirection request
707 void MkdirJob::slotRedirection( const KURL &url)
708 {
709  kdDebug(7007) << "MkdirJob::slotRedirection(" << url << ")" << endl;
710  if (!kapp->authorizeURLAction("redirect", m_url, url))
711  {
712  kdWarning(7007) << "MkdirJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
713  m_error = ERR_ACCESS_DENIED;
714  m_errorText = url.prettyURL();
715  return;
716  }
717  m_redirectionURL = url; // We'll remember that when the job finishes
718  if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
719  m_redirectionURL.setUser(m_url.user()); // Preserve user
720  // Tell the user that we haven't finished yet
721  emit redirection(this, m_redirectionURL);
722 }
723 
724 void MkdirJob::slotFinished()
725 {
726  if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
727  {
728  // Return slave to the scheduler
729  SimpleJob::slotFinished();
730  } else {
731  //kdDebug(7007) << "MkdirJob: Redirection to " << m_redirectionURL << endl;
732  if (queryMetaData("permanent-redirect")=="true")
733  emit permanentRedirection(this, m_url, m_redirectionURL);
734  KURL dummyUrl;
735  int permissions;
736  TQDataStream istream( m_packedArgs, IO_ReadOnly );
737  istream >> dummyUrl >> permissions;
738 
739  m_url = m_redirectionURL;
740  m_redirectionURL = KURL();
741  m_packedArgs.truncate(0);
742  TQDataStream stream( m_packedArgs, IO_WriteOnly );
743  stream << m_url << permissions;
744 
745  // Return slave to the scheduler
746  slaveDone();
747  Scheduler::doJob(this);
748  }
749 }
750 
751 SimpleJob *TDEIO::mkdir( const KURL& url, int permissions )
752 {
753  //kdDebug(7007) << "mkdir " << url << endl;
754  KIO_ARGS << url << permissions;
755  return new MkdirJob(url, CMD_MKDIR, packedArgs, false);
756 }
757 
758 SimpleJob *TDEIO::rmdir( const KURL& url )
759 {
760  //kdDebug(7007) << "rmdir " << url << endl;
761  KIO_ARGS << url << TQ_INT8(false); // isFile is false
762  return new SimpleJob(url, CMD_DEL, packedArgs, false);
763 }
764 
765 SimpleJob *TDEIO::chmod( const KURL& url, int permissions )
766 {
767  //kdDebug(7007) << "chmod " << url << endl;
768  KIO_ARGS << url << permissions;
769  return new SimpleJob(url, CMD_CHMOD, packedArgs, false);
770 }
771 
772 SimpleJob *TDEIO::rename( const KURL& src, const KURL & dest, bool overwrite )
773 {
774  //kdDebug(7007) << "rename " << src << " " << dest << endl;
775  KIO_ARGS << src << dest << (TQ_INT8) overwrite;
776  return new SimpleJob(src, CMD_RENAME, packedArgs, false);
777 }
778 
779 SimpleJob *TDEIO::symlink( const TQString& target, const KURL & dest, bool overwrite, bool showProgressInfo )
780 {
781  //kdDebug(7007) << "symlink target=" << target << " " << dest << endl;
782  KIO_ARGS << target << dest << (TQ_INT8) overwrite;
783  return new SimpleJob(dest, CMD_SYMLINK, packedArgs, showProgressInfo);
784 }
785 
786 SimpleJob *TDEIO::special(const KURL& url, const TQByteArray & data, bool showProgressInfo)
787 {
788  //kdDebug(7007) << "special " << url << endl;
789  return new SimpleJob(url, CMD_SPECIAL, data, showProgressInfo);
790 }
791 
792 SimpleJob *TDEIO::mount( bool ro, const char *fstype, const TQString& dev, const TQString& point, bool showProgressInfo )
793 {
794  KIO_ARGS << int(1) << TQ_INT8( ro ? 1 : 0 )
795  << TQString::fromLatin1(fstype) << dev << point;
796  SimpleJob *job = special( KURL("file:/"), packedArgs, showProgressInfo );
797  if ( showProgressInfo )
798  Observer::self()->mounting( job, dev, point );
799  return job;
800 }
801 
802 SimpleJob *TDEIO::unmount( const TQString& point, bool showProgressInfo )
803 {
804  KIO_ARGS << int(2) << point;
805  SimpleJob *job = special( KURL("file:/"), packedArgs, showProgressInfo );
806  if ( showProgressInfo )
807  Observer::self()->unmounting( job, point );
808  return job;
809 }
810 
812 LocalURLJob::LocalURLJob( const KURL& url, int command,
813  const TQByteArray &packedArgs, bool showProgressInfo )
814  : SimpleJob(url, command, packedArgs, showProgressInfo)
815 {
816 
817 }
818 
819 void LocalURLJob::start(Slave *slave)
820 {
821  connect( slave, TQT_SIGNAL( localURL(const KURL &, bool) ),
822  TQT_SLOT( slotLocalURL(const KURL &, bool) ) );
823 
824  SimpleJob::start(slave);
825 }
826 
827 // Slave sent a response!
828 void LocalURLJob::slotLocalURL(const KURL &url, bool isLocal)
829 {
830  kdDebug(7007) << "LocalURLJob::slotLocalURL(" << url << ")" << endl;
831  emit localURL(this, url, isLocal);
832 }
833 
834 void LocalURLJob::slotFinished()
835 {
836  // Return slave to the scheduler
837  SimpleJob::slotFinished();
838 }
839 
840 LocalURLJob *TDEIO::localURL( const KURL& remoteUrl )
841 {
842  KIO_ARGS << remoteUrl;
843  return new LocalURLJob(remoteUrl, CMD_LOCALURL, packedArgs, false);
844 }
845 
846 
848 
849 StatJob::StatJob( const KURL& url, int command,
850  const TQByteArray &packedArgs, bool showProgressInfo )
851  : SimpleJob(url, command, packedArgs, showProgressInfo),
852  m_bSource(true), m_details(2)
853 {
854 }
855 
856 void StatJob::start(Slave *slave)
857 {
858  m_outgoingMetaData.replace( "statSide", m_bSource ? "source" : "dest" );
859  m_outgoingMetaData.replace( "details", TQString::number(m_details) );
860 
861  connect( slave, TQT_SIGNAL( statEntry( const TDEIO::UDSEntry& ) ),
862  TQT_SLOT( slotStatEntry( const TDEIO::UDSEntry & ) ) );
863  connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
864  TQT_SLOT( slotRedirection(const KURL &) ) );
865 
866  SimpleJob::start(slave);
867 }
868 
869 void StatJob::slotStatEntry( const TDEIO::UDSEntry & entry )
870 {
871  //kdDebug(7007) << "StatJob::slotStatEntry" << endl;
872  m_statResult = entry;
873 }
874 
875 // Slave got a redirection request
876 void StatJob::slotRedirection( const KURL &url)
877 {
878  kdDebug(7007) << "StatJob::slotRedirection(" << url << ")" << endl;
879  if (!kapp->authorizeURLAction("redirect", m_url, url))
880  {
881  kdWarning(7007) << "StatJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
882  m_error = ERR_ACCESS_DENIED;
883  m_errorText = url.prettyURL();
884  return;
885  }
886  m_redirectionURL = url; // We'll remember that when the job finishes
887  if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
888  m_redirectionURL.setUser(m_url.user()); // Preserve user
889  // Tell the user that we haven't finished yet
890  emit redirection(this, m_redirectionURL);
891 }
892 
893 void StatJob::slotFinished()
894 {
895  if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
896  {
897  // Return slave to the scheduler
898  SimpleJob::slotFinished();
899  } else {
900  //kdDebug(7007) << "StatJob: Redirection to " << m_redirectionURL << endl;
901  if (queryMetaData("permanent-redirect")=="true")
902  emit permanentRedirection(this, m_url, m_redirectionURL);
903  m_url = m_redirectionURL;
904  m_redirectionURL = KURL();
905  m_packedArgs.truncate(0);
906  TQDataStream stream( m_packedArgs, IO_WriteOnly );
907  stream << m_url;
908 
909  // Return slave to the scheduler
910  slaveDone();
911  Scheduler::doJob(this);
912  }
913 }
914 
915 void StatJob::slotMetaData( const TDEIO::MetaData &_metaData) {
916  SimpleJob::slotMetaData(_metaData);
917  storeSSLSessionFromJob(m_redirectionURL);
918 }
919 
920 StatJob *TDEIO::stat(const KURL& url, bool showProgressInfo)
921 {
922  // Assume sideIsSource. Gets are more common than puts.
923  return stat( url, true, 2, showProgressInfo );
924 }
925 
926 StatJob *TDEIO::stat(const KURL& url, bool sideIsSource, short int details, bool showProgressInfo)
927 {
928  kdDebug(7007) << "stat " << url << endl;
929  KIO_ARGS << url;
930  StatJob * job = new StatJob(url, CMD_STAT, packedArgs, showProgressInfo );
931  job->setSide( sideIsSource );
932  job->setDetails( details );
933  if ( showProgressInfo )
934  Observer::self()->stating( job, url );
935  return job;
936 }
937 
938 SimpleJob *TDEIO::http_update_cache( const KURL& url, bool no_cache, time_t expireDate)
939 {
940  assert( (url.protocol() == "http") || (url.protocol() == "https") );
941  // Send http update_cache command (2)
942  KIO_ARGS << (int)2 << url << no_cache << expireDate;
943  SimpleJob * job = new SimpleJob( url, CMD_SPECIAL, packedArgs, false );
944  Scheduler::scheduleJob(job);
945  return job;
946 }
947 
949 
950 TransferJob::TransferJob( const KURL& url, int command,
951  const TQByteArray &packedArgs,
952  const TQByteArray &_staticData,
953  bool showProgressInfo)
954  : SimpleJob(url, command, packedArgs, showProgressInfo), staticData( _staticData)
955 {
956  m_suspended = false;
957  m_errorPage = false;
958  m_subJob = 0L;
959  if ( showProgressInfo )
960  Observer::self()->slotTransferring( this, url );
961 }
962 
963 // Slave sends data
964 void TransferJob::slotData( const TQByteArray &_data)
965 {
966  if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error)
967  emit data( this, _data);
968 }
969 
970 // Slave got a redirection request
971 void TransferJob::slotRedirection( const KURL &url)
972 {
973  kdDebug(7007) << "TransferJob::slotRedirection(" << url << ")" << endl;
974  if (!kapp->authorizeURLAction("redirect", m_url, url))
975  {
976  kdWarning(7007) << "TransferJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
977  return;
978  }
979 
980  // Some websites keep redirecting to themselves where each redirection
981  // acts as the stage in a state-machine. We define "endless redirections"
982  // as 5 redirections to the same URL.
983  if (m_redirectionList.contains(url) > 5)
984  {
985  kdDebug(7007) << "TransferJob::slotRedirection: CYCLIC REDIRECTION!" << endl;
986  m_error = ERR_CYCLIC_LINK;
987  m_errorText = m_url.prettyURL();
988  }
989  else
990  {
991  m_redirectionURL = url; // We'll remember that when the job finishes
992  if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
993  m_redirectionURL.setUser(m_url.user()); // Preserve user
994  m_redirectionList.append(url);
995  m_outgoingMetaData["ssl_was_in_use"] = m_incomingMetaData["ssl_in_use"];
996  // Tell the user that we haven't finished yet
997  emit redirection(this, m_redirectionURL);
998  }
999 }
1000 
1001 void TransferJob::slotFinished()
1002 {
1003  //kdDebug(7007) << "TransferJob::slotFinished(" << this << ", " << m_url << ")" << endl;
1004  if (m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
1005  SimpleJob::slotFinished();
1006  else {
1007  //kdDebug(7007) << "TransferJob: Redirection to " << m_redirectionURL << endl;
1008  if (queryMetaData("permanent-redirect")=="true")
1009  emit permanentRedirection(this, m_url, m_redirectionURL);
1010  // Honour the redirection
1011  // We take the approach of "redirecting this same job"
1012  // Another solution would be to create a subjob, but the same problem
1013  // happens (unpacking+repacking)
1014  staticData.truncate(0);
1015  m_incomingMetaData.clear();
1016  if (queryMetaData("cache") != "reload")
1017  addMetaData("cache","refresh");
1018  m_suspended = false;
1019  m_url = m_redirectionURL;
1020  m_redirectionURL = KURL();
1021  // The very tricky part is the packed arguments business
1022  TQString dummyStr;
1023  KURL dummyUrl;
1024  TQDataStream istream( m_packedArgs, IO_ReadOnly );
1025  switch( m_command ) {
1026  case CMD_GET: {
1027  m_packedArgs.truncate(0);
1028  TQDataStream stream( m_packedArgs, IO_WriteOnly );
1029  stream << m_url;
1030  break;
1031  }
1032  case CMD_PUT: {
1033  int permissions;
1034  TQ_INT8 iOverwrite, iResume;
1035  istream >> dummyUrl >> iOverwrite >> iResume >> permissions;
1036  m_packedArgs.truncate(0);
1037  TQDataStream stream( m_packedArgs, IO_WriteOnly );
1038  stream << m_url << iOverwrite << iResume << permissions;
1039  break;
1040  }
1041  case CMD_SPECIAL: {
1042  int specialcmd;
1043  istream >> specialcmd;
1044  if (specialcmd == 1) // HTTP POST
1045  {
1046  addMetaData("cache","reload");
1047  m_packedArgs.truncate(0);
1048  TQDataStream stream( m_packedArgs, IO_WriteOnly );
1049  stream << m_url;
1050  m_command = CMD_GET;
1051  }
1052  break;
1053  }
1054  }
1055 
1056  // Return slave to the scheduler
1057  slaveDone();
1058  Scheduler::doJob(this);
1059  }
1060 }
1061 
1062 void TransferJob::setAsyncDataEnabled(bool enabled)
1063 {
1064  if (enabled)
1065  extraFlags() |= EF_TransferJobAsync;
1066  else
1067  extraFlags() &= ~EF_TransferJobAsync;
1068 }
1069 
1070 void TransferJob::sendAsyncData(const TQByteArray &dataForSlave)
1071 {
1072  if (extraFlags() & EF_TransferJobNeedData)
1073  {
1074  m_slave->send( MSG_DATA, dataForSlave );
1075  if (extraFlags() & EF_TransferJobDataSent)
1076  {
1077  TDEIO::filesize_t size = getProcessedSize()+dataForSlave.size();
1078  setProcessedSize(size);
1079  emit processedSize( this, size );
1080  if ( size > m_totalSize ) {
1081  slotTotalSize(size); // safety
1082  }
1083  emitPercent( size, m_totalSize );
1084  }
1085  }
1086 
1087  extraFlags() &= ~EF_TransferJobNeedData;
1088 }
1089 
1090 void TransferJob::setReportDataSent(bool enabled)
1091 {
1092  if (enabled)
1093  extraFlags() |= EF_TransferJobDataSent;
1094  else
1095  extraFlags() &= ~EF_TransferJobDataSent;
1096 }
1097 
1098 bool TransferJob::reportDataSent()
1099 {
1100  return (extraFlags() & EF_TransferJobDataSent);
1101 }
1102 
1103 
1104 // Slave requests data
1105 void TransferJob::slotDataReq()
1106 {
1107  TQByteArray dataForSlave;
1108 
1109  extraFlags() |= EF_TransferJobNeedData;
1110 
1111  if (!staticData.isEmpty())
1112  {
1113  dataForSlave = staticData;
1114  staticData = TQByteArray();
1115  }
1116  else
1117  {
1118  emit dataReq( this, dataForSlave);
1119 
1120  if (extraFlags() & EF_TransferJobAsync)
1121  return;
1122  }
1123 
1124  static const size_t max_size = 14 * 1024 * 1024;
1125  if (dataForSlave.size() > max_size)
1126  {
1127  kdDebug(7007) << "send " << dataForSlave.size() / 1024 / 1024 << "MB of data in TransferJob::dataReq. This needs to be splitted, which requires a copy. Fix the application.\n";
1128  staticData.duplicate(dataForSlave.data() + max_size , dataForSlave.size() - max_size);
1129  dataForSlave.truncate(max_size);
1130  }
1131 
1132  sendAsyncData(dataForSlave);
1133 
1134  if (m_subJob)
1135  {
1136  // Bitburger protocol in action
1137  suspend(); // Wait for more data from subJob.
1138  m_subJob->resume(); // Ask for more!
1139  }
1140 }
1141 
1142 void TransferJob::slotMimetype( const TQString& type )
1143 {
1144  m_mimetype = type;
1145  emit mimetype( this, m_mimetype);
1146 }
1147 
1148 
1149 void TransferJob::suspend()
1150 {
1151  m_suspended = true;
1152  if (m_slave)
1153  m_slave->suspend();
1154 }
1155 
1156 void TransferJob::resume()
1157 {
1158  m_suspended = false;
1159  if (m_slave)
1160  m_slave->resume();
1161 }
1162 
1163 void TransferJob::start(Slave *slave)
1164 {
1165  assert(slave);
1166  connect( slave, TQT_SIGNAL( data( const TQByteArray & ) ),
1167  TQT_SLOT( slotData( const TQByteArray & ) ) );
1168 
1169  connect( slave, TQT_SIGNAL( dataReq() ),
1170  TQT_SLOT( slotDataReq() ) );
1171 
1172  connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
1173  TQT_SLOT( slotRedirection(const KURL &) ) );
1174 
1175  connect( slave, TQT_SIGNAL(mimeType( const TQString& ) ),
1176  TQT_SLOT( slotMimetype( const TQString& ) ) );
1177 
1178  connect( slave, TQT_SIGNAL(errorPage() ),
1179  TQT_SLOT( slotErrorPage() ) );
1180 
1181  connect( slave, TQT_SIGNAL( needSubURLData() ),
1182  TQT_SLOT( slotNeedSubURLData() ) );
1183 
1184  connect( slave, TQT_SIGNAL(canResume( TDEIO::filesize_t ) ),
1185  TQT_SLOT( slotCanResume( TDEIO::filesize_t ) ) );
1186 
1187  if (slave->suspended())
1188  {
1189  m_mimetype = "unknown";
1190  // WABA: The slave was put on hold. Resume operation.
1191  slave->resume();
1192  }
1193 
1194  SimpleJob::start(slave);
1195  if (m_suspended)
1196  slave->suspend();
1197 }
1198 
1199 void TransferJob::slotNeedSubURLData()
1200 {
1201  // Job needs data from subURL.
1202  m_subJob = TDEIO::get( m_subUrl, false, false);
1203  suspend(); // Put job on hold until we have some data.
1204  connect(m_subJob, TQT_SIGNAL( data(TDEIO::Job*,const TQByteArray &)),
1205  TQT_SLOT( slotSubURLData(TDEIO::Job*,const TQByteArray &)));
1206  addSubjob(m_subJob);
1207 }
1208 
1209 void TransferJob::slotSubURLData(TDEIO::Job*, const TQByteArray &data)
1210 {
1211  // The Alternating Bitburg protocol in action again.
1212  staticData = data;
1213  m_subJob->suspend(); // Put job on hold until we have delivered the data.
1214  resume(); // Activate ourselves again.
1215 }
1216 
1217 void TransferJob::slotMetaData( const TDEIO::MetaData &_metaData) {
1218  SimpleJob::slotMetaData(_metaData);
1219  storeSSLSessionFromJob(m_redirectionURL);
1220 }
1221 
1222 void TransferJob::slotErrorPage()
1223 {
1224  m_errorPage = true;
1225 }
1226 
1227 void TransferJob::slotCanResume( TDEIO::filesize_t offset )
1228 {
1229  emit canResume(this, offset);
1230 }
1231 
1232 void TransferJob::slotResult( TDEIO::Job *job)
1233 {
1234  // This can only be our suburl.
1235  assert(job == m_subJob);
1236  // Did job have an error ?
1237  if ( job->error() )
1238  {
1239  m_error = job->error();
1240  m_errorText = job->errorText();
1241 
1242  emitResult();
1243  return;
1244  }
1245 
1246  if (job == m_subJob)
1247  {
1248  m_subJob = 0; // No action required
1249  resume(); // Make sure we get the remaining data.
1250  }
1251  removeSubjob( job, false, false ); // Remove job, but don't kill this job.
1252 }
1253 
1254 TransferJob *TDEIO::get( const KURL& url, bool reload, bool showProgressInfo )
1255 {
1256  // Send decoded path and encoded query
1257  KIO_ARGS << url;
1258  TransferJob * job = new TransferJob( url, CMD_GET, packedArgs, TQByteArray(), showProgressInfo );
1259  if (reload)
1260  job->addMetaData("cache", "reload");
1261  return job;
1262 }
1263 
1264 class PostErrorJob : public TransferJob
1265 {
1266 public:
1267 
1268  PostErrorJob(int _error, const TQString& url, const TQByteArray &packedArgs, const TQByteArray &postData, bool showProgressInfo)
1269  : TransferJob(KURL(), CMD_SPECIAL, packedArgs, postData, showProgressInfo)
1270  {
1271  m_error = _error;
1272  m_errorText = url;
1273  }
1274 
1275 };
1276 
1277 TransferJob *TDEIO::http_post( const KURL& url, const TQByteArray &postData, bool showProgressInfo )
1278 {
1279  int _error = 0;
1280 
1281  // filter out some malicious ports
1282  static const int bad_ports[] = {
1283  1, // tcpmux
1284  7, // echo
1285  9, // discard
1286  11, // systat
1287  13, // daytime
1288  15, // netstat
1289  17, // qotd
1290  19, // chargen
1291  20, // ftp-data
1292  21, // ftp-cntl
1293  22, // ssh
1294  23, // telnet
1295  25, // smtp
1296  37, // time
1297  42, // name
1298  43, // nicname
1299  53, // domain
1300  77, // priv-rjs
1301  79, // finger
1302  87, // ttylink
1303  95, // supdup
1304  101, // hostriame
1305  102, // iso-tsap
1306  103, // gppitnp
1307  104, // acr-nema
1308  109, // pop2
1309  110, // pop3
1310  111, // sunrpc
1311  113, // auth
1312  115, // sftp
1313  117, // uucp-path
1314  119, // nntp
1315  123, // NTP
1316  135, // loc-srv / epmap
1317  139, // netbios
1318  143, // imap2
1319  179, // BGP
1320  389, // ldap
1321  512, // print / exec
1322  513, // login
1323  514, // shell
1324  515, // printer
1325  526, // tempo
1326  530, // courier
1327  531, // Chat
1328  532, // netnews
1329  540, // uucp
1330  556, // remotefs
1331  587, // sendmail
1332  601, //
1333  989, // ftps data
1334  990, // ftps
1335  992, // telnets
1336  993, // imap/SSL
1337  995, // pop3/SSL
1338  1080, // SOCKS
1339  2049, // nfs
1340  4045, // lockd
1341  6000, // x11
1342  6667, // irc
1343  0};
1344  for (int cnt=0; bad_ports[cnt]; ++cnt)
1345  if (url.port() == bad_ports[cnt])
1346  {
1347  _error = TDEIO::ERR_POST_DENIED;
1348  break;
1349  }
1350 
1351  if( _error )
1352  {
1353  static bool override_loaded = false;
1354  static TQValueList< int >* overriden_ports = NULL;
1355  if( !override_loaded )
1356  {
1357  TDEConfig cfg( "tdeio_httprc", true );
1358  overriden_ports = new TQValueList< int >;
1359  *overriden_ports = cfg.readIntListEntry( "OverriddenPorts" );
1360  override_loaded = true;
1361  }
1362  for( TQValueList< int >::ConstIterator it = overriden_ports->begin();
1363  it != overriden_ports->end();
1364  ++it )
1365  if( overriden_ports->contains( url.port()))
1366  _error = 0;
1367  }
1368 
1369  // filter out non https? protocols
1370  if ((url.protocol() != "http") && (url.protocol() != "https" ))
1371  _error = TDEIO::ERR_POST_DENIED;
1372 
1373  bool redirection = false;
1374  KURL _url(url);
1375  if (_url.path().isEmpty())
1376  {
1377  redirection = true;
1378  _url.setPath("/");
1379  }
1380 
1381  if (!_error && !kapp->authorizeURLAction("open", KURL(), _url))
1382  _error = TDEIO::ERR_ACCESS_DENIED;
1383 
1384  // if request is not valid, return an invalid transfer job
1385  if (_error)
1386  {
1387  KIO_ARGS << (int)1 << url;
1388  TransferJob * job = new PostErrorJob(_error, url.prettyURL(), packedArgs, postData, showProgressInfo);
1389  return job;
1390  }
1391 
1392  // Send http post command (1), decoded path and encoded query
1393  KIO_ARGS << (int)1 << _url;
1394  TransferJob * job = new TransferJob( _url, CMD_SPECIAL,
1395  packedArgs, postData, showProgressInfo );
1396 
1397  if (redirection)
1398  TQTimer::singleShot(0, job, TQT_SLOT(slotPostRedirection()) );
1399 
1400  return job;
1401 }
1402 
1403 // http post got redirected from http://host to http://host/ by TransferJob
1404 // We must do this redirection ourselves because redirections by the
1405 // slave change post jobs into get jobs.
1406 void TransferJob::slotPostRedirection()
1407 {
1408  kdDebug(7007) << "TransferJob::slotPostRedirection(" << m_url << ")" << endl;
1409  // Tell the user about the new url.
1410  emit redirection(this, m_url);
1411 }
1412 
1413 
1414 TransferJob *TDEIO::put( const KURL& url, int permissions,
1415  bool overwrite, bool resume, bool showProgressInfo )
1416 {
1417  KIO_ARGS << url << TQ_INT8( overwrite ? 1 : 0 ) << TQ_INT8( resume ? 1 : 0 ) << permissions;
1418  TransferJob * job = new TransferJob( url, CMD_PUT, packedArgs, TQByteArray(), showProgressInfo );
1419  return job;
1420 }
1421 
1423 
1424 StoredTransferJob::StoredTransferJob(const KURL& url, int command,
1425  const TQByteArray &packedArgs,
1426  const TQByteArray &_staticData,
1427  bool showProgressInfo)
1428  : TransferJob( url, command, packedArgs, _staticData, showProgressInfo ),
1429  m_uploadOffset( 0 )
1430 {
1431  connect( this, TQT_SIGNAL( data( TDEIO::Job *, const TQByteArray & ) ),
1432  TQT_SLOT( slotStoredData( TDEIO::Job *, const TQByteArray & ) ) );
1433  connect( this, TQT_SIGNAL( dataReq( TDEIO::Job *, TQByteArray & ) ),
1434  TQT_SLOT( slotStoredDataReq( TDEIO::Job *, TQByteArray & ) ) );
1435 }
1436 
1437 void StoredTransferJob::setData( const TQByteArray& arr )
1438 {
1439  Q_ASSERT( m_data.isNull() ); // check that we're only called once
1440  Q_ASSERT( m_uploadOffset == 0 ); // no upload started yet
1441  m_data = arr;
1442 }
1443 
1444 void StoredTransferJob::slotStoredData( TDEIO::Job *, const TQByteArray &data )
1445 {
1446  // check for end-of-data marker:
1447  if ( data.size() == 0 )
1448  return;
1449  unsigned int oldSize = m_data.size();
1450  m_data.resize( oldSize + data.size(), TQGArray::SpeedOptim );
1451  memcpy( m_data.data() + oldSize, data.data(), data.size() );
1452 }
1453 
1454 void StoredTransferJob::slotStoredDataReq( TDEIO::Job *, TQByteArray &data )
1455 {
1456  // Inspired from kmail's KMKernel::byteArrayToRemoteFile
1457  // send the data in 64 KB chunks
1458  const int MAX_CHUNK_SIZE = 64*1024;
1459  int remainingBytes = m_data.size() - m_uploadOffset;
1460  if( remainingBytes > MAX_CHUNK_SIZE ) {
1461  // send MAX_CHUNK_SIZE bytes to the receiver (deep copy)
1462  data.duplicate( m_data.data() + m_uploadOffset, MAX_CHUNK_SIZE );
1463  m_uploadOffset += MAX_CHUNK_SIZE;
1464  //kdDebug() << "Sending " << MAX_CHUNK_SIZE << " bytes ("
1465  // << remainingBytes - MAX_CHUNK_SIZE << " bytes remain)\n";
1466  } else {
1467  // send the remaining bytes to the receiver (deep copy)
1468  data.duplicate( m_data.data() + m_uploadOffset, remainingBytes );
1469  m_data = TQByteArray();
1470  m_uploadOffset = 0;
1471  //kdDebug() << "Sending " << remainingBytes << " bytes\n";
1472  }
1473 }
1474 
1475 StoredTransferJob *TDEIO::storedGet( const KURL& url, bool reload, bool showProgressInfo )
1476 {
1477  // Send decoded path and encoded query
1478  KIO_ARGS << url;
1479  StoredTransferJob * job = new StoredTransferJob( url, CMD_GET, packedArgs, TQByteArray(), showProgressInfo );
1480  if (reload)
1481  job->addMetaData("cache", "reload");
1482  return job;
1483 }
1484 
1485 StoredTransferJob *TDEIO::storedPut( const TQByteArray& arr, const KURL& url, int permissions,
1486  bool overwrite, bool resume, bool showProgressInfo )
1487 {
1488  KIO_ARGS << url << TQ_INT8( overwrite ? 1 : 0 ) << TQ_INT8( resume ? 1 : 0 ) << permissions;
1489  StoredTransferJob * job = new StoredTransferJob( url, CMD_PUT, packedArgs, TQByteArray(), showProgressInfo );
1490  job->setData( arr );
1491  return job;
1492 }
1493 
1495 
1496 MimetypeJob::MimetypeJob( const KURL& url, int command,
1497  const TQByteArray &packedArgs, bool showProgressInfo )
1498  : TransferJob(url, command, packedArgs, TQByteArray(), showProgressInfo)
1499 {
1500 }
1501 
1502 void MimetypeJob::start(Slave *slave)
1503 {
1504  TransferJob::start(slave);
1505 }
1506 
1507 
1508 void MimetypeJob::slotFinished( )
1509 {
1510  //kdDebug(7007) << "MimetypeJob::slotFinished()" << endl;
1511  if ( m_error == TDEIO::ERR_IS_DIRECTORY )
1512  {
1513  // It is in fact a directory. This happens when HTTP redirects to FTP.
1514  // Due to the "protocol doesn't support listing" code in KRun, we
1515  // assumed it was a file.
1516  kdDebug(7007) << "It is in fact a directory!" << endl;
1517  m_mimetype = TQString::fromLatin1("inode/directory");
1518  emit TransferJob::mimetype( this, m_mimetype );
1519  m_error = 0;
1520  }
1521  if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error )
1522  {
1523  // Return slave to the scheduler
1524  TransferJob::slotFinished();
1525  } else {
1526  //kdDebug(7007) << "MimetypeJob: Redirection to " << m_redirectionURL << endl;
1527  if (queryMetaData("permanent-redirect")=="true")
1528  emit permanentRedirection(this, m_url, m_redirectionURL);
1529  staticData.truncate(0);
1530  m_suspended = false;
1531  m_url = m_redirectionURL;
1532  m_redirectionURL = KURL();
1533  m_packedArgs.truncate(0);
1534  TQDataStream stream( m_packedArgs, IO_WriteOnly );
1535  stream << m_url;
1536 
1537  // Return slave to the scheduler
1538  slaveDone();
1539  Scheduler::doJob(this);
1540  }
1541 }
1542 
1543 MimetypeJob *TDEIO::mimetype(const KURL& url, bool showProgressInfo )
1544 {
1545  KIO_ARGS << url;
1546  MimetypeJob * job = new MimetypeJob(url, CMD_MIMETYPE, packedArgs, showProgressInfo);
1547  if ( showProgressInfo )
1548  Observer::self()->stating( job, url );
1549  return job;
1550 }
1551 
1553 
1554 DirectCopyJob::DirectCopyJob( const KURL& url, int command,
1555  const TQByteArray &packedArgs, bool showProgressInfo )
1556  : SimpleJob(url, command, packedArgs, showProgressInfo)
1557 {
1558 }
1559 
1560 void DirectCopyJob::start( Slave* slave )
1561 {
1562  connect( slave, TQT_SIGNAL(canResume( TDEIO::filesize_t ) ),
1563  TQT_SLOT( slotCanResume( TDEIO::filesize_t ) ) );
1564  SimpleJob::start(slave);
1565 }
1566 
1567 void DirectCopyJob::slotCanResume( TDEIO::filesize_t offset )
1568 {
1569  emit canResume(this, offset);
1570 }
1571 
1573 
1574 
1575 class FileCopyJob::FileCopyJobPrivate
1576 {
1577 public:
1578  TDEIO::filesize_t m_sourceSize;
1579  time_t m_modificationTime;
1580  SimpleJob *m_delJob;
1581 };
1582 
1583 /*
1584  * The FileCopyJob works according to the famous Bayern
1585  * 'Alternating Bitburger Protocol': we either drink a beer or we
1586  * we order a beer, but never both at the same time.
1587  * Tranlated to io-slaves: We alternate between receiving a block of data
1588  * and sending it away.
1589  */
1590 FileCopyJob::FileCopyJob( const KURL& src, const KURL& dest, int permissions,
1591  bool move, bool overwrite, bool resume, bool showProgressInfo)
1592  : Job(showProgressInfo), m_src(src), m_dest(dest),
1593  m_permissions(permissions), m_move(move), m_overwrite(overwrite), m_resume(resume),
1594  m_totalSize(0)
1595 {
1596  if (showProgressInfo && !move)
1597  Observer::self()->slotCopying( this, src, dest );
1598  else if (showProgressInfo && move)
1599  Observer::self()->slotMoving( this, src, dest );
1600 
1601  //kdDebug(7007) << "FileCopyJob::FileCopyJob()" << endl;
1602  m_moveJob = 0;
1603  m_copyJob = 0;
1604  m_getJob = 0;
1605  m_putJob = 0;
1606  d = new FileCopyJobPrivate;
1607  d->m_delJob = 0;
1608  d->m_sourceSize = (TDEIO::filesize_t) -1;
1609  d->m_modificationTime = static_cast<time_t>( -1 );
1610  TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
1611 }
1612 
1613 void FileCopyJob::slotStart()
1614 {
1615  if ( m_move )
1616  {
1617  // The if() below must be the same as the one in startBestCopyMethod
1618  if ((m_src.protocol() == m_dest.protocol()) &&
1619  (m_src.host() == m_dest.host()) &&
1620  (m_src.port() == m_dest.port()) &&
1621  (m_src.user() == m_dest.user()) &&
1622  (m_src.pass() == m_dest.pass()) &&
1623  !m_src.hasSubURL() && !m_dest.hasSubURL())
1624  {
1625  startRenameJob(m_src);
1626  return;
1627  }
1628  else if (m_src.isLocalFile() && KProtocolInfo::canRenameFromFile(m_dest))
1629  {
1630  startRenameJob(m_dest);
1631  return;
1632  }
1633  else if (m_dest.isLocalFile() && KProtocolInfo::canRenameToFile(m_src))
1634  {
1635  startRenameJob(m_src);
1636  return;
1637  }
1638  // No fast-move available, use copy + del.
1639  }
1640  startBestCopyMethod();
1641 }
1642 
1643 void FileCopyJob::startBestCopyMethod()
1644 {
1645  if ((m_src.protocol() == m_dest.protocol()) &&
1646  (m_src.host() == m_dest.host()) &&
1647  (m_src.port() == m_dest.port()) &&
1648  (m_src.user() == m_dest.user()) &&
1649  (m_src.pass() == m_dest.pass()) &&
1650  !m_src.hasSubURL() && !m_dest.hasSubURL())
1651  {
1652  startCopyJob();
1653  }
1654  else if (m_src.isLocalFile() && KProtocolInfo::canCopyFromFile(m_dest))
1655  {
1656  startCopyJob(m_dest);
1657  }
1658  else if (m_dest.isLocalFile() && KProtocolInfo::canCopyToFile(m_src))
1659  {
1660  startCopyJob(m_src);
1661  }
1662  else
1663  {
1664  startDataPump();
1665  }
1666 }
1667 
1668 FileCopyJob::~FileCopyJob()
1669 {
1670  delete d;
1671 }
1672 
1673 void FileCopyJob::setSourceSize( off_t size )
1674 {
1675  d->m_sourceSize = size;
1676  if (size != (off_t) -1)
1677  m_totalSize = size;
1678 }
1679 
1680 void FileCopyJob::setSourceSize64( TDEIO::filesize_t size )
1681 {
1682  d->m_sourceSize = size;
1683  if (size != (TDEIO::filesize_t) -1)
1684  m_totalSize = size;
1685 }
1686 
1687 void FileCopyJob::setModificationTime( time_t mtime )
1688 {
1689  d->m_modificationTime = mtime;
1690 }
1691 
1692 void FileCopyJob::startCopyJob()
1693 {
1694  startCopyJob(m_src);
1695 }
1696 
1697 void FileCopyJob::startCopyJob(const KURL &slave_url)
1698 {
1699  //kdDebug(7007) << "FileCopyJob::startCopyJob()" << endl;
1700  KIO_ARGS << m_src << m_dest << m_permissions << (TQ_INT8) m_overwrite;
1701  m_copyJob = new DirectCopyJob(slave_url, CMD_COPY, packedArgs, false);
1702  addSubjob( m_copyJob );
1703  connectSubjob( m_copyJob );
1704  connect( m_copyJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
1705  TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
1706 }
1707 
1708 void FileCopyJob::startRenameJob(const KURL &slave_url)
1709 {
1710  KIO_ARGS << m_src << m_dest << (TQ_INT8) m_overwrite;
1711  m_moveJob = new SimpleJob(slave_url, CMD_RENAME, packedArgs, false);
1712  addSubjob( m_moveJob );
1713  connectSubjob( m_moveJob );
1714 }
1715 
1716 void FileCopyJob::connectSubjob( SimpleJob * job )
1717 {
1718  connect( job, TQT_SIGNAL(totalSize( TDEIO::Job*, TDEIO::filesize_t )),
1719  this, TQT_SLOT( slotTotalSize(TDEIO::Job*, TDEIO::filesize_t)) );
1720 
1721  connect( job, TQT_SIGNAL(processedSize( TDEIO::Job*, TDEIO::filesize_t )),
1722  this, TQT_SLOT( slotProcessedSize(TDEIO::Job*, TDEIO::filesize_t)) );
1723 
1724  connect( job, TQT_SIGNAL(percent( TDEIO::Job*, unsigned long )),
1725  this, TQT_SLOT( slotPercent(TDEIO::Job*, unsigned long)) );
1726 
1727 }
1728 
1729 void FileCopyJob::slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t size )
1730 {
1731  setProcessedSize(size);
1732  emit processedSize( this, size );
1733  if ( size > m_totalSize ) {
1734  slotTotalSize( this, size ); // safety
1735  }
1736  emitPercent( size, m_totalSize );
1737 }
1738 
1739 void FileCopyJob::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
1740 {
1741  if (size > m_totalSize)
1742  {
1743  m_totalSize = size;
1744  emit totalSize( this, m_totalSize );
1745  }
1746 }
1747 
1748 void FileCopyJob::slotPercent( TDEIO::Job*, unsigned long pct )
1749 {
1750  if ( pct > m_percent )
1751  {
1752  m_percent = pct;
1753  emit percent( this, m_percent );
1754  }
1755 }
1756 
1757 void FileCopyJob::startDataPump()
1758 {
1759  //kdDebug(7007) << "FileCopyJob::startDataPump()" << endl;
1760 
1761  m_canResume = false;
1762  m_resumeAnswerSent = false;
1763  m_getJob = 0L; // for now
1764  m_putJob = put( m_dest, m_permissions, m_overwrite, m_resume, false /* no GUI */);
1765  if ( d->m_modificationTime != static_cast<time_t>( -1 ) ) {
1766  TQDateTime dt; dt.setTime_t( d->m_modificationTime );
1767  m_putJob->addMetaData( "modified", dt.toString( Qt::ISODate ) );
1768  }
1769  //kdDebug(7007) << "FileCopyJob: m_putJob = " << m_putJob << " m_dest=" << m_dest << endl;
1770 
1771  // The first thing the put job will tell us is whether we can
1772  // resume or not (this is always emitted)
1773  connect( m_putJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
1774  TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
1775  connect( m_putJob, TQT_SIGNAL(dataReq(TDEIO::Job *, TQByteArray&)),
1776  TQT_SLOT( slotDataReq(TDEIO::Job *, TQByteArray&)));
1777  addSubjob( m_putJob );
1778 }
1779 
1780 void FileCopyJob::slotCanResume( TDEIO::Job* job, TDEIO::filesize_t offset )
1781 {
1782  if ( job == m_putJob || job == m_copyJob )
1783  {
1784  //kdDebug(7007) << "FileCopyJob::slotCanResume from PUT job. offset=" << TDEIO::number(offset) << endl;
1785  if (offset)
1786  {
1787  RenameDlg_Result res = R_RESUME;
1788 
1789  if (!KProtocolManager::autoResume() && !m_overwrite)
1790  {
1791  TQString newPath;
1792  TDEIO::Job* job = ( !m_progressId && parentJob() ) ? parentJob() : this;
1793  // Ask confirmation about resuming previous transfer
1794  res = Observer::self()->open_RenameDlg(
1795  job, i18n("File Already Exists"),
1796  m_src.url(),
1797  m_dest.url(),
1798  (RenameDlg_Mode) (M_OVERWRITE | M_RESUME | M_NORENAME), newPath,
1799  d->m_sourceSize, offset );
1800  }
1801 
1802  if ( res == R_OVERWRITE || m_overwrite )
1803  offset = 0;
1804  else if ( res == R_CANCEL )
1805  {
1806  if ( job == m_putJob )
1807  m_putJob->kill(true);
1808  else
1809  m_copyJob->kill(true);
1810  m_error = ERR_USER_CANCELED;
1811  emitResult();
1812  return;
1813  }
1814  }
1815  else
1816  m_resumeAnswerSent = true; // No need for an answer
1817 
1818  if ( job == m_putJob )
1819  {
1820  m_getJob = get( m_src, false, false /* no GUI */ );
1821  //kdDebug(7007) << "FileCopyJob: m_getJob = " << m_getJob << endl;
1822  m_getJob->addMetaData( "errorPage", "false" );
1823  m_getJob->addMetaData( "AllowCompressedPage", "false" );
1824  // Set size in subjob. This helps if the slave doesn't emit totalSize.
1825  if ( d->m_sourceSize != (TDEIO::filesize_t)-1 )
1826  m_getJob->slotTotalSize( d->m_sourceSize );
1827  if (offset)
1828  {
1829  //kdDebug(7007) << "Setting metadata for resume to " << (unsigned long) offset << endl;
1830  // TODO KDE4: rename to seek or offset and document it
1831  // This isn't used only for resuming, but potentially also for extracting (#72302).
1832  m_getJob->addMetaData( "resume", TDEIO::number(offset) );
1833 
1834  // Might or might not get emitted
1835  connect( m_getJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
1836  TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
1837  }
1838  m_putJob->slave()->setOffset( offset );
1839 
1840  m_putJob->suspend();
1841  addSubjob( m_getJob );
1842  connectSubjob( m_getJob ); // Progress info depends on get
1843  m_getJob->resume(); // Order a beer
1844 
1845  connect( m_getJob, TQT_SIGNAL(data(TDEIO::Job*,const TQByteArray&)),
1846  TQT_SLOT( slotData(TDEIO::Job*,const TQByteArray&)) );
1847  connect( m_getJob, TQT_SIGNAL(mimetype(TDEIO::Job*,const TQString&) ),
1848  TQT_SLOT(slotMimetype(TDEIO::Job*,const TQString&)) );
1849  }
1850  else // copyjob
1851  {
1852  m_copyJob->slave()->sendResumeAnswer( offset != 0 );
1853  }
1854  }
1855  else if ( job == m_getJob )
1856  {
1857  // Cool, the get job said ok, we can resume
1858  m_canResume = true;
1859  //kdDebug(7007) << "FileCopyJob::slotCanResume from the GET job -> we can resume" << endl;
1860 
1861  m_getJob->slave()->setOffset( m_putJob->slave()->offset() );
1862  }
1863  else
1864  kdWarning(7007) << "FileCopyJob::slotCanResume from unknown job=" << job
1865  << " m_getJob=" << m_getJob << " m_putJob=" << m_putJob << endl;
1866 }
1867 
1868 void FileCopyJob::slotData( TDEIO::Job * , const TQByteArray &data)
1869 {
1870  //kdDebug(7007) << "FileCopyJob::slotData" << endl;
1871  //kdDebug(7007) << " data size : " << data.size() << endl;
1872  assert(m_putJob);
1873  if (!m_putJob) return; // Don't crash
1874  m_getJob->suspend();
1875  m_putJob->resume(); // Drink the beer
1876  m_buffer = data;
1877 
1878  // On the first set of data incoming, we tell the "put" slave about our
1879  // decision about resuming
1880  if (!m_resumeAnswerSent)
1881  {
1882  m_resumeAnswerSent = true;
1883  //kdDebug(7007) << "FileCopyJob::slotData (first time) -> send resume answer " << m_canResume << endl;
1884  m_putJob->slave()->sendResumeAnswer( m_canResume );
1885  }
1886 }
1887 
1888 void FileCopyJob::slotDataReq( TDEIO::Job * , TQByteArray &data)
1889 {
1890  //kdDebug(7007) << "FileCopyJob::slotDataReq" << endl;
1891  if (!m_resumeAnswerSent && !m_getJob)
1892  {
1893  // This can't happen (except as a migration bug on 12/10/2000)
1894  m_error = ERR_INTERNAL;
1895  m_errorText = "'Put' job didn't send canResume or 'Get' job didn't send data!";
1896  m_putJob->kill(true);
1897  emitResult();
1898  return;
1899  }
1900  if (m_getJob)
1901  {
1902  m_getJob->resume(); // Order more beer
1903  m_putJob->suspend();
1904  }
1905  data = m_buffer;
1906  m_buffer = TQByteArray();
1907 }
1908 
1909 void FileCopyJob::slotMimetype( TDEIO::Job*, const TQString& type )
1910 {
1911  emit mimetype( this, type );
1912 }
1913 
1914 void FileCopyJob::slotResult( TDEIO::Job *job)
1915 {
1916  //kdDebug(7007) << "FileCopyJob this=" << this << " ::slotResult(" << job << ")" << endl;
1917  // Did job have an error ?
1918  if ( job->error() )
1919  {
1920  if ((job == m_moveJob) && (job->error() == ERR_UNSUPPORTED_ACTION))
1921  {
1922  m_moveJob = 0;
1923  startBestCopyMethod();
1924  removeSubjob(job);
1925  return;
1926  }
1927  else if ((job == m_copyJob) && (job->error() == ERR_UNSUPPORTED_ACTION))
1928  {
1929  m_copyJob = 0;
1930  startDataPump();
1931  removeSubjob(job);
1932  return;
1933  }
1934  else if (job == m_getJob)
1935  {
1936  m_getJob = 0L;
1937  if (m_putJob)
1938  m_putJob->kill(true);
1939  }
1940  else if (job == m_putJob)
1941  {
1942  m_putJob = 0L;
1943  if (m_getJob)
1944  m_getJob->kill(true);
1945  }
1946  m_error = job->error();
1947  m_errorText = job->errorText();
1948  emitResult();
1949  return;
1950  }
1951 
1952  if (job == m_moveJob)
1953  {
1954  m_moveJob = 0; // Finished
1955  }
1956 
1957  if (job == m_copyJob)
1958  {
1959  m_copyJob = 0;
1960  if (m_move)
1961  {
1962  d->m_delJob = file_delete( m_src, false/*no GUI*/ ); // Delete source
1963  addSubjob(d->m_delJob);
1964  }
1965  }
1966 
1967  if (job == m_getJob)
1968  {
1969  m_getJob = 0; // No action required
1970  if (m_putJob)
1971  m_putJob->resume();
1972  }
1973 
1974  if (job == m_putJob)
1975  {
1976  //kdDebug(7007) << "FileCopyJob: m_putJob finished " << endl;
1977  m_putJob = 0;
1978  if (m_getJob)
1979  {
1980  kdWarning(7007) << "WARNING ! Get still going on..." << endl;
1981  m_getJob->resume();
1982  }
1983  if (m_move)
1984  {
1985  d->m_delJob = file_delete( m_src, false/*no GUI*/ ); // Delete source
1986  addSubjob(d->m_delJob);
1987  }
1988  }
1989 
1990  if (job == d->m_delJob)
1991  {
1992  d->m_delJob = 0; // Finished
1993  }
1994  removeSubjob(job);
1995 }
1996 
1997 FileCopyJob *TDEIO::file_copy( const KURL& src, const KURL& dest, int permissions,
1998  bool overwrite, bool resume, bool showProgressInfo)
1999 {
2000  return new FileCopyJob( src, dest, permissions, false, overwrite, resume, showProgressInfo );
2001 }
2002 
2003 FileCopyJob *TDEIO::file_move( const KURL& src, const KURL& dest, int permissions,
2004  bool overwrite, bool resume, bool showProgressInfo)
2005 {
2006  return new FileCopyJob( src, dest, permissions, true, overwrite, resume, showProgressInfo );
2007 }
2008 
2009 SimpleJob *TDEIO::file_delete( const KURL& src, bool showProgressInfo)
2010 {
2011  KIO_ARGS << src << TQ_INT8(true); // isFile
2012  return new SimpleJob(src, CMD_DEL, packedArgs, showProgressInfo );
2013 }
2014 
2016 
2017 // KDE 4: Make it const TQString & _prefix
2018 ListJob::ListJob(const KURL& u, bool showProgressInfo, bool _recursive, TQString _prefix, bool _includeHidden) :
2019  SimpleJob(u, CMD_LISTDIR, TQByteArray(), showProgressInfo),
2020  recursive(_recursive), includeHidden(_includeHidden), prefix(_prefix), m_processedEntries(0)
2021 {
2022  // We couldn't set the args when calling the parent constructor,
2023  // so do it now.
2024  TQDataStream stream( m_packedArgs, IO_WriteOnly );
2025  stream << u;
2026 }
2027 
2028 void ListJob::slotListEntries( const TDEIO::UDSEntryList& list )
2029 {
2030  // Emit progress info (takes care of emit processedSize and percent)
2031  m_processedEntries += list.count();
2032  slotProcessedSize( m_processedEntries );
2033 
2034  if (recursive) {
2035  UDSEntryListConstIterator it = list.begin();
2036  UDSEntryListConstIterator end = list.end();
2037 
2038  for (; it != end; ++it) {
2039  bool isDir = false;
2040  bool isLink = false;
2041  KURL itemURL;
2042 
2043  UDSEntry::ConstIterator it2 = (*it).begin();
2044  UDSEntry::ConstIterator end2 = (*it).end();
2045  for( ; it2 != end2; it2++ ) {
2046  switch( (*it2).m_uds ) {
2047  case UDS_FILE_TYPE:
2048  isDir = S_ISDIR((*it2).m_long);
2049  break;
2050  case UDS_NAME:
2051  if( itemURL.isEmpty() ) {
2052  itemURL = url();
2053  itemURL.addPath( (*it2).m_str );
2054  }
2055  break;
2056  case UDS_URL:
2057  itemURL = (*it2).m_str;
2058  break;
2059  case UDS_LINK_DEST:
2060  // This is a link !!! Don't follow !
2061  isLink = !(*it2).m_str.isEmpty();
2062  break;
2063  default:
2064  break;
2065  }
2066  }
2067  if (isDir && !isLink) {
2068  const TQString filename = itemURL.fileName();
2069  // skip hidden dirs when listing if requested
2070  if (filename != ".." && filename != "." && (includeHidden || filename[0] != '.')) {
2071  ListJob *job = new ListJob(itemURL,
2072  false /*no progress info!*/,
2073  true /*recursive*/,
2074  prefix + filename + "/",
2075  includeHidden);
2076  Scheduler::scheduleJob(job);
2077  connect(job, TQT_SIGNAL(entries( TDEIO::Job *,
2078  const TDEIO::UDSEntryList& )),
2079  TQT_SLOT( gotEntries( TDEIO::Job*,
2080  const TDEIO::UDSEntryList& )));
2081  addSubjob(job);
2082  }
2083  }
2084  }
2085  }
2086 
2087  // Not recursive, or top-level of recursive listing : return now (send . and .. as well)
2088  // exclusion of hidden files also requires the full sweep, but the case for full-listing
2089  // a single dir is probably common enough to justify the shortcut
2090  if (prefix.isNull() && includeHidden) {
2091  emit entries(this, list);
2092  } else {
2093  // cull the unwanted hidden dirs and/or parent dir references from the listing, then emit that
2094  UDSEntryList newlist;
2095 
2096  UDSEntryListConstIterator it = list.begin();
2097  UDSEntryListConstIterator end = list.end();
2098  for (; it != end; ++it) {
2099 
2100  UDSEntry newone = *it;
2101  UDSEntry::Iterator it2 = newone.begin();
2102  TQString filename;
2103  for( ; it2 != newone.end(); it2++ ) {
2104  if ((*it2).m_uds == UDS_NAME) {
2105  filename = (*it2).m_str;
2106  (*it2).m_str = prefix + filename;
2107  }
2108  }
2109  // Avoid returning entries like subdir/. and subdir/.., but include . and .. for
2110  // the toplevel dir, and skip hidden files/dirs if that was requested
2111  if ( (prefix.isNull() || (filename != ".." && filename != ".") )
2112  && (includeHidden || (filename[0] != '.') ) )
2113  newlist.append(newone);
2114  }
2115 
2116  emit entries(this, newlist);
2117  }
2118 }
2119 
2120 void ListJob::gotEntries(TDEIO::Job *, const TDEIO::UDSEntryList& list )
2121 {
2122  // Forward entries received by subjob - faking we received them ourselves
2123  emit entries(this, list);
2124 }
2125 
2126 void ListJob::slotResult( TDEIO::Job * job )
2127 {
2128  // If we can't list a subdir, the result is still ok
2129  // This is why we override Job::slotResult() - to skip error checking
2130  removeSubjob( job );
2131 }
2132 
2133 void ListJob::slotRedirection( const KURL & url )
2134 {
2135  if (!kapp->authorizeURLAction("redirect", m_url, url))
2136  {
2137  kdWarning(7007) << "ListJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
2138  return;
2139  }
2140  m_redirectionURL = url; // We'll remember that when the job finishes
2141  if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
2142  m_redirectionURL.setUser(m_url.user()); // Preserve user
2143  emit redirection( this, m_redirectionURL );
2144 }
2145 
2146 void ListJob::slotFinished()
2147 {
2148  // Support for listing archives as directories
2149  if ( m_error == TDEIO::ERR_IS_FILE && m_url.isLocalFile() ) {
2150  KMimeType::Ptr ptr = KMimeType::findByURL( m_url, 0, true, true );
2151  if ( ptr ) {
2152  TQString proto = ptr->property("X-TDE-LocalProtocol").toString();
2153  if ( !proto.isEmpty() && KProtocolInfo::isKnownProtocol(proto) ) {
2154  m_redirectionURL = m_url;
2155  m_redirectionURL.setProtocol( proto );
2156  m_error = 0;
2157  emit redirection(this,m_redirectionURL);
2158  }
2159  }
2160  }
2161  if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error ) {
2162  // Return slave to the scheduler
2163  SimpleJob::slotFinished();
2164  } else {
2165 
2166  //kdDebug(7007) << "ListJob: Redirection to " << m_redirectionURL << endl;
2167  if (queryMetaData("permanent-redirect")=="true")
2168  emit permanentRedirection(this, m_url, m_redirectionURL);
2169  m_url = m_redirectionURL;
2170  m_redirectionURL = KURL();
2171  m_packedArgs.truncate(0);
2172  TQDataStream stream( m_packedArgs, IO_WriteOnly );
2173  stream << m_url;
2174 
2175  // Return slave to the scheduler
2176  slaveDone();
2177  Scheduler::doJob(this);
2178  }
2179 }
2180 
2181 void ListJob::slotMetaData( const TDEIO::MetaData &_metaData) {
2182  SimpleJob::slotMetaData(_metaData);
2183  storeSSLSessionFromJob(m_redirectionURL);
2184 }
2185 
2186 ListJob *TDEIO::listDir( const KURL& url, bool showProgressInfo, bool includeHidden )
2187 {
2188  ListJob * job = new ListJob(url, showProgressInfo,false,TQString::null,includeHidden);
2189  return job;
2190 }
2191 
2192 ListJob *TDEIO::listRecursive( const KURL& url, bool showProgressInfo, bool includeHidden )
2193 {
2194  ListJob * job = new ListJob(url, showProgressInfo, true,TQString::null,includeHidden);
2195  return job;
2196 }
2197 
2198 void ListJob::setUnrestricted(bool unrestricted)
2199 {
2200  if (unrestricted)
2201  extraFlags() |= EF_ListJobUnrestricted;
2202  else
2203  extraFlags() &= ~EF_ListJobUnrestricted;
2204 }
2205 
2206 void ListJob::start(Slave *slave)
2207 {
2208  if (kapp && !kapp->authorizeURLAction("list", m_url, m_url) && !(extraFlags() & EF_ListJobUnrestricted))
2209  {
2210  m_error = ERR_ACCESS_DENIED;
2211  m_errorText = m_url.url();
2212  TQTimer::singleShot(0, this, TQT_SLOT(slotFinished()) );
2213  return;
2214  }
2215  connect( slave, TQT_SIGNAL( listEntries( const TDEIO::UDSEntryList& )),
2216  TQT_SLOT( slotListEntries( const TDEIO::UDSEntryList& )));
2217  connect( slave, TQT_SIGNAL( totalSize( TDEIO::filesize_t ) ),
2218  TQT_SLOT( slotTotalSize( TDEIO::filesize_t ) ) );
2219  connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
2220  TQT_SLOT( slotRedirection(const KURL &) ) );
2221 
2222  SimpleJob::start(slave);
2223 }
2224 
2225 class CopyJob::CopyJobPrivate
2226 {
2227 public:
2228  CopyJobPrivate() {
2229  m_defaultPermissions = false;
2230  m_bURLDirty = false;
2231  }
2232  // This is the dest URL that was initially given to CopyJob
2233  // It is copied into m_dest, which can be changed for a given src URL
2234  // (when using the RENAME dialog in slotResult),
2235  // and which will be reset for the next src URL.
2236  KURL m_globalDest;
2237  // The state info about that global dest
2238  CopyJob::DestinationState m_globalDestinationState;
2239  // See setDefaultPermissions
2240  bool m_defaultPermissions;
2241  // Whether URLs changed (and need to be emitted by the next slotReport call)
2242  bool m_bURLDirty;
2243  // Used after copying all the files into the dirs, to set mtime (TODO: and permissions?)
2244  // after the copy is done
2245  TQValueList<CopyInfo> m_directoriesCopied;
2246 };
2247 
2248 CopyJob::CopyJob( const KURL::List& src, const KURL& dest, CopyMode mode, bool asMethod, bool showProgressInfo )
2249  : Job(showProgressInfo), m_mode(mode), m_asMethod(asMethod),
2250  destinationState(DEST_NOT_STATED), state(STATE_STATING),
2251  m_totalSize(0), m_processedSize(0), m_fileProcessedSize(0),
2252  m_processedFiles(0), m_processedDirs(0),
2253  m_srcList(src), m_currentStatSrc(m_srcList.begin()),
2254  m_bCurrentOperationIsLink(false), m_bSingleFileCopy(false), m_bOnlyRenames(mode==Move),
2255  m_dest(dest), m_bAutoSkip( false ), m_bOverwriteAll( false ),
2256  m_conflictError(0), m_reportTimer(0)
2257 {
2258  d = new CopyJobPrivate;
2259  d->m_globalDest = dest;
2260  d->m_globalDestinationState = destinationState;
2261 
2262  if ( showProgressInfo ) {
2263  connect( this, TQT_SIGNAL( totalFiles( TDEIO::Job*, unsigned long ) ),
2264  Observer::self(), TQT_SLOT( slotTotalFiles( TDEIO::Job*, unsigned long ) ) );
2265 
2266  connect( this, TQT_SIGNAL( totalDirs( TDEIO::Job*, unsigned long ) ),
2267  Observer::self(), TQT_SLOT( slotTotalDirs( TDEIO::Job*, unsigned long ) ) );
2268  }
2269  TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
2284 }
2285 
2286 CopyJob::~CopyJob()
2287 {
2288  delete d;
2289 }
2290 
2291 void CopyJob::slotStart()
2292 {
2298  m_reportTimer = new TQTimer(this);
2299 
2300  connect(m_reportTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotReport()));
2301  m_reportTimer->start(REPORT_TIMEOUT,false);
2302 
2303  // Stat the dest
2304  TDEIO::Job * job = TDEIO::stat( m_dest, false, 2, false );
2305  //kdDebug(7007) << "CopyJob:stating the dest " << m_dest << endl;
2306  addSubjob(job);
2307 }
2308 
2309 // For unit test purposes
2310 TDEIO_EXPORT bool tdeio_resolve_local_urls = true;
2311 
2312 void CopyJob::slotResultStating( Job *job )
2313 {
2314  //kdDebug(7007) << "CopyJob::slotResultStating" << endl;
2315  // Was there an error while stating the src ?
2316  if (job->error() && destinationState != DEST_NOT_STATED )
2317  {
2318  KURL srcurl = ((SimpleJob*)job)->url();
2319  if ( !srcurl.isLocalFile() )
2320  {
2321  // Probably : src doesn't exist. Well, over some protocols (e.g. FTP)
2322  // this info isn't really reliable (thanks to MS FTP servers).
2323  // We'll assume a file, and try to download anyway.
2324  kdDebug(7007) << "Error while stating source. Activating hack" << endl;
2325  subjobs.remove( job );
2326  assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
2327  struct CopyInfo info;
2328  info.permissions = (mode_t) -1;
2329  info.mtime = (time_t) -1;
2330  info.ctime = (time_t) -1;
2331  info.size = (TDEIO::filesize_t)-1;
2332  info.uSource = srcurl;
2333  info.uDest = m_dest;
2334  // Append filename or dirname to destination URL, if allowed
2335  if ( destinationState == DEST_IS_DIR && !m_asMethod )
2336  info.uDest.addPath( srcurl.fileName() );
2337 
2338  files.append( info );
2339  statNextSrc();
2340  return;
2341  }
2342  // Local file. If stat fails, the file definitely doesn't exist.
2343  Job::slotResult( job ); // will set the error and emit result(this)
2344  return;
2345  }
2346 
2347  // Is it a file or a dir ? Does it have a local path?
2348  UDSEntry entry = ((StatJob*)job)->statResult();
2349  bool bDir = false;
2350  bool bLink = false;
2351  TQString sName;
2352  TQString sLocalPath;
2353  UDSEntry::ConstIterator it2 = entry.begin();
2354  for( ; it2 != entry.end(); it2++ ) {
2355  if ( ((*it2).m_uds) == UDS_FILE_TYPE )
2356  bDir = S_ISDIR( (mode_t)(*it2).m_long );
2357  else if ( ((*it2).m_uds) == UDS_LINK_DEST )
2358  bLink = !((*it2).m_str.isEmpty());
2359  else if ( ((*it2).m_uds) == UDS_NAME )
2360  sName = (*it2).m_str;
2361  else if ( ((*it2).m_uds) == UDS_LOCAL_PATH )
2362  sLocalPath = (*it2).m_str;
2363  }
2364 
2365  if ( destinationState == DEST_NOT_STATED )
2366  // we were stating the dest
2367  {
2368  if (job->error())
2369  destinationState = DEST_DOESNT_EXIST;
2370  else {
2371  // Treat symlinks to dirs as dirs here, so no test on bLink
2372  destinationState = bDir ? DEST_IS_DIR : DEST_IS_FILE;
2373  //kdDebug(7007) << "CopyJob::slotResultStating dest is dir:" << bDir << endl;
2374  }
2375  const bool isGlobalDest = m_dest == d->m_globalDest;
2376  if ( isGlobalDest )
2377  d->m_globalDestinationState = destinationState;
2378 
2379  if ( !sLocalPath.isEmpty() && tdeio_resolve_local_urls ) {
2380  m_dest = KURL();
2381  m_dest.setPath(sLocalPath);
2382  if ( isGlobalDest )
2383  d->m_globalDest = m_dest;
2384  }
2385 
2386  subjobs.remove( job );
2387  assert ( subjobs.isEmpty() );
2388 
2389  // After knowing what the dest is, we can start stat'ing the first src.
2390  statCurrentSrc();
2391  return;
2392  }
2393  // We were stating the current source URL
2394  m_currentDest = m_dest; // used by slotEntries
2395  // Create a dummy list with it, for slotEntries
2396  UDSEntryList lst;
2397  lst.append(entry);
2398 
2399  // There 6 cases, and all end up calling slotEntries(job, lst) first :
2400  // 1 - src is a dir, destination is a directory,
2401  // slotEntries will append the source-dir-name to the destination
2402  // 2 - src is a dir, destination is a file, ERROR (done later on)
2403  // 3 - src is a dir, destination doesn't exist, then it's the destination dirname,
2404  // so slotEntries will use it as destination.
2405 
2406  // 4 - src is a file, destination is a directory,
2407  // slotEntries will append the filename to the destination.
2408  // 5 - src is a file, destination is a file, m_dest is the exact destination name
2409  // 6 - src is a file, destination doesn't exist, m_dest is the exact destination name
2410  // Tell slotEntries not to alter the src url
2411  m_bCurrentSrcIsDir = false;
2412  slotEntries(job, lst);
2413 
2414  KURL srcurl;
2415  if (!sLocalPath.isEmpty())
2416  srcurl.setPath(sLocalPath);
2417  else
2418  srcurl = ((SimpleJob*)job)->url();
2419 
2420  subjobs.remove( job );
2421  assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
2422 
2423  if ( bDir
2424  && !bLink // treat symlinks as files (no recursion)
2425  && m_mode != Link ) // No recursion in Link mode either.
2426  {
2427  //kdDebug(7007) << " Source is a directory " << endl;
2428 
2429  m_bCurrentSrcIsDir = true; // used by slotEntries
2430  if ( destinationState == DEST_IS_DIR ) // (case 1)
2431  {
2432  if ( !m_asMethod )
2433  {
2434  // Use <desturl>/<directory_copied> as destination, from now on
2435  TQString directory = srcurl.fileName();
2436  if ( !sName.isEmpty() && KProtocolInfo::fileNameUsedForCopying( srcurl ) == KProtocolInfo::Name )
2437  {
2438  directory = sName;
2439  }
2440  m_currentDest.addPath( directory );
2441  }
2442  }
2443  else if ( destinationState == DEST_IS_FILE ) // (case 2)
2444  {
2445  m_error = ERR_IS_FILE;
2446  m_errorText = m_dest.prettyURL();
2447  emitResult();
2448  return;
2449  }
2450  else // (case 3)
2451  {
2452  // otherwise dest is new name for toplevel dir
2453  // so the destination exists, in fact, from now on.
2454  // (This even works with other src urls in the list, since the
2455  // dir has effectively been created)
2456  destinationState = DEST_IS_DIR;
2457  if ( m_dest == d->m_globalDest )
2458  d->m_globalDestinationState = destinationState;
2459  }
2460 
2461  startListing( srcurl );
2462  }
2463  else
2464  {
2465  //kdDebug(7007) << " Source is a file (or a symlink), or we are linking -> no recursive listing " << endl;
2466  statNextSrc();
2467  }
2468 }
2469 
2470 void CopyJob::slotReport()
2471 {
2472  // If showProgressInfo was set, m_progressId is > 0.
2473  Observer * observer = m_progressId ? Observer::self() : 0L;
2474  switch (state) {
2475  case STATE_COPYING_FILES:
2476  emit processedFiles( this, m_processedFiles );
2477  if (observer) observer->slotProcessedFiles(this, m_processedFiles);
2478  if (d->m_bURLDirty)
2479  {
2480  // Only emit urls when they changed. This saves time, and fixes #66281
2481  d->m_bURLDirty = false;
2482  if (m_mode==Move)
2483  {
2484  if (observer) observer->slotMoving( this, m_currentSrcURL, m_currentDestURL);
2485  emit moving( this, m_currentSrcURL, m_currentDestURL);
2486  }
2487  else if (m_mode==Link)
2488  {
2489  if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL ); // we don't have a slotLinking
2490  emit linking( this, m_currentSrcURL.path(), m_currentDestURL );
2491  }
2492  else
2493  {
2494  if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL );
2495  emit copying( this, m_currentSrcURL, m_currentDestURL );
2496  }
2497  }
2498  break;
2499 
2500  case STATE_CREATING_DIRS:
2501  if (observer) observer->slotProcessedDirs( this, m_processedDirs );
2502  emit processedDirs( this, m_processedDirs );
2503  if (d->m_bURLDirty)
2504  {
2505  d->m_bURLDirty = false;
2506  emit creatingDir( this, m_currentDestURL );
2507  if (observer) observer->slotCreatingDir( this, m_currentDestURL);
2508  }
2509  break;
2510 
2511  case STATE_STATING:
2512  case STATE_LISTING:
2513  if (d->m_bURLDirty)
2514  {
2515  d->m_bURLDirty = false;
2516  if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL );
2517  }
2518  emit totalSize( this, m_totalSize );
2519  emit totalFiles( this, files.count() );
2520  emit totalDirs( this, dirs.count() );
2521  break;
2522 
2523  default:
2524  break;
2525  }
2526 }
2527 
2528 void CopyJob::slotEntries(TDEIO::Job* job, const UDSEntryList& list)
2529 {
2530  UDSEntryListConstIterator it = list.begin();
2531  UDSEntryListConstIterator end = list.end();
2532  for (; it != end; ++it) {
2533  UDSEntry::ConstIterator it2 = (*it).begin();
2534  struct CopyInfo info;
2535  info.permissions = -1;
2536  info.mtime = (time_t) -1;
2537  info.ctime = (time_t) -1;
2538  info.size = (TDEIO::filesize_t)-1;
2539  TQString displayName;
2540  KURL url;
2541  TQString localPath;
2542  bool isDir = false;
2543  for( ; it2 != (*it).end(); it2++ ) {
2544  switch ((*it2).m_uds) {
2545  case UDS_FILE_TYPE:
2546  //info.type = (mode_t)((*it2).m_long);
2547  isDir = S_ISDIR( (mode_t)((*it2).m_long) );
2548  break;
2549  case UDS_NAME: // recursive listing, displayName can be a/b/c/d
2550  displayName = (*it2).m_str;
2551  break;
2552  case UDS_URL: // optional
2553  url = KURL((*it2).m_str);
2554  break;
2555  case UDS_LOCAL_PATH:
2556  localPath = (*it2).m_str;
2557  break;
2558  case UDS_LINK_DEST:
2559  info.linkDest = (*it2).m_str;
2560  break;
2561  case UDS_ACCESS:
2562  info.permissions = ((*it2).m_long);
2563  break;
2564  case UDS_SIZE:
2565  info.size = (TDEIO::filesize_t)((*it2).m_long);
2566  m_totalSize += info.size;
2567  break;
2568  case UDS_MODIFICATION_TIME:
2569  info.mtime = (time_t)((*it2).m_long);
2570  break;
2571  case UDS_CREATION_TIME:
2572  info.ctime = (time_t)((*it2).m_long);
2573  default:
2574  break;
2575  }
2576  }
2577  if (displayName != ".." && displayName != ".")
2578  {
2579  bool hasCustomURL = !url.isEmpty() || !localPath.isEmpty();
2580  if( !hasCustomURL ) {
2581  // Make URL from displayName
2582  url = ((SimpleJob *)job)->url();
2583  if ( m_bCurrentSrcIsDir ) { // Only if src is a directory. Otherwise uSource is fine as is
2584  //kdDebug(7007) << "adding path " << displayName << endl;
2585  url.addPath( displayName );
2586  }
2587  }
2588  //kdDebug(7007) << "displayName=" << displayName << " url=" << url << endl;
2589  if (!localPath.isEmpty() && tdeio_resolve_local_urls) {
2590  url = KURL();
2591  url.setPath(localPath);
2592  }
2593 
2594  info.uSource = url;
2595  info.uDest = m_currentDest;
2596  //kdDebug(7007) << " uSource=" << info.uSource << " uDest(1)=" << info.uDest << endl;
2597  // Append filename or dirname to destination URL, if allowed
2598  if ( destinationState == DEST_IS_DIR &&
2599  // "copy/move as <foo>" means 'foo' is the dest for the base srcurl
2600  // (passed here during stating) but not its children (during listing)
2601  ( ! ( m_asMethod && state == STATE_STATING ) ) )
2602  {
2603  TQString destFileName;
2604  if ( hasCustomURL &&
2605  KProtocolInfo::fileNameUsedForCopying( url ) == KProtocolInfo::FromURL ) {
2606  //destFileName = url.fileName(); // Doesn't work for recursive listing
2607  // Count the number of prefixes used by the recursive listjob
2608  int numberOfSlashes = displayName.contains( '/' ); // don't make this a find()!
2609  TQString path = url.path();
2610  int pos = 0;
2611  for ( int n = 0; n < numberOfSlashes + 1; ++n ) {
2612  pos = path.findRev( '/', pos - 1 );
2613  if ( pos == -1 ) { // error
2614  kdWarning(7007) << "tdeioslave bug: not enough slashes in UDS_URL " << path << " - looking for " << numberOfSlashes << " slashes" << endl;
2615  break;
2616  }
2617  }
2618  if ( pos >= 0 ) {
2619  destFileName = path.mid( pos + 1 );
2620  }
2621 
2622  } else { // destination filename taken from UDS_NAME
2623  destFileName = displayName;
2624  }
2625 
2626  // Here we _really_ have to add some filename to the dest.
2627  // Otherwise, we end up with e.g. dest=..../Desktop/ itself.
2628  // (This can happen when dropping a link to a webpage with no path)
2629  if ( destFileName.isEmpty() )
2630  destFileName = TDEIO::encodeFileName( info.uSource.prettyURL() );
2631 
2632  //kdDebug(7007) << " adding destFileName=" << destFileName << endl;
2633  info.uDest.addPath( destFileName );
2634  }
2635  //kdDebug(7007) << " uDest(2)=" << info.uDest << endl;
2636  //kdDebug(7007) << " " << info.uSource << " -> " << info.uDest << endl;
2637  if ( info.linkDest.isEmpty() && isDir && m_mode != Link ) // Dir
2638  {
2639  dirs.append( info ); // Directories
2640  if (m_mode == Move)
2641  dirsToRemove.append( info.uSource );
2642  }
2643  else {
2644  files.append( info ); // Files and any symlinks
2645  }
2646  }
2647  }
2648 }
2649 
2650 void CopyJob::skipSrc()
2651 {
2652  m_dest = d->m_globalDest;
2653  destinationState = d->m_globalDestinationState;
2654  ++m_currentStatSrc;
2655  skip( m_currentSrcURL );
2656  statCurrentSrc();
2657 }
2658 
2659 void CopyJob::statNextSrc()
2660 {
2661  /* Revert to the global destination, the one that applies to all source urls.
2662  * Imagine you copy the items a b and c into /d, but /d/b exists so the user uses "Rename" to put it in /foo/b instead.
2663  * m_dest is /foo/b for b, but we have to revert to /d for item c and following.
2664  */
2665  m_dest = d->m_globalDest;
2666  destinationState = d->m_globalDestinationState;
2667  ++m_currentStatSrc;
2668  statCurrentSrc();
2669 }
2670 
2671 void CopyJob::statCurrentSrc()
2672 {
2673  if ( m_currentStatSrc != m_srcList.end() )
2674  {
2675  m_currentSrcURL = (*m_currentStatSrc);
2676  d->m_bURLDirty = true;
2677  if ( m_mode == Link )
2678  {
2679  // Skip the "stating the source" stage, we don't need it for linking
2680  m_currentDest = m_dest;
2681  struct CopyInfo info;
2682  info.permissions = -1;
2683  info.mtime = (time_t) -1;
2684  info.ctime = (time_t) -1;
2685  info.size = (TDEIO::filesize_t)-1;
2686  info.uSource = m_currentSrcURL;
2687  info.uDest = m_currentDest;
2688  // Append filename or dirname to destination URL, if allowed
2689  if ( destinationState == DEST_IS_DIR && !m_asMethod )
2690  {
2691  if (
2692  (m_currentSrcURL.protocol() == info.uDest.protocol()) &&
2693  (m_currentSrcURL.host() == info.uDest.host()) &&
2694  (m_currentSrcURL.port() == info.uDest.port()) &&
2695  (m_currentSrcURL.user() == info.uDest.user()) &&
2696  (m_currentSrcURL.pass() == info.uDest.pass()) )
2697  {
2698  // This is the case of creating a real symlink
2699  info.uDest.addPath( m_currentSrcURL.fileName() );
2700  }
2701  else
2702  {
2703  // Different protocols, we'll create a .desktop file
2704  // We have to change the extension anyway, so while we're at it,
2705  // name the file like the URL
2706  info.uDest.addPath( TDEIO::encodeFileName( m_currentSrcURL.prettyURL() )+".desktop" );
2707  }
2708  }
2709  files.append( info ); // Files and any symlinks
2710  statNextSrc(); // we could use a loop instead of a recursive call :)
2711  return;
2712  }
2713  else if ( m_mode == Move && (
2714  // Don't go renaming right away if we need a stat() to find out the destination filename
2715  KProtocolInfo::fileNameUsedForCopying( m_currentSrcURL ) == KProtocolInfo::FromURL ||
2716  destinationState != DEST_IS_DIR || m_asMethod )
2717  )
2718  {
2719  // If moving, before going for the full stat+[list+]copy+del thing, try to rename
2720  // The logic is pretty similar to FileCopyJob::slotStart()
2721  if ( (m_currentSrcURL.protocol() == m_dest.protocol()) &&
2722  (m_currentSrcURL.host() == m_dest.host()) &&
2723  (m_currentSrcURL.port() == m_dest.port()) &&
2724  (m_currentSrcURL.user() == m_dest.user()) &&
2725  (m_currentSrcURL.pass() == m_dest.pass()) )
2726  {
2727  startRenameJob( m_currentSrcURL );
2728  return;
2729  }
2730  else if ( m_currentSrcURL.isLocalFile() && KProtocolInfo::canRenameFromFile( m_dest ) )
2731  {
2732  startRenameJob( m_dest );
2733  return;
2734  }
2735  else if ( m_dest.isLocalFile() && KProtocolInfo::canRenameToFile( m_currentSrcURL ) )
2736  {
2737  startRenameJob( m_currentSrcURL );
2738  return;
2739  }
2740  }
2741 
2742  // if the file system doesn't support deleting, we do not even stat
2743  if (m_mode == Move && !KProtocolInfo::supportsDeleting(m_currentSrcURL)) {
2744  TQGuardedPtr<CopyJob> that = this;
2745  if (isInteractive())
2746  KMessageBox::information( 0, buildErrorString(ERR_CANNOT_DELETE, m_currentSrcURL.prettyURL()));
2747  if (that)
2748  statNextSrc(); // we could use a loop instead of a recursive call :)
2749  return;
2750  }
2751 
2752  // Stat the next src url
2753  Job * job = TDEIO::stat( m_currentSrcURL, true, 2, false );
2754  //kdDebug(7007) << "TDEIO::stat on " << m_currentSrcURL << endl;
2755  state = STATE_STATING;
2756  addSubjob(job);
2757  m_currentDestURL=m_dest;
2758  m_bOnlyRenames = false;
2759  d->m_bURLDirty = true;
2760  }
2761  else
2762  {
2763  // Finished the stat'ing phase
2764  // First make sure that the totals were correctly emitted
2765  state = STATE_STATING;
2766  d->m_bURLDirty = true;
2767  slotReport();
2768  if (!dirs.isEmpty())
2769  emit aboutToCreate( this, dirs );
2770  if (!files.isEmpty())
2771  emit aboutToCreate( this, files );
2772  // Check if we are copying a single file
2773  m_bSingleFileCopy = ( files.count() == 1 && dirs.isEmpty() );
2774  // Then start copying things
2775  state = STATE_CREATING_DIRS;
2776  createNextDir();
2777  }
2778 }
2779 
2780 void CopyJob::startRenameJob( const KURL& slave_url )
2781 {
2782  KURL dest = m_dest;
2783  // Append filename or dirname to destination URL, if allowed
2784  if ( destinationState == DEST_IS_DIR && !m_asMethod )
2785  dest.addPath( m_currentSrcURL.fileName() );
2786  kdDebug(7007) << "This seems to be a suitable case for trying to rename before stat+[list+]copy+del" << endl;
2787  state = STATE_RENAMING;
2788 
2789  struct CopyInfo info;
2790  info.permissions = -1;
2791  info.mtime = (time_t) -1;
2792  info.ctime = (time_t) -1;
2793  info.size = (TDEIO::filesize_t)-1;
2794  info.uSource = m_currentSrcURL;
2795  info.uDest = dest;
2796  TQValueList<CopyInfo> files;
2797  files.append(info);
2798  emit aboutToCreate( this, files );
2799 
2800  KIO_ARGS << m_currentSrcURL << dest << (TQ_INT8) false /*no overwrite*/;
2801  SimpleJob * newJob = new SimpleJob(slave_url, CMD_RENAME, packedArgs, false);
2802  Scheduler::scheduleJob(newJob);
2803  addSubjob( newJob );
2804  if ( m_currentSrcURL.directory() != dest.directory() ) // For the user, moving isn't renaming. Only renaming is.
2805  m_bOnlyRenames = false;
2806 }
2807 
2808 void CopyJob::startListing( const KURL & src )
2809 {
2810  state = STATE_LISTING;
2811  d->m_bURLDirty = true;
2812  ListJob * newjob = listRecursive( src, false );
2813  newjob->setUnrestricted(true);
2814  connect(newjob, TQT_SIGNAL(entries( TDEIO::Job *,
2815  const TDEIO::UDSEntryList& )),
2816  TQT_SLOT( slotEntries( TDEIO::Job*,
2817  const TDEIO::UDSEntryList& )));
2818  addSubjob( newjob );
2819 }
2820 
2821 void CopyJob::skip( const KURL & sourceUrl )
2822 {
2823  // Check if this is one if toplevel sources
2824  // If yes, remove it from m_srcList, for a correct FilesRemoved() signal
2825  //kdDebug(7007) << "CopyJob::skip: looking for " << sourceUrl << endl;
2826  KURL::List::Iterator sit = m_srcList.find( sourceUrl );
2827  if ( sit != m_srcList.end() )
2828  {
2829  //kdDebug(7007) << "CopyJob::skip: removing " << sourceUrl << " from list" << endl;
2830  m_srcList.remove( sit );
2831  }
2832  dirsToRemove.remove( sourceUrl );
2833 }
2834 
2835 bool CopyJob::shouldOverwrite( const TQString& path ) const
2836 {
2837  if ( m_bOverwriteAll )
2838  return true;
2839  TQStringList::ConstIterator sit = m_overwriteList.begin();
2840  for( ; sit != m_overwriteList.end(); ++sit )
2841  if ( path.startsWith( *sit ) )
2842  return true;
2843  return false;
2844 }
2845 
2846 bool CopyJob::shouldSkip( const TQString& path ) const
2847 {
2848  TQStringList::ConstIterator sit = m_skipList.begin();
2849  for( ; sit != m_skipList.end(); ++sit )
2850  if ( path.startsWith( *sit ) )
2851  return true;
2852  return false;
2853 }
2854 
2855 void CopyJob::slotResultCreatingDirs( Job * job )
2856 {
2857  // The dir we are trying to create:
2858  TQValueList<CopyInfo>::Iterator it = dirs.begin();
2859  // Was there an error creating a dir ?
2860  if ( job->error() )
2861  {
2862  m_conflictError = job->error();
2863  if ( (m_conflictError == ERR_DIR_ALREADY_EXIST)
2864  || (m_conflictError == ERR_FILE_ALREADY_EXIST) ) // can't happen?
2865  {
2866  KURL oldURL = ((SimpleJob*)job)->url();
2867  // Should we skip automatically ?
2868  if ( m_bAutoSkip ) {
2869  // We don't want to copy files in this directory, so we put it on the skip list
2870  m_skipList.append( oldURL.path( 1 ) );
2871  skip( oldURL );
2872  dirs.remove( it ); // Move on to next dir
2873  } else {
2874  // Did the user choose to overwrite already?
2875  const TQString destFile = (*it).uDest.path();
2876  if ( shouldOverwrite( destFile ) ) { // overwrite => just skip
2877  emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
2878  dirs.remove( it ); // Move on to next dir
2879  } else {
2880  if ( !isInteractive() ) {
2881  Job::slotResult( job ); // will set the error and emit result(this)
2882  return;
2883  }
2884 
2885  assert( ((SimpleJob*)job)->url().url() == (*it).uDest.url() );
2886  subjobs.remove( job );
2887  assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
2888 
2889  // We need to stat the existing dir, to get its last-modification time
2890  KURL existingDest( (*it).uDest );
2891  SimpleJob * newJob = TDEIO::stat( existingDest, false, 2, false );
2892  Scheduler::scheduleJob(newJob);
2893  kdDebug(7007) << "TDEIO::stat for resolving conflict on " << existingDest << endl;
2894  state = STATE_CONFLICT_CREATING_DIRS;
2895  addSubjob(newJob);
2896  return; // Don't move to next dir yet !
2897  }
2898  }
2899  }
2900  else
2901  {
2902  // Severe error, abort
2903  Job::slotResult( job ); // will set the error and emit result(this)
2904  return;
2905  }
2906  }
2907  else // no error : remove from list, to move on to next dir
2908  {
2909  //this is required for the undo feature
2910  emit copyingDone( this, (*it).uSource, (*it).uDest, true, false );
2911  d->m_directoriesCopied.append( *it );
2912  dirs.remove( it );
2913  }
2914 
2915  m_processedDirs++;
2916  //emit processedDirs( this, m_processedDirs );
2917  subjobs.remove( job );
2918  assert( subjobs.isEmpty() ); // We should have only one job at a time ...
2919  createNextDir();
2920 }
2921 
2922 void CopyJob::slotResultConflictCreatingDirs( TDEIO::Job * job )
2923 {
2924  // We come here after a conflict has been detected and we've stated the existing dir
2925 
2926  // The dir we were trying to create:
2927  TQValueList<CopyInfo>::Iterator it = dirs.begin();
2928  // Its modification time:
2929  time_t destmtime = (time_t)-1;
2930  time_t destctime = (time_t)-1;
2931  TDEIO::filesize_t destsize = 0;
2932  TQString linkDest;
2933 
2934  UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
2935  TDEIO::UDSEntry::ConstIterator it2 = entry.begin();
2936  for( ; it2 != entry.end(); it2++ ) {
2937  switch ((*it2).m_uds) {
2938  case UDS_MODIFICATION_TIME:
2939  destmtime = (time_t)((*it2).m_long);
2940  break;
2941  case UDS_CREATION_TIME:
2942  destctime = (time_t)((*it2).m_long);
2943  break;
2944  case UDS_SIZE:
2945  destsize = (*it2).m_long;
2946  break;
2947  case UDS_LINK_DEST:
2948  linkDest = (*it2).m_str;
2949  break;
2950  }
2951  }
2952  subjobs.remove( job );
2953  assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
2954 
2955  // Always multi and skip (since there are files after that)
2956  RenameDlg_Mode mode = (RenameDlg_Mode)( M_MULTI | M_SKIP );
2957  // Overwrite only if the existing thing is a dir (no chance with a file)
2958  if ( m_conflictError == ERR_DIR_ALREADY_EXIST )
2959  {
2960  if( (*it).uSource == (*it).uDest ||
2961  ((*it).uSource.protocol() == (*it).uDest.protocol() &&
2962  (*it).uSource.path(-1) == linkDest) )
2963  mode = (RenameDlg_Mode)( mode | M_OVERWRITE_ITSELF);
2964  else
2965  mode = (RenameDlg_Mode)( mode | M_OVERWRITE );
2966  }
2967 
2968  TQString existingDest = (*it).uDest.path();
2969  TQString newPath;
2970  if (m_reportTimer)
2971  m_reportTimer->stop();
2972  RenameDlg_Result r = Observer::self()->open_RenameDlg( this, i18n("Folder Already Exists"),
2973  (*it).uSource.url(),
2974  (*it).uDest.url(),
2975  mode, newPath,
2976  (*it).size, destsize,
2977  (*it).ctime, destctime,
2978  (*it).mtime, destmtime );
2979  if (m_reportTimer)
2980  m_reportTimer->start(REPORT_TIMEOUT,false);
2981  switch ( r ) {
2982  case R_CANCEL:
2983  m_error = ERR_USER_CANCELED;
2984  emitResult();
2985  return;
2986  case R_RENAME:
2987  {
2988  TQString oldPath = (*it).uDest.path( 1 );
2989  KURL newUrl( (*it).uDest );
2990  newUrl.setPath( newPath );
2991  emit renamed( this, (*it).uDest, newUrl ); // for e.g. kpropsdlg
2992 
2993  // Change the current one and strip the trailing '/'
2994  (*it).uDest.setPath( newUrl.path( -1 ) );
2995  newPath = newUrl.path( 1 ); // With trailing slash
2996  TQValueList<CopyInfo>::Iterator renamedirit = it;
2997  ++renamedirit;
2998  // Change the name of subdirectories inside the directory
2999  for( ; renamedirit != dirs.end() ; ++renamedirit )
3000  {
3001  TQString path = (*renamedirit).uDest.path();
3002  if ( path.left(oldPath.length()) == oldPath ) {
3003  TQString n = path;
3004  n.replace( 0, oldPath.length(), newPath );
3005  kdDebug(7007) << "dirs list: " << (*renamedirit).uSource.path()
3006  << " was going to be " << path
3007  << ", changed into " << n << endl;
3008  (*renamedirit).uDest.setPath( n );
3009  }
3010  }
3011  // Change filenames inside the directory
3012  TQValueList<CopyInfo>::Iterator renamefileit = files.begin();
3013  for( ; renamefileit != files.end() ; ++renamefileit )
3014  {
3015  TQString path = (*renamefileit).uDest.path();
3016  if ( path.left(oldPath.length()) == oldPath ) {
3017  TQString n = path;
3018  n.replace( 0, oldPath.length(), newPath );
3019  kdDebug(7007) << "files list: " << (*renamefileit).uSource.path()
3020  << " was going to be " << path
3021  << ", changed into " << n << endl;
3022  (*renamefileit).uDest.setPath( n );
3023  }
3024  }
3025  if (!dirs.isEmpty())
3026  emit aboutToCreate( this, dirs );
3027  if (!files.isEmpty())
3028  emit aboutToCreate( this, files );
3029  }
3030  break;
3031  case R_AUTO_SKIP:
3032  m_bAutoSkip = true;
3033  // fall through
3034  case R_SKIP:
3035  m_skipList.append( existingDest );
3036  skip( (*it).uSource );
3037  // Move on to next dir
3038  dirs.remove( it );
3039  m_processedDirs++;
3040  break;
3041  case R_OVERWRITE:
3042  m_overwriteList.append( existingDest );
3043  emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
3044  // Move on to next dir
3045  dirs.remove( it );
3046  m_processedDirs++;
3047  break;
3048  case R_OVERWRITE_ALL:
3049  m_bOverwriteAll = true;
3050  emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
3051  // Move on to next dir
3052  dirs.remove( it );
3053  m_processedDirs++;
3054  break;
3055  default:
3056  assert( 0 );
3057  }
3058  state = STATE_CREATING_DIRS;
3059  //emit processedDirs( this, m_processedDirs );
3060  createNextDir();
3061 }
3062 
3063 void CopyJob::createNextDir()
3064 {
3065  KURL udir;
3066  if ( !dirs.isEmpty() )
3067  {
3068  // Take first dir to create out of list
3069  TQValueList<CopyInfo>::Iterator it = dirs.begin();
3070  // Is this URL on the skip list or the overwrite list ?
3071  while( it != dirs.end() && udir.isEmpty() )
3072  {
3073  const TQString dir = (*it).uDest.path();
3074  if ( shouldSkip( dir ) ) {
3075  dirs.remove( it );
3076  it = dirs.begin();
3077  } else
3078  udir = (*it).uDest;
3079  }
3080  }
3081  if ( !udir.isEmpty() ) // any dir to create, finally ?
3082  {
3083  // Create the directory - with default permissions so that we can put files into it
3084  // TODO : change permissions once all is finished; but for stuff coming from CDROM it sucks...
3085  TDEIO::SimpleJob *newjob = TDEIO::mkdir( udir, -1 );
3086  Scheduler::scheduleJob(newjob);
3087 
3088  m_currentDestURL = udir;
3089  d->m_bURLDirty = true;
3090 
3091  addSubjob(newjob);
3092  return;
3093  }
3094  else // we have finished creating dirs
3095  {
3096  emit processedDirs( this, m_processedDirs ); // make sure final number appears
3097  if (m_progressId) Observer::self()->slotProcessedDirs( this, m_processedDirs );
3098 
3099  state = STATE_COPYING_FILES;
3100  m_processedFiles++; // Ralf wants it to start at 1, not 0
3101  copyNextFile();
3102  }
3103 }
3104 
3105 void CopyJob::slotResultCopyingFiles( Job * job )
3106 {
3107  // The file we were trying to copy:
3108  TQValueList<CopyInfo>::Iterator it = files.begin();
3109  if ( job->error() )
3110  {
3111  // Should we skip automatically ?
3112  if ( m_bAutoSkip )
3113  {
3114  skip( (*it).uSource );
3115  m_fileProcessedSize = (*it).size;
3116  files.remove( it ); // Move on to next file
3117  }
3118  else
3119  {
3120  if ( !isInteractive() ) {
3121  Job::slotResult( job ); // will set the error and emit result(this)
3122  return;
3123  }
3124 
3125  m_conflictError = job->error(); // save for later
3126  // Existing dest ?
3127  if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
3128  || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
3129  || ( m_conflictError == ERR_IDENTICAL_FILES ) )
3130  {
3131  subjobs.remove( job );
3132  assert ( subjobs.isEmpty() );
3133  // We need to stat the existing file, to get its last-modification time
3134  KURL existingFile( (*it).uDest );
3135  SimpleJob * newJob = TDEIO::stat( existingFile, false, 2, false );
3136  Scheduler::scheduleJob(newJob);
3137  kdDebug(7007) << "TDEIO::stat for resolving conflict on " << existingFile << endl;
3138  state = STATE_CONFLICT_COPYING_FILES;
3139  addSubjob(newJob);
3140  return; // Don't move to next file yet !
3141  }
3142  else
3143  {
3144  if ( m_bCurrentOperationIsLink && ::tqqt_cast<TDEIO::DeleteJob*>( job ) )
3145  {
3146  // Very special case, see a few lines below
3147  // We are deleting the source of a symlink we successfully moved... ignore error
3148  m_fileProcessedSize = (*it).size;
3149  files.remove( it );
3150  } else {
3151  // Go directly to the conflict resolution, there is nothing to stat
3152  slotResultConflictCopyingFiles( job );
3153  return;
3154  }
3155  }
3156  }
3157  } else // no error
3158  {
3159  // Special case for moving links. That operation needs two jobs, unlike others.
3160  if ( m_bCurrentOperationIsLink && m_mode == Move
3161  && !::tqqt_cast<TDEIO::DeleteJob *>( job ) // Deleting source not already done
3162  )
3163  {
3164  subjobs.remove( job );
3165  assert ( subjobs.isEmpty() );
3166  // The only problem with this trick is that the error handling for this del operation
3167  // is not going to be right... see 'Very special case' above.
3168  TDEIO::Job * newjob = TDEIO::del( (*it).uSource, false /*don't shred*/, false /*no GUI*/ );
3169  addSubjob( newjob );
3170  return; // Don't move to next file yet !
3171  }
3172 
3173  if ( m_bCurrentOperationIsLink )
3174  {
3175  TQString target = ( m_mode == Link ? (*it).uSource.path() : (*it).linkDest );
3176  //required for the undo feature
3177  emit copyingLinkDone( this, (*it).uSource, target, (*it).uDest );
3178  }
3179  else
3180  //required for the undo feature
3181  emit copyingDone( this, (*it).uSource, (*it).uDest, false, false );
3182  // remove from list, to move on to next file
3183  files.remove( it );
3184  }
3185  m_processedFiles++;
3186 
3187  // clear processed size for last file and add it to overall processed size
3188  m_processedSize += m_fileProcessedSize;
3189  m_fileProcessedSize = 0;
3190 
3191  //kdDebug(7007) << files.count() << " files remaining" << endl;
3192 
3193  removeSubjob( job, true, false ); // merge metadata
3194  assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
3195  copyNextFile();
3196 }
3197 
3198 void CopyJob::slotResultConflictCopyingFiles( TDEIO::Job * job )
3199 {
3200  // We come here after a conflict has been detected and we've stated the existing file
3201  // The file we were trying to create:
3202  TQValueList<CopyInfo>::Iterator it = files.begin();
3203 
3204  RenameDlg_Result res;
3205  TQString newPath;
3206 
3207  if (m_reportTimer)
3208  m_reportTimer->stop();
3209 
3210  if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
3211  || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
3212  || ( m_conflictError == ERR_IDENTICAL_FILES ) )
3213  {
3214  // Its modification time:
3215  time_t destmtime = (time_t)-1;
3216  time_t destctime = (time_t)-1;
3217  TDEIO::filesize_t destsize = 0;
3218  TQString linkDest;
3219  UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
3220  TDEIO::UDSEntry::ConstIterator it2 = entry.begin();
3221  for( ; it2 != entry.end(); it2++ ) {
3222  switch ((*it2).m_uds) {
3223  case UDS_MODIFICATION_TIME:
3224  destmtime = (time_t)((*it2).m_long);
3225  break;
3226  case UDS_CREATION_TIME:
3227  destctime = (time_t)((*it2).m_long);
3228  break;
3229  case UDS_SIZE:
3230  destsize = (*it2).m_long;
3231  break;
3232  case UDS_LINK_DEST:
3233  linkDest = (*it2).m_str;
3234  break;
3235  }
3236  }
3237 
3238  // Offer overwrite only if the existing thing is a file
3239  // If src==dest, use "overwrite-itself"
3240  RenameDlg_Mode mode;
3241  bool isDir = true;
3242 
3243  if( m_conflictError == ERR_DIR_ALREADY_EXIST )
3244  mode = (RenameDlg_Mode) 0;
3245  else
3246  {
3247  if ( (*it).uSource == (*it).uDest ||
3248  ((*it).uSource.protocol() == (*it).uDest.protocol() &&
3249  (*it).uSource.path(-1) == linkDest) )
3250  mode = M_OVERWRITE_ITSELF;
3251  else
3252  mode = M_OVERWRITE;
3253  isDir = false;
3254  }
3255 
3256  if ( m_bSingleFileCopy )
3257  mode = (RenameDlg_Mode) ( mode | M_SINGLE );
3258  else
3259  mode = (RenameDlg_Mode) ( mode | M_MULTI | M_SKIP );
3260 
3261  res = Observer::self()->open_RenameDlg( this, !isDir ?
3262  i18n("File Already Exists") : i18n("Already Exists as Folder"),
3263  (*it).uSource.url(),
3264  (*it).uDest.url(),
3265  mode, newPath,
3266  (*it).size, destsize,
3267  (*it).ctime, destctime,
3268  (*it).mtime, destmtime );
3269 
3270  }
3271  else
3272  {
3273  if ( job->error() == ERR_USER_CANCELED )
3274  res = R_CANCEL;
3275  else if ( !isInteractive() ) {
3276  Job::slotResult( job ); // will set the error and emit result(this)
3277  return;
3278  }
3279  else
3280  {
3281  SkipDlg_Result skipResult = Observer::self()->open_SkipDlg( this, files.count() > 1,
3282  job->errorString() );
3283 
3284  // Convert the return code from SkipDlg into a RenameDlg code
3285  res = ( skipResult == S_SKIP ) ? R_SKIP :
3286  ( skipResult == S_AUTO_SKIP ) ? R_AUTO_SKIP :
3287  R_CANCEL;
3288  }
3289  }
3290 
3291  if (m_reportTimer)
3292  m_reportTimer->start(REPORT_TIMEOUT,false);
3293 
3294  subjobs.remove( job );
3295  assert ( subjobs.isEmpty() );
3296  switch ( res ) {
3297  case R_CANCEL:
3298  m_error = ERR_USER_CANCELED;
3299  emitResult();
3300  return;
3301  case R_RENAME:
3302  {
3303  KURL newUrl( (*it).uDest );
3304  newUrl.setPath( newPath );
3305  emit renamed( this, (*it).uDest, newUrl ); // for e.g. kpropsdlg
3306  (*it).uDest = newUrl;
3307 
3308  TQValueList<CopyInfo> files;
3309  files.append(*it);
3310  emit aboutToCreate( this, files );
3311  }
3312  break;
3313  case R_AUTO_SKIP:
3314  m_bAutoSkip = true;
3315  // fall through
3316  case R_SKIP:
3317  // Move on to next file
3318  skip( (*it).uSource );
3319  m_processedSize += (*it).size;
3320  files.remove( it );
3321  m_processedFiles++;
3322  break;
3323  case R_OVERWRITE_ALL:
3324  m_bOverwriteAll = true;
3325  break;
3326  case R_OVERWRITE:
3327  // Add to overwrite list, so that copyNextFile knows to overwrite
3328  m_overwriteList.append( (*it).uDest.path() );
3329  break;
3330  default:
3331  assert( 0 );
3332  }
3333  state = STATE_COPYING_FILES;
3334  //emit processedFiles( this, m_processedFiles );
3335  copyNextFile();
3336 }
3337 
3338 void CopyJob::copyNextFile()
3339 {
3340  bool bCopyFile = false;
3341  //kdDebug(7007) << "CopyJob::copyNextFile()" << endl;
3342  // Take the first file in the list
3343  TQValueList<CopyInfo>::Iterator it = files.begin();
3344  // Is this URL on the skip list ?
3345  while (it != files.end() && !bCopyFile)
3346  {
3347  const TQString destFile = (*it).uDest.path();
3348  bCopyFile = !shouldSkip( destFile );
3349  if ( !bCopyFile ) {
3350  files.remove( it );
3351  it = files.begin();
3352  }
3353  }
3354 
3355  if (bCopyFile) // any file to create, finally ?
3356  {
3357  // Do we set overwrite ?
3358  bool bOverwrite;
3359  const TQString destFile = (*it).uDest.path();
3360  kdDebug(7007) << "copying " << destFile << endl;
3361  if ( (*it).uDest == (*it).uSource )
3362  bOverwrite = false;
3363  else
3364  bOverwrite = shouldOverwrite( destFile );
3365 
3366  m_bCurrentOperationIsLink = false;
3367  TDEIO::Job * newjob = 0L;
3368  if ( m_mode == Link )
3369  {
3370  //kdDebug(7007) << "Linking" << endl;
3371  if (
3372  ((*it).uSource.protocol() == (*it).uDest.protocol()) &&
3373  ((*it).uSource.host() == (*it).uDest.host()) &&
3374  ((*it).uSource.port() == (*it).uDest.port()) &&
3375  ((*it).uSource.user() == (*it).uDest.user()) &&
3376  ((*it).uSource.pass() == (*it).uDest.pass()) )
3377  {
3378  // This is the case of creating a real symlink
3379  TDEIO::SimpleJob *newJob = TDEIO::symlink( (*it).uSource.path(), (*it).uDest, bOverwrite, false /*no GUI*/ );
3380  newjob = newJob;
3381  Scheduler::scheduleJob(newJob);
3382  //kdDebug(7007) << "CopyJob::copyNextFile : Linking target=" << (*it).uSource.path() << " link=" << (*it).uDest << endl;
3383  //emit linking( this, (*it).uSource.path(), (*it).uDest );
3384  m_bCurrentOperationIsLink = true;
3385  m_currentSrcURL=(*it).uSource;
3386  m_currentDestURL=(*it).uDest;
3387  d->m_bURLDirty = true;
3388  //Observer::self()->slotCopying( this, (*it).uSource, (*it).uDest ); // should be slotLinking perhaps
3389  } else {
3390  //kdDebug(7007) << "CopyJob::copyNextFile : Linking URL=" << (*it).uSource << " link=" << (*it).uDest << endl;
3391  if ( (*it).uDest.isLocalFile() )
3392  {
3393  bool devicesOk=false;
3394 
3395  // if the source is a devices url, handle it a littlebit special
3396  if ((*it).uSource.protocol()==TQString::fromLatin1("devices"))
3397  {
3398  TQByteArray data;
3399  TQByteArray param;
3400  TQCString retType;
3401  TQDataStream streamout(param,IO_WriteOnly);
3402  streamout<<(*it).uSource;
3403  streamout<<(*it).uDest;
3404  if ( kapp && kapp->dcopClient()->call( "kded",
3405  "mountwatcher", "createLink(KURL, KURL)", param,retType,data,false ) )
3406  {
3407  TQDataStream streamin(data,IO_ReadOnly);
3408  streamin>>devicesOk;
3409  }
3410  if (devicesOk)
3411  {
3412  files.remove( it );
3413  m_processedFiles++;
3414  //emit processedFiles( this, m_processedFiles );
3415  copyNextFile();
3416  return;
3417  }
3418  }
3419 
3420  if (!devicesOk)
3421  {
3422  TQString path = (*it).uDest.path();
3423  //kdDebug(7007) << "CopyJob::copyNextFile path=" << path << endl;
3424  TQFile f( path );
3425  if ( f.open( IO_ReadWrite ) )
3426  {
3427  f.close();
3428  KSimpleConfig config( path );
3429  config.setDesktopGroup();
3430  KURL url = (*it).uSource;
3431  url.setPass( "" );
3432  config.writePathEntry( TQString::fromLatin1("URL"), url.url() );
3433  config.writeEntry( TQString::fromLatin1("Name"), url.url() );
3434  config.writeEntry( TQString::fromLatin1("Type"), TQString::fromLatin1("Link") );
3435  TQString protocol = (*it).uSource.protocol();
3436  if ( protocol == TQString::fromLatin1("ftp") )
3437  config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("ftp") );
3438  else if ( protocol == TQString::fromLatin1("http") )
3439  config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("www") );
3440  else if ( protocol == TQString::fromLatin1("info") )
3441  config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("info") );
3442  else if ( protocol == TQString::fromLatin1("mailto") ) // sven:
3443  config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("kmail") ); // added mailto: support
3444  else
3445  config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("unknown") );
3446  config.sync();
3447  files.remove( it );
3448  m_processedFiles++;
3449  //emit processedFiles( this, m_processedFiles );
3450  copyNextFile();
3451  return;
3452  }
3453  else
3454  {
3455  kdDebug(7007) << "CopyJob::copyNextFile ERR_CANNOT_OPEN_FOR_WRITING" << endl;
3456  m_error = ERR_CANNOT_OPEN_FOR_WRITING;
3457  m_errorText = (*it).uDest.path();
3458  emitResult();
3459  return;
3460  }
3461  }
3462  } else {
3463  // Todo: not show "link" on remote dirs if the src urls are not from the same protocol+host+...
3464  m_error = ERR_CANNOT_SYMLINK;
3465  m_errorText = (*it).uDest.prettyURL();
3466  emitResult();
3467  return;
3468  }
3469  }
3470  }
3471  else if ( !(*it).linkDest.isEmpty() &&
3472  ((*it).uSource.protocol() == (*it).uDest.protocol()) &&
3473  ((*it).uSource.host() == (*it).uDest.host()) &&
3474  ((*it).uSource.port() == (*it).uDest.port()) &&
3475  ((*it).uSource.user() == (*it).uDest.user()) &&
3476  ((*it).uSource.pass() == (*it).uDest.pass()))
3477  // Copying a symlink - only on the same protocol/host/etc. (#5601, downloading an FTP file through its link),
3478  {
3479  TDEIO::SimpleJob *newJob = TDEIO::symlink( (*it).linkDest, (*it).uDest, bOverwrite, false /*no GUI*/ );
3480  Scheduler::scheduleJob(newJob);
3481  newjob = newJob;
3482  //kdDebug(7007) << "CopyJob::copyNextFile : Linking target=" << (*it).linkDest << " link=" << (*it).uDest << endl;
3483  //emit linking( this, (*it).linkDest, (*it).uDest );
3484  m_currentSrcURL=(*it).linkDest;
3485  m_currentDestURL=(*it).uDest;
3486  d->m_bURLDirty = true;
3487  //Observer::self()->slotCopying( this, (*it).linkDest, (*it).uDest ); // should be slotLinking perhaps
3488  m_bCurrentOperationIsLink = true;
3489  // NOTE: if we are moving stuff, the deletion of the source will be done in slotResultCopyingFiles
3490  } else if (m_mode == Move) // Moving a file
3491  {
3492  TDEIO::FileCopyJob * moveJob = TDEIO::file_move( (*it).uSource, (*it).uDest, (*it).permissions, bOverwrite, false, false/*no GUI*/ );
3493  moveJob->setSourceSize64( (*it).size );
3494  newjob = moveJob;
3495  //kdDebug(7007) << "CopyJob::copyNextFile : Moving " << (*it).uSource << " to " << (*it).uDest << endl;
3496  //emit moving( this, (*it).uSource, (*it).uDest );
3497  m_currentSrcURL=(*it).uSource;
3498  m_currentDestURL=(*it).uDest;
3499  d->m_bURLDirty = true;
3500  //Observer::self()->slotMoving( this, (*it).uSource, (*it).uDest );
3501  }
3502  else // Copying a file
3503  {
3504  // If source isn't local and target is local, we ignore the original permissions
3505  // Otherwise, files downloaded from HTTP end up with -r--r--r--
3506  bool remoteSource = !KProtocolInfo::supportsListing((*it).uSource);
3507  int permissions = (*it).permissions;
3508  if ( d->m_defaultPermissions || ( remoteSource && (*it).uDest.isLocalFile() ) )
3509  permissions = -1;
3510  TDEIO::FileCopyJob * copyJob = TDEIO::file_copy( (*it).uSource, (*it).uDest, permissions, bOverwrite, false, false/*no GUI*/ );
3511  copyJob->setParentJob( this ); // in case of rename dialog
3512  copyJob->setSourceSize64( (*it).size );
3513  copyJob->setModificationTime( (*it).mtime );
3514  newjob = copyJob;
3515  //kdDebug(7007) << "CopyJob::copyNextFile : Copying " << (*it).uSource << " to " << (*it).uDest << endl;
3516  m_currentSrcURL=(*it).uSource;
3517  m_currentDestURL=(*it).uDest;
3518  d->m_bURLDirty = true;
3519  }
3520  addSubjob(newjob);
3521  connect( newjob, TQT_SIGNAL( processedSize( TDEIO::Job*, TDEIO::filesize_t ) ),
3522  this, TQT_SLOT( slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
3523  connect( newjob, TQT_SIGNAL( totalSize( TDEIO::Job*, TDEIO::filesize_t ) ),
3524  this, TQT_SLOT( slotTotalSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
3525  }
3526  else
3527  {
3528  // We're done
3529  //kdDebug(7007) << "copyNextFile finished" << endl;
3530  deleteNextDir();
3531  }
3532 }
3533 
3534 void CopyJob::deleteNextDir()
3535 {
3536  if ( m_mode == Move && !dirsToRemove.isEmpty() ) // some dirs to delete ?
3537  {
3538  state = STATE_DELETING_DIRS;
3539  d->m_bURLDirty = true;
3540  // Take first dir to delete out of list - last ones first !
3541  KURL::List::Iterator it = dirsToRemove.fromLast();
3542  SimpleJob *job = TDEIO::rmdir( *it );
3543  Scheduler::scheduleJob(job);
3544  dirsToRemove.remove(it);
3545  addSubjob( job );
3546  }
3547  else
3548  {
3549  // This step is done, move on
3550  setNextDirAttribute();
3551  }
3552 }
3553 
3554 void CopyJob::setNextDirAttribute()
3555 {
3556  if ( !d->m_directoriesCopied.isEmpty() )
3557  {
3558  state = STATE_SETTING_DIR_ATTRIBUTES;
3559 #ifdef Q_OS_UNIX
3560  // TODO KDE4: this should use a SlaveBase method, but we have none yet in KDE3.
3561  TQValueList<CopyInfo>::Iterator it = d->m_directoriesCopied.begin();
3562  for ( ; it != d->m_directoriesCopied.end() ; ++it ) {
3563  const KURL& url = (*it).uDest;
3564  if ( url.isLocalFile() && (*it).mtime != (time_t)-1 ) {
3565  const TQCString path = TQFile::encodeName( url.path() );
3566  KDE_struct_stat statbuf;
3567  if (KDE_lstat(path, &statbuf) == 0) {
3568  struct utimbuf utbuf;
3569  utbuf.actime = statbuf.st_atime; // access time, unchanged
3570  utbuf.modtime = (*it).mtime; // modification time
3571  utime( path, &utbuf );
3572  }
3573 
3574  }
3575  }
3576 #endif
3577  d->m_directoriesCopied.clear();
3578  }
3579 
3580  // No "else" here, since the above is a simple sync loop
3581 
3582  {
3583  // Finished - tell the world
3584  if ( !m_bOnlyRenames )
3585  {
3586  KDirNotify_stub allDirNotify("*", "KDirNotify*");
3587  KURL url( d->m_globalDest );
3588  if ( d->m_globalDestinationState != DEST_IS_DIR || m_asMethod )
3589  url.setPath( url.directory() );
3590  //kdDebug(7007) << "KDirNotify'ing FilesAdded " << url << endl;
3591  allDirNotify.FilesAdded( url );
3592 
3593  if ( m_mode == Move && !m_srcList.isEmpty() ) {
3594  //kdDebug(7007) << "KDirNotify'ing FilesRemoved " << m_srcList.toStringList() << endl;
3595  allDirNotify.FilesRemoved( m_srcList );
3596  }
3597  }
3598  if (m_reportTimer)
3599  m_reportTimer->stop();
3600  --m_processedFiles; // undo the "start at 1" hack
3601  slotReport(); // display final numbers, important if progress dialog stays up
3602 
3603  emitResult();
3604  }
3605 }
3606 
3607 void CopyJob::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size )
3608 {
3609  //kdDebug(7007) << "CopyJob::slotProcessedSize " << data_size << endl;
3610  m_fileProcessedSize = data_size;
3611  setProcessedSize(m_processedSize + m_fileProcessedSize);
3612 
3613  if ( m_processedSize + m_fileProcessedSize > m_totalSize )
3614  {
3615  m_totalSize = m_processedSize + m_fileProcessedSize;
3616  //kdDebug(7007) << "Adjusting m_totalSize to " << m_totalSize << endl;
3617  emit totalSize( this, m_totalSize ); // safety
3618  }
3619  //kdDebug(7007) << "emit processedSize " << (unsigned long) (m_processedSize + m_fileProcessedSize) << endl;
3620  emit processedSize( this, m_processedSize + m_fileProcessedSize );
3621  emitPercent( m_processedSize + m_fileProcessedSize, m_totalSize );
3622 }
3623 
3624 void CopyJob::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
3625 {
3626  //kdDebug(7007) << "slotTotalSize: " << size << endl;
3627  // Special case for copying a single file
3628  // This is because some protocols don't implement stat properly
3629  // (e.g. HTTP), and don't give us a size in some cases (redirection)
3630  // so we'd rather rely on the size given for the transfer
3631  if ( m_bSingleFileCopy && size > m_totalSize)
3632  {
3633  //kdDebug(7007) << "slotTotalSize: updating totalsize to " << size << endl;
3634  m_totalSize = size;
3635  emit totalSize( this, size );
3636  }
3637 }
3638 
3639 void CopyJob::slotResultDeletingDirs( Job * job )
3640 {
3641  if (job->error())
3642  {
3643  // Couldn't remove directory. Well, perhaps it's not empty
3644  // because the user pressed Skip for a given file in it.
3645  // Let's not display "Could not remove dir ..." for each of those dir !
3646  }
3647  subjobs.remove( job );
3648  assert ( subjobs.isEmpty() );
3649  deleteNextDir();
3650 }
3651 
3652 #if 0 // TODO KDE4
3653 void CopyJob::slotResultSettingDirAttributes( Job * job )
3654 {
3655  if (job->error())
3656  {
3657  // Couldn't set directory attributes. Ignore the error, it can happen
3658  // with inferior file systems like VFAT.
3659  // Let's not display warnings for each dir like "cp -a" does.
3660  }
3661  subjobs.remove( job );
3662  assert ( subjobs.isEmpty() );
3663  setNextDirAttribute();
3664 }
3665 #endif
3666 
3667 void CopyJob::slotResultRenaming( Job* job )
3668 {
3669  int err = job->error();
3670  const TQString errText = job->errorText();
3671  removeSubjob( job, true, false ); // merge metadata
3672  assert ( subjobs.isEmpty() );
3673  // Determine dest again
3674  KURL dest = m_dest;
3675  if ( destinationState == DEST_IS_DIR && !m_asMethod )
3676  dest.addPath( m_currentSrcURL.fileName() );
3677  if ( err )
3678  {
3679  // Direct renaming didn't work. Try renaming to a temp name,
3680  // this can help e.g. when renaming 'a' to 'A' on a VFAT partition.
3681  // In that case it's the _same_ dir, we don't want to copy+del (data loss!)
3682  if ( m_currentSrcURL.isLocalFile() && m_currentSrcURL.url(-1) != dest.url(-1) &&
3683  m_currentSrcURL.url(-1).lower() == dest.url(-1).lower() &&
3684  ( err == ERR_FILE_ALREADY_EXIST ||
3685  err == ERR_DIR_ALREADY_EXIST ||
3686  err == ERR_IDENTICAL_FILES ) )
3687  {
3688  kdDebug(7007) << "Couldn't rename directly, dest already exists. Detected special case of lower/uppercase renaming in same dir, try with 2 rename calls" << endl;
3689  TQCString _src( TQFile::encodeName(m_currentSrcURL.path()) );
3690  TQCString _dest( TQFile::encodeName(dest.path()) );
3691  KTempFile tmpFile( m_currentSrcURL.directory(false) );
3692  TQCString _tmp( TQFile::encodeName(tmpFile.name()) );
3693  kdDebug(7007) << "CopyJob::slotResult KTempFile status:" << tmpFile.status() << " using " << _tmp << " as intermediary" << endl;
3694  tmpFile.unlink();
3695  if ( ::rename( _src, _tmp ) == 0 )
3696  {
3697  if ( !TQFile::exists( _dest ) && ::rename( _tmp, _dest ) == 0 )
3698  {
3699  kdDebug(7007) << "Success." << endl;
3700  err = 0;
3701  }
3702  else
3703  {
3704  // Revert back to original name!
3705  if ( ::rename( _tmp, _src ) != 0 ) {
3706  kdError(7007) << "Couldn't rename " << tmpFile.name() << " back to " << _src << " !" << endl;
3707  // Severe error, abort
3708  Job::slotResult( job ); // will set the error and emit result(this)
3709  return;
3710  }
3711  }
3712  }
3713  }
3714  }
3715  if ( err )
3716  {
3717  // This code is similar to CopyJob::slotResultConflictCopyingFiles
3718  // but here it's about the base src url being moved/renamed
3719  // (*m_currentStatSrc) and its dest (m_dest), not about a single file.
3720  // It also means we already stated the dest, here.
3721  // On the other hand we haven't stated the src yet (we skipped doing it
3722  // to save time, since it's not necessary to rename directly!)...
3723 
3724  Q_ASSERT( m_currentSrcURL == *m_currentStatSrc );
3725 
3726  // Existing dest?
3727  if ( ( err == ERR_DIR_ALREADY_EXIST ||
3728  err == ERR_FILE_ALREADY_EXIST ||
3729  err == ERR_IDENTICAL_FILES )
3730  && isInteractive() )
3731  {
3732  if (m_reportTimer)
3733  m_reportTimer->stop();
3734 
3735  // Should we skip automatically ?
3736  if ( m_bAutoSkip ) {
3737  // Move on to next file
3738  skipSrc();
3739  return;
3740  } else if ( m_bOverwriteAll ) {
3741  ; // nothing to do, stat+copy+del will overwrite
3742  } else {
3743  TQString newPath;
3744  // If src==dest, use "overwrite-itself"
3745  RenameDlg_Mode mode = (RenameDlg_Mode)
3746  ( ( m_currentSrcURL == dest ) ? M_OVERWRITE_ITSELF : M_OVERWRITE );
3747 
3748  if ( m_srcList.count() > 1 )
3749  mode = (RenameDlg_Mode) ( mode | M_MULTI | M_SKIP );
3750  else
3751  mode = (RenameDlg_Mode) ( mode | M_SINGLE );
3752 
3753  // we lack mtime info for both the src (not stated)
3754  // and the dest (stated but this info wasn't stored)
3755  // Let's do it for local files, at least
3756  TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1;
3757  TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1;
3758  time_t ctimeSrc = (time_t) -1;
3759  time_t ctimeDest = (time_t) -1;
3760  time_t mtimeSrc = (time_t) -1;
3761  time_t mtimeDest = (time_t) -1;
3762 
3763  KDE_struct_stat stat_buf;
3764  if ( m_currentSrcURL.isLocalFile() &&
3765  KDE_stat(TQFile::encodeName(m_currentSrcURL.path()), &stat_buf) == 0 ) {
3766  sizeSrc = stat_buf.st_size;
3767  ctimeSrc = stat_buf.st_ctime;
3768  mtimeSrc = stat_buf.st_mtime;
3769  }
3770  if ( dest.isLocalFile() &&
3771  KDE_stat(TQFile::encodeName(dest.path()), &stat_buf) == 0 ) {
3772  sizeDest = stat_buf.st_size;
3773  ctimeDest = stat_buf.st_ctime;
3774  mtimeDest = stat_buf.st_mtime;
3775  }
3776 
3777  RenameDlg_Result r = Observer::self()->open_RenameDlg(
3778  this,
3779  err != ERR_DIR_ALREADY_EXIST ? i18n("File Already Exists") : i18n("Already Exists as Folder"),
3780  m_currentSrcURL.url(),
3781  dest.url(),
3782  mode, newPath,
3783  sizeSrc, sizeDest,
3784  ctimeSrc, ctimeDest,
3785  mtimeSrc, mtimeDest );
3786  if (m_reportTimer)
3787  m_reportTimer->start(REPORT_TIMEOUT,false);
3788 
3789  switch ( r )
3790  {
3791  case R_CANCEL:
3792  {
3793  m_error = ERR_USER_CANCELED;
3794  emitResult();
3795  return;
3796  }
3797  case R_RENAME:
3798  {
3799  // Set m_dest to the chosen destination
3800  // This is only for this src url; the next one will revert to d->m_globalDest
3801  m_dest.setPath( newPath );
3802  TDEIO::Job* job = TDEIO::stat( m_dest, false, 2, false );
3803  state = STATE_STATING;
3804  destinationState = DEST_NOT_STATED;
3805  addSubjob(job);
3806  return;
3807  }
3808  case R_AUTO_SKIP:
3809  m_bAutoSkip = true;
3810  // fall through
3811  case R_SKIP:
3812  // Move on to next file
3813  skipSrc();
3814  return;
3815  case R_OVERWRITE_ALL:
3816  m_bOverwriteAll = true;
3817  break;
3818  case R_OVERWRITE:
3819  // Add to overwrite list
3820  // Note that we add dest, not m_dest.
3821  // This ensures that when moving several urls into a dir (m_dest),
3822  // we only overwrite for the current one, not for all.
3823  // When renaming a single file (m_asMethod), it makes no difference.
3824  kdDebug(7007) << "adding to overwrite list: " << dest.path() << endl;
3825  m_overwriteList.append( dest.path() );
3826  break;
3827  default:
3828  //assert( 0 );
3829  break;
3830  }
3831  }
3832  } else if ( err != TDEIO::ERR_UNSUPPORTED_ACTION ) {
3833  kdDebug(7007) << "Couldn't rename " << m_currentSrcURL << " to " << dest << ", aborting" << endl;
3834  m_error = err;
3835  m_errorText = errText;
3836  emitResult();
3837  return;
3838  }
3839  kdDebug(7007) << "Couldn't rename " << m_currentSrcURL << " to " << dest << ", reverting to normal way, starting with stat" << endl;
3840  //kdDebug(7007) << "TDEIO::stat on " << m_currentSrcURL << endl;
3841  TDEIO::Job* job = TDEIO::stat( m_currentSrcURL, true, 2, false );
3842  state = STATE_STATING;
3843  addSubjob(job);
3844  m_bOnlyRenames = false;
3845  }
3846  else
3847  {
3848  //kdDebug(7007) << "Renaming succeeded, move on" << endl;
3849  emit copyingDone( this, *m_currentStatSrc, dest, true, true );
3850  statNextSrc();
3851  }
3852 }
3853 
3854 void CopyJob::slotResult( Job *job )
3855 {
3856  //kdDebug(7007) << "CopyJob::slotResult() state=" << (int) state << endl;
3857  // In each case, what we have to do is :
3858  // 1 - check for errors and treat them
3859  // 2 - subjobs.remove(job);
3860  // 3 - decide what to do next
3861 
3862  switch ( state ) {
3863  case STATE_STATING: // We were trying to stat a src url or the dest
3864  slotResultStating( job );
3865  break;
3866  case STATE_RENAMING: // We were trying to do a direct renaming, before even stat'ing
3867  {
3868  slotResultRenaming( job );
3869  break;
3870  }
3871  case STATE_LISTING: // recursive listing finished
3872  //kdDebug(7007) << "totalSize: " << (unsigned int) m_totalSize << " files: " << files.count() << " dirs: " << dirs.count() << endl;
3873  // Was there an error ?
3874  if (job->error())
3875  {
3876  Job::slotResult( job ); // will set the error and emit result(this)
3877  return;
3878  }
3879 
3880  subjobs.remove( job );
3881  assert ( subjobs.isEmpty() );
3882 
3883  statNextSrc();
3884  break;
3885  case STATE_CREATING_DIRS:
3886  slotResultCreatingDirs( job );
3887  break;
3888  case STATE_CONFLICT_CREATING_DIRS:
3889  slotResultConflictCreatingDirs( job );
3890  break;
3891  case STATE_COPYING_FILES:
3892  slotResultCopyingFiles( job );
3893  break;
3894  case STATE_CONFLICT_COPYING_FILES:
3895  slotResultConflictCopyingFiles( job );
3896  break;
3897  case STATE_DELETING_DIRS:
3898  slotResultDeletingDirs( job );
3899  break;
3900  case STATE_SETTING_DIR_ATTRIBUTES: // TODO KDE4
3901  assert( 0 );
3902  //slotResultSettingDirAttributes( job );
3903  break;
3904  default:
3905  assert( 0 );
3906  }
3907 }
3908 
3909 void TDEIO::CopyJob::setDefaultPermissions( bool b )
3910 {
3911  d->m_defaultPermissions = b;
3912 }
3913 
3914 // KDE4: remove
3915 void TDEIO::CopyJob::setInteractive( bool b )
3916 {
3917  Job::setInteractive( b );
3918 }
3919 
3920 CopyJob *TDEIO::copy(const KURL& src, const KURL& dest, bool showProgressInfo )
3921 {
3922  //kdDebug(7007) << "TDEIO::copy src=" << src << " dest=" << dest << endl;
3923  KURL::List srcList;
3924  srcList.append( src );
3925  return new CopyJob( srcList, dest, CopyJob::Copy, false, showProgressInfo );
3926 }
3927 
3928 CopyJob *TDEIO::copyAs(const KURL& src, const KURL& dest, bool showProgressInfo )
3929 {
3930  //kdDebug(7007) << "TDEIO::copyAs src=" << src << " dest=" << dest << endl;
3931  KURL::List srcList;
3932  srcList.append( src );
3933  return new CopyJob( srcList, dest, CopyJob::Copy, true, showProgressInfo );
3934 }
3935 
3936 CopyJob *TDEIO::copy( const KURL::List& src, const KURL& dest, bool showProgressInfo )
3937 {
3938  //kdDebug(7007) << src << " " << dest << endl;
3939  return new CopyJob( src, dest, CopyJob::Copy, false, showProgressInfo );
3940 }
3941 
3942 CopyJob *TDEIO::move(const KURL& src, const KURL& dest, bool showProgressInfo )
3943 {
3944  //kdDebug(7007) << src << " " << dest << endl;
3945  KURL::List srcList;
3946  srcList.append( src );
3947  return new CopyJob( srcList, dest, CopyJob::Move, false, showProgressInfo );
3948 }
3949 
3950 CopyJob *TDEIO::moveAs(const KURL& src, const KURL& dest, bool showProgressInfo )
3951 {
3952  //kdDebug(7007) << src << " " << dest << endl;
3953  KURL::List srcList;
3954  srcList.append( src );
3955  return new CopyJob( srcList, dest, CopyJob::Move, true, showProgressInfo );
3956 }
3957 
3958 CopyJob *TDEIO::move( const KURL::List& src, const KURL& dest, bool showProgressInfo )
3959 {
3960  //kdDebug(7007) << src << " " << dest << endl;
3961  return new CopyJob( src, dest, CopyJob::Move, false, showProgressInfo );
3962 }
3963 
3964 CopyJob *TDEIO::link(const KURL& src, const KURL& destDir, bool showProgressInfo )
3965 {
3966  KURL::List srcList;
3967  srcList.append( src );
3968  return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
3969 }
3970 
3971 CopyJob *TDEIO::link(const KURL::List& srcList, const KURL& destDir, bool showProgressInfo )
3972 {
3973  return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
3974 }
3975 
3976 CopyJob *TDEIO::linkAs(const KURL& src, const KURL& destDir, bool showProgressInfo )
3977 {
3978  KURL::List srcList;
3979  srcList.append( src );
3980  return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
3981 }
3982 
3983 CopyJob *TDEIO::trash(const KURL& src, bool showProgressInfo )
3984 {
3985  KURL::List srcList;
3986  srcList.append( src );
3987  return new CopyJob( srcList, KURL( "trash:/" ), CopyJob::Move, false, showProgressInfo );
3988 }
3989 
3990 CopyJob *TDEIO::trash(const KURL::List& srcList, bool showProgressInfo )
3991 {
3992  return new CopyJob( srcList, KURL( "trash:/" ), CopyJob::Move, false, showProgressInfo );
3993 }
3994 
3996 
3997 DeleteJob::DeleteJob( const KURL::List& src, bool /*shred*/, bool showProgressInfo )
3998 : Job(showProgressInfo), m_totalSize( 0 ), m_processedSize( 0 ), m_fileProcessedSize( 0 ),
3999  m_processedFiles( 0 ), m_processedDirs( 0 ), m_totalFilesDirs( 0 ),
4000  m_srcList(src), m_currentStat(m_srcList.begin()), m_reportTimer(0)
4001 {
4002  if ( showProgressInfo ) {
4003 
4004  connect( this, TQT_SIGNAL( totalFiles( TDEIO::Job*, unsigned long ) ),
4005  Observer::self(), TQT_SLOT( slotTotalFiles( TDEIO::Job*, unsigned long ) ) );
4006 
4007  connect( this, TQT_SIGNAL( totalDirs( TDEIO::Job*, unsigned long ) ),
4008  Observer::self(), TQT_SLOT( slotTotalDirs( TDEIO::Job*, unsigned long ) ) );
4009 
4010  // See slotReport
4011  /*connect( this, TQT_SIGNAL( processedFiles( TDEIO::Job*, unsigned long ) ),
4012  m_observer, TQT_SLOT( slotProcessedFiles( TDEIO::Job*, unsigned long ) ) );
4013 
4014  connect( this, TQT_SIGNAL( processedDirs( TDEIO::Job*, unsigned long ) ),
4015  m_observer, TQT_SLOT( slotProcessedDirs( TDEIO::Job*, unsigned long ) ) );
4016 
4017  connect( this, TQT_SIGNAL( deleting( TDEIO::Job*, const KURL& ) ),
4018  m_observer, TQT_SLOT( slotDeleting( TDEIO::Job*, const KURL& ) ) );*/
4019 
4020  m_reportTimer=new TQTimer(this);
4021  connect(m_reportTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotReport()));
4022  //this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
4023  m_reportTimer->start(REPORT_TIMEOUT,false);
4024  }
4025 
4026  TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
4027 }
4028 
4029 void DeleteJob::slotStart()
4030 {
4031  statNextSrc();
4032 }
4033 
4034 //this is called often, so calling the functions
4035 //from Observer here directly might improve the performance a little bit
4036 //aleXXX
4037 void DeleteJob::slotReport()
4038 {
4039  if (m_progressId==0)
4040  return;
4041 
4042  Observer * observer = Observer::self();
4043 
4044  emit deleting( this, m_currentURL );
4045  observer->slotDeleting(this,m_currentURL);
4046 
4047  switch( state ) {
4048  case STATE_STATING:
4049  case STATE_LISTING:
4050  emit totalSize( this, m_totalSize );
4051  emit totalFiles( this, files.count() );
4052  emit totalDirs( this, dirs.count() );
4053  break;
4054  case STATE_DELETING_DIRS:
4055  emit processedDirs( this, m_processedDirs );
4056  observer->slotProcessedDirs(this,m_processedDirs);
4057  emitPercent( m_processedFiles + m_processedDirs, m_totalFilesDirs );
4058  break;
4059  case STATE_DELETING_FILES:
4060  observer->slotProcessedFiles(this,m_processedFiles);
4061  emit processedFiles( this, m_processedFiles );
4062  emitPercent( m_processedFiles, m_totalFilesDirs );
4063  break;
4064  }
4065 }
4066 
4067 
4068 void DeleteJob::slotEntries(TDEIO::Job* job, const UDSEntryList& list)
4069 {
4070  UDSEntryListConstIterator it = list.begin();
4071  UDSEntryListConstIterator end = list.end();
4072  for (; it != end; ++it)
4073  {
4074  UDSEntry::ConstIterator it2 = (*it).begin();
4075  bool bDir = false;
4076  bool bLink = false;
4077  TQString displayName;
4078  KURL url;
4079  int atomsFound(0);
4080  for( ; it2 != (*it).end(); it2++ )
4081  {
4082  switch ((*it2).m_uds)
4083  {
4084  case UDS_FILE_TYPE:
4085  bDir = S_ISDIR((*it2).m_long);
4086  atomsFound++;
4087  break;
4088  case UDS_NAME:
4089  displayName = (*it2).m_str;
4090  atomsFound++;
4091  break;
4092  case UDS_URL:
4093  url = KURL((*it2).m_str);
4094  atomsFound++;
4095  break;
4096  case UDS_LINK_DEST:
4097  bLink = !(*it2).m_str.isEmpty();
4098  atomsFound++;
4099  break;
4100  case UDS_SIZE:
4101  m_totalSize += (TDEIO::filesize_t)((*it2).m_long);
4102  atomsFound++;
4103  break;
4104  default:
4105  break;
4106  }
4107  if (atomsFound==5) break;
4108  }
4109  assert(!displayName.isEmpty());
4110  if (displayName != ".." && displayName != ".")
4111  {
4112  if( url.isEmpty() ) {
4113  url = ((SimpleJob *)job)->url(); // assumed to be a dir
4114  url.addPath( displayName );
4115  }
4116  //kdDebug(7007) << "DeleteJob::slotEntries " << displayName << " (" << url << ")" << endl;
4117  if ( bLink )
4118  symlinks.append( url );
4119  else if ( bDir )
4120  dirs.append( url );
4121  else
4122  files.append( url );
4123  }
4124  }
4125 }
4126 
4127 
4128 void DeleteJob::statNextSrc()
4129 {
4130  //kdDebug(7007) << "statNextSrc" << endl;
4131  if ( m_currentStat != m_srcList.end() )
4132  {
4133  m_currentURL = (*m_currentStat);
4134 
4135  // if the file system doesn't support deleting, we do not even stat
4136  if (!KProtocolInfo::supportsDeleting(m_currentURL)) {
4137  TQGuardedPtr<DeleteJob> that = this;
4138  ++m_currentStat;
4139  if (isInteractive())
4140  KMessageBox::information( 0, buildErrorString(ERR_CANNOT_DELETE, m_currentURL.prettyURL()));
4141  if (that)
4142  statNextSrc();
4143  return;
4144  }
4145  // Stat it
4146  state = STATE_STATING;
4147  TDEIO::SimpleJob * job = TDEIO::stat( m_currentURL, true, 1, false );
4148  Scheduler::scheduleJob(job);
4149  //kdDebug(7007) << "TDEIO::stat (DeleteJob) " << m_currentURL << endl;
4150  addSubjob(job);
4151  //if ( m_progressId ) // Did we get an ID from the observer ?
4152  // Observer::self()->slotDeleting( this, *it ); // show asap
4153  } else
4154  {
4155  m_totalFilesDirs = files.count()+symlinks.count() + dirs.count();
4156  slotReport();
4157  // Now we know which dirs hold the files we're going to delete.
4158  // To speed things up and prevent double-notification, we disable KDirWatch
4159  // on those dirs temporarily (using KDirWatch::self, that's the instanced
4160  // used by e.g. kdirlister).
4161  for ( TQStringList::Iterator it = m_parentDirs.begin() ; it != m_parentDirs.end() ; ++it )
4162  KDirWatch::self()->stopDirScan( *it );
4163  state = STATE_DELETING_FILES;
4164  deleteNextFile();
4165  }
4166 }
4167 
4168 void DeleteJob::deleteNextFile()
4169 {
4170  //kdDebug(7007) << "deleteNextFile" << endl;
4171  if ( !files.isEmpty() || !symlinks.isEmpty() )
4172  {
4173  SimpleJob *job;
4174  do {
4175  // Take first file to delete out of list
4176  KURL::List::Iterator it = files.begin();
4177  bool isLink = false;
4178  if ( it == files.end() ) // No more files
4179  {
4180  it = symlinks.begin(); // Pick up a symlink to delete
4181  isLink = true;
4182  }
4183  // Normal deletion
4184  // If local file, try do it directly
4185  if ( (*it).isLocalFile() && unlink( TQFile::encodeName((*it).path()) ) == 0 ) {
4186  //kdDebug(7007) << "DeleteJob deleted " << (*it).path() << endl;
4187  job = 0;
4188  m_processedFiles++;
4189  if ( m_processedFiles % 300 == 0 || m_totalFilesDirs < 300) { // update progress info every 300 files
4190  m_currentURL = *it;
4191  slotReport();
4192  }
4193  } else
4194  { // if remote - or if unlink() failed (we'll use the job's error handling in that case)
4195  job = TDEIO::file_delete( *it, false /*no GUI*/);
4196  Scheduler::scheduleJob(job);
4197  m_currentURL=(*it);
4198  }
4199  if ( isLink )
4200  symlinks.remove(it);
4201  else
4202  files.remove(it);
4203  if ( job ) {
4204  addSubjob(job);
4205  return;
4206  }
4207  // loop only if direct deletion worked (job=0) and there is something else to delete
4208  } while (!job && (!files.isEmpty() || !symlinks.isEmpty()));
4209  }
4210  state = STATE_DELETING_DIRS;
4211  deleteNextDir();
4212 }
4213 
4214 void DeleteJob::deleteNextDir()
4215 {
4216  if ( !dirs.isEmpty() ) // some dirs to delete ?
4217  {
4218  do {
4219  // Take first dir to delete out of list - last ones first !
4220  KURL::List::Iterator it = dirs.fromLast();
4221  // If local dir, try to rmdir it directly
4222  if ( (*it).isLocalFile() && ::rmdir( TQFile::encodeName((*it).path()) ) == 0 ) {
4223 
4224  m_processedDirs++;
4225  if ( m_processedDirs % 100 == 0 ) { // update progress info every 100 dirs
4226  m_currentURL = *it;
4227  slotReport();
4228  }
4229  } else {
4230  SimpleJob* job;
4231  if ( KProtocolInfo::canDeleteRecursive( *it ) ) {
4232  // If the ioslave supports recursive deletion of a directory, then
4233  // we only need to send a single CMD_DEL command, so we use file_delete :)
4234  job = TDEIO::file_delete( *it, false /*no gui*/ );
4235  } else {
4236  job = TDEIO::rmdir( *it );
4237  }
4238  Scheduler::scheduleJob(job);
4239  dirs.remove(it);
4240  addSubjob( job );
4241  return;
4242  }
4243  dirs.remove(it);
4244  } while ( !dirs.isEmpty() );
4245  }
4246 
4247  // Re-enable watching on the dirs that held the deleted files
4248  for ( TQStringList::Iterator it = m_parentDirs.begin() ; it != m_parentDirs.end() ; ++it )
4249  KDirWatch::self()->restartDirScan( *it );
4250 
4251  // Finished - tell the world
4252  if ( !m_srcList.isEmpty() )
4253  {
4254  KDirNotify_stub allDirNotify("*", "KDirNotify*");
4255  //kdDebug(7007) << "KDirNotify'ing FilesRemoved " << m_srcList.toStringList() << endl;
4256  allDirNotify.FilesRemoved( m_srcList );
4257  }
4258  if (m_reportTimer!=0)
4259  m_reportTimer->stop();
4260  emitResult();
4261 }
4262 
4263 void DeleteJob::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size )
4264 {
4265  // Note: this is the same implementation as CopyJob::slotProcessedSize but
4266  // it's different from FileCopyJob::slotProcessedSize - which is why this
4267  // is not in Job.
4268 
4269  m_fileProcessedSize = data_size;
4270  setProcessedSize(m_processedSize + m_fileProcessedSize);
4271 
4272  //kdDebug(7007) << "DeleteJob::slotProcessedSize " << (unsigned int) (m_processedSize + m_fileProcessedSize) << endl;
4273 
4274  emit processedSize( this, m_processedSize + m_fileProcessedSize );
4275 
4276  // calculate percents
4277  unsigned long ipercent = m_percent;
4278 
4279  if ( m_totalSize == 0 )
4280  m_percent = 100;
4281  else
4282  m_percent = (unsigned long)(( (float)(m_processedSize + m_fileProcessedSize) / (float)m_totalSize ) * 100.0);
4283 
4284  if ( m_percent > ipercent )
4285  {
4286  emit percent( this, m_percent );
4287  //kdDebug(7007) << "DeleteJob::slotProcessedSize - percent = " << (unsigned int) m_percent << endl;
4288  }
4289 
4290 }
4291 
4292 void DeleteJob::slotResult( Job *job )
4293 {
4294  switch ( state )
4295  {
4296  case STATE_STATING:
4297  {
4298  // Was there an error while stating ?
4299  if (job->error() )
4300  {
4301  // Probably : doesn't exist
4302  Job::slotResult( job ); // will set the error and emit result(this)
4303  return;
4304  }
4305 
4306  // Is it a file or a dir ?
4307  UDSEntry entry = ((StatJob*)job)->statResult();
4308  bool bDir = false;
4309  bool bLink = false;
4310  TDEIO::filesize_t size = (TDEIO::filesize_t)-1;
4311  UDSEntry::ConstIterator it2 = entry.begin();
4312  int atomsFound(0);
4313  for( ; it2 != entry.end(); it2++ )
4314  {
4315  if ( ((*it2).m_uds) == UDS_FILE_TYPE )
4316  {
4317  bDir = S_ISDIR( (mode_t)(*it2).m_long );
4318  atomsFound++;
4319  }
4320  else if ( ((*it2).m_uds) == UDS_LINK_DEST )
4321  {
4322  bLink = !((*it2).m_str.isEmpty());
4323  atomsFound++;
4324  }
4325  else if ( ((*it2).m_uds) == UDS_SIZE )
4326  {
4327  size = (*it2).m_long;
4328  atomsFound++;
4329  }
4330  if (atomsFound==3) break;
4331  }
4332 
4333  KURL url = ((SimpleJob*)job)->url();
4334 
4335  subjobs.remove( job );
4336  assert( subjobs.isEmpty() );
4337 
4338  if (bDir && !bLink)
4339  {
4340  // Add toplevel dir in list of dirs
4341  dirs.append( url );
4342  if ( url.isLocalFile() && !m_parentDirs.contains( url.path(-1) ) )
4343  m_parentDirs.append( url.path(-1) );
4344 
4345  if ( !KProtocolInfo::canDeleteRecursive( url ) ) {
4346  //kdDebug(7007) << " Target is a directory " << endl;
4347  // List it
4348  state = STATE_LISTING;
4349  ListJob *newjob = listRecursive( url, false );
4350  newjob->setUnrestricted(true); // No KIOSK restrictions
4351  Scheduler::scheduleJob(newjob);
4352  connect(newjob, TQT_SIGNAL(entries( TDEIO::Job *,
4353  const TDEIO::UDSEntryList& )),
4354  TQT_SLOT( slotEntries( TDEIO::Job*,
4355  const TDEIO::UDSEntryList& )));
4356  addSubjob(newjob);
4357  } else {
4358  ++m_currentStat;
4359  statNextSrc();
4360  }
4361  }
4362  else
4363  {
4364  if ( bLink ) {
4365  //kdDebug(7007) << " Target is a symlink" << endl;
4366  symlinks.append( url );
4367  } else {
4368  //kdDebug(7007) << " Target is a file" << endl;
4369  files.append( url );
4370  }
4371  if ( url.isLocalFile() && !m_parentDirs.contains( url.directory(false) ) )
4372  m_parentDirs.append( url.directory(false) );
4373  ++m_currentStat;
4374  statNextSrc();
4375  }
4376  }
4377  break;
4378  case STATE_LISTING:
4379  if ( job->error() )
4380  {
4381  // Try deleting nonetheless, it may be empty (and non-listable)
4382  }
4383  subjobs.remove( job );
4384  assert( subjobs.isEmpty() );
4385  ++m_currentStat;
4386  statNextSrc();
4387  break;
4388  case STATE_DELETING_FILES:
4389  if ( job->error() )
4390  {
4391  Job::slotResult( job ); // will set the error and emit result(this)
4392  return;
4393  }
4394  subjobs.remove( job );
4395  assert( subjobs.isEmpty() );
4396  m_processedFiles++;
4397 
4398  deleteNextFile();
4399  break;
4400  case STATE_DELETING_DIRS:
4401  if ( job->error() )
4402  {
4403  Job::slotResult( job ); // will set the error and emit result(this)
4404  return;
4405  }
4406  subjobs.remove( job );
4407  assert( subjobs.isEmpty() );
4408  m_processedDirs++;
4409  //emit processedDirs( this, m_processedDirs );
4410  //if (!m_shred)
4411  //emitPercent( m_processedFiles + m_processedDirs, m_totalFilesDirs );
4412 
4413  deleteNextDir();
4414  break;
4415  default:
4416  assert(0);
4417  }
4418 }
4419 
4420 DeleteJob *TDEIO::del( const KURL& src, bool shred, bool showProgressInfo )
4421 {
4422  KURL::List srcList;
4423  srcList.append( src );
4424  DeleteJob *job = new DeleteJob( srcList, shred, showProgressInfo );
4425  return job;
4426 }
4427 
4428 DeleteJob *TDEIO::del( const KURL::List& src, bool shred, bool showProgressInfo )
4429 {
4430  DeleteJob *job = new DeleteJob( src, shred, showProgressInfo );
4431  return job;
4432 }
4433 
4434 MultiGetJob::MultiGetJob(const KURL& url,
4435  bool showProgressInfo)
4436  : TransferJob(url, 0, TQByteArray(), TQByteArray(), showProgressInfo)
4437 {
4438  m_waitQueue.setAutoDelete(true);
4439  m_activeQueue.setAutoDelete(true);
4440  m_currentEntry = 0;
4441 }
4442 
4443 void MultiGetJob::get(long id, const KURL &url, const MetaData &metaData)
4444 {
4445  GetRequest *entry = new GetRequest(id, url, metaData);
4446  entry->metaData["request-id"] = TQString("%1").arg(id);
4447  m_waitQueue.append(entry);
4448 }
4449 
4450 void MultiGetJob::flushQueue(TQPtrList<GetRequest> &queue)
4451 {
4452  GetRequest *entry;
4453  // Use multi-get
4454  // Scan all jobs in m_waitQueue
4455  for(entry = m_waitQueue.first(); entry; )
4456  {
4457  if ((m_url.protocol() == entry->url.protocol()) &&
4458  (m_url.host() == entry->url.host()) &&
4459  (m_url.port() == entry->url.port()) &&
4460  (m_url.user() == entry->url.user()))
4461  {
4462  m_waitQueue.take();
4463  queue.append(entry);
4464  entry = m_waitQueue.current();
4465  }
4466  else
4467  {
4468  entry = m_waitQueue.next();
4469  }
4470  }
4471  // Send number of URLs, (URL, metadata)*
4472  KIO_ARGS << (TQ_INT32) queue.count();
4473  for(entry = queue.first(); entry; entry = queue.next())
4474  {
4475  stream << entry->url << entry->metaData;
4476  }
4477  m_packedArgs = packedArgs;
4478  m_command = CMD_MULTI_GET;
4479  m_outgoingMetaData.clear();
4480 }
4481 
4482 void MultiGetJob::start(Slave *slave)
4483 {
4484  // Add first job from m_waitQueue and add it to m_activeQueue
4485  GetRequest *entry = m_waitQueue.take(0);
4486  m_activeQueue.append(entry);
4487 
4488  m_url = entry->url;
4489 
4490  if (!entry->url.protocol().startsWith("http"))
4491  {
4492  // Use normal get
4493  KIO_ARGS << entry->url;
4494  m_packedArgs = packedArgs;
4495  m_outgoingMetaData = entry->metaData;
4496  m_command = CMD_GET;
4497  b_multiGetActive = false;
4498  }
4499  else
4500  {
4501  flushQueue(m_activeQueue);
4502  b_multiGetActive = true;
4503  }
4504 
4505  TransferJob::start(slave); // Anything else to do??
4506 }
4507 
4508 bool MultiGetJob::findCurrentEntry()
4509 {
4510  if (b_multiGetActive)
4511  {
4512  long id = m_incomingMetaData["request-id"].toLong();
4513  for(GetRequest *entry = m_activeQueue.first(); entry; entry = m_activeQueue.next())
4514  {
4515  if (entry->id == id)
4516  {
4517  m_currentEntry = entry;
4518  return true;
4519  }
4520  }
4521  m_currentEntry = 0;
4522  return false;
4523  }
4524  else
4525  {
4526  m_currentEntry = m_activeQueue.first();
4527  return (m_currentEntry != 0);
4528  }
4529 }
4530 
4531 void MultiGetJob::slotRedirection( const KURL &url)
4532 {
4533  if (!findCurrentEntry()) return; // Error
4534  if (kapp && !kapp->authorizeURLAction("redirect", m_url, url))
4535  {
4536  kdWarning(7007) << "MultiGetJob: Redirection from " << m_currentEntry->url << " to " << url << " REJECTED!" << endl;
4537  return;
4538  }
4539  m_redirectionURL = url;
4540  if (m_currentEntry->url.hasUser() && !url.hasUser() && (m_currentEntry->url.host().lower() == url.host().lower()))
4541  m_redirectionURL.setUser(m_currentEntry->url.user()); // Preserve user
4542  get(m_currentEntry->id, m_redirectionURL, m_currentEntry->metaData); // Try again
4543 }
4544 
4545 
4546 void MultiGetJob::slotFinished()
4547 {
4548  if (!findCurrentEntry()) return;
4549  if (m_redirectionURL.isEmpty())
4550  {
4551  // No redirection, tell the world that we are finished.
4552  emit result(m_currentEntry->id);
4553  }
4554  m_redirectionURL = KURL();
4555  m_error = 0;
4556  m_incomingMetaData.clear();
4557  m_activeQueue.removeRef(m_currentEntry);
4558  if (m_activeQueue.count() == 0)
4559  {
4560  if (m_waitQueue.count() == 0)
4561  {
4562  // All done
4563  TransferJob::slotFinished();
4564  }
4565  else
4566  {
4567  // return slave to pool
4568  // fetch new slave for first entry in m_waitQueue and call start
4569  // again.
4570  GetRequest *entry = m_waitQueue.at(0);
4571  m_url = entry->url;
4572  slaveDone();
4573  Scheduler::doJob(this);
4574  }
4575  }
4576 }
4577 
4578 void MultiGetJob::slotData( const TQByteArray &_data)
4579 {
4580  if(!m_currentEntry) return;// Error, unknown request!
4581  if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error)
4582  emit data(m_currentEntry->id, _data);
4583 }
4584 
4585 void MultiGetJob::slotMimetype( const TQString &_mimetype )
4586 {
4587  if (b_multiGetActive)
4588  {
4589  TQPtrList<GetRequest> newQueue;
4590  flushQueue(newQueue);
4591  if (!newQueue.isEmpty())
4592  {
4593  while(!newQueue.isEmpty())
4594  m_activeQueue.append(newQueue.take(0));
4595  m_slave->send( m_command, m_packedArgs );
4596  }
4597  }
4598  if (!findCurrentEntry()) return; // Error, unknown request!
4599  emit mimetype(m_currentEntry->id, _mimetype);
4600 }
4601 
4602 MultiGetJob *TDEIO::multi_get(long id, const KURL &url, const MetaData &metaData)
4603 {
4604  MultiGetJob * job = new MultiGetJob( url, false );
4605  job->get(id, url, metaData);
4606  return job;
4607 }
4608 
4609 
4610 #ifdef CACHE_INFO
4611 CacheInfo::CacheInfo(const KURL &url)
4612 {
4613  m_url = url;
4614 }
4615 
4616 TQString CacheInfo::cachedFileName()
4617 {
4618  const TQChar separator = '_';
4619 
4620  TQString CEF = m_url.path();
4621 
4622  int p = CEF.find('/');
4623 
4624  while(p != -1)
4625  {
4626  CEF[p] = separator;
4627  p = CEF.find('/', p);
4628  }
4629 
4630  TQString host = m_url.host().lower();
4631  CEF = host + CEF + '_';
4632 
4633  TQString dir = KProtocolManager::cacheDir();
4634  if (dir[dir.length()-1] != '/')
4635  dir += "/";
4636 
4637  int l = m_url.host().length();
4638  for(int i = 0; i < l; i++)
4639  {
4640  if (host[i].isLetter() && (host[i] != 'w'))
4641  {
4642  dir += host[i];
4643  break;
4644  }
4645  }
4646  if (dir[dir.length()-1] == '/')
4647  dir += "0";
4648 
4649  unsigned long hash = 0x00000000;
4650  TQCString u = m_url.url().latin1();
4651  for(int i = u.length(); i--;)
4652  {
4653  hash = (hash * 12211 + u[i]) % 2147483563;
4654  }
4655 
4656  TQString hashString;
4657  hashString.sprintf("%08lx", hash);
4658 
4659  CEF = CEF + hashString;
4660 
4661  CEF = dir + "/" + CEF;
4662 
4663  return CEF;
4664 }
4665 
4666 TQFile *CacheInfo::cachedFile()
4667 {
4668 #ifdef Q_WS_WIN
4669  const char *mode = (readWrite ? "rb+" : "rb");
4670 #else
4671  const char *mode = (readWrite ? "r+" : "r");
4672 #endif
4673 
4674  FILE *fs = fopen(TQFile::encodeName(CEF), mode); // Open for reading and writing
4675  if (!fs)
4676  return 0;
4677 
4678  char buffer[401];
4679  bool ok = true;
4680 
4681  // CacheRevision
4682  if (ok && (!fgets(buffer, 400, fs)))
4683  ok = false;
4684  if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
4685  ok = false;
4686 
4687  time_t date;
4688  time_t currentDate = time(0);
4689 
4690  // URL
4691  if (ok && (!fgets(buffer, 400, fs)))
4692  ok = false;
4693  if (ok)
4694  {
4695  int l = strlen(buffer);
4696  if (l>0)
4697  buffer[l-1] = 0; // Strip newline
4698  if (m_.url.url() != buffer)
4699  {
4700  ok = false; // Hash collision
4701  }
4702  }
4703 
4704  // Creation Date
4705  if (ok && (!fgets(buffer, 400, fs)))
4706  ok = false;
4707  if (ok)
4708  {
4709  date = (time_t) strtoul(buffer, 0, 10);
4710  if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
4711  {
4712  m_bMustRevalidate = true;
4713  m_expireDate = currentDate;
4714  }
4715  }
4716 
4717  // Expiration Date
4718  m_cacheExpireDateOffset = ftell(fs);
4719  if (ok && (!fgets(buffer, 400, fs)))
4720  ok = false;
4721  if (ok)
4722  {
4723  if (m_request.cache == CC_Verify)
4724  {
4725  date = (time_t) strtoul(buffer, 0, 10);
4726  // After the expire date we need to revalidate.
4727  if (!date || difftime(currentDate, date) >= 0)
4728  m_bMustRevalidate = true;
4729  m_expireDate = date;
4730  }
4731  }
4732 
4733  // ETag
4734  if (ok && (!fgets(buffer, 400, fs)))
4735  ok = false;
4736  if (ok)
4737  {
4738  m_etag = TQString(buffer).stripWhiteSpace();
4739  }
4740 
4741  // Last-Modified
4742  if (ok && (!fgets(buffer, 400, fs)))
4743  ok = false;
4744  if (ok)
4745  {
4746  m_lastModified = TQString(buffer).stripWhiteSpace();
4747  }
4748 
4749  fclose(fs);
4750 
4751  if (ok)
4752  return fs;
4753 
4754  unlink( TQFile::encodeName(CEF) );
4755  return 0;
4756 
4757 }
4758 
4759 void CacheInfo::flush()
4760 {
4761  cachedFile().remove();
4762 }
4763 
4764 void CacheInfo::touch()
4765 {
4766 
4767 }
4768 void CacheInfo::setExpireDate(int);
4769 void CacheInfo::setExpireTimeout(int);
4770 
4771 
4772 int CacheInfo::creationDate();
4773 int CacheInfo::expireDate();
4774 int CacheInfo::expireTimeout();
4775 #endif
4776 
4777 void Job::virtual_hook( int, void* )
4778 { /*BASE::virtual_hook( id, data );*/ }
4779 
4780 void SimpleJob::virtual_hook( int id, void* data )
4781 { TDEIO::Job::virtual_hook( id, data ); }
4782 
4783 void MkdirJob::virtual_hook( int id, void* data )
4784 { SimpleJob::virtual_hook( id, data ); }
4785 
4786 void StatJob::virtual_hook( int id, void* data )
4787 { SimpleJob::virtual_hook( id, data ); }
4788 
4789 void TransferJob::virtual_hook( int id, void* data )
4790 { SimpleJob::virtual_hook( id, data ); }
4791 
4792 void MultiGetJob::virtual_hook( int id, void* data )
4793 { TransferJob::virtual_hook( id, data ); }
4794 
4795 void MimetypeJob::virtual_hook( int id, void* data )
4796 { TransferJob::virtual_hook( id, data ); }
4797 
4798 void FileCopyJob::virtual_hook( int id, void* data )
4799 { Job::virtual_hook( id, data ); }
4800 
4801 void ListJob::virtual_hook( int id, void* data )
4802 { SimpleJob::virtual_hook( id, data ); }
4803 
4804 void CopyJob::virtual_hook( int id, void* data )
4805 { Job::virtual_hook( id, data ); }
4806 
4807 void DeleteJob::virtual_hook( int id, void* data )
4808 { Job::virtual_hook( id, data ); }
4809 
4810 void LocalURLJob::virtual_hook( int id, void* data )
4811 { Job::virtual_hook( id, data ); }
4812 
4813 
4814 #include "jobclasses.moc"

tdeio/tdeio

Skip menu "tdeio/tdeio"
  • Main Page
  • Modules
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

tdeio/tdeio

Skip menu "tdeio/tdeio"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • knewstuff
  • libtdemid
  • libtdescreensaver
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdeioslave
  •   http
  • tdemdi
  •   tdemdi
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for tdeio/tdeio by doxygen 1.8.3.1
This website is maintained by Timothy Pearson.