Actual source code: box.c


  2: #include <petscwebclient.h>
  3: #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  4: #pragma gcc diagnostic ignored "-Wdeprecated-declarations"

  6: /*
  7:    These variables identify the code as a PETSc application to Box.

  9:    See -   https://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
 10:    Users can get their own application IDs - goto https://developer.box.com

 12: */
 13: #define PETSC_BOX_CLIENT_ID  "sse42nygt4zqgrdwi0luv79q1u1f0xza"
 14: #define PETSC_BOX_CLIENT_ST  "A0Dy4KgOYLB2JIYZqpbze4EzjeIiX5k4"

 16: #if defined(PETSC_HAVE_SAWS)
 17: #include <mongoose.h>

 19: static volatile char *result = NULL;

 21: static int PetscBoxWebServer_Private(struct mg_connection *conn)
 22: {
 23:   const struct mg_request_info *request_info = mg_get_request_info(conn);
 24:   result = (char*) request_info->query_string;
 25:   return 1;  /* Mongoose will now not handle the request */
 26: }

 28: /*
 29:     Box can only return an authorization code to a Webserver, hence we need to start one up and wait for
 30:     the authorization code to arrive from Box
 31: */
 32: static PetscErrorCode PetscBoxStartWebServer_Private(void)
 33: {
 34:   int                 optionsLen = 5;
 35:   const char          *options[optionsLen];
 36:   struct mg_callbacks callbacks;
 37:   struct mg_context   *ctx;
 38:   char                keyfile[PETSC_MAX_PATH_LEN];
 39:   PetscBool           exists;

 41:   options[0] = "listening_ports";
 42:   options[1] = "8081s";

 44:   PetscStrcpy(keyfile,"sslclient.pem");
 45:   PetscTestFile(keyfile,'r',&exists);
 46:   if (!exists) {
 47:     PetscGetHomeDirectory(keyfile,PETSC_MAX_PATH_LEN);
 48:     PetscStrcat(keyfile,"/");
 49:     PetscStrcat(keyfile,"sslclient.pem");
 50:     PetscTestFile(keyfile,'r',&exists);
 52:   }

 54:   options[2] = "ssl_certificate";
 55:   options[3] = keyfile;
 56:   options[4] = NULL;

 58:   /* Prepare callbacks structure. We have only one callback, the rest are NULL. */
 59:   PetscMemzero(&callbacks, sizeof(callbacks));
 60:   callbacks.begin_request = PetscBoxWebServer_Private;
 61:   ctx = mg_start(&callbacks, NULL, options);
 63:   while (!result) {};
 64:   return 0;
 65: }

 67: #if defined(PETSC_HAVE_UNISTD_H)
 68: #include <unistd.h>
 69: #endif

 71: /*@C
 72:      PetscBoxAuthorize - Get authorization and refresh token for accessing Box drive from PETSc

 74:    Not collective, only the first process in MPI_Comm does anything

 76:    Input Parameters:
 77: +  comm - the MPI communicator
 78: -  tokensize - size of the token arrays

 80:    Output Parameters:
 81: +  access_token - can be used with PetscBoxUpload() for this one session
 82: -  refresh_token - can be used for ever to obtain new access_tokens with PetscBoxRefresh(), guard this like a password
 83:                    it gives access to your Box Drive

 85:    Notes:
 86:     This call requires stdout and stdin access from process 0 on the MPI communicator

 88:    You can run src/sys/webclient/tutorials/boxobtainrefreshtoken to get a refresh token and then in the future pass it to
 89:    PETSc programs with -box_refresh_token XXX

 91:    This requires PETSc be installed using --with-saws or --download-saws

 93:    Requires the user have created a self-signed ssl certificate with

 95: $    saws/CA.pl  -newcert  (using the passphrase of password)
 96: $    cat newkey.pem newcert.pem > sslclient.pem

 98:     and put the resulting file in either the current directory (with the application) or in the home directory. This seems kind of
 99:     silly but it was all I could figure out.

101:    Level: intermediate

103: .seealso: PetscBoxRefresh(), PetscBoxUpload(), PetscURLShorten()

105: @*/
106: PetscErrorCode PetscBoxAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
107: {
108:   SSL_CTX        *ctx;
109:   SSL            *ssl;
110:   int            sock;
112:   char           buff[8*1024],body[1024];
113:   PetscMPIInt    rank;
114:   PetscBool      flg,found;

116:   MPI_Comm_rank(comm,&rank);
117:   if (rank == 0) {
119:     PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
120:                             "https://www.box.com/api/oauth2/authorize?"
121:                             "response_type=code&"
122:                             "client_id="
123:                             PETSC_BOX_CLIENT_ID
124:                             "&state=PETScState"
125:                             "\n\n");
126:     PetscBoxStartWebServer_Private();
127:     PetscStrbeginswith((const char*)result,"state=PETScState&code=",&flg);
129:     PetscStrncpy(buff,(const char*)result+22,sizeof(buff));

131:     PetscSSLInitializeContext(&ctx);
132:     PetscHTTPSConnect("www.box.com",443,ctx,&sock,&ssl);
133:     PetscStrcpy(body,"code=");
134:     PetscStrcat(body,buff);
135:     PetscStrcat(body,"&client_id=");
136:     PetscStrcat(body,PETSC_BOX_CLIENT_ID);
137:     PetscStrcat(body,"&client_secret=");
138:     PetscStrcat(body,PETSC_BOX_CLIENT_ST);
139:     PetscStrcat(body,"&grant_type=authorization_code");

141:     PetscHTTPSRequest("POST","www.box.com/api/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));
142:     PetscSSLDestroyContext(ctx);
143:     close(sock);

145:     PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);
147:     PetscPullJSONValue(buff,"refresh_token",refresh_token,tokensize,&found);

150:     PetscPrintf(comm,"Here is your Box refresh token, save it in a save place, in the future you can run PETSc\n");
151:     PetscPrintf(comm,"programs with the option -box_refresh_token %s\n",refresh_token);
152:     PetscPrintf(comm,"to access Box Drive automatically\n");
153:   }
154:   return 0;
155: }
156: #endif

158: /*@C
159:      PetscBoxRefresh - Get a new authorization token for accessing Box drive from PETSc from a refresh token

161:    Not collective, only the first process in the MPI_Comm does anything

163:    Input Parameters:
164: +   comm - MPI communicator
165: .   refresh token - obtained with PetscBoxAuthorize(), if NULL PETSc will first look for one in the options data
166:                     if not found it will call PetscBoxAuthorize()
167: -   tokensize - size of the output string access_token

169:    Output Parameters:
170: +   access_token - token that can be passed to PetscBoxUpload()
171: -   new_refresh_token - the old refresh token is no longer valid, not this is different than Google where the same refresh_token is used forever

173:    Level: intermediate

175: .seealso: PetscURLShorten(), PetscBoxAuthorize(), PetscBoxUpload()

177: @*/
178: PetscErrorCode PetscBoxRefresh(MPI_Comm comm,const char refresh_token[],char access_token[],char new_refresh_token[],size_t tokensize)
179: {
180:   SSL_CTX        *ctx;
181:   SSL            *ssl;
182:   int            sock;
183:   char           buff[8*1024],body[1024];
184:   PetscMPIInt    rank;
185:   char           *refreshtoken = (char*)refresh_token;
186:   PetscBool      found;

188:   MPI_Comm_rank(comm,&rank);
189:   if (rank == 0) {
190:     if (!refresh_token) {
191:       PetscBool set;
192:       PetscMalloc1(512,&refreshtoken);
193:       PetscOptionsGetString(NULL,NULL,"-box_refresh_token",refreshtoken,sizeof(refreshtoken),&set);
194: #if defined(PETSC_HAVE_SAWS)
195:       if (!set) {
196:         PetscBoxAuthorize(comm,access_token,new_refresh_token,512*sizeof(char));
197:         PetscFree(refreshtoken);
198:         return 0;
199:       }
200: #else
202: #endif
203:     }
204:     PetscSSLInitializeContext(&ctx);
205:     PetscHTTPSConnect("www.box.com",443,ctx,&sock,&ssl);
206:     PetscStrcpy(body,"client_id=");
207:     PetscStrcat(body,PETSC_BOX_CLIENT_ID);
208:     PetscStrcat(body,"&client_secret=");
209:     PetscStrcat(body,PETSC_BOX_CLIENT_ST);
210:     PetscStrcat(body,"&refresh_token=");
211:     PetscStrcat(body,refreshtoken);
212:     if (!refresh_token) PetscFree(refreshtoken);
213:     PetscStrcat(body,"&grant_type=refresh_token");

215:     PetscHTTPSRequest("POST","www.box.com/api/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));
216:     PetscSSLDestroyContext(ctx);
217:     close(sock);

219:     PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);
221:     PetscPullJSONValue(buff,"refresh_token",new_refresh_token,tokensize,&found);

224:     PetscPrintf(comm,"Here is your new Box refresh token, save it in a save place, in the future you can run PETSc\n");
225:     PetscPrintf(comm,"programs with the option -box_refresh_token %s\n",new_refresh_token);
226:     PetscPrintf(comm,"to access Box Drive automatically\n");
227:   }
228:   return 0;
229: }

231: #include <sys/stat.h>

233: /*@C
234:      PetscBoxUpload - Loads a file to the Box Drive

236:      This routine has not yet been written; it is just copied from Google Drive

238:      Not collective, only the first process in the MPI_Comm uploads the file

240:   Input Parameters:
241: +   comm - MPI communicator
242: .   access_token - obtained with PetscBoxRefresh(), pass NULL to have PETSc generate one
243: -   filename - file to upload; if you upload multiple times it will have different names each time on Box Drive

245:   Options Database:
246: .  -box_refresh_token XXX - the token value

248:   Usage Patterns:
249:     With PETSc option -box_refresh_token XXX given
250:     PetscBoxUpload(comm,NULL,filename);        will upload file with no user interaction

252:     Without PETSc option -box_refresh_token XXX given
253:     PetscBoxUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Box Drive with their processor

255:     With PETSc option -box_refresh_token  XXX given
256:     PetscBoxRefresh(comm,NULL,access_token,sizeof(access_token));
257:     PetscBoxUpload(comm,access_token,filename);

259:     With refresh token entered in some way by the user
260:     PetscBoxRefresh(comm,refresh_token,access_token,sizeof(access_token));
261:     PetscBoxUpload(comm,access_token,filename);

263:     PetscBoxAuthorize(comm,access_token,refresh_token,sizeof(access_token));
264:     PetscBoxUpload(comm,access_token,filename);

266:    Level: intermediate

268: .seealso: PetscURLShorten(), PetscBoxAuthorize(), PetscBoxRefresh()

270: @*/
271: PetscErrorCode PetscBoxUpload(MPI_Comm comm,const char access_token[],const char filename[])
272: {
273:   SSL_CTX        *ctx;
274:   SSL            *ssl;
275:   int            sock;
277:   char           head[1024],buff[8*1024],*body,*title;
278:   PetscMPIInt    rank;
279:   struct stat    sb;
280:   size_t         len,blen,rd;
281:   FILE           *fd;
282:   int            err;

284:   MPI_Comm_rank(comm,&rank);
285:   if (rank == 0) {
286:     PetscStrcpy(head,"Authorization: Bearer ");
287:     PetscStrcat(head,access_token);
288:     PetscStrcat(head,"\r\n");
289:     PetscStrcat(head,"uploadType: multipart\r\n");

291:     err = stat(filename,&sb);
293:     len = 1024 + sb.st_size;
294:     PetscMalloc1(len,&body);
295:     PetscStrcpy(body,"--foo_bar_baz\r\n"
296:                             "Content-Type: application/json\r\n\r\n"
297:                             "{");
298:     PetscPushJSONValue(body,"title",filename,len);
299:     PetscStrcat(body,",");
300:     PetscPushJSONValue(body,"mimeType","text.html",len);
301:     PetscStrcat(body,",");
302:     PetscPushJSONValue(body,"description","a file",len);
303:     PetscStrcat(body, "}\r\n\r\n"
304:                              "--foo_bar_baz\r\n"
305:                              "Content-Type: text/html\r\n\r\n");
306:     PetscStrlen(body,&blen);
307:     fd = fopen (filename, "r");
309:     rd = fread (body+blen, sizeof (unsigned char), sb.st_size, fd);
311:     fclose(fd);
312:     body[blen + rd] = 0;
313:     PetscStrcat(body,"\r\n\r\n"
314:                             "--foo_bar_baz\r\n");
315:     PetscSSLInitializeContext(&ctx);
316:     PetscHTTPSConnect("www.boxapis.com",443,ctx,&sock,&ssl);
317:     PetscHTTPSRequest("POST","www.boxapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff));
318:     PetscFree(body);
319:     PetscSSLDestroyContext(ctx);
320:     close(sock);
321:     PetscStrstr(buff,"\"title\"",&title);
323:   }
324:   return 0;
325: }