summaryrefslogtreecommitdiff
path: root/methods/nshttp.mm
blob: 4f4e438b0193e8f1968715768dbcf61ad6cdcc7c (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
// -*- mode: cpp; mode: fold -*-
// Description								/*{{{*/
/* ######################################################################

   RSH method - Transfer files via rsh compatible program

   Written by Ben Collins <bcollins@debian.org>, Copyright (c) 2000
   Licensed under the GNU General Public License v2 [no exception clauses]

   ##################################################################### */
									/*}}}*/
// Include Files							/*{{{*/
#include <config.h>

#include <apt-pkg/configuration.h>
#include <apt-pkg/error.h>
#include <apt-pkg/fileutl.h>
#include <apt-pkg/hashes.h>
#include <apt-pkg/strutl.h>

#include "nshttp.h"
#include <errno.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>

#include <apti18n.h>

unsigned long TimeOut = 30;
Configuration::Item const *HttpOptions = 0;
time_t HttpMethod::FailTime = 0;

// HttpMethod::HttpMethod - Constructor					/*{{{*/
HttpMethod::HttpMethod(std::string &&pProg) : aptMethod(std::move(pProg),"1.0",SendConfig)
{
   signal(SIGTERM,SigTerm);
   signal(SIGINT,SigTerm);
}
									/*}}}*/
// HttpMethod::Configuration - Handle a configuration message		/*{{{*/
// ---------------------------------------------------------------------
bool HttpMethod::Configuration(std::string Message)
{
   // enabling privilege dropping for this method requires configuration…
   // … which is otherwise lifted straight from root, so use it by default.
   _config->Set(std::string("Binary::") + Binary + "::APT::Sandbox::User", "");

   if (aptMethod::Configuration(Message) == false)
      return false;

   std::string const timeconf = std::string("Acquire::") + Binary + "::Timeout";
   TimeOut = _config->FindI(timeconf, TimeOut);
   std::string const optsconf = std::string("Acquire::") + Binary + "::Options";
   HttpOptions = _config->Tree(optsconf.c_str());

   return true;
}
									/*}}}*/
// HttpMethod::SigTerm - Clean up and timestamp the files on exit	/*{{{*/
// ---------------------------------------------------------------------
/* */
void HttpMethod::SigTerm(int)
{
   _exit(100);
}
									/*}}}*/
// HttpMethod::Fetch - Fetch a URI					/*{{{*/
// ---------------------------------------------------------------------
/* */
bool HttpMethod::Fetch(FetchItem *Itm)
{
   URI Get = Itm->Uri;
   std::string cppGet = Get;
   NSURL *URL = [NSURL URLWithString:[NSString stringWithUTF8String:cppGet.c_str()]];
   __block FetchResult Res;
   Res.Filename = Itm->DestFile;
   Res.IMSHit = false;

   __block BOOL success = NO;

   dispatch_semaphore_t sem = dispatch_semaphore_create(0);

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TimeOut];
   [request setHTTPMethod:@"HEAD"];
   [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *, NSURLResponse *response, NSError *error){
      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
      if (httpResponse.statusCode >= 200){
         if (httpResponse.expectedContentLength != NSURLResponseUnknownLength)
            Res.Size = httpResponse.expectedContentLength;
         NSString *dateModified = httpResponse.allHeaderFields[@"Date"];
         if (dateModified){
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en"]];
            [formatter setDateFormat:@"EEEE, dd LLL yyyy HH:mm:ss zzz"];
            NSDate *date = [formatter dateFromString:dateModified];
            this->FailTime = [date timeIntervalSince1970];
            [formatter release];
         }
         success = YES;
      } else {
         success = NO;
      }
      dispatch_semaphore_signal(sem);
   }] resume];

   Status(_("Connecting to %s"), Get.Host.c_str());
   dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, TimeOut * NSEC_PER_SEC));

   // Get the files information
   if (!success)
   {
      return false;
   }

   // See if it is an IMS hit
   if (Itm->LastModified == FailTime) {
      Res.Size = 0;
      Res.IMSHit = true;
      URIDone(Res);
      return true;
   }

   // See if the file exists
   struct stat Buf;
   if (stat(Itm->DestFile.c_str(),&Buf) == 0) {
      if (Res.Size == (unsigned long long)Buf.st_size && FailTime == Buf.st_mtime) {
         Res.Size = Buf.st_size;
         Res.LastModified = Buf.st_mtime;
         Res.ResumePoint = Buf.st_size;
         URIDone(Res);
         return true;
      }

      // Resume?
      if (FailTime == Buf.st_mtime && Res.Size > (unsigned long long)Buf.st_size)
         Res.ResumePoint = Buf.st_size;
   }

   // Open the file
   Hashes Hash(Itm->ExpectedHashes);
   {
      [request setHTTPMethod:@"GET"];

      success = NO;

      NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error){
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
         if (httpResponse.statusCode == 200 && !error){
            NSString *destFile = [NSString stringWithUTF8String:Itm->DestFile.c_str()];
            [[NSFileManager defaultManager] removeItemAtPath:destFile error:nil];
            success = [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:destFile error:&error];
            if (error){
               success = NO;
            }
         }
         dispatch_semaphore_signal(sem);
      }];
      [task resume];
      dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, TimeOut * NSEC_PER_SEC));

      if (!success){
         Fail(true);
         return true;
      }

      FileFd Fd(Itm->DestFile,FileFd::WriteExists);
      Hash.AddFD(Fd,Hashes::UntilEOF);

      URIStart(Res);

      Res.Size = Fd.Size();
      struct timeval times[2];
      times[0].tv_sec = FailTime;
      times[1].tv_sec = FailTime;
      times[0].tv_usec = times[1].tv_usec = 0;
      utimes(Fd.Name().c_str(), times);
   }

   Res.LastModified = FailTime;
   Res.TakeHashes(Hash);

   URIDone(Res);

   return true;
}
									/*}}}*/

int main(int, const char *argv[])
{
   return HttpMethod(flNotDir(argv[0])).Run();
}