]> git.saurik.com Git - apt.git/blame - methods/rsh.cc
doc/apt-get.8.xml: document download
[apt.git] / methods / rsh.cc
CommitLineData
b2e465d6
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
7db98ffc 3// $Id: rsh.cc,v 1.6.2.1 2004/01/16 18:58:50 mdz Exp $
b2e465d6
AL
4/* ######################################################################
5
6 RSH method - Transfer files via rsh compatible program
7
8 Written by Ben Collins <bcollins@debian.org>, Copyright (c) 2000
9 Licensed under the GNU General Public License v2 [no exception clauses]
10
11 ##################################################################### */
12 /*}}}*/
5e775e59 13// Include Files /*{{{*/
b2e465d6
AL
14#include "rsh.h"
15#include <apt-pkg/error.h>
16
17#include <sys/stat.h>
18#include <sys/time.h>
19#include <utime.h>
20#include <unistd.h>
21#include <signal.h>
22#include <stdio.h>
23#include <errno.h>
24#include <stdarg.h>
d77559ac 25#include <apti18n.h>
b2e465d6
AL
26 /*}}}*/
27
28const char *Prog;
29unsigned long TimeOut = 120;
5e775e59 30Configuration::Item const *RshOptions = 0;
b2e465d6
AL
31time_t RSHMethod::FailTime = 0;
32string RSHMethod::FailFile;
33int RSHMethod::FailFd = -1;
34
35// RSHConn::RSHConn - Constructor /*{{{*/
36// ---------------------------------------------------------------------
37/* */
38RSHConn::RSHConn(URI Srv) : Len(0), WriteFd(-1), ReadFd(-1),
39 ServerName(Srv), Process(-1) {}
40 /*}}}*/
41// RSHConn::RSHConn - Destructor /*{{{*/
42// ---------------------------------------------------------------------
43/* */
44RSHConn::~RSHConn()
45{
46 Close();
47}
48 /*}}}*/
49// RSHConn::Close - Forcibly terminate the connection /*{{{*/
50// ---------------------------------------------------------------------
51/* Often this is called when things have gone wrong to indicate that the
52 connection is no longer usable. */
53void RSHConn::Close()
54{
55 if (Process == -1)
56 return;
57
58 close(WriteFd);
59 close(ReadFd);
60 kill(Process,SIGINT);
61 ExecWait(Process,"",true);
62 WriteFd = -1;
63 ReadFd = -1;
64 Process = -1;
65}
66 /*}}}*/
67// RSHConn::Open - Connect to a host /*{{{*/
68// ---------------------------------------------------------------------
69/* */
70bool RSHConn::Open()
71{
72 // Use the already open connection if possible.
73 if (Process != -1)
74 return true;
75
76 if (Connect(ServerName.Host,ServerName.User) == false)
77 return false;
78
79 return true;
80}
81 /*}}}*/
82// RSHConn::Connect - Fire up rsh and connect /*{{{*/
83// ---------------------------------------------------------------------
84/* */
85bool RSHConn::Connect(string Host, string User)
86{
87 // Create the pipes
88 int Pipes[4] = {-1,-1,-1,-1};
89 if (pipe(Pipes) != 0 || pipe(Pipes+2) != 0)
90 {
dc738e7a 91 _error->Errno("pipe",_("Failed to create IPC pipe to subprocess"));
b2e465d6
AL
92 for (int I = 0; I != 4; I++)
93 close(Pipes[I]);
94 return false;
95 }
96 for (int I = 0; I != 4; I++)
97 SetCloseExec(Pipes[I],true);
98
99 Process = ExecFork();
100
101 // The child
102 if (Process == 0)
103 {
5e775e59
AL
104 const char *Args[400];
105 unsigned int i = 0;
b2e465d6
AL
106
107 dup2(Pipes[1],STDOUT_FILENO);
108 dup2(Pipes[2],STDIN_FILENO);
109
110 // Probably should do
111 // dup2(open("/dev/null",O_RDONLY),STDERR_FILENO);
112
5e775e59
AL
113 // Insert user-supplied command line options
114 Configuration::Item const *Opts = RshOptions;
115 if (Opts != 0)
116 {
117 Opts = Opts->Child;
118 for (; Opts != 0; Opts = Opts->Next)
119 {
120 if (Opts->Value.empty() == true)
121 continue;
122 Args[i++] = Opts->Value.c_str();
123 }
124 }
125
b2e465d6
AL
126 Args[i++] = Prog;
127 if (User.empty() == false) {
128 Args[i++] = "-l";
129 Args[i++] = User.c_str();
130 }
131 if (Host.empty() == false) {
132 Args[i++] = Host.c_str();
133 }
134 Args[i++] = "/bin/sh";
135 Args[i] = 0;
136 execvp(Args[0],(char **)Args);
137 exit(100);
138 }
139
140 ReadFd = Pipes[0];
141 WriteFd = Pipes[3];
142 SetNonBlock(Pipes[0],true);
143 SetNonBlock(Pipes[3],true);
144 close(Pipes[1]);
145 close(Pipes[2]);
146
147 return true;
148}
149 /*}}}*/
150// RSHConn::ReadLine - Very simple buffered read with timeout /*{{{*/
151// ---------------------------------------------------------------------
152/* */
153bool RSHConn::ReadLine(string &Text)
154{
155 if (Process == -1 || ReadFd == -1)
156 return false;
157
158 // Suck in a line
159 while (Len < sizeof(Buffer))
160 {
161 // Scan the buffer for a new line
162 for (unsigned int I = 0; I != Len; I++)
163 {
164 // Escape some special chars
165 if (Buffer[I] == 0)
166 Buffer[I] = '?';
167
168 // End of line?
169 if (Buffer[I] != '\n')
170 continue;
171
172 I++;
173 Text = string(Buffer,I);
174 memmove(Buffer,Buffer+I,Len - I);
175 Len -= I;
176 return true;
177 }
178
179 // Wait for some data..
180 if (WaitFd(ReadFd,false,TimeOut) == false)
181 {
182 Close();
dc738e7a 183 return _error->Error(_("Connection timeout"));
b2e465d6
AL
184 }
185
186 // Suck it back
187 int Res = read(ReadFd,Buffer + Len,sizeof(Buffer) - Len);
188 if (Res <= 0)
189 {
dc738e7a 190 _error->Errno("read",_("Read error"));
b2e465d6
AL
191 Close();
192 return false;
193 }
194 Len += Res;
195 }
196
dc738e7a 197 return _error->Error(_("A response overflowed the buffer."));
b2e465d6
AL
198}
199 /*}}}*/
200// RSHConn::WriteMsg - Send a message with optional remote sync. /*{{{*/
201// ---------------------------------------------------------------------
202/* The remote sync flag appends a || echo which will insert blank line
203 once the command completes. */
204bool RSHConn::WriteMsg(string &Text,bool Sync,const char *Fmt,...)
205{
206 va_list args;
207 va_start(args,Fmt);
208
209 // sprintf the description
210 char S[512];
211 vsnprintf(S,sizeof(S) - 4,Fmt,args);
212 if (Sync == true)
213 strcat(S," 2> /dev/null || echo\n");
214 else
215 strcat(S," 2> /dev/null\n");
216
217 // Send it off
218 unsigned long Len = strlen(S);
219 unsigned long Start = 0;
220 while (Len != 0)
221 {
222 if (WaitFd(WriteFd,true,TimeOut) == false)
223 {
224
225 Close();
dc738e7a 226 return _error->Error(_("Connection timeout"));
b2e465d6
AL
227 }
228
229 int Res = write(WriteFd,S + Start,Len);
230 if (Res <= 0)
231 {
db0db9fe 232 _error->Errno("write",_("Write error"));
b2e465d6
AL
233 Close();
234 return false;
235 }
236
237 Len -= Res;
238 Start += Res;
239 }
240
241 if (Sync == true)
242 return ReadLine(Text);
243 return true;
244}
245 /*}}}*/
246// RSHConn::Size - Return the size of the file /*{{{*/
247// ---------------------------------------------------------------------
248/* Right now for successfull transfer the file size must be known in
249 advance. */
250bool RSHConn::Size(const char *Path,unsigned long &Size)
251{
252 // Query the size
253 string Msg;
254 Size = 0;
255
256 if (WriteMsg(Msg,true,"find %s -follow -printf '%%s\\n'",Path) == false)
257 return false;
258
259 // FIXME: Sense if the bad reply is due to a File Not Found.
260
261 char *End;
262 Size = strtoul(Msg.c_str(),&End,10);
263 if (End == Msg.c_str())
db0db9fe 264 return _error->Error(_("File not found"));
b2e465d6
AL
265 return true;
266}
267 /*}}}*/
268// RSHConn::ModTime - Get the modification time in UTC /*{{{*/
269// ---------------------------------------------------------------------
270/* */
271bool RSHConn::ModTime(const char *Path, time_t &Time)
272{
273 Time = time(&Time);
274 // Query the mod time
275 string Msg;
276
277 if (WriteMsg(Msg,true,"TZ=UTC find %s -follow -printf '%%TY%%Tm%%Td%%TH%%TM%%TS\\n'",Path) == false)
278 return false;
279
280 // Parse it
96cc64a5 281 return FTPMDTMStrToTime(Msg.c_str(), Time);
b2e465d6
AL
282}
283 /*}}}*/
284// RSHConn::Get - Get a file /*{{{*/
285// ---------------------------------------------------------------------
286/* */
287bool RSHConn::Get(const char *Path,FileFd &To,unsigned long Resume,
63b1700f 288 Hashes &Hash,bool &Missing, unsigned long Size)
b2e465d6
AL
289{
290 Missing = false;
291
292 // Round to a 2048 byte block
293 Resume = Resume - (Resume % 2048);
294
295 if (To.Truncate(Resume) == false)
296 return false;
297 if (To.Seek(0) == false)
298 return false;
299
300 if (Resume != 0) {
63b1700f 301 if (Hash.AddFD(To.Fd(),Resume) == false) {
dc738e7a 302 _error->Errno("read",_("Problem hashing file"));
b2e465d6
AL
303 return false;
304 }
305 }
306
307 // FIXME: Detect file-not openable type errors.
308 string Jnk;
309 if (WriteMsg(Jnk,false,"dd if=%s bs=2048 skip=%u", Path, Resume / 2048) == false)
310 return false;
311
312 // Copy loop
313 unsigned int MyLen = Resume;
314 unsigned char Buffer[4096];
315 while (MyLen < Size)
316 {
317 // Wait for some data..
318 if (WaitFd(ReadFd,false,TimeOut) == false)
319 {
320 Close();
dc738e7a 321 return _error->Error(_("Data socket timed out"));
b2e465d6
AL
322 }
323
324 // Read the data..
325 int Res = read(ReadFd,Buffer,sizeof(Buffer));
326 if (Res == 0)
327 {
328 Close();
dc738e7a 329 return _error->Error(_("Connection closed prematurely"));
b2e465d6
AL
330 }
331
332 if (Res < 0)
333 {
334 if (errno == EAGAIN)
335 continue;
336 break;
337 }
338 MyLen += Res;
339
63b1700f 340 Hash.Add(Buffer,Res);
b2e465d6
AL
341 if (To.Write(Buffer,Res) == false)
342 {
343 Close();
344 return false;
345 }
346 }
347
348 return true;
349}
350 /*}}}*/
351
352// RSHMethod::RSHMethod - Constructor /*{{{*/
353// ---------------------------------------------------------------------
354/* */
5e775e59 355RSHMethod::RSHMethod() : pkgAcqMethod("1.0",SendConfig)
b2e465d6
AL
356{
357 signal(SIGTERM,SigTerm);
358 signal(SIGINT,SigTerm);
359 Server = 0;
360 FailFd = -1;
361};
362 /*}}}*/
5e775e59
AL
363// RSHMethod::Configuration - Handle a configuration message /*{{{*/
364// ---------------------------------------------------------------------
365bool RSHMethod::Configuration(string Message)
366{
367 char ProgStr[100];
368
369 if (pkgAcqMethod::Configuration(Message) == false)
370 return false;
371
372 snprintf(ProgStr, sizeof ProgStr, "Acquire::%s::Timeout", Prog);
373 TimeOut = _config->FindI(ProgStr,TimeOut);
374 snprintf(ProgStr, sizeof ProgStr, "Acquire::%s::Options", Prog);
375 RshOptions = _config->Tree(ProgStr);
376
377 return true;
378}
379 /*}}}*/
b2e465d6
AL
380// RSHMethod::SigTerm - Clean up and timestamp the files on exit /*{{{*/
381// ---------------------------------------------------------------------
382/* */
383void RSHMethod::SigTerm(int sig)
384{
385 if (FailFd == -1)
386 _exit(100);
387 close(FailFd);
388
389 // Timestamp
390 struct utimbuf UBuf;
391 UBuf.actime = FailTime;
392 UBuf.modtime = FailTime;
393 utime(FailFile.c_str(),&UBuf);
394
395 _exit(100);
396}
397 /*}}}*/
398// RSHMethod::Fetch - Fetch a URI /*{{{*/
399// ---------------------------------------------------------------------
400/* */
401bool RSHMethod::Fetch(FetchItem *Itm)
402{
403 URI Get = Itm->Uri;
404 const char *File = Get.Path.c_str();
405 FetchResult Res;
406 Res.Filename = Itm->DestFile;
407 Res.IMSHit = false;
408
409 // Connect to the server
410 if (Server == 0 || Server->Comp(Get) == false) {
411 delete Server;
412 Server = new RSHConn(Get);
413 }
414
415 // Could not connect is a transient error..
416 if (Server->Open() == false) {
417 Server->Close();
418 Fail(true);
419 return true;
420 }
421
422 // We say this mainly because the pause here is for the
423 // ssh connection that is still going
dc738e7a 424 Status(_("Connecting to %s"), Get.Host.c_str());
b2e465d6
AL
425
426 // Get the files information
427 unsigned long Size;
428 if (Server->Size(File,Size) == false ||
429 Server->ModTime(File,FailTime) == false)
430 {
431 //Fail(true);
db0db9fe 432 //_error->Error(_("File not found")); // Will be handled by Size
b2e465d6
AL
433 return false;
434 }
435 Res.Size = Size;
436
437 // See if it is an IMS hit
438 if (Itm->LastModified == FailTime) {
439 Res.Size = 0;
440 Res.IMSHit = true;
441 URIDone(Res);
442 return true;
443 }
444
445 // See if the file exists
446 struct stat Buf;
447 if (stat(Itm->DestFile.c_str(),&Buf) == 0) {
448 if (Size == (unsigned)Buf.st_size && FailTime == Buf.st_mtime) {
449 Res.Size = Buf.st_size;
450 Res.LastModified = Buf.st_mtime;
451 Res.ResumePoint = Buf.st_size;
452 URIDone(Res);
453 return true;
454 }
455
456 // Resume?
457 if (FailTime == Buf.st_mtime && Size > (unsigned)Buf.st_size)
458 Res.ResumePoint = Buf.st_size;
459 }
460
461 // Open the file
63b1700f 462 Hashes Hash;
b2e465d6
AL
463 {
464 FileFd Fd(Itm->DestFile,FileFd::WriteAny);
465 if (_error->PendingError() == true)
466 return false;
467
468 URIStart(Res);
469
470 FailFile = Itm->DestFile;
471 FailFile.c_str(); // Make sure we dont do a malloc in the signal handler
472 FailFd = Fd.Fd();
473
474 bool Missing;
63b1700f 475 if (Server->Get(File,Fd,Res.ResumePoint,Hash,Missing,Res.Size) == false)
b2e465d6
AL
476 {
477 Fd.Close();
478
479 // Timestamp
480 struct utimbuf UBuf;
481 UBuf.actime = FailTime;
482 UBuf.modtime = FailTime;
483 utime(FailFile.c_str(),&UBuf);
484
485 // If the file is missing we hard fail otherwise transient fail
486 if (Missing == true)
487 return false;
488 Fail(true);
489 return true;
490 }
491
492 Res.Size = Fd.Size();
493 }
494
495 Res.LastModified = FailTime;
a7c835af 496 Res.TakeHashes(Hash);
b2e465d6
AL
497
498 // Timestamp
499 struct utimbuf UBuf;
500 UBuf.actime = FailTime;
501 UBuf.modtime = FailTime;
502 utime(Queue->DestFile.c_str(),&UBuf);
503 FailFd = -1;
504
505 URIDone(Res);
506
507 return true;
508}
509 /*}}}*/
510
511int main(int argc, const char *argv[])
512{
b25423f6
MZ
513 setlocale(LC_ALL, "");
514
b2e465d6
AL
515 RSHMethod Mth;
516 Prog = strrchr(argv[0],'/');
517 Prog++;
518 return Mth.Run();
519}