summaryrefslogtreecommitdiffstats
path: root/filesharing/advanced/kcm_sambaconf/sambafile.cpp
blob: 4703716bd8f3ceff1c105100ad112c2d46b2062e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/*
  Copyright (c) 2002-2004 Jan Schaefer <[email protected]>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*/

#include <tqfile.h>
#include <tqprocess.h>
#include <tqfileinfo.h>

#include <ksimpleconfig.h>
#include <kdebug.h>
#include <tqfileinfo.h>
#include <kio/job.h>
#include <kprocess.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <ktempfile.h>
#include <ksambashare.h>

#include <pwd.h>
#include <time.h>
#include <unistd.h>

#include "sambafile.h"

#define FILESHARE_DEBUG 5009

SambaConfigFile::SambaConfigFile(SambaFile* sambaFile)
{
  TQDict<TQString>(10,false);
  setAutoDelete(true);
  _sambaFile = sambaFile;
}

TQString SambaConfigFile::getDefaultValue(const TQString & name)
{
  SambaShare* defaults = _sambaFile->getTestParmValues();
  TQString s = defaults->getValue(name,false,false);

  return s;
}

SambaShare* SambaConfigFile::addShare(const TQString & name)
{
  SambaShare* newShare = new SambaShare(name,this);
  addShare(name,newShare);
  return newShare;
}


void SambaConfigFile::addShare(const TQString & name, SambaShare* share)
{
  insert(name,share),
  _shareList.append(name);
}

void SambaConfigFile::removeShare(const TQString & name)
{
  remove(name);
  _shareList.remove(name);
}


TQStringList SambaConfigFile::getShareList()
{
  return _shareList;
}

SambaFile::SambaFile(const TQString & _path, bool _readonly)
  : readonly(_readonly), 
    changed(false), 
    path(_path), 
    localPath(_path), 
    _sambaConfig(0),
    _testParmValues(0),
    _sambaVersion(-1),
    _tempFile(0)
{
}

SambaFile::~SambaFile()
{
  delete _sambaConfig;
  delete _testParmValues;
  delete _tempFile;

}

bool SambaFile::isRemoteFile() {
  return ! KURL(path).isLocalFile();
}

/** No descriptions */
TQString SambaFile::findShareByPath(const TQString & path) const
{
  TQDictIterator<SambaShare> it(*_sambaConfig);
  KURL url(path);
  url.adjustPath(-1);

  for (  ; it.current(); ++it )
  {
    SambaShare* share = it.current();

    TQString *s = share->find("path");
    if (s) {
        KURL curUrl(*s);
        curUrl.adjustPath(-1);

        kdDebug(5009) << url.path() << " =? " << curUrl.path() << endl;

        if (url.path() == curUrl.path())
            return it.currentKey();
    }
  }

  return TQString();
}

bool SambaFile::save() {
  return slotApply();
}


bool SambaFile::slotApply()
{
  if (readonly) {
      kdDebug(FILESHARE_DEBUG) << "SambaFile::slotApply: readonly=true" << endl;
      return false;
  }      

  // If we have write access to the smb.conf
  // we simply save the values to it
  // if not we have to save the results in
  // a temporary file and copy it afterwards
  // over the smb.conf file with tdesu.
  if (TQFileInfo(path).isWritable())
  {
    saveTo(path);
    changed = false;
    return true;
  }

  // Create a temporary smb.conf file
   delete _tempFile;
  _tempFile = new KTempFile();
  _tempFile->setAutoDelete(true);

  if (!saveTo(_tempFile->name())) {
    kdDebug(5009) << "SambaFile::slotApply: Could not save to temporary file" << endl; 
    delete _tempFile;
    _tempFile = 0;
    return false;
  }

  TQFileInfo fi(path);
  KURL url(path);

  if (KURL(path).isLocalFile()) {
    KProcess proc;
    kdDebug(5009) << "SambaFile::slotApply: is local file!" << endl;
    
    TQString suCommand=TQString("cp %1 %2; rm %3")
              .arg(_tempFile->name())
              .arg(path)
              .arg(_tempFile->name());
    proc << "tdesu" << "-d" << suCommand;

    if (! proc.start(KProcess::Block)) {
        kdDebug(5009) << "SambaFile::slotApply: saving to " << path << " failed!" << endl;
        //KMessageBox::sorry(0,i18n("Saving the results to %1 failed.").arg(path));
        delete _tempFile;
        _tempFile = 0;
        return false;
    }        
    else {
        changed = false;
        delete _tempFile;
        _tempFile = 0;
        kdDebug(5009) << "SambaFile::slotApply: changes successfully saved!" << endl;
        return true;
    }        
  } else {
    kdDebug(5009) << "SambaFile::slotApply: is remote file!" << endl;
    _tempFile->setAutoDelete(true);
    KURL srcURL;
    srcURL.setPath( _tempFile->name() );

    KIO::FileCopyJob * job =  KIO::file_copy( srcURL, url, -1, true  );
    connect( job, TQT_SIGNAL( result( KIO::Job * ) ), 
             this, TQT_SLOT( slotSaveJobFinished ( KIO::Job * ) ) );
    return (job->error()==0);
  }

  return true;
}

  /**
  * Returns a name which isn't already used for a share
  **/
TQString SambaFile::getUnusedName(const TQString alreadyUsedName) const
{

  TQString init = i18n("Unnamed");
  if (alreadyUsedName != TQString())
    init = alreadyUsedName;

  TQString s = init;

  int i = 2;

  while (_sambaConfig->find(s))
  {
    s = init+TQString::number(i);
    i++;
  }

  return s;
}



SambaShare* SambaFile::newShare(const TQString & name)
{
  if (_sambaConfig->find(name))
    return 0L;

  SambaShare* share = new SambaShare(name,_sambaConfig);
  _sambaConfig->addShare(name,share);

  changed = true;

  return share;

}

SambaShare* SambaFile::newShare(const TQString & name, const TQString & path)
{
  SambaShare* share = newShare(name);
  if (share)
  {
    share->setValue("path",path);
  }

  return share;
}

SambaShare* SambaFile::newPrinter(const TQString & name, const TQString & printer)
{
  SambaShare* share = newShare(name);

  if (share)
  {
    share->setValue("printable",true);
    share->setValue("printer name",printer);
  }

  return share;
}


/** No descriptions */
void SambaFile::removeShare(const TQString & share)
{
  changed = true;

  _sambaConfig->removeShare(share);
}

void SambaFile::removeShare(SambaShare* share)
{
  removeShare(share->getName());
}

void SambaFile::removeShareByPath(const TQString & path) {
  TQString share = findShareByPath(path);
  removeShare(share);
}

/** No descriptions */
SambaShare* SambaFile::getShare(const TQString & share) const
{
  SambaShare *s = _sambaConfig->find(share);

  return s;
}

/**
* Returns a list of all shared directories
**/
SambaShareList* SambaFile::getSharedDirs() const
{
  SambaShareList* list = new SambaShareList();

  TQDictIterator<SambaShare> it(*_sambaConfig);

  for( ; it.current(); ++it )
  {
    if (!it.current()->isPrinter() &&
        it.current()->getName() != "global")
    {
      list->append(it.current());
    }
  }

  return list;
}

/**
* Returns a list of all shared printers
**/
SambaShareList* SambaFile::getSharedPrinters() const
{
  SambaShareList* list = new SambaShareList();

  TQDictIterator<SambaShare> it(*_sambaConfig);

  for( ; it.current(); ++it )
  {
    if (it.current()->isPrinter())
      list->append(it.current());
  }

  return list;
}

int SambaFile::getSambaVersion() {
  if (_sambaVersion > -1)
    return _sambaVersion;
    
  KProcess testParam;
  testParam << "testparm";
  testParam << "-V";
  _parmOutput = TQString("");
  _sambaVersion = 2;
      
  connect( &testParam, TQT_SIGNAL(receivedStdout(KProcess*,char*,int)),
          this, TQT_SLOT(testParmStdOutReceived(KProcess*,char*,int)));

          
          
  if (testParam.start(KProcess::Block,KProcess::Stdout)) {
    if (_parmOutput.find("3") > -1)
      _sambaVersion = 3;
  } 

  kdDebug(5009) << "Samba version = " << _sambaVersion << endl;
    
  return _sambaVersion;
}


SambaShare* SambaFile::getTestParmValues(bool reload)
{
  if (_testParmValues && !reload)
    return _testParmValues;


  KProcess testParam;
  testParam << "testparm";
  testParam << "-s"; 
  
  if (getSambaVersion() == 3)
     testParam << "-v";


  testParam << "/dev/null";
  _parmOutput = TQString("");
  
  connect( &testParam, TQT_SIGNAL(receivedStdout(KProcess*,char*,int)),
          this, TQT_SLOT(testParmStdOutReceived(KProcess*,char*,int)));

  if (testParam.start(KProcess::Block,KProcess::Stdout))
  {
    parseParmStdOutput();
  } else
    _testParmValues = new SambaShare(_sambaConfig);

  return _testParmValues;
}

void SambaFile::testParmStdOutReceived(KProcess *, char *buffer, int buflen)
{
  _parmOutput+=TQString::fromLatin1(buffer,buflen);
}

void SambaFile::parseParmStdOutput()
{

  TQTextIStream s(&_parmOutput);

  if (_testParmValues)
    delete _testParmValues;
  _testParmValues = new SambaShare(_sambaConfig);

  TQString section="";

  while (!s.atEnd())
  {
    TQString line = s.readLine().stripWhiteSpace();

    // empty lines
    if (line.isEmpty())
      continue;

    // comments
    if ('#' == line[0])
      continue;

    // sections
    if ('[' == line[0])
    {
      // get the name of the section
      section = line.mid(1,line.length()-2).lower();
      continue;
    }

    // we are only interested in the global section
    if (section != KGlobal::staticQString("global"))
      continue;

    // parameter
    // parameter
    int i = line.find('=');

    if (i>-1) {
      TQString name = line.left(i).stripWhiteSpace();
      TQString value = line.mid(i+1).stripWhiteSpace();
      _testParmValues->setValue(name,value,false,false);
    }
    
  }



}

/**
* Try to find the samba config file position
* First tries the config file, then checks
* several common positions
* If nothing is found returns TQString()
**/
TQString SambaFile::findSambaConf()
{
    return KSambaShare::instance()->smbConfPath();
}

void SambaFile::slotSaveJobFinished( KIO::Job * job ) {
  delete _tempFile;
  _tempFile = 0;
}

void SambaFile::slotJobFinished( KIO::Job * job )
{
  if (job->error())
    emit canceled( job->errorString() );
  else
  {
    openFile();
    emit completed();
  }
}

bool SambaFile::load()
{
  if (path.isNull() || path.isEmpty())
      return false;
      
  kdDebug(FILESHARE_DEBUG) << "SambaFile::load: path=" << path << endl;
  KURL url(path);

  if (!url.isLocalFile()) {
    KTempFile tempFile;
    localPath = tempFile.name();
    KURL destURL;
    destURL.setPath( localPath );
    KIO::FileCopyJob * job =  KIO::file_copy( url, destURL, 0600, true, false, true );
//    emit started( d->m_job );
    connect( job, TQT_SIGNAL( result( KIO::Job * ) ), this, TQT_SLOT( slotJobFinished ( KIO::Job * ) ) );
    return true;
  } else {
    localPath = path;
    bool ret = openFile();
    if (ret)
        emit completed();
    return ret;
  }
}

bool SambaFile::openFile() {

  TQFile f(localPath);

  if (!f.open(IO_ReadOnly)) {
    //throw SambaFileLoadException(TQString("<qt>Could not open file <em>%1</em> for reading.</qt>").arg(path));
    return false;
  }

  TQTextStream s(&f);

  delete _sambaConfig;

  _sambaConfig = new SambaConfigFile(this);

  SambaShare *currentShare = 0L;
  bool continuedLine = false; // is true if the line before ended with a backslash
  TQString completeLine;
  TQStringList comments;

  while (!s.eof())
  {
    TQString currentLine = s.readLine().stripWhiteSpace();

    if (continuedLine)
    {
      completeLine += currentLine;
      continuedLine = false;
    } else
      completeLine = currentLine;
            
    // is the line continued in the next line ?
    if ( completeLine[completeLine.length()-1] == '\\' )
    {
      continuedLine = true;
      // remove the ending backslash
      completeLine.truncate( completeLine.length()-1 ); 
      continue;
    }

    // comments or empty lines
    if (completeLine.isEmpty() ||
        '#' == completeLine[0] ||
        ';' == completeLine[0])
    {
      comments.append(completeLine);
      continue;
    }


    // sections
    if ('[' == completeLine[0])
    {
      // get the name of the section
      TQString section = completeLine.mid(1,completeLine.length()-2);
      currentShare = _sambaConfig->addShare(section);
      currentShare->setComments(comments);
      comments.clear();

      continue;
    }

    // parameter
    int i = completeLine.find('=');

    if (i>-1)
    {
      TQString name = completeLine.left(i).stripWhiteSpace();
      TQString value = completeLine.mid(i+1).stripWhiteSpace();

      if (currentShare)
      {
        currentShare->setComments(name,comments);
        currentShare->setValue(name,value,true,true);

        comments.clear();
      }
    }
  }

  f.close();

  // Make sure there is a global share
  if (!getShare("global")) {
     _sambaConfig->addShare("global");
  }
  
  return true;  
}

bool SambaFile::saveTo(const TQString & path)
{
  TQFile f(path);

  if (!f.open(IO_WriteOnly))
    return false;

  TQTextStream s(&f);

  TQStringList shareList = _sambaConfig->getShareList();

  for ( TQStringList::Iterator it = shareList.begin(); it != shareList.end(); ++it )
  {
    SambaShare* share = _sambaConfig->find(*it);

    // First add all comments of the share to the file
    TQStringList comments = share->getComments();
    for ( TQStringList::Iterator cmtIt = comments.begin(); cmtIt != comments.end(); ++cmtIt )
    {
      s << *cmtIt << endl;

      kdDebug(5009) << *cmtIt << endl;
    }

    // If there are no lines before the section add
    // a blank line
    if (comments.isEmpty())
      s << endl;

    // Add the name of the share / section
    s << "[" << share->getName() << "]" << endl;

    // Add all options of the share 
    TQStringList optionList = share->getOptionList();

    for ( TQStringList::Iterator optionIt = optionList.begin(); optionIt != optionList.end(); ++optionIt )
    {

      // Add the comments of the option
      comments = share->getComments(*optionIt);
      for ( TQStringList::Iterator cmtIt = comments.begin(); cmtIt != comments.end(); ++cmtIt )
      {
        s << *cmtIt << endl;
      }

      // Add the option
      s << *optionIt << " = " << *share->find(*optionIt) << endl;
    }


  }

  f.close();

  return true;     
}


SambaConfigFile* SambaFile::getSambaConfigFile(KSimpleConfig* config)
{
  TQStringList groups = config->groupList();

  SambaConfigFile* samba = new SambaConfigFile(this);

  for ( TQStringList::Iterator it = groups.begin(); it != groups.end(); ++it )
  {
    TQMap<TQString,TQString> entries = config->entryMap(*it);

    SambaShare *share = new SambaShare(*it,samba);
    samba->insert(*it,share);

    for (TQMap<TQString,TQString>::Iterator it2 = entries.begin(); it2 != entries.end(); ++it2 )
    {
      if (!it2.data().isEmpty())
          share->setValue(it2.key(),TQString(it2.data()),false,false);
    }

  }

  return samba;

}

KSimpleConfig* SambaFile::getSimpleConfig(SambaConfigFile* sambaConfig, const TQString & path)
{
  KSimpleConfig *config = new KSimpleConfig(path,false);

  TQDictIterator<SambaShare> it(*sambaConfig);

  for ( ; it.current(); ++it )
  {
    SambaShare* share = it.current();

    config->setGroup(it.currentKey());

    TQDictIterator<TQString> it2(*share);

    for (; it2.current(); ++it2 )
    {
      config->writeEntry(it2.currentKey(), *it2.current());
    }

  }

  return config;
}

#include "sambafile.moc"