xref: /petsc/src/sys/webclient/globus.c (revision f15a11d28b36f01875e426cb22da92fd19b081e4)
1 #include <petscwebclient.h>
2 
3 /*
4     Encodes and decodes from MIME Base64
5 */
6 static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
7                                 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
8                                 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
9                                 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
10                                 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
11                                 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
12                                 'w', 'x', 'y', 'z', '0', '1', '2', '3',
13                                 '4', '5', '6', '7', '8', '9', '+', '/'};
14 
15 static PetscErrorCode base64_encode(const unsigned char *data,unsigned char *encoded_data,size_t len)
16 {
17   static size_t  mod_table[] = {0, 2, 1};
18   size_t         i,j;
19   size_t         input_length,output_length;
20   PetscErrorCode ierr;
21 
22   PetscFunctionBegin;
23   ierr = PetscStrlen((const char*)data,&input_length);CHKERRQ(ierr);
24   output_length = 4 * ((input_length + 2) / 3);
25   if (output_length > len) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Output length not large enough");
26 
27   for (i = 0, j = 0; i < input_length;) {
28      uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
29      uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
30      uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
31      uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
32 
33      encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
34      encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
35      encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
36      encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
37   }
38   encoded_data[j] = 0;
39   for (i = 0; i < mod_table[input_length % 3]; i++) encoded_data[output_length - 1 - i] = '=';
40   PetscFunctionReturn(0);
41 }
42 
43 PETSC_UNUSED static PetscErrorCode base64_decode(const unsigned char *data,unsigned char* decoded_data, size_t length)
44 {
45   static char    decoding_table[257];
46   static int     decode_table_built = 0;
47   size_t         i,j;
48   PetscErrorCode ierr;
49   size_t         input_length,output_length;
50 
51   PetscFunctionBegin;
52   if (!decode_table_built) {
53     for (i = 0; i < 64; i++) decoding_table[(unsigned char) encoding_table[i]] = i;
54     decode_table_built = 1;
55   }
56 
57   ierr = PetscStrlen((const char*)data,&input_length);CHKERRQ(ierr);
58   if (input_length % 4 != 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Input length must be divisible by 4");
59 
60   output_length = input_length / 4 * 3;
61   if (data[input_length - 1] == '=') (output_length)--;
62   if (data[input_length - 2] == '=') (output_length)--;
63   if (output_length > length) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Output length too shore");
64 
65   for (i = 0, j = 0; i < input_length;) {
66     uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[(int)data[i++]];
67     uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[(int)data[i++]];
68     uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[(int)data[i++]];
69     uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[(int)data[i++]];
70     uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);
71 
72     if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
73     if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
74     if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
75   }
76   decoded_data[j] = 0;
77   PetscFunctionReturn(0);
78 }
79 
80 #if defined(PETSC_HAVE_UNISTD_H)
81 #include <unistd.h>
82 #endif
83 
84 #undef __FUNCT__
85 #define __FUNCT__ "PetscGlobusAuthorize"
86 /*@C
87      PetscGlobusAuthorize - Get an access token allowing PETSc applications to make Globus file transfer requests
88 
89    Not collective, only the first process in MPI_Comm does anything
90 
91    Input Parameters:
92 +  comm - the MPI communicator
93 -  tokensize - size of the token array
94 
95    Output Parameters:
96 .  access_token - can be used with PetscGlobusUpLoad() for 30 days
97 
98    Notes: This call requires stdout and stdin access from process 0 on the MPI communicator
99 
100    You can run src/sys/webclient/examples/tutorials/globusobtainaccesstoken to get an access token
101 
102 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten(), PetscGlobusUpload()
103 
104 @*/
105 PetscErrorCode PetscGlobusAuthorize(MPI_Comm comm,char access_token[],size_t tokensize)
106 {
107   SSL_CTX        *ctx;
108   SSL            *ssl;
109   int            sock;
110   PetscErrorCode ierr;
111   char           buff[8*1024],*ptr,head[1024];
112   PetscMPIInt    rank;
113   size_t         len;
114   PetscBool      found;
115 
116   PetscFunctionBegin;
117   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
118   if (!rank) {
119     if (!isatty(fileno(PETSC_STDOUT))) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Requires users input/output");
120     ierr = PetscPrintf(comm,"Enter globus username:");CHKERRQ(ierr);
121     ptr  = fgets(buff, 1024, stdin);
122     if (!ptr) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
123     ierr = PetscStrlen(buff,&len);CHKERRQ(ierr);
124     buff[len-1] = ':'; /* remove carriage return at end of line */
125 
126     ierr = PetscPrintf(comm,"Enter globus password:");CHKERRQ(ierr);
127     ptr  = fgets(buff+len, 1024-len, stdin);
128     if (!ptr) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Error reading from stdin: %d", errno);
129     ierr = PetscStrlen(buff,&len);CHKERRQ(ierr);
130     buff[len-1] = '\0'; /* remove carriage return at end of line */
131     ierr = PetscStrcpy(head,"Authorization: Basic ");CHKERRQ(ierr);
132     ierr = base64_encode((const unsigned char*)buff,(unsigned char*)(head+21),sizeof(head)-21);CHKERRQ(ierr);
133     ierr = PetscStrcat(head,"\r\n");CHKERRQ(ierr);
134 
135     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
136     ierr = PetscHTTPSConnect("nexus.api.globusonline.org",443,ctx,&sock,&ssl);CHKERRQ(ierr);
137     ierr = PetscHTTPSRequest("GET","nexus.api.globusonline.org/goauth/token?grant_type=client_credentials",head,"application/x-www-form-urlencoded",NULL,ssl,buff,sizeof(buff));CHKERRQ(ierr);
138     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
139     close(sock);
140 
141     ierr   = PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);CHKERRQ(ierr);
142     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Globus did not return access token");
143 
144     ierr = PetscPrintf(comm,"Here is your Globus access token, save it in a save place, in the future you can run PETSc\n");CHKERRQ(ierr);
145     ierr = PetscPrintf(comm,"programs with the option -globus_access_token %s\n",access_token);CHKERRQ(ierr);
146     ierr = PetscPrintf(comm,"to access Globus automatically\n");CHKERRQ(ierr);
147   }
148   PetscFunctionReturn(0);
149 }
150 
151 
152 #undef __FUNCT__
153 #define __FUNCT__ "PetscGlobusGetTransfers"
154 /*@C
155      PetscGlobusGetTransfers - Get a record of current transfers requested from Globus
156 
157    Not collective, only the first process in MPI_Comm does anything
158 
159    Input Parameters:
160 +  comm - the MPI communicator
161 .  access_token - Globus access token, if NULL will check in options database for -globus_access_token XXX otherwise
162                   will call PetscGlobusAuthorize().
163 -  buffsize - size of the buffer
164 
165    Output Parameters:
166 .  buff - location to put Globus information
167 
168 .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten(), PetscGlobusUpload(), PetscGlobusAuthorize()
169 
170 @*/
171 PetscErrorCode PetscGlobusGetTransfers(MPI_Comm comm,const char access_token[],char buff[],size_t buffsize)
172 {
173   SSL_CTX        *ctx;
174   SSL            *ssl;
175   int            sock;
176   PetscErrorCode ierr;
177   char           head[4096];
178   PetscMPIInt    rank;
179 
180   PetscFunctionBegin;
181   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
182   if (!rank) {
183     ierr = PetscStrcpy(head,"Authorization : Globus-Goauthtoken ");CHKERRQ(ierr);
184     if (access_token) {
185       ierr = PetscStrcat(head,access_token);CHKERRQ(ierr);
186     } else {
187       PetscBool set;
188       char      accesstoken[4096];
189       ierr = PetscOptionsGetString(NULL,"-globus_access_token",accesstoken,sizeof(accesstoken),&set);CHKERRQ(ierr);
190       if (!set) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Pass in Globus accesstoken or use -globus_access_token XXX");
191       ierr = PetscStrcat(head,accesstoken);CHKERRQ(ierr);
192     }
193     ierr = PetscStrcat(head,"\r\n");CHKERRQ(ierr);
194 
195     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
196     ierr = PetscHTTPSConnect("transfer.api.globusonline.org",443,ctx,&sock,&ssl);CHKERRQ(ierr);
197     ierr = PetscHTTPSRequest("GET","transfer.api.globusonline.org/v0.10/tasksummary",head,"application/json",NULL,ssl,buff,buffsize);CHKERRQ(ierr);
198     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
199     close(sock);
200   }
201   PetscFunctionReturn(0);
202 }
203 
204 #undef __FUNCT__
205 #define __FUNCT__ "PetscGlobusUpload"
206 /*@C
207      PetscGlobusUpload - Loads a file to Globus
208 
209      Not collective, only the first process in the MPI_Comm uploads the file
210 
211   Input Parameters:
212 +   comm - MPI communicator
213 .   access_token - obtained with PetscGlobusAuthorize(), pass NULL to use -globus_access_token XXX from the PETSc database
214 -   filename - file to upload
215 
216   Options Database:
217 .  -globus_access_token   XXX
218 
219 .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveRefresh(), PetscGlobusAuthorize()
220 
221 @*/
222 PetscErrorCode PetscGlobusUpload(MPI_Comm comm,const char access_token[],const char filename[])
223 {
224   SSL_CTX        *ctx;
225   SSL            *ssl;
226   int            sock;
227   PetscErrorCode ierr;
228   char           head[4096],buff[8*1024],body[4096],submission_id[4096];
229   PetscMPIInt    rank;
230   PetscBool      flg,found;
231 
232   PetscFunctionBegin;
233   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
234   if (!rank) {
235     ierr = PetscTestFile(filename,'r',&flg);CHKERRQ(ierr);
236     if (!flg) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Unable to find file: %s",filename);
237 
238     ierr = PetscStrcpy(head,"Authorization : Globus-Goauthtoken ");CHKERRQ(ierr);
239     if (access_token) {
240       ierr = PetscStrcat(head,access_token);CHKERRQ(ierr);
241     } else {
242       PetscBool set;
243       char      accesstoken[4096];
244       ierr = PetscOptionsGetString(NULL,"-globus_access_token",accesstoken,sizeof(accesstoken),&set);CHKERRQ(ierr);
245       if (!set) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Pass in Globus accesstoken or use -globus_access_token XXX");
246       ierr = PetscStrcat(head,accesstoken);CHKERRQ(ierr);
247     }
248     ierr = PetscStrcat(head,"\r\n");CHKERRQ(ierr);
249 
250     /* Get Globus submission id */
251     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
252     ierr = PetscHTTPSConnect("transfer.api.globusonline.org",443,ctx,&sock,&ssl);CHKERRQ(ierr);
253     ierr = PetscHTTPSRequest("GET","transfer.api.globusonline.org/v0.10/submission_id",head,"application/json",NULL,ssl,buff,sizeof(buff));CHKERRQ(ierr);
254     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
255     close(sock);
256     ierr   = PetscPullJSONValue(buff,"value",submission_id,sizeof(submission_id),&found);CHKERRQ(ierr);
257     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Globus did not return submission id");
258 
259     /* build JSON body of transfer request */
260     ierr = PetscStrcpy(body,"{");CHKERRQ(ierr);
261     ierr = PetscPushJSONValue(body,"submission_id",submission_id,sizeof(body));CHKERRQ(ierr);                 ierr = PetscStrcat(body,",");CHKERRQ(ierr);
262     ierr = PetscPushJSONValue(body,"DATA_TYPE","transfer",sizeof(body));CHKERRQ(ierr);                        ierr = PetscStrcat(body,",");CHKERRQ(ierr);
263     ierr = PetscPushJSONValue(body,"sync_level","null",sizeof(body));CHKERRQ(ierr);                           ierr = PetscStrcat(body,",");CHKERRQ(ierr);
264     ierr = PetscPushJSONValue(body,"source_endpoint","barryfsmith#MacBookPro",sizeof(body));CHKERRQ(ierr);    ierr = PetscStrcat(body,",");CHKERRQ(ierr);
265     ierr = PetscPushJSONValue(body,"label","PETSc transfer label",sizeof(body));CHKERRQ(ierr);                ierr = PetscStrcat(body,",");CHKERRQ(ierr);
266     ierr = PetscPushJSONValue(body,"length","1",sizeof(body));CHKERRQ(ierr);                                  ierr = PetscStrcat(body,",");CHKERRQ(ierr);
267     ierr = PetscPushJSONValue(body,"destination_endpoint","mcs#home",sizeof(body));CHKERRQ(ierr);             ierr = PetscStrcat(body,",");CHKERRQ(ierr);
268 
269     ierr = PetscStrcat(body,"\"DATA\": [ {");CHKERRQ(ierr);
270     ierr = PetscPushJSONValue(body,"source_path","/~/FEM_GPU.pdf",sizeof(body));CHKERRQ(ierr);                ierr = PetscStrcat(body,",");CHKERRQ(ierr);
271     ierr = PetscPushJSONValue(body,"destination_path","/~/FEM_GPU.pdf",sizeof(body));CHKERRQ(ierr);           ierr = PetscStrcat(body,",");CHKERRQ(ierr);
272     ierr = PetscPushJSONValue(body,"verify_size","null",sizeof(body));CHKERRQ(ierr);                          ierr = PetscStrcat(body,",");CHKERRQ(ierr);
273     ierr = PetscPushJSONValue(body,"recursive","false",sizeof(body));CHKERRQ(ierr);                           ierr = PetscStrcat(body,",");CHKERRQ(ierr);
274     ierr = PetscPushJSONValue(body,"DATA_TYPE","transfer_item",sizeof(body));CHKERRQ(ierr);
275     ierr = PetscStrcat(body,"} ] }");CHKERRQ(ierr);
276 
277     ierr = PetscSSLInitializeContext(&ctx);CHKERRQ(ierr);
278     ierr = PetscHTTPSConnect("transfer.api.globusonline.org",443,ctx,&sock,&ssl);CHKERRQ(ierr);
279     ierr = PetscHTTPSRequest("POST","transfer.api.globusonline.org/v0.10/transfer",head,"application/json",body,ssl,buff,sizeof(buff));CHKERRQ(ierr);
280     ierr = PetscSSLDestroyContext(ctx);CHKERRQ(ierr);
281     close(sock);
282     ierr   = PetscPullJSONValue(buff,"code",submission_id,sizeof(submission_id),&found);CHKERRQ(ierr);
283     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Globus did not return code on transfer");
284     ierr = PetscStrcmp(submission_id,"Accepted",&found);CHKERRQ(ierr);
285     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB,"Globus did not accept transfer");
286   }
287   PetscFunctionReturn(0);
288 }
289 
290 
291