Objectively
Object oriented framework for C.
Loading...
Searching...
No Matches
URLSessionTask.c File Reference
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <curl/curl.h>
#include "URLRequest.h"
#include "URLResponse.h"
#include "URLSession.h"
#include "URLSessionTask.h"

Go to the source code of this file.

Macros

#define _Class   _URLSessionTask
 

Functions

Class * _URLSessionTask (void)
 
static void cancel (URLSessionTask *self)
 
static Object * copy (const Object *self)
 
static void dealloc (Object *self)
 
static void execute (URLSessionTask *self)
 
static void initialize (Class *clazz)
 
static URLSessionTask * initWithRequestInSession (URLSessionTask *self, struct URLRequest *request, struct URLSession *session, URLSessionTaskCompletion completion)
 
static int progress (ident self, curl_off_t bytesExpectedToReceive, curl_off_t bytesReceived, curl_off_t bytesExpectedToSend, curl_off_t bytesSent)
 The CURLOPT_XFERINFOFUNCTION, which updates internal state and dispatches the task's progress function.
 
static void requestHeaders_enumerator (const Dictionary *dictionary, ident obj, ident key, ident data)
 A helper to populate the request headers list for CURL.
 
static size_t responseHeader (char *buffer, size_t size, size_t count, void *data)
 The CURLOPT_HEADERFUNCTION for parsing response headers.
 
static void resume (URLSessionTask *self)
 
static void setup (URLSessionTask *self)
 
static void suspend (URLSessionTask *self)
 
static void teardown (URLSessionTask *self)
 

Macro Definition Documentation

◆ _Class

#define _Class   _URLSessionTask

Definition at line 34 of file URLSessionTask.c.

Function Documentation

◆ _URLSessionTask()

Class * _URLSessionTask ( void  )

Definition at line 386 of file URLSessionTask.c.

386 {
387 static Class *clazz;
388 static Once once;
389
390 do_once(&once, {
391 clazz = _initialize(&(const ClassDef) {
392 .name = "URLSessionTask",
393 .superclass = _Object(),
394 .instanceSize = sizeof(URLSessionTask),
395 .interfaceSize = sizeof(URLSessionTaskInterface),
396 .initialize = initialize,
397 });
398 });
399
400 return clazz;
401}
Class * _initialize(const ClassDef *def)
Initializes the given Class.
Definition Class.c:151
Class * _Object(void)
Definition Object.c:136
static void initialize(Class *clazz)
long Once
The Once type.
Definition Once.h:37
#define do_once(once, block)
Executes the given block at most one time.
Definition Once.h:43
ClassDefs are passed to _initialize via an archetype to initialize a Class.
Definition Class.h:41
The runtime representation of a Class.
Definition Class.h:90
URL session tasks are handles to pending URL operations.

◆ cancel()

static void cancel ( URLSessionTask *  self)
static

Definition at line 69 of file URLSessionTask.c.

69 {
70
71 synchronized(self->session->condition, {
72 switch (self->state) {
78 $(self->session->condition, signal);
79 break;
80 default:
81 break;
82 }
83 });
84}
@ URLSESSIONTASK_RESUMING
@ URLSESSIONTASK_SUSPENDING
@ URLSESSIONTASK_SUSPENDED
@ URLSESSIONTASK_RESUMED
@ URLSESSIONTASK_CANCELING
struct URLSession * session
The session, which is not retained.
URLSessionTaskState state
The state.

◆ copy()

static Object * copy ( const Object *  self)
static
See also
Object::copy(const Object *)

Definition at line 41 of file URLSessionTask.c.

41 {
42
43 return NULL;
44}

◆ dealloc()

static void dealloc ( Object *  self)
static
See also
Object::dealloc(Object *)

Definition at line 49 of file URLSessionTask.c.

49 {
50
51 URLSessionTask *this = (URLSessionTask *) self;
52
53 if (this->error) {
54 free(this->error);
55 }
56
57 release(this->request);
58 release(this->response);
59
60 super(Object, self, dealloc);
61}
ident release(ident obj)
Atomically decrement the given Object's reference count. If the resulting reference count is 0,...
Definition Class.c:356
#define super(type, obj, method,...)
static void error(const Log *self, const char *fmt,...)
Definition Log.c:80
static int request(RESTClient *self, HTTPMethod method, const char *url_string, const Data *body, const char **headers, Data **out_data)
Definition RESTClient.c:62
static void dealloc(Object *self)
Object is the root Class of The Objectively Class hierarchy.
Definition Object.h:46

◆ execute()

static void execute ( URLSessionTask *  self)
static

Definition at line 90 of file URLSessionTask.c.

90 {
91
92 Condition *condition = self->session->condition;
93
94 bool isExecuting = false;
95
96 synchronized(condition, {
97 switch (self->state) {
100 break;
103 break;
104 default:
105 self->isExecuting = isExecuting = true;
106 break;
107 }
108 });
109
110 if (isExecuting == false) {
111 return;
112 }
113
114 $(self, setup);
115
116 self->result = curl_easy_perform(self->handle);
117
118 curl_easy_getinfo(self->handle, CURLINFO_RESPONSE_CODE, (long *) &self->response->httpStatusCode);
119
120 synchronized(condition, {
121 self->isExecuting = false;
122 if (self->state == URLSESSIONTASK_CANCELING) {
124 } else {
126 }
127 $(condition, signal);
128 });
129
130 $(self, teardown);
131}
static void teardown(void)
Called atexit to teardown Objectively.
Definition Class.c:76
static void setup(void)
Called when initializing Object to setup Objectively.
Definition Class.c:113
@ URLSESSIONTASK_CANCELED
@ URLSESSIONTASK_COMPLETED
POSIX Threads conditional variables.
Definition Condition.h:44
int httpStatusCode
The HTTP response status code.
Definition URLResponse.h:63
struct URLResponse * response
The response.
int result
The libcurl result code (CURLcode) of the transfer, 0 on success.

◆ initialize()

static void initialize ( Class *  clazz)
static
See also
Class::initialize(Class *)

Definition at line 368 of file URLSessionTask.c.

368 {
369
370 ((ObjectInterface *) clazz->interface)->copy = copy;
371 ((ObjectInterface *) clazz->interface)->dealloc = dealloc;
372
373 ((URLSessionTaskInterface *) clazz->interface)->cancel = cancel;
374 ((URLSessionTaskInterface *) clazz->interface)->execute = execute;
375 ((URLSessionTaskInterface *) clazz->interface)->initWithRequestInSession = initWithRequestInSession;
376 ((URLSessionTaskInterface *) clazz->interface)->resume = resume;
377 ((URLSessionTaskInterface *) clazz->interface)->setup = setup;
378 ((URLSessionTaskInterface *) clazz->interface)->suspend = suspend;
379 ((URLSessionTaskInterface *) clazz->interface)->teardown = teardown;
380}
static URLSessionTask * initWithRequestInSession(URLSessionTask *self, struct URLRequest *request, struct URLSession *session, URLSessionTaskCompletion completion)
static void resume(URLSessionTask *self)
static void cancel(URLSessionTask *self)
static void execute(URLSessionTask *self)
static Object * copy(const Object *self)
static void suspend(URLSessionTask *self)
ident interface
The interface of the Class.
Definition Class.h:100
void dealloc(Object *self)
Frees all resources held by this Object.
Definition Array.c:99
void resume(URLSessionTask *)
Starts or resumes this task.

◆ initWithRequestInSession()

static URLSessionTask * initWithRequestInSession ( URLSessionTask *  self,
struct URLRequest *  request,
struct URLSession *  session,
URLSessionTaskCompletion  completion 
)
static

Definition at line 137 of file URLSessionTask.c.

138 {
139
140 assert(request);
141 assert(session);
142
143 self = (URLSessionTask *) super(Object, self, init);
144 if (self) {
145
146 self->error = calloc(1, CURL_ERROR_SIZE);
147 assert(self->error);
148
149 self->request = retain(request);
150 self->session = session;
151
152 self->response = $(alloc(URLResponse), init);
153
154 self->completion = completion;
155
157 }
158
159 return self;
160}
static Array * init(Array *self)
Definition Array.c:420
ident retain(ident obj)
Atomically increment the given Object's reference count.
Definition Class.c:372
#define alloc(type)
Allocate and initialize and instance of type.
Definition Class.h:226
A protocol-agnostic abstraction for URLSessionTask responses.
Definition URLResponse.h:42
char * error
The error buffer.
struct URLRequest * request
The request.
URLSessionTaskCompletion completion
The completion function.

◆ progress()

static int progress ( ident  self,
curl_off_t  bytesExpectedToReceive,
curl_off_t  bytesReceived,
curl_off_t  bytesExpectedToSend,
curl_off_t  bytesSent 
)
static

The CURLOPT_XFERINFOFUNCTION, which updates internal state and dispatches the task's progress function.

Returns
Nonzero to abort the transfer, which is how cancel interrupts execute.

Definition at line 225 of file URLSessionTask.c.

226 {
227
228 URLSessionTask *this = (URLSessionTask *) self;
229
230 curl_easy_getinfo(this->handle, CURLINFO_RESPONSE_CODE, (long *) &this->response->httpStatusCode);
231
232 this->bytesExpectedToReceive = bytesExpectedToReceive;
233 this->bytesExpectedToSend = bytesExpectedToSend;
234
235 if (this->progress) {
236 this->progress(this);
237 }
238
239 bool isCanceling;
240 synchronized(this->session->condition, {
241 isCanceling = this->state == URLSESSIONTASK_CANCELING;
242 });
243
244 return isCanceling;
245}
static int progress(ident self, curl_off_t bytesExpectedToReceive, curl_off_t bytesReceived, curl_off_t bytesExpectedToSend, curl_off_t bytesSent)
The CURLOPT_XFERINFOFUNCTION, which updates internal state and dispatches the task's progress functio...

◆ requestHeaders_enumerator()

static void requestHeaders_enumerator ( const Dictionary *  dictionary,
ident  obj,
ident  key,
ident  data 
)
static

A helper to populate the request headers list for CURL.

Definition at line 184 of file URLSessionTask.c.

184 {
185
186 String *header = $(alloc(String), initWithFormat, "%s: %s", ((String * ) key)->chars, ((String * ) obj)->chars);
187
188 struct curl_slist **headers = (struct curl_slist **) data;
189 *headers = curl_slist_append(*headers, header->chars);
190
191 release(header);
192}
#define obj
static Data * data(void)
Definition Data.c:286
static DateFormatter * initWithFormat(DateFormatter *self, const char *fmt)
UTF-8 strings.
Definition String.h:69
char * chars
The backing null-terminated UTF-8 encoded character array.
Definition String.h:85

◆ responseHeader()

static size_t responseHeader ( char *  buffer,
size_t  size,
size_t  count,
void *  data 
)
static

The CURLOPT_HEADERFUNCTION for parsing response headers.

Definition at line 197 of file URLSessionTask.c.

197 {
198
200
201 char *header = calloc(count + 1, 1);
202 memcpy(header, buffer, count);
203
204 char *delim = strchr(header, ':');
205 if (delim) {
206 *delim = 0;
207
208 char *field = header;
209 char *value = strtrim(delim + 1);
210
211 $(this->response, setValueForHTTPHeaderField, value, field);
212
213 free(value);
214 }
215
216 free(header);
217 return count;
218}
char * strtrim(const char *s)
Copies the given null-terminated C string, trimming leading and trailing whitespace.
Definition String.c:1091
static void setValueForHTTPHeaderField(URLRequest *self, const char *value, const char *field)
Definition URLRequest.c:169

◆ resume()

static void resume ( URLSessionTask *  self)
static

Definition at line 166 of file URLSessionTask.c.

166 {
167
168 synchronized(self->session->condition, {
169 switch (self->state) {
173 $(self->session->condition, signal);
174 break;
175 default:
176 break;
177 }
178 });
179}

◆ setup()

static void setup ( URLSessionTask *  self)
static

Definition at line 251 of file URLSessionTask.c.

251 {
252
253 self->handle = curl_easy_init();
254 assert(self->handle);
255
256 curl_easy_setopt(self->handle, CURLOPT_ERRORBUFFER, self->error);
257 curl_easy_setopt(self->handle, CURLOPT_FOLLOWLOCATION, true);
258
259 const URLSessionConfiguration *config = self->session->configuration;
260 if (config->connectTimeout) {
261 curl_easy_setopt(self->handle, CURLOPT_CONNECTTIMEOUT, config->connectTimeout);
262 }
263 if (config->timeout) {
264 curl_easy_setopt(self->handle, CURLOPT_TIMEOUT, config->timeout);
265 }
266 if (!config->longPolling) {
267 curl_easy_setopt(self->handle, CURLOPT_LOW_SPEED_LIMIT, 1L);
268 curl_easy_setopt(self->handle, CURLOPT_LOW_SPEED_TIME, 10L);
269 }
270
271 curl_easy_setopt(self->handle, CURLOPT_HEADERFUNCTION, responseHeader);
272 curl_easy_setopt(self->handle, CURLOPT_HEADERDATA, self);
273
274 curl_easy_setopt(self->handle, CURLOPT_NOPROGRESS, 0L);
275 curl_easy_setopt(self->handle, CURLOPT_XFERINFOFUNCTION, progress);
276 curl_easy_setopt(self->handle, CURLOPT_XFERINFODATA, self);
277
278 Data *body = self->request->httpBody;
279 if (body) {
280 curl_easy_setopt(self->handle, CURLOPT_POSTFIELDS, body->bytes);
281 curl_easy_setopt(self->handle, CURLOPT_POSTFIELDSIZE, body->length);
282 }
283
284 struct curl_slist *httpHeaders = NULL;
285 const Dictionary *headers = NULL;
286
287 headers = self->session->configuration->httpHeaders;
288 if (headers) {
289 $(headers, enumerateObjectsAndKeys, requestHeaders_enumerator, &httpHeaders);
290 }
291
292 headers = self->request->httpHeaders;
293 if (headers) {
294 $(headers, enumerateObjectsAndKeys, requestHeaders_enumerator, &httpHeaders);
295 }
296
297 curl_easy_setopt(self->handle, CURLOPT_HTTPHEADER, httpHeaders);
298
299 self->requestHeaders = httpHeaders;
300
301 switch (self->request->httpMethod) {
302 case HTTP_POST:
303 curl_easy_setopt(self->handle, CURLOPT_POST, true);
304 break;
305 case HTTP_PUT:
306 curl_easy_setopt(self->handle, CURLOPT_PUT, true);
307 break;
308 case HTTP_DELETE:
309 curl_easy_setopt(self->handle, CURLOPT_CUSTOMREQUEST, "DELETE");
310 break;
311 case HTTP_PATCH:
312 curl_easy_setopt(self->handle, CURLOPT_CUSTOMREQUEST, "PATCH");
313 break;
314 case HTTP_HEAD:
315 curl_easy_setopt(self->handle, CURLOPT_NOBODY, true);
316 break;
317 case HTTP_OPTIONS:
318 curl_easy_setopt(self->handle, CURLOPT_CUSTOMREQUEST, "OPTIONS");
319 break;
320 default:
321 break;
322 }
323
324 curl_easy_setopt(self->handle, CURLOPT_URL, self->request->url->urlString->chars);
325}
static void enumerateObjectsAndKeys(const Dictionary *self, DictionaryEnumerator enumerator, ident data)
Definition Dictionary.c:295
@ HTTP_PUT
Definition URLRequest.h:48
@ HTTP_DELETE
Definition URLRequest.h:50
@ HTTP_OPTIONS
Definition URLRequest.h:45
@ HTTP_POST
Definition URLRequest.h:47
@ HTTP_HEAD
Definition URLRequest.h:44
@ HTTP_PATCH
Definition URLRequest.h:49
static void requestHeaders_enumerator(const Dictionary *dictionary, ident obj, ident key, ident data)
A helper to populate the request headers list for CURL.
static size_t responseHeader(char *buffer, size_t size, size_t count, void *data)
The CURLOPT_HEADERFUNCTION for parsing response headers.
Data buffers.
Definition Data.h:50
size_t length
The length of bytes.
Definition Data.h:76
uint8_t * bytes
The bytes.
Definition Data.h:66
Key-value stores.
Definition Dictionary.h:60
String * urlString
The URL String.
Definition URL.h:90
HTTPMethod httpMethod
The HTTP request method.
Definition URLRequest.h:84
Dictionary * httpHeaders
The HTTP request headers.
Definition URLRequest.h:79
URL * url
The URL.
Definition URLRequest.h:89
Data * httpBody
The HTTP request body, sent as POST or PUT data.
Definition URLRequest.h:74
Configuration bundle for URLSession.
long connectTimeout
The timeout interval for establishing a connection, in seconds. 0 means no limit.
Dictionary * httpHeaders
The HTTP headers added to every HTTP URLRequest.
bool longPolling
If true, disables stall detection (LOW_SPEED_LIMIT / LOW_SPEED_TIME). Use for requests that legitimat...
long timeout
The timeout for the entire transfer, in seconds. 0 means no limit.
URLSessionConfiguration * configuration
The session configuration.
Definition URLSession.h:81

◆ suspend()

static void suspend ( URLSessionTask *  self)
static

Definition at line 331 of file URLSessionTask.c.

331 {
332
333 synchronized(self->session->condition, {
334 switch (self->state) {
338 $(self->session->condition, signal);
339 break;
340 default:
341 break;
342 }
343 });
344}

◆ teardown()

static void teardown ( URLSessionTask *  self)
static

Definition at line 350 of file URLSessionTask.c.

350 {
351
352 if (self->handle) {
353 curl_easy_cleanup(self->handle);
354 self->handle = NULL;
355 }
356
357 if (self->requestHeaders) {
358 curl_slist_free_all(self->requestHeaders);
359 self->requestHeaders = NULL;
360 }
361}