Objectively
Object oriented framework for C.
Loading...
Searching...
No Matches
URLSession.c
Go to the documentation of this file.
1/*
2 * Objectively: Ultra-lightweight object oriented framework for GNU C.
3 * Copyright (C) 2014 Jay Dolan <jay@jaydolan.com>
4 *
5 * This software is provided 'as-is', without any express or implied
6 * warranty. In no event will the authors be held liable for any damages
7 * arising from the use of this software.
8 *
9 * Permission is granted to anyone to use this software for any purpose,
10 * including commercial applications, and to alter it and redistribute it
11 * freely, subject to the following restrictions:
12 *
13 * 1. The origin of this software must not be misrepresented; you must not
14 * claim that you wrote the original software. If you use this software
15 * in a product, an acknowledgment in the product documentation would be
16 * appreciated but is not required.
17 *
18 * 2. Altered source versions must be plainly marked as such, and must not be
19 * misrepresented as being the original software.
20 *
21 * 3. This notice may not be removed or altered from any source distribution.
22 */
23
24#include <assert.h>
25
26#include <curl/curl.h>
27
28#include "URLSession.h"
29
30#define _Class _URLSession
31
32#pragma mark - Object
33
37static void dealloc(Object *self) {
38
39 URLSession *this = (URLSession *) self;
40
41 $(this, invalidateAndCancel);
42
43 $(this->thread, join, NULL);
44
45 release(this->condition);
46 release(this->thread);
47 release(this->tasks);
48 release(this->configuration);
49
50 super(Object, self, dealloc);
51}
52
53#pragma mark - URLSession
54
59
60 task = $((URLSessionTask *) task, initWithRequestInSession, request, self, completion);
61 if (task) {
62
63 bool isInvalidated;
64
65 synchronized(self->condition, {
66 isInvalidated = $(self->thread, isCancelled);
67 if (isInvalidated == false) {
68 $(self->tasks, addObject, task);
69 $(self->condition, signal);
70 }
71 });
72
73 if (isInvalidated) {
74 task = release(task);
75 }
76 }
77
78 return task;
79}
80
86
88 initWithRequestInSession, request, self, completion);
89 if (task) {
90
91 bool isInvalidated;
92
93 synchronized(self->condition, {
94 isInvalidated = $(self->thread, isCancelled);
95 });
96
97 if (isInvalidated) {
98 return release(task);
99 }
100
101 URLCache *cache = self->configuration->urlCache;
102 if (cache) {
104 if (task->cachedResponse) {
105 return task;
106 }
107 }
108
109 synchronized(self->condition, {
110 isInvalidated = $(self->thread, isCancelled);
111 if (isInvalidated == false) {
112 $(self->tasks, addObject, task);
113 $(self->condition, signal);
114 }
115 });
116
117 if (isInvalidated) {
118 task = release(task);
119 }
120 }
121
122 return task;
123}
124
130
132 request->httpMethod = HTTP_GET;
133
134 URLSessionDataTask *task = $(self, dataTaskWithRequest, request, completion);
135
137
138 return task;
139}
140
149
155
157
158 URLSessionDownloadTask *task = $(self, downloadTaskWithRequest, request, completion);
159
161
162 return task;
163}
164
169static URLSession *init(URLSession *self) {
170
172
173 self = $(self, initWithConfiguration, configuration);
174
175 release(configuration);
176
177 return self;
178}
179
186static bool hasWork(const URLSession *self) {
187
188 const Array *tasks = (Array *) self->tasks;
189 for (size_t i = 0; i < tasks->count; i++) {
190
191 const URLSessionTask *task = $(tasks, objectAtIndex, i);
192 if (task->isExecuting == false && task->state != URLSESSIONTASK_SUSPENDED) {
193 return true;
194 }
195 }
196
197 return false;
198}
199
203static ident run(Thread *thread) {
204
205 URLSession *self = thread->data;
206
207 self->handle = curl_multi_init();
208 assert(self->handle);
209
210 while (true) {
211 int ret;
212
213 bool idle;
214 synchronized(self->condition, {
215 while (!hasWork(self) && !($(thread, isCancelled) && self->tasks->count == 0)) {
216 $(self->condition, wait);
217 }
218 idle = $(thread, isCancelled) && self->tasks->count == 0;
219 });
220
221 if (idle) {
222 break;
223 }
224
225 Array *tasks = $(self, tasks);
226
227 for (size_t i = 0; i < tasks->count; i++) {
228
229 URLSessionTask *task = $(tasks, objectAtIndex, i);
230
231 bool isExecuting;
232 synchronized(self->condition, {
233 isExecuting = task->isExecuting;
234 });
235
236 if (isExecuting) {
237 continue;
238 }
239
240 if (task->state == URLSESSIONTASK_SUSPENDING) {
241
242 if (task->handle) {
243 const CURLcode err = curl_easy_pause(task->handle, CURLPAUSE_ALL);
244 assert(err == CURLE_OK);
245 }
246
247 synchronized(self->condition, {
248 if (task->state == URLSESSIONTASK_SUSPENDING) {
250 }
251 });
252
253 } else if (task->state == URLSESSIONTASK_RESUMING) {
254
255 if (task->handle == NULL) {
256
257 $(task, setup);
258 assert(task->handle);
259
260 const CURLMcode merr = curl_multi_add_handle(self->handle, task->handle);
261 assert(merr == CURLM_OK);
262 } else {
263 const CURLcode err = curl_easy_pause(task->handle, CURLPAUSE_CONT);
264 assert(err == CURLE_OK);
265 }
266
267 synchronized(self->condition, {
268 if (task->state == URLSESSIONTASK_RESUMING) {
270 }
271 });
272
273 } else if (task->state == URLSESSIONTASK_CANCELING) {
274
275 if (task->handle) {
276 const CURLMcode merr = curl_multi_remove_handle(self->handle, task->handle);
277 assert(merr == CURLM_OK);
278 }
279
280 task->result = CURLE_ABORTED_BY_CALLBACK;
282
283 if (task->completion) {
284 task->completion(task, false);
285 }
286
287 $(task, teardown);
288
289 synchronized(self->condition, {
290 $(self->tasks, removeObject, task);
291 });
292 } else if (task->state == URLSESSIONTASK_CANCELED || task->state == URLSESSIONTASK_COMPLETED) {
293
294 synchronized(self->condition, {
295 $(self->tasks, removeObject, task);
296 });
297 }
298 }
299
300 CURLMcode merr = curl_multi_wait(self->handle, NULL, 0, 0, NULL);
301 assert(merr == CURLM_OK);
302
303 merr = curl_multi_perform(self->handle, &ret);
304 assert(merr == CURLM_OK);
305
306 CURLMsg *message;
307 while ((message = curl_multi_info_read(self->handle, &ret))) {
308
309 URLSessionTask *task = NULL;
310 for (size_t i = 0; i < tasks->count; i++) {
311
313 if (t->handle == message->easy_handle) {
314 task = t;
315 break;
316 }
317 }
318
319 assert(task);
320
321 if (message->msg == CURLMSG_DONE) {
322
323 merr = curl_multi_remove_handle(self->handle, task->handle);
324 assert(merr == CURLM_OK);
325
326 task->result = message->data.result;
327
328 synchronized(self->condition, {
329 if (task->state == URLSESSIONTASK_CANCELING) {
331 } else {
333 }
334 });
335
336 curl_easy_getinfo(task->handle, CURLINFO_RESPONSE_CODE, (long *) &task->response->httpStatusCode);
337
338 const bool success = task->state == URLSESSIONTASK_COMPLETED && task->result == CURLE_OK;
339
340 if (success && $((Object *) task, isKindOfClass, _URLSessionDataTask())) {
342 }
343
344 if (task->completion) {
345 task->completion(task, success);
346 }
347
348 $(task, teardown);
349
350 synchronized(self->condition, {
351 $(self->tasks, removeObject, task);
352 });
353 }
354 }
355
356 release(tasks);
357 }
358
359 curl_multi_cleanup(self->handle);
360
361 return NULL;
362}
363
369
370 assert(configuration);
371
372 self = (URLSession *) super(Object, self, init);
373 if (self) {
374 self->configuration = retain(configuration);
375
376 self->condition = $(alloc(Condition), init);
377 self->tasks = $(alloc(Array), init);
378 self->thread = $(alloc(Thread), initWithFunction, run, self);
379
380 $(self->thread, start);
381 }
382
383 return self;
384}
385
390static void invalidateAndCancel(URLSession *self) {
391
392 bool isInvalidated;
393
394 synchronized(self->condition, {
395 isInvalidated = $(self->thread, isCancelled);
396 if (isInvalidated == false) {
397 $(self->thread, cancel);
398 $(self->condition, signal);
399 }
400 });
401
402 if (isInvalidated) {
403 return;
404 }
405
406 Array *tasks = $(self, tasks);
407
408 for (size_t i = 0; i < tasks->count; i++) {
409
410 URLSessionTask *task = $(tasks, objectAtIndex, i);
411 $(task, cancel);
412 }
413
414 release(tasks);
415}
416
418
424
425 static Once once;
426
427 do_once(&once, {
429 });
430
431 return _sharedInstance;
432}
433
438static Array *tasks(const URLSession *self) {
439
440 Array *array;
441
442 synchronized(self->condition, {
443 array = $$(Array, arrayWithArray, (Array *) self->tasks);
444 });
445
446 return array;
447}
448
457
458#pragma mark - Class lifecycle
459
463static void destroy(Class *clazz) {
464
466
467 curl_global_cleanup();
468}
469
473static void initialize(Class *clazz) {
474
475 ((ObjectInterface *) clazz->interface)->dealloc = dealloc;
476
477 ((URLSessionInterface *) clazz->interface)->dataTaskWithRequest = dataTaskWithRequest;
478 ((URLSessionInterface *) clazz->interface)->dataTaskWithURL = dataTaskWithURL;
479 ((URLSessionInterface *) clazz->interface)->downloadTaskWithRequest = downloadTaskWithRequest;
480 ((URLSessionInterface *) clazz->interface)->downloadTaskWithURL = downloadTaskWithURL;
481 ((URLSessionInterface *) clazz->interface)->init = init;
482 ((URLSessionInterface *) clazz->interface)->initWithConfiguration = initWithConfiguration;
483 ((URLSessionInterface *) clazz->interface)->invalidateAndCancel = invalidateAndCancel;
484 ((URLSessionInterface *) clazz->interface)->sharedInstance = sharedInstance;
485 ((URLSessionInterface *) clazz->interface)->tasks = tasks;
486 ((URLSessionInterface *) clazz->interface)->uploadTaskWithRequest = uploadTaskWithRequest;
487
488 const CURLcode code = curl_global_init(CURL_GLOBAL_ALL);
489 assert(code == CURLE_OK);
490}
491
497 static Class *clazz;
498 static Once once;
499
500 do_once(&once, {
501 clazz = _initialize(&(const ClassDef) {
502 .name = "URLSession",
503 .superclass = _Object(),
504 .instanceSize = sizeof(URLSession),
505 .interfaceSize = sizeof(URLSessionInterface),
506 .initialize = initialize,
507 .destroy = destroy,
508 });
509 });
510
511 return clazz;
512}
513
514#undef _Class
static ident objectAtIndex(const Array *self, size_t index)
Definition Array.c:578
static void removeObject(Array *self, const ident obj)
Definition Array.c:642
static Array * arrayWithArray(const Array *array)
Definition Array.c:243
static void addObject(Array *self, const ident obj)
Definition Array.c:181
static Array * array(void)
Definition Array.c:234
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
ident release(ident obj)
Atomically decrement the given Object's reference count. If the resulting reference count is 0,...
Definition Class.c:356
Class * _initialize(const ClassDef *def)
Initializes the given Class.
Definition Class.c:151
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
#define super(type, obj, method,...)
static bool isKindOfClass(const Object *self, const Class *clazz)
Definition Object.c:101
Class * _Object(void)
Definition Object.c:136
static bool isCancelled(const Operation *self)
Definition Operation.c:140
static Operation * initWithFunction(Operation *self, OperationFunction function, ident data)
Definition Operation.c:125
static void start(Operation *self)
Definition Operation.c:185
static void cancel(Operation *self)
Definition Operation.c:73
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 join(Thread *self, ident *status)
Definition Thread.c:139
void * ident
The identity type, similar to Objective-C id.
Definition Types.h:49
static URLCachedResponse * cachedResponseForRequest(URLCache *self, const URLRequest *request)
Definition URLCache.c:268
static URLRequest * initWithURL(URLRequest *self, URL *url)
Definition URLRequest.c:150
@ HTTP_GET
Definition URLRequest.h:46
static URLSessionDataTask * dataTaskWithRequest(URLSession *self, URLRequest *request, URLSessionTaskCompletion completion)
Definition URLSession.c:85
static void destroy(Class *clazz)
Definition URLSession.c:463
static URLSessionUploadTask * uploadTaskWithRequest(URLSession *self, URLRequest *request, URLSessionTaskCompletion completion)
Definition URLSession.c:453
static bool hasWork(const URLSession *self)
Checks whether any task needs the run loop.
Definition URLSession.c:186
static URLSession * initWithConfiguration(URLSession *self, URLSessionConfiguration *configuration)
Definition URLSession.c:368
Class * _URLSession(void)
Definition URLSession.c:496
static URLSessionDownloadTask * downloadTaskWithURL(URLSession *self, URL *url, URLSessionTaskCompletion completion)
Definition URLSession.c:154
static Array * tasks(const URLSession *self)
Definition URLSession.c:438
static URLSession * init(URLSession *self)
Definition URLSession.c:169
static ident taskWithRequest(URLSession *self, ident task, URLRequest *request, URLSessionTaskCompletion completion)
URLSessionTask factory function.
Definition URLSession.c:58
static URLSession * sharedInstance(void)
Definition URLSession.c:423
static ident run(Thread *thread)
ThreadFunction for a URLSession.
Definition URLSession.c:203
static void dealloc(Object *self)
Definition URLSession.c:37
static URLSessionDataTask * dataTaskWithURL(URLSession *self, URL *url, URLSessionTaskCompletion completion)
Definition URLSession.c:129
static URLSession * _sharedInstance
Definition URLSession.c:417
static void invalidateAndCancel(URLSession *self)
Definition URLSession.c:390
static void initialize(Class *clazz)
Definition URLSession.c:473
static URLSessionDownloadTask * downloadTaskWithRequest(URLSession *self, URLRequest *request, URLSessionTaskCompletion completion)
Definition URLSession.c:145
A management context for loading resources via URLs.
Class * _URLSessionDataTask(void)
static void cacheResponse(URLSessionDataTask *self)
static URLSessionTask * initWithRequestInSession(URLSessionTask *self, struct URLRequest *request, struct URLSession *session, URLSessionTaskCompletion completion)
void(* URLSessionTaskCompletion)(URLSessionTask *task, bool success)
A function pointer for URLSessionTask completion.
@ URLSESSIONTASK_RESUMING
@ URLSESSIONTASK_CANCELED
@ URLSESSIONTASK_SUSPENDING
@ URLSESSIONTASK_SUSPENDED
@ URLSESSIONTASK_COMPLETED
@ URLSESSIONTASK_RESUMED
@ URLSESSIONTASK_CANCELING
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
Arrays.
Definition Array.h:56
size_t count
The count of elements.
Definition Array.h:72
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
ident interface
The interface of the Class.
Definition Class.h:100
POSIX Threads conditional variables.
Definition Condition.h:44
Object is the root Class of The Objectively Class hierarchy.
Definition Object.h:46
Object * init(Object *self)
Initializes this Object.
Definition Object.c:83
POSIX Threads.
Definition Thread.h:53
ident data
The user data.
Definition Thread.h:69
A cache for HTTP responses.
Definition URLCache.h:44
Uniform Resource Locators (RFC 3986).
Definition URL.h:44
A protocol-agnostic abstraction for requesting resources via URLs.
Definition URLRequest.h:58
int httpStatusCode
The HTTP response status code.
Definition URLResponse.h:63
Configuration bundle for URLSession.
URLCache * urlCache
The cache for URL responses, or NULL to disable caching.
Use data tasks to send and receive Data in-memory.
URLCachedResponse * cachedResponse
A cached response, if this task was fulfilled from URLCache.
Use download tasks to save remote resources to file.
A management context for loading resources via URLs.
Definition URLSession.h:59
URLSessionConfiguration * configuration
The session configuration.
Definition URLSession.h:81
void invalidateAndCancel(URLSession *)
Invalidates this URLSession and cancels all pending tasks.
Definition URLSession.c:390
URLSession * initWithConfiguration(URLSession *, URLSessionConfiguration *)
Initializes this URLSession with the given configuration.
Definition URLSession.c:368
URL session tasks are handles to pending URL operations.
struct URLResponse * response
The response.
int result
The libcurl result code (CURLcode) of the transfer, 0 on success.
URLSessionTaskState state
The state.
URLSessionTaskCompletion completion
The completion function.
Use upload tasks to send files directly from disk.