MagickCore 7.1.2-37
Convert, Edit, Or Compose Bitmap Images
Loading...
Searching...
No Matches
distribute-cache.c
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% DDDD IIIII SSSSS TTTTT RRRR IIIII BBBB U U TTTTT EEEEE %
6% D D I SS T R R I B B U U T E %
7% D D I SSS T RRRR I BBBB U U T EEE %
8% D D I SS T R R I B B U U T E %
9% DDDDA IIIII SSSSS T R R IIIII BBBB UUU T EEEEE %
10% %
11% CCCC AAA CCCC H H EEEEE %
12% C A A C H H E %
13% C AAAAA C HHHHH EEE %
14% C A A C H H E %
15% CCCC A A CCCC H H EEEEE %
16% %
17% %
18% MagickCore Distributed Pixel Cache Methods %
19% %
20% Software Design %
21% Cristy %
22% January 2013 %
23% %
24% %
25% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
26% dedicated to making software imaging solutions freely available. %
27% %
28% You may not use this file except in compliance with the License. You may %
29% obtain a copy of the License at %
30% %
31% https://imagemagick.org/license/ %
32% %
33% Unless required by applicable law or agreed to in writing, software %
34% distributed under the License is distributed on an "AS IS" BASIS, %
35% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
36% See the License for the specific language governing permissions and %
37% limitations under the License. %
38% %
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40%
41% A distributed pixel cache is an extension of the traditional pixel cache
42% available on a single host. The distributed pixel cache may span multiple
43% servers so that it can grow in size and transactional capacity to support
44% very large images. Start up the pixel cache server on one or more machines.
45% When you read or operate on an image and the local pixel cache resources are
46% exhausted, ImageMagick contacts one or more of these remote pixel servers to
47% store or retrieve pixels.
48%
49*/
50␌
51/*
52 Include declarations.
53*/
54#include "MagickCore/studio.h"
55#include "MagickCore/cache.h"
56#include "MagickCore/cache-private.h"
57#include "MagickCore/distribute-cache.h"
58#include "MagickCore/distribute-cache-private.h"
59#include "MagickCore/exception.h"
60#include "MagickCore/exception-private.h"
61#include "MagickCore/geometry.h"
62#include "MagickCore/image.h"
63#include "MagickCore/image-private.h"
64#include "MagickCore/list.h"
65#include "MagickCore/locale_.h"
66#include "MagickCore/memory_.h"
67#include "MagickCore/nt-base-private.h"
68#include "MagickCore/pixel.h"
69#include "MagickCore/policy.h"
70#include "MagickCore/random_.h"
71#include "MagickCore/registry.h"
72#include "MagickCore/splay-tree.h"
73#include "MagickCore/string_.h"
74#include "MagickCore/string-private.h"
75#include "MagickCore/utility-private.h"
76#include "MagickCore/version.h"
77#include "MagickCore/version-private.h"
78#define SOCKET_TYPE int
79#undef MAGICKCORE_HAVE_DISTRIBUTE_CACHE
80#if defined(MAGICKCORE_DPC_SUPPORT)
81#if defined(MAGICKCORE_HAVE_SOCKET) && defined(MAGICKCORE_THREAD_SUPPORT)
82#include <netinet/in.h>
83#include <netinet/tcp.h>
84#include <netdb.h>
85#include <sys/socket.h>
86#include <arpa/inet.h>
87#define CLOSE_SOCKET(socket) (void) close_utf8(socket)
88#define HANDLER_RETURN_TYPE void *
89#define HANDLER_RETURN_VALUE (void *) NULL
90#define SOCKET_TYPE int
91#define LENGTH_TYPE size_t
92#define MAGICKCORE_HAVE_DISTRIBUTE_CACHE 1
93#elif defined(_MSC_VER)
94#define CLOSE_SOCKET(socket) (void) closesocket(socket)
95#define HANDLER_RETURN_TYPE DWORD WINAPI
96#define HANDLER_RETURN_VALUE 0
97#define LENGTH_TYPE int
98#define MAGICKCORE_HAVE_DISTRIBUTE_CACHE 1
99#define MAGICKCORE_HAVE_WINSOCK2 1
100#endif
101#endif
102␌
103/*
104 Define declarations.
105*/
106#define DPCHostname "127.0.0.1"
107#define DPCMacLength 32
108#define DPCMaxClientWorkers 128
109#define DPCMaxUnauthenticatedClientWorkers 16
110#define DPCPendingConnections 10
111#define DPCPort 6668
112#define DPCScratchExtent 16384 /* bytes; send-side encrypt buffer */
113#define DPCSessionKeyLength 16
114#ifndef MSG_NOSIGNAL
115# define MSG_NOSIGNAL 0
116#endif
117␌
118/*
119 Typedef declarations.
120*/
121typedef struct
122{
123 uint32_t
124 state[8];
125
126 uint64_t
127 count;
128
129 unsigned char
130 buffer[64];
131} SHA256Hash;
132␌
133/*
134 Static declarations.
135*/
136#ifdef MAGICKCORE_HAVE_WINSOCK2
137static SemaphoreInfo
138 *winsock_semaphore = (SemaphoreInfo *) NULL;
139
140static WSADATA
141 *wsaData = (WSADATA*) NULL;
142#endif
143
144#if defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
145static SemaphoreInfo
146 *dpc_semaphore = (SemaphoreInfo *) NULL;
147
148static char
149 *dpc_shared_secret = (char *) NULL;
150
151static size_t
152 dpc_clients = 0,
153 dpc_unauthenticated_clients = 0;
154#endif
155␌
156/*
157%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
158% %
159% %
160% %
161+ A c q u i r e D i s t r i b u t e C a c h e I n f o %
162% %
163% %
164% %
165%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
166%
167% AcquireDistributeCacheInfo() allocates the DistributeCacheInfo structure.
168%
169% The format of the AcquireDistributeCacheInfo method is:
170%
171% DistributeCacheInfo *AcquireDistributeCacheInfo(ExceptionInfo *exception)
172%
173% A description of each parameter follows:
174%
175% o exception: return any errors or warnings in this structure.
176%
177*/
178
179#if !defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
180static inline MagickOffsetType dpc_receive(SOCKET_TYPE magick_unused(file),
181 const MagickSizeType magick_unused(length),
182 unsigned char *magick_restrict magick_unused(message))
183{
184 magick_unreferenced(file);
185 magick_unreferenced(length);
186 magick_unreferenced(message);
187 return(-1);
188}
189#else
190static void SetSocketNoDelay(SOCKET_TYPE file)
191{
192 int
193 one = 1;
194
195 /*
196 Disable Nagle.
197 */
198 (void) setsockopt(file,IPPROTO_TCP,TCP_NODELAY,(const char *) &one,
199 (socklen_t) sizeof(one));
200}
201
202static void SetSocketReceiveTimeout(SOCKET_TYPE file,double seconds)
203{
204 /*
205 Set a receive timeout.
206 */
207#if defined(MAGICKCORE_HAVE_WINSOCK2)
208 {
209 DWORD timeout = (DWORD) (seconds*1000.0);
210 (void) setsockopt(file,SOL_SOCKET,SO_RCVTIMEO,
211 (const char *) &timeout,sizeof(timeout));
212 }
213#else
214 {
215 struct timeval tv;
216 tv.tv_sec=(int) seconds;
217 tv.tv_usec=(int) ((seconds-(double) tv.tv_sec)*1000000.0);
218 (void) setsockopt(file,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv));
219 }
220#endif
221}
222
223static inline MagickOffsetType dpc_receive(SOCKET_TYPE file,
224 const MagickSizeType length,unsigned char *magick_restrict message)
225{
226 MagickOffsetType offset = 0;
227 while (offset < (MagickOffsetType) length)
228 {
229 MagickSizeType chunk = MagickMin(length-offset,(MagickSizeType)
230 MagickMaxBufferExtent);
231 ssize_t count = recv(file,(char *) message+offset,(LENGTH_TYPE) chunk,0);
232 if (count > 0)
233 offset+=(MagickOffsetType) count;
234 else
235 if (count == 0)
236 return(0);
237 else
238 {
239#ifdef MAGICKCORE_HAVE_WINSOCK2
240 int wsa_err = WSAGetLastError();
241 if ((wsa_err == WSAEINTR) || (wsa_err == WSAEWOULDBLOCK))
242 continue;
243 if (wsa_err == WSAECONNRESET)
244 return(-2);
245#else
246 if ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK))
247 continue;
248 if (errno == ECONNRESET)
249 return(-2);
250#endif
251 return(-1);
252 }
253 }
254 return(offset);
255}
256
257static inline MagickOffsetType dpc_receive_deadline(SOCKET_TYPE file,
258 MagickSizeType length,unsigned char *message,double deadline)
259{
260 /*
261 Enforce an absolute deadline for authentication and command reads.
262 */
263 MagickOffsetType offset = 0;
264 while (offset < (MagickOffsetType) length)
265 {
266 double
267 now = (double) time((time_t *) NULL),
268 remaining = deadline-now;
269
270 MagickSizeType
271 chunk;
272
273 ssize_t
274 count;
275
276 if (now >= deadline)
277 return(-1);
278 if (remaining < 0.001)
279 remaining=0.001;
280 SetSocketReceiveTimeout(file,remaining);
281 chunk=MagickMin(length-offset,(MagickSizeType) MagickMaxBufferExtent);
282 count=recv(file,(char *) message+offset,(LENGTH_TYPE) chunk,0);
283 if (count > 0)
284 offset+=(MagickOffsetType) count;
285 else
286 if (count == 0)
287 return(0);
288 else
289 {
290#ifdef MAGICKCORE_HAVE_WINSOCK2
291 int wsa_err = WSAGetLastError();
292 if ((wsa_err == WSAEINTR) || (wsa_err == WSAEWOULDBLOCK))
293 continue;
294 if (wsa_err == WSAECONNRESET)
295 return(-2);
296 return(-1);
297#else
298 if ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK))
299 continue;
300 if (errno == ECONNRESET)
301 return(-2);
302 return(-1);
303#endif
304 }
305 }
306 return(offset);
307}
308#endif
309
310#if defined(MAGICKCORE_HAVE_WINSOCK2)
311static void InitializeWinsock2(MagickBooleanType use_lock)
312{
313 if (use_lock != MagickFalse)
314 {
315 if (winsock_semaphore == (SemaphoreInfo *) NULL)
316 ActivateSemaphoreInfo(&winsock_semaphore);
317 LockSemaphoreInfo(winsock_semaphore);
318 }
319 if (wsaData == (WSADATA *) NULL)
320 {
321 wsaData=(WSADATA *) AcquireMagickMemory(sizeof(WSADATA));
322 if (WSAStartup(MAKEWORD(2,2),wsaData) != 0)
323 ThrowFatalException(CacheFatalError,"WSAStartup failed");
324 }
325 if (use_lock != MagickFalse)
326 UnlockSemaphoreInfo(winsock_semaphore);
327}
328#endif
329
330#if !defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
331static int ConnectPixelCacheServer(const char *magick_unused(hostname),
332 const int magick_unused(port),uint64_t *magick_unused(session_key),
333 ExceptionInfo *exception)
334{
335 magick_unreferenced(hostname);
336 magick_unreferenced(port);
337 magick_unreferenced(session_key);
338 (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError,
339 "DelegateLibrarySupportNotBuiltIn","distributed pixel cache");
340 return(MagickFalse);
341}
342#else
343static inline uint64_t ROTL(uint64_t x,int b)
344{
345 return((x << b) | (x >> (64-b)));
346}
347
348static inline uint64_t U8TO64_LE(const uint8_t *p)
349{
350 return(((uint64_t) p[0] << 0) | ((uint64_t) p[1] << 8) |
351 ((uint64_t) p[2] << 16) | ((uint64_t) p[3] << 24) |
352 ((uint64_t) p[4] << 32) | ((uint64_t) p[5] << 40) |
353 ((uint64_t) p[6] << 48) | ((uint64_t) p[7] << 56));
354}
355
356static inline uint64_t SIPHash24(const uint8_t key[16],const uint8_t *message,
357 const size_t length)
358{
359 const uint8_t
360 *end = message+length-(length % 8);
361
362 size_t
363 i;
364
365 uint64_t
366 b = ((uint64_t) length) << 56,
367 k0 = U8TO64_LE(key),
368 k1 = U8TO64_LE(key+8),
369 m,
370 v0 = 0x736f6d6570736575ULL ^ k0,
371 v1 = 0x646f72616e646f6dULL ^ k1,
372 v2 = 0x6c7967656e657261ULL ^ k0,
373 v3 = 0x7465646279746573ULL ^ k1;
374
375 for ( ; message != end; message+=8)
376 {
377 m=U8TO64_LE(message);
378 v3^=m;
379 for (i=0; i < 2; i++)
380 {
381 v0+=v1; v1=ROTL(v1,13); v1^=v0; v0=ROTL(v0,32);
382 v2+=v3; v3=ROTL(v3,16); v3^=v2;
383 v0+=v3; v3=ROTL(v3,21); v3^=v0;
384 v2+=v1; v1=ROTL(v1,17); v1^=v2; v2=ROTL(v2,32);
385 }
386 v0^=m;
387 }
388 switch (length & 0x07)
389 {
390 case 7: b|=((uint64_t) message[6]) << 48; magick_fallthrough;
391 case 6: b|=((uint64_t) message[5]) << 40; magick_fallthrough;
392 case 5: b|=((uint64_t) message[4]) << 32; magick_fallthrough;
393 case 4: b|=((uint64_t) message[3]) << 24; magick_fallthrough;
394 case 3: b|=((uint64_t) message[2]) << 16; magick_fallthrough;
395 case 2: b|=((uint64_t) message[1]) << 8; magick_fallthrough;
396 case 1: b|=((uint64_t) message[0]); magick_fallthrough;
397 default: break;
398 }
399 v3^=b;
400 for (i=0; i < 2; i++)
401 {
402 v0+=v1; v1=ROTL(v1,13); v1^=v0; v0=ROTL(v0,32);
403 v2+=v3; v3=ROTL(v3,16); v3^=v2;
404 v0+=v3; v3=ROTL(v3,21); v3^=v0;
405 v2+=v1; v1=ROTL(v1,17); v1^=v2; v2=ROTL(v2,32);
406 }
407 v0^=b;
408 v2^=0xff;
409 for (i=0; i < 4; i++)
410 {
411 v0+=v1; v1=ROTL(v1,13); v1^=v0; v0=ROTL(v0,32);
412 v2+=v3; v3=ROTL(v3,16); v3^=v2;
413 v0+=v3; v3=ROTL(v3,21); v3^=v0;
414 v2+=v1; v1=ROTL(v1,17); v1^=v2; v2=ROTL(v2,32);
415 }
416 return(v0^v1^v2^v3);
417}
418
419static inline void DeriveSIPKeyFromSecret(const char *shared_secret,
420 uint8_t key[16])
421{
422 size_t
423 i,
424 length;
425
426 uint64_t
427 k0 = 0x0706050403020100ULL,
428 k1 = 0x0f0e0d0c0b0a0908ULL;
429
430 length=strlen(shared_secret);
431 for (i=0; i < length; i++)
432 {
433 uint8_t
434 b = (uint8_t) shared_secret[i];
435
436 k0^=b;
437 k0*=0x100000001b3ULL;
438 k1^=(uint64_t) b << ((i & 7)*8);
439 k1=(k1 << 5) | (k1 >> (64-5));
440 }
441 (void) memcpy(key,&k0,8);
442 (void) memcpy(key+8,&k1,8);
443}
444
445static inline uint64_t GenerateSessionKey(const char *shared_secret,
446 const unsigned char *nonce,size_t length)
447{
448 uint8_t
449 key[16];
450
451 DeriveSIPKeyFromSecret(shared_secret,key);
452 return(SIPHash24(key,nonce,length));
453}
454
455static int ConnectPixelCacheServer(const char *hostname,const int port,
456 uint64_t *session_key,ExceptionInfo *exception)
457{
458#if defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
459 char
460 *message,
461 service[MagickPathExtent],
462 *shared_secret;
463
464 int
465 status;
466
467 SOCKET_TYPE
468 client_socket;
469
470 ssize_t
471 count;
472
473 struct addrinfo
474 hints,
475 *result;
476
477 unsigned char
478 nonce[DPCSessionKeyLength];
479
480 /*
481 Connect to distributed pixel cache server and get session key.
482 */
483 *session_key=0;
484#if defined(MAGICKCORE_HAVE_WINSOCK2)
485 InitializeWinsock2(MagickTrue);
486#endif
487 (void) memset(&hints,0,sizeof(hints));
488 hints.ai_family=AF_INET;
489 hints.ai_socktype=SOCK_STREAM;
490 hints.ai_flags=AI_PASSIVE;
491 (void) FormatLocaleString(service,MagickPathExtent,"%d",port);
492 status=getaddrinfo(hostname,service,&hints,&result);
493 if (status != 0)
494 {
495 (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
496 "DistributedPixelCache","'%s': %s",hostname,gai_strerror(status));
497 return(-1);
498 }
499 client_socket=(SOCKET_TYPE) socket(result->ai_family,result->ai_socktype,
500 result->ai_protocol);
501 if (client_socket == -1)
502 {
503 freeaddrinfo(result);
504 message=GetExceptionMessage(errno);
505 (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
506 "DistributedPixelCache","'%s': %s",hostname,message);
507 message=DestroyString(message);
508 return(-1);
509 }
510 status=connect(client_socket,result->ai_addr,(socklen_t) result->ai_addrlen);
511 freeaddrinfo(result);
512 if (status == -1)
513 {
514 CLOSE_SOCKET(client_socket);
515 message=GetExceptionMessage(errno);
516 (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
517 "DistributedPixelCache","'%s': %s",hostname,message);
518 message=DestroyString(message);
519 return(-1);
520 }
521 SetSocketNoDelay(client_socket);
522 /*
523 Receive server nonce.
524 */
525 count=recv(client_socket,(char *) nonce,sizeof(nonce),0);
526 if (count != (ssize_t) sizeof(nonce))
527 {
528 CLOSE_SOCKET(client_socket);
529 message=GetExceptionMessage(errno);
530 (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
531 "DistributedPixelCache","'%s': %s",hostname,message);
532 message=DestroyString(message);
533 return(-1);
534 }
535 /*
536 Compute keyed hash(shared_secret,nonce).
537 */
538 shared_secret=GetPolicyValue("cache:shared-secret");
539 if (shared_secret == (const char *) NULL)
540 {
541 CLOSE_SOCKET(client_socket);
542 (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
543 "DistributedPixelCache","'%s': shared secret required",hostname);
544 return(-1);
545 }
546 *session_key=GenerateSessionKey(shared_secret,nonce,sizeof(nonce));
547 shared_secret=DestroyString(shared_secret);
548 /*
549 Send keyed hash back to client.
550 */
551 count=send(client_socket,(char *) session_key,sizeof(*session_key),
552 MSG_NOSIGNAL);
553 if (count != (ssize_t) sizeof(*session_key))
554 {
555 CLOSE_SOCKET(client_socket);
556 (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
557 "DistributedPixelCache","'%s': authentication failed",hostname);
558 return(-1);
559 }
560 return((int) client_socket);
561#else
562 (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError,
563 "DelegateLibrarySupportNotBuiltIn","distributed pixel cache");
564 return(-1);
565#endif
566}
567#endif
568
569static char *GetHostname(int *port,ExceptionInfo *exception)
570{
571 char
572 *host,
573 *hosts,
574 **hostlist;
575
576 int
577 argc;
578
579 ssize_t
580 i;
581
582 static size_t
583 id = 0;
584
585 /*
586 Parse host list (e.g. 192.168.100.1:6668,192.168.100.2:6668).
587 */
588 hosts=(char *) GetImageRegistry(StringRegistryType,"cache:hosts",exception);
589 if (hosts == (char *) NULL)
590 {
591 *port=DPCPort;
592 return(AcquireString(DPCHostname));
593 }
594 (void) SubstituteString(&hosts,","," ");
595 hostlist=StringToArgv(hosts,&argc);
596 hosts=DestroyString(hosts);
597 if ((hostlist == (char **) NULL) || ((argc-1) == 0))
598 {
599 *port=DPCPort;
600 return(AcquireString(DPCHostname));
601 }
602 {
603 size_t host_count = (size_t) argc-1;
604 size_t index = (id++ % host_count)+1;
605 hosts=AcquireString(hostlist[index]);
606 }
607 for (i=0; i < (ssize_t) argc; i++)
608 hostlist[i]=DestroyString(hostlist[i]);
609 hostlist=(char **) RelinquishMagickMemory(hostlist);
610 (void) SubstituteString(&hosts,":"," ");
611 hostlist=StringToArgv(hosts,&argc);
612 if (hostlist == (char **) NULL)
613 {
614 *port=DPCPort;
615 return(AcquireString(DPCHostname));
616 }
617 host=AcquireString(hostlist[1]);
618 if (hostlist[2] == (char *) NULL)
619 *port=DPCPort;
620 else
621 *port=(int) StringToLong(hostlist[2]);
622 for (i=0; i < (ssize_t) argc; i++)
623 hostlist[i]=DestroyString(hostlist[i]);
624 hostlist=(char **) RelinquishMagickMemory(hostlist);
625 return(host);
626}
627
628MagickPrivate DistributeCacheInfo *AcquireDistributeCacheInfo(
629 ExceptionInfo *exception)
630{
631 char
632 *hostname;
633
634 DistributeCacheInfo
635 *server_info;
636
637 uint64_t
638 session_key;
639
640 /*
641 Connect to the distributed pixel cache server.
642 */
643 server_info=(DistributeCacheInfo *) AcquireCriticalMemory(
644 sizeof(*server_info));
645 (void) memset(server_info,0,sizeof(*server_info));
646 server_info->signature=MagickCoreSignature;
647 server_info->port=0;
648 hostname=GetHostname(&server_info->port,exception);
649 session_key=0;
650 server_info->file=ConnectPixelCacheServer(hostname,server_info->port,
651 &session_key,exception);
652 if (server_info->file == -1)
653 server_info=DestroyDistributeCacheInfo(server_info);
654 else
655 {
656 server_info->session_key=session_key;
657 (void) CopyMagickString(server_info->hostname,hostname,MagickPathExtent);
658 server_info->debug=(GetLogEventMask() & CacheEvent) != 0 ? MagickTrue :
659 MagickFalse;
660 }
661 hostname=DestroyString(hostname);
662 return(server_info);
663}
664␌
665/*
666%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
667% %
668% %
669% %
670+ C o m p u t e H M A C S H A 2 5 6 M a c %
671% %
672% %
673% %
674%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
675%
676% ComputeHMACSHA256Mac() opens a pixel cache on a remote server.
677%
678% The format of the ComputeHMACSHA256Mac method is:
679%
680% int ComputeHMACSHA256Mac(const void *key,size_t key_length,
681% const void *message,size_t message_length,unsigned char *mac,
682% size_t mac_length)
683%
684% A description of each parameter follows:
685%
686% o key: the HMAC key.
687%
688% o key_length: HMAC key length in bytes.
689%
690% o message: the message.
691%
692% o message_length: the message length in bytes.
693%
694% o mac: the mac is computed and returned in this buffer.
695%
696% o mac_length: the mac length in bytes . mac must be at least this length.
697%
698*/
699
700static void InitializeSHA256Hash(SHA256Hash *sha256_hash)
701{
702 sha256_hash->count=0;
703 sha256_hash->state[0]=0x6a09e667;
704 sha256_hash->state[1]=0xbb67ae85;
705 sha256_hash->state[2]=0x3c6ef372;
706 sha256_hash->state[3]=0xa54ff53a;
707 sha256_hash->state[4]=0x510e527f;
708 sha256_hash->state[5]=0x9b05688c;
709 sha256_hash->state[6]=0x1f83d9ab;
710 sha256_hash->state[7]=0x5be0cd19;
711}
712
713static void TransformSHA256Hash(SHA256Hash *sha256_hash,
714 const unsigned char data[])
715{
716#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
717#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))
718#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
719#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
720#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
721#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
722#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))
723
724 static const uint32_t K[64] =
725 {
726 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
727 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
728 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
729 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
730 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
731 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
732 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
733 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
734 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
735 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
736 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
737 };
738
739 uint32_t
740 a,
741 b,
742 c,
743 d,
744 e,
745 f,
746 g,
747 h,
748 i,
749 j,
750 m[64];
751
752 j=0;
753 for (i=0; i < 16; i++, j+=4)
754 m[i]=((uint32_t) data[j] << 24) | ((uint32_t) data[j+1] << 16) |
755 ((uint32_t) data[j+2] << 8) | ((uint32_t) data[j+3]);
756 for ( ; i < 64; i++)
757 m[i]=SIG1(m[i-2])+m[i-7]+SIG0(m[i-15])+m[i-16];
758 a=sha256_hash->state[0];
759 b=sha256_hash->state[1];
760 c=sha256_hash->state[2];
761 d=sha256_hash->state[3];
762 e=sha256_hash->state[4];
763 f=sha256_hash->state[5];
764 g=sha256_hash->state[6];
765 h=sha256_hash->state[7];
766 for (i=0; i < 64; i++)
767 {
768 uint32_t
769 alpha = h+EP1(e)+CH(e,f,g)+K[i]+m[i],
770 beta = EP0(a)+MAJ(a,b,c);
771
772 h=g;
773 g=f;
774 f=e;
775 e=d+alpha;
776 d=c;
777 c=b;
778 b=a;
779 a=alpha+beta;
780 }
781 sha256_hash->state[0]+=a;
782 sha256_hash->state[1]+=b;
783 sha256_hash->state[2]+=c;
784 sha256_hash->state[3]+=d;
785 sha256_hash->state[4]+=e;
786 sha256_hash->state[5]+=f;
787 sha256_hash->state[6]+=g;
788 sha256_hash->state[7]+=h;
789}
790
791static void UpdateSHA256Hash(SHA256Hash *sha256_hash,const unsigned char *data,
792 const size_t data_length)
793{
794 size_t
795 i,
796 index = (size_t) ((sha256_hash->count/8) % 64);
797
798 sha256_hash->count+=(uint64_t) data_length*8;
799 for (i=0; i < data_length; i++)
800 {
801 sha256_hash->buffer[index++]=data[i];
802 if (index == 64)
803 {
804 TransformSHA256Hash(sha256_hash,sha256_hash->buffer);
805 index=0;
806 }
807 }
808}
809
810static void FinalizeSHA256Hash(SHA256Hash *sha256_hash,unsigned char hash[32])
811{
812 size_t
813 i,
814 index = (size_t) ((sha256_hash->count/8) % 64),
815 pad_length = (index < 56) ? (56-index) : (120-index);
816
817 uint64_t
818 bit_count = sha256_hash->count; /* message length before padding */
819
820 unsigned char
821 pad[64];
822
823 pad[0]=0x80;
824 (void) memset(pad+1,0,pad_length-1);
825 UpdateSHA256Hash(sha256_hash,pad,pad_length);
826 for (i=0; i < 8; i++)
827 pad[i]=(unsigned char) (bit_count >> ((7-i)*8));
828 UpdateSHA256Hash(sha256_hash, pad, 8);
829 for (i=0; i < 32; i++)
830 hash[i]=(unsigned char) (sha256_hash->state[i/4] >> ((3-(i % 4))*8));
831}
832
833static void ComputeSHA256Hash(const unsigned char *data,size_t length,
834 unsigned char hash[32])
835{
837 sha256_hash;
838
839 /*
840 Hash a buffer in one shot.
841 */
842 InitializeSHA256Hash(&sha256_hash);
843 UpdateSHA256Hash(&sha256_hash,data,length);
844 FinalizeSHA256Hash(&sha256_hash,hash);
845}
846
847static int ComputeHMACSHA256Mac(const void *key,size_t key_length,
848 const void *message,size_t message_length,unsigned char *mac,
849 size_t mac_length)
850{
852 sha256_hash;
853
854 size_t
855 i;
856
857 unsigned char
858 full_hash[32],
859 inner_hash[32],
860 inner_pad[64],
861 k_prime[64]={0},
862 outer_pad[64];
863
864 /*
865 If key is longer than 64 bytes, hash it down first.
866 */
867 if ((mac == (unsigned char *) NULL) || (mac_length == 0))
868 return(-1);
869 if (((key == (const void *) NULL) && (key_length != 0)) ||
870 ((message == (const void *) NULL) && (message_length != 0)))
871 return(-1);
872 if (key_length > 64)
873 ComputeSHA256Hash((unsigned char *) key,key_length,k_prime);
874 else
875 (void) memcpy(k_prime,key,key_length);
876 /*
877 Prepare inner pad and outer pad masks.
878 */
879 for (i=0; i < 64; i++)
880 {
881 inner_pad[i]=k_prime[i] ^ 0x36;
882 outer_pad[i]=k_prime[i] ^ 0x5c;
883 }
884 /*
885 Inner hash: SHA256(inner pad || message)
886 */
887 InitializeSHA256Hash(&sha256_hash);
888 UpdateSHA256Hash(&sha256_hash,inner_pad,64);
889 UpdateSHA256Hash(&sha256_hash,(unsigned char *) message,message_length);
890 FinalizeSHA256Hash(&sha256_hash,inner_hash);
891 /*
892 Outer hash: SHA256(outer pad || inner hash)
893 */
894 InitializeSHA256Hash(&sha256_hash);
895 UpdateSHA256Hash(&sha256_hash,outer_pad,64);
896 UpdateSHA256Hash(&sha256_hash,inner_hash,32);
897 FinalizeSHA256Hash(&sha256_hash,full_hash);
898 /*
899 Truncate or copy to destination buffer based on requested mac length.
900 */
901 (void) memcpy(mac,full_hash,(mac_length < 32) ? mac_length : 32);
902 return(0);
903}
904␌
905/*
906%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
907% %
908% %
909% %
910+ D e s t r o y D i s t r i b u t e C a c h e I n f o %
911% %
912% %
913% %
914%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
915%
916% DestroyDistributeCacheInfo() deallocates memory associated with an
917% DistributeCacheInfo structure.
918%
919% The format of the DestroyDistributeCacheInfo method is:
920%
921% DistributeCacheInfo *DestroyDistributeCacheInfo(
922% DistributeCacheInfo *server_info)
923%
924% A description of each parameter follows:
925%
926% o server_info: the distributed cache info.
927%
928*/
929MagickPrivate DistributeCacheInfo *DestroyDistributeCacheInfo(
930 DistributeCacheInfo *server_info)
931{
932 assert(server_info != (DistributeCacheInfo *) NULL);
933 assert(server_info->signature == MagickCoreSignature);
934#if defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
935 if (server_info->file >= 0)
936 CLOSE_SOCKET(server_info->file);
937#endif
938 server_info->signature=(~MagickCoreSignature);
939 server_info=(DistributeCacheInfo *) RelinquishMagickMemory(server_info);
940 return(server_info);
941}
942␌
943/*
944%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
945% %
946% %
947% %
948+ D i s t r i b u t e P i x e l C a c h e S e r v e r %
949% %
950% %
951% %
952%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
953%
954% DistributePixelCacheServer() waits on the specified port for commands to
955% create, read, update, or destroy a pixel cache.
956%
957% The format of the DistributePixelCacheServer() method is:
958%
959% void DistributePixelCacheServer(const int port)
960%
961% A description of each parameter follows:
962%
963% o port: connect the distributed pixel cache at this port.
964%
965% o exception: return any errors or warnings in this structure.
966%
967*/
968
969#if !defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
970static inline MagickOffsetType dpc_send(SOCKET_TYPE magick_unused(file),
971 const MagickSizeType magick_unused(length),
972 const void *magick_restrict magick_unused(message))
973{
974 magick_unreferenced(file);
975 magick_unreferenced(length);
976 magick_unreferenced(message);
977 return(-1);
978}
979#else
980static inline MagickOffsetType dpc_send(SOCKET_TYPE file,
981 const MagickSizeType length,const void *magick_restrict message)
982{
983 MagickOffsetType
984 i;
985
986 ssize_t
987 count;
988
989 /*
990 Ensure a complete message is sent.
991 */
992 count=0;
993 for (i=0; i < (MagickOffsetType) length; i+=count)
994 {
995 count=(ssize_t) send(file,(const char *) message+i,(LENGTH_TYPE) MagickMin(
996 length-(MagickSizeType) i,(MagickSizeType) MagickMaxBufferExtent),
997 MSG_NOSIGNAL);
998 if (count <= 0)
999 {
1000 count=0;
1001 if (errno != EINTR)
1002 break;
1003 }
1004 }
1005 return(i);
1006}
1007#endif
1008
1009static const char *GetDPCSharedSecret(void)
1010{
1011#if defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
1012 /*
1013 The server loads the secret at start-up; a client loads it on first use.
1014 */
1015 if (dpc_shared_secret == (char *) NULL)
1016 {
1017 if (dpc_semaphore == (SemaphoreInfo *) NULL)
1018 ActivateSemaphoreInfo(&dpc_semaphore);
1019 LockSemaphoreInfo(dpc_semaphore);
1020 if (dpc_shared_secret == (char *) NULL)
1021 dpc_shared_secret=GetPolicyValue("cache:shared-secret");
1022 UnlockSemaphoreInfo(dpc_semaphore);
1023 }
1024 return(dpc_shared_secret);
1025#else
1026 return((const char *) NULL);
1027#endif
1028}
1029
1030static int DeriveDPCKey(const uint64_t session_key,const char label,
1031 unsigned char key[DPCMacLength])
1032{
1033 const char
1034 *shared_secret;
1035
1036 unsigned char
1037 info[sizeof(session_key)+1];
1038
1039 /*
1040 key = HMAC-SHA-256(shared secret, session key || label). The session key
1041 travels in the clear, so the shared secret is what keeps this private.
1042 */
1043 shared_secret=GetDPCSharedSecret();
1044 if (shared_secret == (const char *) NULL)
1045 return(-1);
1046 (void) memcpy(info,&session_key,sizeof(session_key));
1047 info[sizeof(session_key)]=(unsigned char) label;
1048 return(ComputeHMACSHA256Mac(shared_secret,strlen(shared_secret),info,
1049 sizeof(info),key,DPCMacLength));
1050}
1051
1052static inline void WipeDPCKey(unsigned char *key,const size_t length)
1053{
1054 volatile unsigned char
1055 *p = key;
1056
1057 size_t
1058 i;
1059
1060 for (i=0; i < length; i++)
1061 p[i]=0;
1062}
1063
1064static void DPCKeystream(const unsigned char *stream_key,
1065 const unsigned char *mac,const MagickSizeType offset,unsigned char *data,
1066 const size_t length)
1067{
1069 block_hash,
1070 keyed_hash;
1071
1072 size_t
1073 i,
1074 k;
1075
1076 uint64_t
1077 block;
1078
1079 unsigned char
1080 counter[8],
1081 keystream[32];
1082
1083 /*
1084 XOR data with keystream block n = SHA-256(stream key || mac || n).
1085 */
1086 InitializeSHA256Hash(&keyed_hash);
1087 UpdateSHA256Hash(&keyed_hash,stream_key,DPCMacLength);
1088 UpdateSHA256Hash(&keyed_hash,mac,DPCMacLength);
1089 (void) memset(keystream,0,sizeof(keystream));
1090 for (i=0; i < length; i++)
1091 {
1092 size_t
1093 j = (size_t) ((offset+i) & 31);
1094
1095 if ((i == 0) || (j == 0))
1096 {
1097 block=(uint64_t) ((offset+i) >> 5);
1098 for (k=0; k < sizeof(counter); k++)
1099 counter[k]=(unsigned char) (block >> (8*k));
1100 block_hash=keyed_hash;
1101 UpdateSHA256Hash(&block_hash,counter,sizeof(counter));
1102 FinalizeSHA256Hash(&block_hash,keystream);
1103 }
1104 data[i]^=keystream[j];
1105 }
1106 WipeDPCKey(keystream,sizeof(keystream));
1107 WipeDPCKey((unsigned char *) &block_hash,sizeof(block_hash));
1108 WipeDPCKey((unsigned char *) &keyed_hash,sizeof(keyed_hash));
1109}
1110
1111static inline int mac_compare(const unsigned char *a,const unsigned char *b,
1112 const size_t length)
1113{
1114 size_t
1115 i;
1116
1117 volatile unsigned char
1118 difference = 0;
1119
1120 /*
1121 Compare in time independent of where (or whether) the buffers differ.
1122 */
1123 for (i=0; i < length; i++)
1124 difference|=(unsigned char) (a[i] ^ b[i]);
1125 return(difference == 0 ? 0 : -1);
1126}
1127
1128static inline MagickOffsetType dpc_send_mac(SOCKET_TYPE file,
1129 const MagickSizeType length,const void *magick_restrict message,
1130 uint64_t session_key)
1131{
1132 const unsigned char
1133 *p = (const unsigned char *) message;
1134
1135 MagickOffsetType
1136 status;
1137
1138 MagickSizeType
1139 offset;
1140
1141 unsigned char
1142 mac[DPCMacLength],
1143 mac_key[DPCMacLength],
1144 scratch[DPCScratchExtent],
1145 stream_key[DPCMacLength];
1146
1147 /*
1148 MAC the plaintext, then send MAC || (plaintext XOR keystream).
1149 */
1150 if (length > (MagickSizeType) MAGICK_SSIZE_MAX)
1151 return(-1);
1152 if ((DeriveDPCKey(session_key,'m',mac_key) != 0) ||
1153 (DeriveDPCKey(session_key,'e',stream_key) != 0) ||
1154 (ComputeHMACSHA256Mac(mac_key,sizeof(mac_key),message,(size_t) length,mac,sizeof(mac)) != 0))
1155 {
1156 WipeDPCKey(mac_key,sizeof(mac_key));
1157 WipeDPCKey(stream_key,sizeof(stream_key));
1158 return(-1); /* key derivation or HMAC computation failed */
1159 }
1160 WipeDPCKey(mac_key,sizeof(mac_key));
1161 status=dpc_send(file,sizeof(mac),mac);
1162 if (status != (MagickOffsetType) sizeof(mac))
1163 {
1164 WipeDPCKey(stream_key,sizeof(stream_key));
1165 return(-1);
1166 }
1167 /*
1168 Encrypt into a scratch buffer: the caller's buffer may be the live cache.
1169 */
1170 for (offset=0; offset < length; )
1171 {
1172 size_t
1173 chunk = (size_t) MagickMin(length-offset,(MagickSizeType)
1174 sizeof(scratch));
1175
1176 (void) memcpy(scratch,p+offset,chunk);
1177 DPCKeystream(stream_key,mac,offset,scratch,chunk);
1178 status=dpc_send(file,(MagickSizeType) chunk,scratch);
1179 if (status != (MagickOffsetType) chunk)
1180 break;
1181 offset+=(MagickSizeType) chunk;
1182 }
1183 WipeDPCKey(stream_key,sizeof(stream_key));
1184 WipeDPCKey(scratch,sizeof(scratch));
1185 if (offset != length)
1186 return(-1);
1187 return((MagickOffsetType) length);
1188}
1189
1190static inline MagickOffsetType dpc_receive_mac(SOCKET_TYPE file,
1191 const MagickSizeType length,unsigned char *magick_restrict message,
1192 uint64_t session_key)
1193{
1194 MagickOffsetType
1195 count;
1196
1197 unsigned char
1198 expected_mac[DPCMacLength],
1199 mac_key[DPCMacLength],
1200 received_mac[DPCMacLength],
1201 stream_key[DPCMacLength];
1202
1203 int
1204 status;
1205
1206 /*
1207 Read MAC || ciphertext, decrypt in place, then verify the MAC.
1208 */
1209 if (length > (MagickSizeType) MAGICK_SSIZE_MAX)
1210 return(-1);
1211 count=dpc_receive(file,sizeof(received_mac),received_mac);
1212 if (count != (MagickOffsetType) sizeof(received_mac))
1213 return(-1);
1214 count=dpc_receive(file,length,message);
1215 if (count != (MagickOffsetType) length)
1216 return(count);
1217 status=DeriveDPCKey(session_key,'e',stream_key);
1218 if (status == 0)
1219 {
1220 DPCKeystream(stream_key,received_mac,0,message,(size_t) length);
1221 status=DeriveDPCKey(session_key,'m',mac_key);
1222 }
1223 if (status == 0)
1224 status=ComputeHMACSHA256Mac(mac_key,sizeof(mac_key),message,
1225 (size_t) length,expected_mac,sizeof(expected_mac));
1226 WipeDPCKey(mac_key,sizeof(mac_key));
1227 WipeDPCKey(stream_key,sizeof(stream_key));
1228 if (status != 0)
1229 return(-1); /* key derivation or HMAC computation failed */
1230 if (mac_compare(received_mac,expected_mac,sizeof(expected_mac)) != 0)
1231 return(-1); /* HMAC verification failed */
1232 return(count);
1233}
1234
1235#if !defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
1236MagickExport void DistributePixelCacheServer(const int magick_unused(port),
1237 ExceptionInfo *magick_unused(exception))
1238{
1239 magick_unreferenced(port);
1240 magick_unreferenced(exception);
1241 ThrowFatalException(MissingDelegateError,"DelegateLibrarySupportNotBuiltIn");
1242}
1243#else
1244static MagickBooleanType DestroyDistributeCache(SplayTreeInfo *registry,
1245 const uint64_t session_key)
1246{
1247 MagickAddressType
1248 key = (MagickAddressType) session_key;
1249
1250 /*
1251 Destroy distributed pixel cache.
1252 */
1253 return(DeleteNodeFromSplayTree(registry,(const void *) key));
1254}
1255
1256static MagickBooleanType OpenDistributeCache(SplayTreeInfo *registry,
1257 SOCKET_TYPE file,const uint64_t session_key,ExceptionInfo *exception)
1258{
1259 Image
1260 *image;
1261
1262 MagickAddressType
1263 key = (MagickAddressType) session_key;
1264
1265 MagickBooleanType
1266 status;
1267
1268 MagickOffsetType
1269 count;
1270
1271 MagickSizeType
1272 length;
1273
1274 unsigned char
1275 message[MagickPathExtent],
1276 *p;
1277
1278 /*
1279 Open distributed pixel cache.
1280 */
1281 image=AcquireImage((ImageInfo *) NULL,exception);
1282 if (image == (Image *) NULL)
1283 return(MagickFalse);
1284 length=sizeof(image->storage_class)+sizeof(image->colorspace)+
1285 sizeof(image->alpha_trait)+sizeof(image->channels)+sizeof(image->columns)+
1286 sizeof(image->rows)+sizeof(image->number_channels)+MaxPixelChannels*
1287 sizeof(*image->channel_map)+sizeof(image->metacontent_extent);
1288 count=dpc_receive(file,length,message);
1289 if (count != (MagickOffsetType) length)
1290 {
1291 image=DestroyImage(image);
1292 return(MagickFalse);
1293 }
1294 /*
1295 Deserialize the image attributes.
1296 */
1297 p=message;
1298 (void) memcpy(&image->storage_class,p,sizeof(image->storage_class));
1299 p+=(ptrdiff_t) sizeof(image->storage_class);
1300 (void) memcpy(&image->colorspace,p,sizeof(image->colorspace));
1301 p+=(ptrdiff_t) sizeof(image->colorspace);
1302 (void) memcpy(&image->alpha_trait,p,sizeof(image->alpha_trait));
1303 p+=(ptrdiff_t) sizeof(image->alpha_trait);
1304 (void) memcpy(&image->channels,p,sizeof(image->channels));
1305 p+=(ptrdiff_t) sizeof(image->channels);
1306 (void) memcpy(&image->columns,p,sizeof(image->columns));
1307 p+=(ptrdiff_t) sizeof(image->columns);
1308 (void) memcpy(&image->rows,p,sizeof(image->rows));
1309 p+=(ptrdiff_t) sizeof(image->rows);
1310 (void) memcpy(&image->number_channels,p,sizeof(image->number_channels));
1311 p+=(ptrdiff_t) sizeof(image->number_channels);
1312 (void) memcpy(image->channel_map,p,MaxPixelChannels*
1313 sizeof(*image->channel_map));
1314 p+=(ptrdiff_t) MaxPixelChannels*sizeof(*image->channel_map);
1315 (void) memcpy(&image->metacontent_extent,p,sizeof(image->metacontent_extent));
1316 p+=(ptrdiff_t) sizeof(image->metacontent_extent);
1317 if (SyncImagePixelCache(image,exception) == MagickFalse)
1318 {
1319 image=DestroyImage(image);
1320 return(MagickFalse);
1321 }
1322 status=AddValueToSplayTree(registry,(const void *) key,image);
1323 if (status == MagickFalse)
1324 {
1325 image=DestroyImage(image);
1326 return(MagickFalse);
1327 }
1328 return(status);
1329}
1330
1331static inline MagickBooleanType ValidateDistributedPixelCache(
1332 const RectangleInfo *region,const size_t per_pixel,
1333 const MagickSizeType length)
1334{
1335 size_t
1336 extent = 0,
1337 pixels = 0;
1338
1339 if (HeapOverflowSanityCheckGetSize(region->width,region->height,&pixels) != MagickFalse)
1340 return(MagickFalse);
1341 if (HeapOverflowSanityCheckGetSize(pixels,per_pixel,&extent) != MagickFalse)
1342 return(MagickFalse);
1343 if (length > (MagickSizeType) extent)
1344 return(MagickFalse);
1345 return(MagickTrue);
1346}
1347
1348static MagickBooleanType ReadDistributeCacheMetacontent(SplayTreeInfo *registry,
1349 SOCKET_TYPE file,const uint64_t session_key,ExceptionInfo *exception)
1350{
1351 const Quantum
1352 *p;
1353
1354 const unsigned char
1355 *metacontent;
1356
1357 Image
1358 *image;
1359
1360 MagickAddressType
1361 key = (MagickAddressType) session_key;
1362
1363 MagickOffsetType
1364 count;
1365
1366 MagickSizeType
1367 length;
1368
1369 RectangleInfo
1370 region;
1371
1372 size_t
1373 per_pixel;
1374
1375 unsigned char
1376 message[MagickPathExtent],
1377 *q;
1378
1379 /*
1380 Read distributed pixel cache metacontent.
1381 */
1382 image=(Image *) GetValueFromSplayTree(registry,(const void *) key);
1383 if (image == (Image *) NULL)
1384 return(MagickFalse);
1385 length=sizeof(region.width)+sizeof(region.height)+sizeof(region.x)+
1386 sizeof(region.y)+sizeof(length);
1387 count=dpc_receive(file,length,message);
1388 if (count != (MagickOffsetType) length)
1389 return(MagickFalse);
1390 q=message;
1391 (void) memcpy(&region.width,q,sizeof(region.width));
1392 q+=(ptrdiff_t) sizeof(region.width);
1393 (void) memcpy(&region.height,q,sizeof(region.height));
1394 q+=(ptrdiff_t) sizeof(region.height);
1395 (void) memcpy(&region.x,q,sizeof(region.x));
1396 q+=(ptrdiff_t) sizeof(region.x);
1397 (void) memcpy(&region.y,q,sizeof(region.y));
1398 q+=(ptrdiff_t) sizeof(region.y);
1399 (void) memcpy(&length,q,sizeof(length));
1400 q+=(ptrdiff_t) sizeof(length);
1401 per_pixel=image->number_meta_channels*sizeof(Quantum);
1402 if (ValidateDistributedPixelCache(&region,per_pixel,length) == MagickFalse)
1403 return(MagickFalse);
1404 p=GetVirtualPixels(image,region.x,region.y,region.width,region.height,
1405 exception);
1406 if (p == (const Quantum *) NULL)
1407 return(MagickFalse);
1408 metacontent=(const unsigned char *) GetVirtualMetacontent(image);
1409 count=dpc_send_mac(file,length,metacontent,session_key);
1410 if (count != (MagickOffsetType) length)
1411 return(MagickFalse);
1412 return(MagickTrue);
1413}
1414
1415static MagickBooleanType ReadDistributeCachePixels(SplayTreeInfo *registry,
1416 SOCKET_TYPE file,const uint64_t session_key,ExceptionInfo *exception)
1417{
1418 const Quantum
1419 *p;
1420
1421 Image
1422 *image;
1423
1424 MagickAddressType
1425 key = (MagickAddressType) session_key;
1426
1427 MagickOffsetType
1428 count;
1429
1430 MagickSizeType
1431 length;
1432
1433 RectangleInfo
1434 region;
1435
1436 size_t
1437 per_pixel;
1438
1439 unsigned char
1440 message[MagickPathExtent],
1441 *q;
1442
1443 /*
1444 Read distributed pixel cache pixels.
1445 */
1446 image=(Image *) GetValueFromSplayTree(registry,(const void *) key);
1447 if (image == (Image *) NULL)
1448 return(MagickFalse);
1449 length=sizeof(region.width)+sizeof(region.height)+sizeof(region.x)+
1450 sizeof(region.y)+sizeof(length);
1451 count=dpc_receive(file,length,message);
1452 if (count != (MagickOffsetType) length)
1453 return(MagickFalse);
1454 q=message;
1455 (void) memcpy(&region.width,q,sizeof(region.width));
1456 q+=(ptrdiff_t) sizeof(region.width);
1457 (void) memcpy(&region.height,q,sizeof(region.height));
1458 q+=(ptrdiff_t) sizeof(region.height);
1459 (void) memcpy(&region.x,q,sizeof(region.x));
1460 q+=(ptrdiff_t) sizeof(region.x);
1461 (void) memcpy(&region.y,q,sizeof(region.y));
1462 q+=(ptrdiff_t) sizeof(region.y);
1463 (void) memcpy(&length,q,sizeof(length));
1464 per_pixel=image->number_channels*sizeof(Quantum);
1465 if (ValidateDistributedPixelCache(&region,per_pixel,length) == MagickFalse)
1466 return(MagickFalse);
1467 q+=(ptrdiff_t) sizeof(length);
1468 p=GetVirtualPixels(image,region.x,region.y,region.width,region.height,
1469 exception);
1470 if (p == (const Quantum *) NULL)
1471 return(MagickFalse);
1472 count=dpc_send_mac(file,length,p,session_key);
1473 if (count != (MagickOffsetType) length)
1474 return(MagickFalse);
1475 return(MagickTrue);
1476}
1477
1478static void *RelinquishImageRegistry(void *image)
1479{
1480 return((void *) DestroyImageList((Image *) image));
1481}
1482
1483static MagickBooleanType WriteDistributeCacheMetacontent(
1484 SplayTreeInfo *registry,SOCKET_TYPE file,const uint64_t session_key,
1485 ExceptionInfo *exception)
1486{
1487 Image
1488 *image;
1489
1490 MagickAddressType
1491 key = (MagickAddressType) session_key;
1492
1493 MagickOffsetType
1494 count;
1495
1496 MagickSizeType
1497 length;
1498
1499 Quantum
1500 *q;
1501
1502 RectangleInfo
1503 region;
1504
1505 size_t
1506 per_pixel;
1507
1508 unsigned char
1509 message[MagickPathExtent],
1510 *metacontent,
1511 *p;
1512
1513 /*
1514 Write distributed pixel cache metacontent.
1515 */
1516 image=(Image *) GetValueFromSplayTree(registry,(const void *) key);
1517 if (image == (Image *) NULL)
1518 return(MagickFalse);
1519 length=sizeof(region.width)+sizeof(region.height)+sizeof(region.x)+
1520 sizeof(region.y)+sizeof(length);
1521 count=dpc_receive(file,length,message);
1522 if (count != (MagickOffsetType) length)
1523 return(MagickFalse);
1524 p=message;
1525 (void) memcpy(&region.width,p,sizeof(region.width));
1526 p+=(ptrdiff_t) sizeof(region.width);
1527 (void) memcpy(&region.height,p,sizeof(region.height));
1528 p+=(ptrdiff_t) sizeof(region.height);
1529 (void) memcpy(&region.x,p,sizeof(region.x));
1530 p+=(ptrdiff_t) sizeof(region.x);
1531 (void) memcpy(&region.y,p,sizeof(region.y));
1532 p+=(ptrdiff_t) sizeof(region.y);
1533 (void) memcpy(&length,p,sizeof(length));
1534 per_pixel=image->number_meta_channels*sizeof(Quantum);
1535 if (ValidateDistributedPixelCache(&region,per_pixel,length) == MagickFalse)
1536 return(MagickFalse);
1537 p+=(ptrdiff_t) sizeof(length);
1538 q=GetAuthenticPixels(image,region.x,region.y,region.width,region.height,
1539 exception);
1540 if (q == (Quantum *) NULL)
1541 return(MagickFalse);
1542 metacontent=(unsigned char *) GetAuthenticMetacontent(image);
1543 count=dpc_receive_mac(file,length,metacontent,session_key);
1544 if (count != (MagickOffsetType) length)
1545 return(MagickFalse);
1546 return(SyncAuthenticPixels(image,exception));
1547}
1548
1549static MagickBooleanType WriteDistributeCachePixels(SplayTreeInfo *registry,
1550 SOCKET_TYPE file,const uint64_t session_key,ExceptionInfo *exception)
1551{
1552 Image
1553 *image;
1554
1555 MagickAddressType
1556 key = (MagickAddressType) session_key;
1557
1558 MagickOffsetType
1559 count;
1560
1561 MagickSizeType
1562 length;
1563
1564 Quantum
1565 *q;
1566
1567 RectangleInfo
1568 region;
1569
1570 size_t
1571 per_pixel;
1572
1573 unsigned char
1574 message[MagickPathExtent],
1575 *p;
1576
1577 /*
1578 Write distributed pixel cache pixels.
1579 */
1580 image=(Image *) GetValueFromSplayTree(registry,(const void *) key);
1581 if (image == (Image *) NULL)
1582 return(MagickFalse);
1583 length=sizeof(region.width)+sizeof(region.height)+sizeof(region.x)+
1584 sizeof(region.y)+sizeof(length);
1585 count=dpc_receive(file,length,message);
1586 if (count != (MagickOffsetType) length)
1587 return(MagickFalse);
1588 p=message;
1589 (void) memcpy(&region.width,p,sizeof(region.width));
1590 p+=(ptrdiff_t) sizeof(region.width);
1591 (void) memcpy(&region.height,p,sizeof(region.height));
1592 p+=(ptrdiff_t) sizeof(region.height);
1593 (void) memcpy(&region.x,p,sizeof(region.x));
1594 p+=(ptrdiff_t) sizeof(region.x);
1595 (void) memcpy(&region.y,p,sizeof(region.y));
1596 p+=(ptrdiff_t) sizeof(region.y);
1597 (void) memcpy(&length,p,sizeof(length));
1598 per_pixel=image->number_channels*sizeof(Quantum);
1599 if (ValidateDistributedPixelCache(&region,per_pixel,length) == MagickFalse)
1600 return(MagickFalse);
1601 p+=(ptrdiff_t) sizeof(length);
1602 q=GetAuthenticPixels(image,region.x,region.y,region.width,region.height,
1603 exception);
1604 if (q == (Quantum *) NULL)
1605 return(MagickFalse);
1606 count=dpc_receive_mac(file,length,(unsigned char *) q,session_key);
1607 if (count != (MagickOffsetType) length)
1608 return(MagickFalse);
1609 return(SyncAuthenticPixels(image,exception));
1610}
1611
1612static void LockDPCSemaphore(void)
1613{
1614 if (dpc_semaphore == (SemaphoreInfo *) NULL)
1615 ActivateSemaphoreInfo(&dpc_semaphore);
1616 LockSemaphoreInfo(dpc_semaphore);
1617}
1618
1619static void AuthenticateDPCClient(void)
1620{
1621 LockDPCSemaphore();
1622 if (dpc_unauthenticated_clients != 0)
1623 dpc_unauthenticated_clients--;
1624 UnlockSemaphoreInfo(dpc_semaphore);
1625}
1626
1627static void RelinquishDPCClient(const MagickBooleanType unauthenticated)
1628{
1629 LockDPCSemaphore();
1630 if ((unauthenticated != MagickFalse) && (dpc_unauthenticated_clients != 0))
1631 dpc_unauthenticated_clients--;
1632 if (dpc_clients != 0)
1633 dpc_clients--;
1634 UnlockSemaphoreInfo(dpc_semaphore);
1635}
1636
1637static HANDLER_RETURN_TYPE DistributePixelCacheConnectionHandler(
1638 void *socket_arg)
1639{
1640 ExceptionInfo
1641 *exception;
1642
1643 MagickBooleanType
1644 authenticated = MagickFalse,
1645 status = MagickFalse;
1646
1647 MagickOffsetType
1648 count;
1649
1650 RandomInfo
1651 *random_info;
1652
1653 SOCKET_TYPE
1654 client_socket,
1655 *client_socket_ptr = (SOCKET_TYPE *) socket_arg;
1656
1657 SplayTreeInfo
1658 *registry;
1659
1660 StringInfo
1661 *entropy;
1662
1663 uint64_t
1664 key,
1665 session_key;
1666
1667 unsigned char
1668 command,
1669 nonce[DPCSessionKeyLength];
1670
1671 client_socket=(*client_socket_ptr);
1672 client_socket_ptr=(SOCKET_TYPE *) RelinquishMagickMemory(client_socket_ptr);
1673 /*
1674 Generate random nonce.
1675 */
1676 random_info=AcquireRandomInfo();
1677 entropy=GetRandomKey(random_info,sizeof(nonce));
1678 (void) memcpy(nonce,GetStringInfoDatum(entropy),sizeof(nonce));
1679 entropy=DestroyStringInfo(entropy);
1680 random_info=DestroyRandomInfo(random_info);
1681 /*
1682 Derive session key.
1683 */
1684 session_key=GenerateSessionKey(dpc_shared_secret,nonce,sizeof(nonce));
1685 /*
1686 Send nonce to client.
1687 */
1688 count=dpc_send(client_socket,sizeof(nonce),nonce);
1689 if (count != (MagickOffsetType) sizeof(nonce))
1690 {
1691 CLOSE_SOCKET(client_socket);
1692 RelinquishDPCClient(MagickTrue);
1693 return(HANDLER_RETURN_VALUE);
1694 }
1695 /*
1696 Receive client's keyed hash.
1697 */
1698 count=dpc_receive_deadline(client_socket,sizeof(key),(unsigned char *) &key,
1699 (double) time((time_t *) NULL)+5.0);
1700 if ((count != (MagickOffsetType) sizeof(key)) || (key != session_key))
1701 {
1702 CLOSE_SOCKET(client_socket);
1703 RelinquishDPCClient(MagickTrue);
1704 return(HANDLER_RETURN_VALUE);
1705 }
1706 AuthenticateDPCClient();
1707 authenticated=MagickTrue;
1708 exception=AcquireExceptionInfo();
1709 registry=NewSplayTree((int (*)(const void *,const void *)) NULL,
1710 (void *(*)(void *)) NULL,RelinquishImageRegistry);
1711 /*
1712 Command loop.
1713 */
1714 for (status=MagickFalse; ; )
1715 {
1716 /*
1717 Each command must echo the authenticated session key.
1718 */
1719 count=dpc_receive_deadline(client_socket,1,(unsigned char *) &command,
1720 (double) time((time_t *) NULL)+5.0);
1721 if (count <= 0)
1722 break;
1723 count=dpc_receive_deadline(client_socket,sizeof(key),(unsigned char *) &key,
1724 (double) time((time_t *) NULL)+5.0);
1725 if ((count != (MagickOffsetType) sizeof(key)) || (key != session_key))
1726 break;
1727 switch (command)
1728 {
1729 case 'o':
1730 {
1731 status=OpenDistributeCache(registry,client_socket,session_key,
1732 exception);
1733 dpc_send(client_socket,sizeof(status),&status);
1734 break;
1735 }
1736 case 'r':
1737 {
1738 status=ReadDistributeCachePixels(registry,client_socket,session_key,
1739 exception);
1740 break;
1741 }
1742 case 'R':
1743 {
1744 status=ReadDistributeCacheMetacontent(registry,client_socket,
1745 session_key,exception);
1746 break;
1747 }
1748 case 'w':
1749 {
1750 status=WriteDistributeCachePixels(registry,client_socket,session_key,
1751 exception);
1752 break;
1753 }
1754 case 'W':
1755 {
1756 status=WriteDistributeCacheMetacontent(registry,client_socket,
1757 session_key,exception);
1758 break;
1759 }
1760 case 'd':
1761 {
1762 status=DestroyDistributeCache(registry,session_key);
1763 break;
1764 }
1765 default:
1766 break;
1767 }
1768 if ((status == MagickFalse) || (command == 'd'))
1769 break;
1770 }
1771 count=dpc_send(client_socket,sizeof(status),&status);
1772 CLOSE_SOCKET(client_socket);
1773 exception=DestroyExceptionInfo(exception);
1774 registry=DestroySplayTree(registry);
1775 RelinquishDPCClient(authenticated == MagickFalse ? MagickTrue :
1776 MagickFalse);
1777 return(HANDLER_RETURN_VALUE);
1778}
1779
1780static size_t GetDPCPolicyLimit(const char *name,const size_t default_limit)
1781{
1782 char
1783 policy_name[MagickPathExtent],
1784 *policy_value;
1785
1786 size_t
1787 limit;
1788
1789 limit=default_limit;
1790 (void) FormatLocaleString(policy_name,MagickPathExtent,"cache:%s",name);
1791 policy_value=GetPolicyValue(policy_name);
1792 if (policy_value != (char *) NULL)
1793 {
1794 char
1795 *q;
1796
1797 unsigned long
1798 policy_limit;
1799
1800 errno=0;
1801 policy_limit=strtoul(policy_value,&q,10);
1802 if ((errno == 0) && (q != policy_value) && (policy_limit != 0))
1803 limit=(size_t) policy_limit;
1804 policy_value=DestroyString(policy_value);
1805 }
1806 return(limit);
1807}
1808
1809static size_t GetMaxDPCClients(void)
1810{
1811 return(GetDPCPolicyLimit("max-dpc-clients",DPCMaxClientWorkers));
1812}
1813
1814static size_t GetMaxDPCUnauthenticatedClients(void)
1815{
1816 size_t
1817 client_workers,
1818 unauthenticated_workers;
1819
1820 client_workers=GetMaxDPCClients();
1821 unauthenticated_workers=GetDPCPolicyLimit("max-dpc-unauthenticated-clients",
1822 DPCMaxUnauthenticatedClientWorkers);
1823 return(MagickMin(unauthenticated_workers,client_workers));
1824}
1825
1826static MagickBooleanType AcquireDPCClientWorker(void)
1827{
1828 MagickBooleanType
1829 status;
1830
1831 size_t
1832 max_dpc_clients,
1833 unauthenticated_worker_limit;
1834
1835 status=MagickFalse;
1836 max_dpc_clients=GetMaxDPCClients();
1837 unauthenticated_worker_limit=GetMaxDPCUnauthenticatedClients();
1838 LockDPCSemaphore();
1839 if ((dpc_clients < max_dpc_clients) &&
1840 (dpc_unauthenticated_clients < unauthenticated_worker_limit))
1841 {
1842 dpc_clients++;
1843 dpc_unauthenticated_clients++;
1844 status=MagickTrue;
1845 }
1846 UnlockSemaphoreInfo(dpc_semaphore);
1847 return(status);
1848}
1849
1850MagickExport void DistributePixelCacheServer(const int port,
1851 ExceptionInfo *exception)
1852{
1853 char
1854 service[MagickPathExtent];
1855
1856 int
1857 status;
1858
1859#if defined(MAGICKCORE_THREAD_SUPPORT)
1860 pthread_attr_t
1861 attributes;
1862
1863 pthread_t
1864 thread_id;
1865#elif defined(_MSC_VER)
1866 DWORD
1867 threadID;
1868#else
1869 Not implemented!
1870#endif
1871
1872 SOCKET_TYPE
1873 server_socket;
1874
1875 struct addrinfo
1876 *p;
1877
1878 struct addrinfo
1879 hint,
1880 *result;
1881
1882 struct sockaddr_in
1883 address;
1884
1885 /*
1886 Launch distributed pixel cache server.
1887 */
1888 assert(exception != (ExceptionInfo *) NULL);
1889 assert(exception->signature == MagickCoreSignature);
1890 magick_unreferenced(exception);
1891 dpc_shared_secret=GetPolicyValue("cache:shared-secret");
1892 if (dpc_shared_secret == (char *) NULL)
1893 ThrowFatalException(CacheFatalError,"no shared secret");
1894#if defined(MAGICKCORE_HAVE_WINSOCK2)
1895 InitializeWinsock2(MagickFalse);
1896#endif
1897 (void) memset(&hint,0,sizeof(hint));
1898 hint.ai_family=AF_INET;
1899 hint.ai_socktype=SOCK_STREAM;
1900 hint.ai_flags=AI_PASSIVE;
1901 FormatLocaleString(service,MagickPathExtent,"%d",port);
1902 status=getaddrinfo(NULL,service,&hint,&result);
1903 if (status != 0)
1904 ThrowFatalException(CacheFatalError,"UnableToListen");
1905 server_socket=(SOCKET_TYPE) 0;
1906 for (p=result; p != NULL; p=p->ai_next)
1907 {
1908 int
1909 one = 1;
1910
1911 server_socket=(SOCKET_TYPE) socket(p->ai_family,p->ai_socktype,
1912 p->ai_protocol);
1913 if (server_socket == -1)
1914 continue;
1915 status=setsockopt(server_socket,SOL_SOCKET,SO_REUSEADDR,(char *) &one,
1916 (socklen_t) sizeof(one));
1917 if (status == -1)
1918 {
1919 CLOSE_SOCKET(server_socket);
1920 continue;
1921 }
1922 SetSocketReceiveTimeout(server_socket,5.0);
1923 status=bind(server_socket,p->ai_addr,(socklen_t) p->ai_addrlen);
1924 if (status == -1)
1925 {
1926 CLOSE_SOCKET(server_socket);
1927 continue;
1928 }
1929 break;
1930 }
1931 if (p == (struct addrinfo *) NULL)
1932 ThrowFatalException(CacheFatalError,"UnableToBind");
1933 freeaddrinfo(result);
1934 status=listen(server_socket,DPCPendingConnections);
1935 if (status != 0)
1936 ThrowFatalException(CacheFatalError,"UnableToListen");
1937#if defined(MAGICKCORE_THREAD_SUPPORT)
1938 pthread_attr_init(&attributes);
1939 pthread_attr_setdetachstate(&attributes,PTHREAD_CREATE_DETACHED);
1940#endif
1941 for ( ; ; )
1942 {
1943 SOCKET_TYPE
1944 *client_socket_ptr;
1945
1946 socklen_t
1947 length = (socklen_t) sizeof(address);
1948
1949 client_socket_ptr=(SOCKET_TYPE *) AcquireMagickMemory(sizeof(SOCKET_TYPE));
1950 if (client_socket_ptr == NULL)
1951 continue; /* skip connection */
1952 *client_socket_ptr=(SOCKET_TYPE) accept(server_socket,(struct sockaddr *)
1953 &address,&length);
1954 if (*client_socket_ptr == -1)
1955 {
1956 client_socket_ptr=(SOCKET_TYPE *) RelinquishMagickMemory(
1957 client_socket_ptr);
1958 continue;
1959 }
1960 if (AcquireDPCClientWorker() == MagickFalse)
1961 {
1962 CLOSE_SOCKET(*client_socket_ptr);
1963 client_socket_ptr=(SOCKET_TYPE *) RelinquishMagickMemory(
1964 client_socket_ptr);
1965 continue;
1966 }
1967 SetSocketReceiveTimeout(*client_socket_ptr,5.0);
1968 SetSocketNoDelay(*client_socket_ptr);
1969 if (status == -1)
1970 {
1971 CLOSE_SOCKET(*client_socket_ptr);
1972 RelinquishDPCClient(MagickTrue);
1973 client_socket_ptr=(SOCKET_TYPE *) RelinquishMagickMemory(
1974 client_socket_ptr);
1975 continue;
1976 }
1977#if defined(MAGICKCORE_THREAD_SUPPORT)
1978 status=pthread_create(&thread_id,&attributes,
1979 DistributePixelCacheConnectionHandler,(void *) client_socket_ptr);
1980 if (status != 0)
1981 {
1982 CLOSE_SOCKET(*client_socket_ptr);
1983 RelinquishDPCClient(MagickTrue);
1984 RelinquishMagickMemory(client_socket_ptr);
1985 continue;
1986 }
1987#elif defined(_MSC_VER)
1988 if (CreateThread(0,0,DistributePixelCacheConnectionHandler,(void*) client_socket_ptr,0,&threadID) == (HANDLE) NULL)
1989 {
1990 CLOSE_SOCKET(*client_socket_ptr);
1991 RelinquishDPCClient(MagickTrue);
1992 RelinquishMagickMemory(client_socket_ptr);
1993 continue;
1994 }
1995#else
1996 Not implemented!
1997#endif
1998 }
1999}
2000#endif
2001␌
2002/*
2003%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2004% %
2005% %
2006% %
2007+ D i s t r i b u t e C a c h e T e r m i n u s %
2008% %
2009% %
2010% %
2011%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2012%
2013% DistributeCacheTerminus() destroys the Distributed Cache.
2014%
2015*/
2016MagickPrivate void DistributeCacheTerminus(void)
2017{
2018#ifdef MAGICKCORE_HAVE_WINSOCK2
2019 if (winsock_semaphore == (SemaphoreInfo *) NULL)
2020 ActivateSemaphoreInfo(&winsock_semaphore);
2021 LockSemaphoreInfo(winsock_semaphore);
2022 if (wsaData != (WSADATA *) NULL)
2023 {
2024 WSACleanup();
2025 wsaData=(WSADATA *) RelinquishMagickMemory((void *) wsaData);
2026 }
2027 UnlockSemaphoreInfo(winsock_semaphore);
2028 RelinquishSemaphoreInfo(&winsock_semaphore);
2029#endif
2030#if defined(MAGICKCORE_HAVE_DISTRIBUTE_CACHE)
2031 if (dpc_shared_secret != (char *) NULL)
2032 dpc_shared_secret=DestroyString(dpc_shared_secret);
2033 if (dpc_semaphore != (SemaphoreInfo *) NULL)
2034 RelinquishSemaphoreInfo(&dpc_semaphore);
2035#endif
2036}
2037
2038/*
2039%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2040% %
2041% %
2042% %
2043+ G e t D i s t r i b u t e C a c h e F i l e %
2044% %
2045% %
2046% %
2047%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2048%
2049% GetDistributeCacheFile() returns the file associated with this
2050% DistributeCacheInfo structure.
2051%
2052% The format of the GetDistributeCacheFile method is:
2053%
2054% int GetDistributeCacheFile(const DistributeCacheInfo *server_info)
2055%
2056% A description of each parameter follows:
2057%
2058% o server_info: the distributed cache info.
2059%
2060*/
2061MagickPrivate int GetDistributeCacheFile(const DistributeCacheInfo *server_info)
2062{
2063 assert(server_info != (DistributeCacheInfo *) NULL);
2064 assert(server_info->signature == MagickCoreSignature);
2065 return(server_info->file);
2066}
2067␌
2068/*
2069%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2070% %
2071% %
2072% %
2073+ G e t D i s t r i b u t e C a c h e H o s t n a m e %
2074% %
2075% %
2076% %
2077%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2078%
2079% GetDistributeCacheHostname() returns the hostname associated with this
2080% DistributeCacheInfo structure.
2081%
2082% The format of the GetDistributeCacheHostname method is:
2083%
2084% const char *GetDistributeCacheHostname(
2085% const DistributeCacheInfo *server_info)
2086%
2087% A description of each parameter follows:
2088%
2089% o server_info: the distributed cache info.
2090%
2091*/
2092MagickPrivate const char *GetDistributeCacheHostname(
2093 const DistributeCacheInfo *server_info)
2094{
2095 assert(server_info != (DistributeCacheInfo *) NULL);
2096 assert(server_info->signature == MagickCoreSignature);
2097 return(server_info->hostname);
2098}
2099␌
2100/*
2101%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2102% %
2103% %
2104% %
2105+ G e t D i s t r i b u t e C a c h e P o r t %
2106% %
2107% %
2108% %
2109%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2110%
2111% GetDistributeCachePort() returns the port associated with this
2112% DistributeCacheInfo structure.
2113%
2114% The format of the GetDistributeCachePort method is:
2115%
2116% int GetDistributeCachePort(const DistributeCacheInfo *server_info)
2117%
2118% A description of each parameter follows:
2119%
2120% o server_info: the distributed cache info.
2121%
2122*/
2123MagickPrivate int GetDistributeCachePort(const DistributeCacheInfo *server_info)
2124{
2125 assert(server_info != (DistributeCacheInfo *) NULL);
2126 assert(server_info->signature == MagickCoreSignature);
2127 return(server_info->port);
2128}
2129␌
2130/*
2131%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2132% %
2133% %
2134% %
2135+ O p e n D i s t r i b u t e P i x e l C a c h e %
2136% %
2137% %
2138% %
2139%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2140%
2141% OpenDistributePixelCache() opens a pixel cache on a remote server.
2142%
2143% The format of the OpenDistributePixelCache method is:
2144%
2145% MagickBooleanType *OpenDistributePixelCache(
2146% DistributeCacheInfo *server_info,Image *image)
2147%
2148% A description of each parameter follows:
2149%
2150% o server_info: the distributed cache info.
2151%
2152% o image: the image.
2153%
2154*/
2155MagickPrivate MagickBooleanType OpenDistributePixelCache(
2156 DistributeCacheInfo *server_info,Image *image)
2157{
2158 MagickBooleanType
2159 status;
2160
2161 MagickOffsetType
2162 count;
2163
2164 unsigned char
2165 message[MagickPathExtent],
2166 *p;
2167
2168 /*
2169 Open distributed pixel cache.
2170 */
2171 assert(server_info != (DistributeCacheInfo *) NULL);
2172 assert(server_info->signature == MagickCoreSignature);
2173 assert(image != (Image *) NULL);
2174 assert(image->signature == MagickCoreSignature);
2175 p=message;
2176 *p++='o'; /* open */
2177 /*
2178 Serialize image attributes (see ValidatePixelCacheMorphology()).
2179 */
2180 (void) memcpy(p,&server_info->session_key,sizeof(server_info->session_key));
2181 p+=(ptrdiff_t) sizeof(server_info->session_key);
2182 (void) memcpy(p,&image->storage_class,sizeof(image->storage_class));
2183 p+=(ptrdiff_t) sizeof(image->storage_class);
2184 (void) memcpy(p,&image->colorspace,sizeof(image->colorspace));
2185 p+=(ptrdiff_t) sizeof(image->colorspace);
2186 (void) memcpy(p,&image->alpha_trait,sizeof(image->alpha_trait));
2187 p+=(ptrdiff_t) sizeof(image->alpha_trait);
2188 (void) memcpy(p,&image->channels,sizeof(image->channels));
2189 p+=(ptrdiff_t) sizeof(image->channels);
2190 (void) memcpy(p,&image->columns,sizeof(image->columns));
2191 p+=(ptrdiff_t) sizeof(image->columns);
2192 (void) memcpy(p,&image->rows,sizeof(image->rows));
2193 p+=(ptrdiff_t) sizeof(image->rows);
2194 (void) memcpy(p,&image->number_channels,sizeof(image->number_channels));
2195 p+=(ptrdiff_t) sizeof(image->number_channels);
2196 (void) memcpy(p,image->channel_map,MaxPixelChannels*
2197 sizeof(*image->channel_map));
2198 p+=(ptrdiff_t) MaxPixelChannels*sizeof(*image->channel_map);
2199 (void) memcpy(p,&image->metacontent_extent,sizeof(image->metacontent_extent));
2200 p+=(ptrdiff_t) sizeof(image->metacontent_extent);
2201 count=dpc_send(server_info->file,(MagickSizeType) (p-message),message);
2202 if (count != (MagickOffsetType) (p-message))
2203 return(MagickFalse);
2204 status=MagickFalse;
2205 count=dpc_receive(server_info->file,sizeof(status),(unsigned char *) &status);
2206 if (count != (MagickOffsetType) sizeof(status))
2207 return(MagickFalse);
2208 return(status);
2209}
2210␌
2211/*
2212%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2213% %
2214% %
2215% %
2216+ R e a d D i s t r i b u t e P i x e l C a c h e M e t a c o n t e n t %
2217% %
2218% %
2219% %
2220%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2221%
2222% ReadDistributePixelCacheMetacontents() reads metacontent from the specified
2223% region of the distributed pixel cache.
2224%
2225% The format of the ReadDistributePixelCacheMetacontents method is:
2226%
2227% MagickOffsetType ReadDistributePixelCacheMetacontents(
2228% DistributeCacheInfo *server_info,const RectangleInfo *region,
2229% const MagickSizeType length,unsigned char *metacontent)
2230%
2231% A description of each parameter follows:
2232%
2233% o server_info: the distributed cache info.
2234%
2235% o image: the image.
2236%
2237% o region: read the metacontent from this region of the image.
2238%
2239% o length: the length in bytes of the metacontent.
2240%
2241% o metacontent: read these metacontent from the pixel cache.
2242%
2243*/
2244MagickPrivate MagickOffsetType ReadDistributePixelCacheMetacontent(
2245 DistributeCacheInfo *server_info,const RectangleInfo *region,
2246 const MagickSizeType length,unsigned char *metacontent)
2247{
2248 MagickOffsetType
2249 count;
2250
2251 unsigned char
2252 message[MagickPathExtent],
2253 *p;
2254
2255 /*
2256 Read distributed pixel cache metacontent.
2257 */
2258 assert(server_info != (DistributeCacheInfo *) NULL);
2259 assert(server_info->signature == MagickCoreSignature);
2260 assert(region != (RectangleInfo *) NULL);
2261 assert(metacontent != (unsigned char *) NULL);
2262 if (length > (MagickSizeType) MAGICK_SSIZE_MAX)
2263 return(-1);
2264 p=message;
2265 *p++='R';
2266 (void) memcpy(p,&server_info->session_key,sizeof(server_info->session_key));
2267 p+=(ptrdiff_t) sizeof(server_info->session_key);
2268 (void) memcpy(p,&region->width,sizeof(region->width));
2269 p+=(ptrdiff_t) sizeof(region->width);
2270 (void) memcpy(p,&region->height,sizeof(region->height));
2271 p+=(ptrdiff_t) sizeof(region->height);
2272 (void) memcpy(p,&region->x,sizeof(region->x));
2273 p+=(ptrdiff_t) sizeof(region->x);
2274 (void) memcpy(p,&region->y,sizeof(region->y));
2275 p+=(ptrdiff_t) sizeof(region->y);
2276 (void) memcpy(p,&length,sizeof(length));
2277 p+=(ptrdiff_t) sizeof(length);
2278 count=dpc_send(server_info->file,(MagickSizeType) (p-message),message);
2279 if (count != (MagickOffsetType) (p-message))
2280 return(-1);
2281 return(dpc_receive_mac(server_info->file,length,metacontent,
2282 server_info->session_key));
2283}
2284␌
2285/*
2286%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2287% %
2288% %
2289% %
2290+ R e a d D i s t r i b u t e P i x e l C a c h e P i x e l s %
2291% %
2292% %
2293% %
2294%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2295%
2296% ReadDistributePixelCachePixels() reads pixels from the specified region of
2297% the distributed pixel cache.
2298%
2299% The format of the ReadDistributePixelCachePixels method is:
2300%
2301% MagickOffsetType ReadDistributePixelCachePixels(
2302% DistributeCacheInfo *server_info,const RectangleInfo *region,
2303% const MagickSizeType length,unsigned char *magick_restrict pixels)
2304%
2305% A description of each parameter follows:
2306%
2307% o server_info: the distributed cache info.
2308%
2309% o image: the image.
2310%
2311% o region: read the pixels from this region of the image.
2312%
2313% o length: the length in bytes of the pixels.
2314%
2315% o pixels: read these pixels from the pixel cache.
2316%
2317*/
2318MagickPrivate MagickOffsetType ReadDistributePixelCachePixels(
2319 DistributeCacheInfo *server_info,const RectangleInfo *region,
2320 const MagickSizeType length,unsigned char *magick_restrict pixels)
2321{
2322 MagickOffsetType
2323 count;
2324
2325 unsigned char
2326 message[MagickPathExtent],
2327 *p;
2328
2329 /*
2330 Read distributed pixel cache pixels.
2331 */
2332 assert(server_info != (DistributeCacheInfo *) NULL);
2333 assert(server_info->signature == MagickCoreSignature);
2334 assert(region != (RectangleInfo *) NULL);
2335 assert(pixels != (unsigned char *) NULL);
2336 if (length > (MagickSizeType) MAGICK_SSIZE_MAX)
2337 return(-1);
2338 p=message;
2339 *p++='r';
2340 (void) memcpy(p,&server_info->session_key,sizeof(server_info->session_key));
2341 p+=(ptrdiff_t) sizeof(server_info->session_key);
2342 (void) memcpy(p,&region->width,sizeof(region->width));
2343 p+=(ptrdiff_t) sizeof(region->width);
2344 (void) memcpy(p,&region->height,sizeof(region->height));
2345 p+=(ptrdiff_t) sizeof(region->height);
2346 (void) memcpy(p,&region->x,sizeof(region->x));
2347 p+=(ptrdiff_t) sizeof(region->x);
2348 (void) memcpy(p,&region->y,sizeof(region->y));
2349 p+=(ptrdiff_t) sizeof(region->y);
2350 (void) memcpy(p,&length,sizeof(length));
2351 p+=(ptrdiff_t) sizeof(length);
2352 count=dpc_send(server_info->file,(MagickSizeType) (p-message),message);
2353 if (count != (MagickOffsetType) (p-message))
2354 return(-1);
2355 return(dpc_receive_mac(server_info->file,length,pixels,
2356 server_info->session_key));
2357}
2358␌
2359/*
2360%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2361% %
2362% %
2363% %
2364+ R e l i n q u i s h D i s t r i b u t e P i x e l C a c h e %
2365% %
2366% %
2367% %
2368%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2369%
2370% RelinquishDistributePixelCache() frees resources acquired with
2371% OpenDistributePixelCache().
2372%
2373% The format of the RelinquishDistributePixelCache method is:
2374%
2375% MagickBooleanType RelinquishDistributePixelCache(
2376% DistributeCacheInfo *server_info)
2377%
2378% A description of each parameter follows:
2379%
2380% o server_info: the distributed cache info.
2381%
2382*/
2383MagickPrivate MagickBooleanType RelinquishDistributePixelCache(
2384 DistributeCacheInfo *server_info)
2385{
2386 MagickBooleanType
2387 status;
2388
2389 MagickOffsetType
2390 count;
2391
2392 unsigned char
2393 message[MagickPathExtent],
2394 *p;
2395
2396 /*
2397 Delete distributed pixel cache.
2398 */
2399 assert(server_info != (DistributeCacheInfo *) NULL);
2400 assert(server_info->signature == MagickCoreSignature);
2401 p=message;
2402 *p++='d';
2403 (void) memcpy(p,&server_info->session_key,sizeof(server_info->session_key));
2404 p+=(ptrdiff_t) sizeof(server_info->session_key);
2405 count=dpc_send(server_info->file,(MagickSizeType) (p-message),message);
2406 if (count != (MagickOffsetType) (p-message))
2407 return(MagickFalse);
2408 status=MagickFalse;
2409 count=dpc_receive(server_info->file,sizeof(status),(unsigned char *) &status);
2410 if (count != (MagickOffsetType) sizeof(status))
2411 return(MagickFalse);
2412 return(status);
2413}
2414␌
2415/*
2416%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2417% %
2418% %
2419% %
2420+ W r i t e D i s t r i b u t e P i x e l C a c h e M e t a c o n t e n t %
2421% %
2422% %
2423% %
2424%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2425%
2426% WriteDistributePixelCacheMetacontents() writes image metacontent to the
2427% specified region of the distributed pixel cache.
2428%
2429% The format of the WriteDistributePixelCacheMetacontents method is:
2430%
2431% MagickOffsetType WriteDistributePixelCacheMetacontents(
2432% DistributeCacheInfo *server_info,const RectangleInfo *region,
2433% const MagickSizeType length,const unsigned char *metacontent)
2434%
2435% A description of each parameter follows:
2436%
2437% o server_info: the distributed cache info.
2438%
2439% o image: the image.
2440%
2441% o region: write the metacontent to this region of the image.
2442%
2443% o length: the length in bytes of the metacontent.
2444%
2445% o metacontent: write these metacontent to the pixel cache.
2446%
2447*/
2448MagickPrivate MagickOffsetType WriteDistributePixelCacheMetacontent(
2449 DistributeCacheInfo *server_info,const RectangleInfo *region,
2450 const MagickSizeType length,const unsigned char *metacontent)
2451{
2452 MagickOffsetType
2453 count;
2454
2455 unsigned char
2456 message[MagickPathExtent],
2457 *p;
2458
2459 /*
2460 Write distributed pixel cache metacontent.
2461 */
2462 assert(server_info != (DistributeCacheInfo *) NULL);
2463 assert(server_info->signature == MagickCoreSignature);
2464 assert(region != (RectangleInfo *) NULL);
2465 assert(metacontent != (unsigned char *) NULL);
2466 if (length > (MagickSizeType) MAGICK_SSIZE_MAX)
2467 return(-1);
2468 p=message;
2469 *p++='W';
2470 (void) memcpy(p,&server_info->session_key,sizeof(server_info->session_key));
2471 p+=(ptrdiff_t) sizeof(server_info->session_key);
2472 (void) memcpy(p,&region->width,sizeof(region->width));
2473 p+=(ptrdiff_t) sizeof(region->width);
2474 (void) memcpy(p,&region->height,sizeof(region->height));
2475 p+=(ptrdiff_t) sizeof(region->height);
2476 (void) memcpy(p,&region->x,sizeof(region->x));
2477 p+=(ptrdiff_t) sizeof(region->x);
2478 (void) memcpy(p,&region->y,sizeof(region->y));
2479 p+=(ptrdiff_t) sizeof(region->y);
2480 (void) memcpy(p,&length,sizeof(length));
2481 p+=(ptrdiff_t) sizeof(length);
2482 count=dpc_send(server_info->file,(MagickSizeType) (p-message),message);
2483 if (count != (MagickOffsetType) (p-message))
2484 return(-1);
2485 return(dpc_send_mac(server_info->file,length,metacontent,
2486 server_info->session_key));
2487}
2488␌
2489/*
2490%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2491% %
2492% %
2493% %
2494+ W r i t e D i s t r i b u t e P i x e l C a c h e P i x e l s %
2495% %
2496% %
2497% %
2498%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2499%
2500% WriteDistributePixelCachePixels() writes image pixels to the specified
2501% region of the distributed pixel cache.
2502%
2503% The format of the WriteDistributePixelCachePixels method is:
2504%
2505% MagickBooleanType WriteDistributePixelCachePixels(
2506% DistributeCacheInfo *server_info,const RectangleInfo *region,
2507% const MagickSizeType length,
2508% const unsigned char *magick_restrict pixels)
2509%
2510% A description of each parameter follows:
2511%
2512% o server_info: the distributed cache info.
2513%
2514% o image: the image.
2515%
2516% o region: write the pixels to this region of the image.
2517%
2518% o length: the length in bytes of the pixels.
2519%
2520% o pixels: write these pixels to the pixel cache.
2521%
2522*/
2523MagickPrivate MagickOffsetType WriteDistributePixelCachePixels(
2524 DistributeCacheInfo *server_info,const RectangleInfo *region,
2525 const MagickSizeType length,const unsigned char *magick_restrict pixels)
2526{
2527 MagickOffsetType
2528 count;
2529
2530 unsigned char
2531 message[MagickPathExtent],
2532 *p;
2533
2534 /*
2535 Write distributed pixel cache pixels.
2536 */
2537 assert(server_info != (DistributeCacheInfo *) NULL);
2538 assert(server_info->signature == MagickCoreSignature);
2539 assert(region != (RectangleInfo *) NULL);
2540 assert(pixels != (const unsigned char *) NULL);
2541 if (length > (MagickSizeType) MAGICK_SSIZE_MAX)
2542 return(-1);
2543 p=message;
2544 *p++='w';
2545 (void) memcpy(p,&server_info->session_key,sizeof(server_info->session_key));
2546 p+=(ptrdiff_t) sizeof(server_info->session_key);
2547 (void) memcpy(p,&region->width,sizeof(region->width));
2548 p+=(ptrdiff_t) sizeof(region->width);
2549 (void) memcpy(p,&region->height,sizeof(region->height));
2550 p+=(ptrdiff_t) sizeof(region->height);
2551 (void) memcpy(p,&region->x,sizeof(region->x));
2552 p+=(ptrdiff_t) sizeof(region->x);
2553 (void) memcpy(p,&region->y,sizeof(region->y));
2554 p+=(ptrdiff_t) sizeof(region->y);
2555 (void) memcpy(p,&length,sizeof(length));
2556 p+=(ptrdiff_t) sizeof(length);
2557 count=dpc_send(server_info->file,(MagickSizeType) (p-message),message);
2558 if (count != (MagickOffsetType) (p-message))
2559 return(-1);
2560 return(dpc_send_mac(server_info->file,length,pixels,
2561 server_info->session_key));
2562}