File: DKMethodCall.m

package info (click to toggle)
dbuskit 0.1.1-14
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,956 kB
  • sloc: objc: 10,543; sh: 9,463; ansic: 200; makefile: 32
file content (381 lines) | stat: -rw-r--r-- 10,918 bytes parent folder | download | duplicates (4)
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
/** Implementation of the DKMethodCall class for calling D-Bus methods.

   Copyright (C) 2010 Free Software Foundation, Inc.

   Written by:  Niels Grewe <niels.grewe@halbordnung.de>
   Created: June 2010

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

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02111 USA.
   */

#import "DKMethodCall.h"
#import "DKProxy+Private.h"
#import "DKEndpoint.h"
#import "DKEndpointManager.h"
#import "DKMethod.h"

#import <Foundation/NSDate.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSException.h>
#import <Foundation/NSInvocation.h>
#import <Foundation/NSRunLoop.h>
#import <Foundation/NSString.h>
#import <Foundation/NSThread.h>

#import <GNUstepBase/NSDebug+GNUstepBase.h>

#include <sched.h>
#include <string.h>

@interface DKMethodCall (Private)
- (BOOL) serialize;
@end

@implementation DKMethodCall
- (id) initWithProxy: (DKProxy*)aProxy
              method: (DKMethod*)aMethod
          invocation: (NSInvocation*)anInvocation
{
  return [self initWithProxy: aProxy
                      method: aMethod
                  invocation: anInvocation
                     timeout: 0];
}
- (id) initWithProxy: (DKProxy*)aProxy
              method: (DKMethod*)aMethod
          invocation: (NSInvocation*)anInvocation
             timeout: (NSTimeInterval)aTimeout
{
  DBusMessage *theMessage = NULL;
  DKEndpoint *theEndpoint = [aProxy _endpoint];
  const char* dest = [[aProxy _service] UTF8String];
  const char* path = [[aProxy _path] UTF8String];
  const char* interface = [[aMethod interface] UTF8String];
  const char* methodName = [[aMethod name] UTF8String];

  if (((nil == aProxy) || (nil == aMethod)) || (nil == anInvocation))
  {
    [self release];
    return nil;
  }
  theMessage = dbus_message_new_method_call(dest,
    path,
    interface,
    methodName);
  if (NULL == theMessage)
  {
    [self release];
    return nil;
  }

  /*
   * Initialize the superclass. Since we need the DBusPendingCall, we cannot use
   * the resource preallocation feature. The superclass takes owenership of the
   * DBusMessage.
   */
  if (nil == (self = [super initWithDBusMessage: theMessage
                                    forEndpoint: theEndpoint
                           preallocateResources: NO]))
  {
    dbus_message_unref(theMessage);
    return nil;
  }

  dbus_message_unref(theMessage);

  ASSIGN(invocation,anInvocation);
  ASSIGN(method,aMethod);
  if (0 == aTimeout)
  {
    // Default timeout
    timeout = -1;
  }

  /*
   * Convert NSTimeInterval (seconds, floating point) into D-Bus representation
   * (milliseconds, integer).
   */
  timeout = (NSInteger)(aTimeout * 1000.0);

  if (NO == [self serialize])
  {
    [self release];
    return nil;
  }
  return self;
}

- (BOOL)serialize
{
  BOOL didSucceed = YES;
  DBusMessageIter iter;

  dbus_message_iter_init_append(msg, &iter);
  NS_DURING
  {
    [method marshallFromInvocation: invocation
                      intoIterator: &iter
                       messageType: DBUS_MESSAGE_TYPE_METHOD_CALL];
  }
  NS_HANDLER
  {
    NSWarnMLog(@"Could not marshall arguments into D-Bus message. Exception raised: %@",
      localException);
    didSucceed = NO;
  }
  NS_ENDHANDLER
  return didSucceed;
}
- (BOOL)hasObjectReturn
{
  return  (0 == strcmp(@encode(id), [[invocation methodSignature] methodReturnType]));
}

- (void)handleReplyFromPendingCall: (DBusPendingCall*)pending
                             async: (BOOL)didAsyncOperation
{
  DBusMessage *reply = dbus_pending_call_steal_reply(pending);
  int msgType;
  DBusError error;
  NSException *errorException = nil;
  DBusMessageIter iter;
  // This is the future we are going to use for asynchronous resolution.
  id future = nil;

  // Bad things would happen if we tried this
  NSAssert(!(didAsyncOperation && (NO == [self hasObjectReturn])),
    @"Filling asynchronous return values for non-objects is impossible.");

  if (NULL == reply)
  {
    [NSException raise: @"DKDBusMethodReplyException"
                format: @"Could not obtain reply for pending D-Bus method call."];
  }

  msgType = dbus_message_get_type(reply);

  // Only accept error messages or method replies:
  if (NO == ((msgType == DBUS_MESSAGE_TYPE_METHOD_RETURN)
    || (msgType == DBUS_MESSAGE_TYPE_ERROR)))
  {
    [NSException raise: @"DKDBusMethodReplyException"
                format: @"Invalid message type (%ld) in D-Bus reply", msgType];
  }

  // Handle the error case:
  if (msgType == DBUS_MESSAGE_TYPE_ERROR)
  {
    NSString *errorName = nil;
    NSString *errorMessage = nil;
    NSDictionary *infoDict = nil;

    dbus_error_init(&error);
    dbus_set_error_from_message(&error, reply);
    if (dbus_error_is_set(&error))
    {
      NSString *exceptionName = @"DKDBusRemoteErrorException";
      NSString *exceptionReason = @"A remote object returned an error upon a method call.";
      errorName = [NSString stringWithUTF8String: error.name];
      errorMessage = [NSString stringWithUTF8String: error.message];

      // Check whether the error actually comes from another object exported by
      // DBusKit. If so, we can set the exception name to something the user
      // expects.
      if (([errorName hasPrefix: @"org.gnustep.objc.exception."])
	&& ([errorName length] > 28))
      {
	exceptionName = [errorName substringFromIndex: 27];
	exceptionReason = errorMessage;
      }
      infoDict = [[NSDictionary alloc] initWithObjectsAndKeys:
        errorMessage, errorName,
	invocation, @"invocation", nil];
      errorException = [NSException exceptionWithName: exceptionName
                                               reason: exceptionReason
                                             userInfo: infoDict];
      [infoDict release];
    }
    else
    {
      errorException = [NSException exceptionWithName: @"DKDBusMethodReplyException"
                                               reason: @"Undefined error in D-Bus method reply"
                                             userInfo: nil];
    }
      if (didAsyncOperation)
      {
	// TODO: Pass the exception to the future. It will raise once user code
	// tries to reference the object.
	return;
      }
      else
      {
	[errorException raise];
      }
    }


  // Implicit else if (type == DBUS_MESSAGE_TYPE_METHOD_RETURN)

  if (YES == didAsyncOperation)
  {
    // Extract the future from the invocation, we need it for later use:
    [invocation getReturnValue: &future];
  }


  // We need to catch possible exceptions in order to pass them to the future if
  // we are operating asynchronously.
  NS_DURING
  {
    // dbus_message_iter_init() will return NO if there are no arguments to
    // unmarshall.
    if (YES == (BOOL)dbus_message_iter_init(reply, &iter))
    {
      [method unmarshallFromIterator: &iter
                      intoInvocation: invocation
                         messageType: DBUS_MESSAGE_TYPE_METHOD_RETURN];
    }
  }
  NS_HANDLER
  {
    errorException = localException;
  }
  NS_ENDHANDLER

  if (YES == didAsyncOperation)
  {
    id realObject = nil;
    if (nil != errorException)
    {
      //TODO: Pass the exception to the future.
    }

    // Extract the real returned object from the invocation:
    [invocation getReturnValue: &realObject];

    // TODO: Pass the object to the future. Message sends to the future will no
    // longer block.
  }
  else
  {
    if (nil != errorException)
    {
      [errorException raise];
    }

  }
}

/**
 * Helper method to schedule sending of the message on the worker thread.
 */
- (BOOL)sendWithPendingCallAt: (DBusPendingCall**)pending
{
  return (BOOL)dbus_connection_send_with_reply([endpoint DBusConnection],
    msg,
    pending,
    timeout);

}
- (void)sendAsynchronously
{
  // If the endpoint manager is in synchronizing mode, we don't bother doing an
  // asynchronous call.
  if (([[DKEndpointManager sharedEndpointManager] isSynchronizing])
    || ([[NSThread currentThread] isEqual: [[DKEndpointManager sharedEndpointManager] workerThread]]))
  {
    [self sendSynchronously];
  }
  //TODO: Implement asynchronous behaviour.
}

- (void)sendSynchronously
{
  DBusPendingCall *pending = NULL;
  // -1 means default timeout
  BOOL couldSend = NO;
  NSInteger count = 0;
  DKEndpointManager *manager = [DKEndpointManager sharedEndpointManager];
  IMP isSynchronizing = [manager methodForSelector: @selector(isSynchronizing)];
  couldSend = [manager boolReturnForPerformingSelector: @selector(sendWithPendingCallAt:)
                                                target: self
                                                  data: (void*)&pending
                                         waitForReturn: YES];
  if (NO == couldSend)
  {
    [NSException raise: @"DKDBusOutOfMemoryException"
                format: @"Out of memory when sending D-Bus message."];

  }

  if (NULL == pending)
  {
    [NSException raise: @"DKDBusDisconnectedException"
                format: @"Disconnected from D-Bus when sending message."];

  }

  do
  {
    // Determine wether the manager is in synchronized mode and we need to use
    // the runloop.
    BOOL useCurrentRunLoop = ((BOOL)(uintptr_t)isSynchronizing(manager, @selector(isSynchronizing))
    || ([[NSThread currentThread] isEqual: [manager workerThread]]));

    // If we are using the worker thread, we can yield aggressively until the
    // call completes.
    if (((++count % 16) == 0)
      && (NO == useCurrentRunLoop))
    {
      sched_yield();
    }
    else if (useCurrentRunLoop)
    {
      // Otherwise, we need to the runloop to complete our request.
      [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.1]];
    }
  } while (NO == (BOOL)dbus_pending_call_get_completed(pending));

  //Now we are sure that we don't need the message any more.
  if (NULL != msg)
  {
    dbus_message_unref(msg);
    msg = NULL;
  }

  NS_DURING
  {
    [self handleReplyFromPendingCall: pending
                               async: NO];
  }
  NS_HANDLER
  {
    // Throw away the pending call
    if (NULL != pending)
    {
      dbus_pending_call_unref(pending);
      pending = NULL;
    }
    [localException raise];
  }
  NS_ENDHANDLER
  if (NULL != pending)
  {
    dbus_pending_call_unref(pending);
    pending = NULL;
  }
}
@end