Actual source code: google.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 Google.

  9:    See -   https://stackoverflow.com/questions/4616553/using-oauth-in-free-open-source-software
 10:    Users can get their own application IDs - https://code.google.com/p/google-apps-manager/wiki/GettingAnOAuthConsoleKey

 12: */
 13: #define PETSC_GOOGLE_CLIENT_ID  "521429262559-i19i57eek8tnt9ftpp4p91rcl0bo9ag5.apps.googleusercontent.com"
 14: #define PETSC_GOOGLE_CLIENT_ST  "vOds_A71I3_S_aHMq_kZAI0t"
 15: #define PETSC_GOOGLE_API_KEY    "AIzaSyDRZsOcySpWVzsUvIBL2UG3J2tcg-MXbyk"

 17: /*@C
 18:      PetscGoogleDriveRefresh - Get a new authorization token for accessing Google drive from PETSc from a refresh token

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

 22:    Input Parameters:
 23: +   comm - MPI communicator
 24: .   refresh token - obtained with PetscGoogleDriveAuthorize(), if NULL PETSc will first look for one in the options data
 25:                     if not found it will call PetscGoogleDriveAuthorize()
 26: -   tokensize - size of the output string access_token

 28:    Output Parameter:
 29: .   access_token - token that can be passed to PetscGoogleDriveUpload()

 31:    Options Database:
 32: .  -google_refresh_token XXX - where XXX was obtained from PetscGoogleDriveAuthorize()

 34:    Level: intermediate

 36: .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveUpload()

 38: @*/
 39: PetscErrorCode PetscGoogleDriveRefresh(MPI_Comm comm,const char refresh_token[],char access_token[],size_t tokensize)
 40: {
 41:   SSL_CTX        *ctx;
 42:   SSL            *ssl;
 43:   int            sock;
 44:   char           buff[8*1024],body[1024];
 45:   PetscMPIInt    rank;
 46:   char           *refreshtoken = (char*)refresh_token;
 47:   PetscBool      found;

 49:   MPI_Comm_rank(comm,&rank);
 50:   if (rank == 0) {
 51:     if (!refresh_token) {
 52:       PetscBool set;
 53:       PetscMalloc1(512,&refreshtoken);
 54:       PetscOptionsGetString(NULL,NULL,"-google_refresh_token",refreshtoken,sizeof(refreshtoken),&set);
 55:       if (!set) {
 56:         PetscGoogleDriveAuthorize(comm,access_token,refreshtoken,512*sizeof(char));
 57:         PetscFree(refreshtoken);
 58:         return 0;
 59:       }
 60:     }
 61:     PetscSSLInitializeContext(&ctx);
 62:     PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);
 63:     PetscStrcpy(body,"client_id=");
 64:     PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);
 65:     PetscStrcat(body,"&client_secret=");
 66:     PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);
 67:     PetscStrcat(body,"&refresh_token=");
 68:     PetscStrcat(body,refreshtoken);
 69:     if (!refresh_token) PetscFree(refreshtoken);
 70:     PetscStrcat(body,"&grant_type=refresh_token");

 72:     PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));
 73:     PetscSSLDestroyContext(ctx);
 74:     close(sock);

 76:     PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);
 78:   }
 79:   return 0;
 80: }

 82: #include <sys/stat.h>

 84: /*@C
 85:      PetscGoogleDriveUpload - Loads a file to the Google Drive

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

 89:   Input Parameters:
 90: +   comm - MPI communicator
 91: .   access_token - obtained with PetscGoogleDriveRefresh(), pass NULL to have PETSc generate one
 92: -   filename - file to upload; if you upload multiple times it will have different names each time on Google Drive

 94:   Options Database:
 95: .  -google_refresh_token XXX - pass the access token for the operation

 97:   Usage Patterns:
 98:     With PETSc option -google_refresh_token  XXX given
 99:     PetscGoogleDriveUpload(comm,NULL,filename);        will upload file with no user interaction

101:     Without PETSc option -google_refresh_token XXX given
102:     PetscGoogleDriveUpload(comm,NULL,filename);        for first use will prompt user to authorize access to Google Drive with their browser

104:     With PETSc option -google_refresh_token  XXX given
105:     PetscGoogleDriveRefresh(comm,NULL,access_token,sizeof(access_token));
106:     PetscGoogleDriveUpload(comm,access_token,filename);

108:     With refresh token entered in some way by the user
109:     PetscGoogleDriveRefresh(comm,refresh_token,access_token,sizeof(access_token));
110:     PetscGoogleDriveUpload(comm,access_token,filename);

112:     PetscGoogleDriveAuthorize(comm,access_token,refresh_token,sizeof(access_token));
113:     PetscGoogleDriveUpload(comm,access_token,filename);

115:    Level: intermediate

117: .seealso: PetscURLShorten(), PetscGoogleDriveAuthorize(), PetscGoogleDriveRefresh()

119: @*/
120: PetscErrorCode PetscGoogleDriveUpload(MPI_Comm comm,const char access_token[],const char filename[])
121: {
122:   SSL_CTX        *ctx;
123:   SSL            *ssl;
124:   int            sock;
126:   char           head[1024],buff[8*1024],*body,*title;
127:   PetscMPIInt    rank;
128:   struct stat    sb;
129:   size_t         len,blen,rd;
130:   FILE           *fd;
131:   int            err;

133:   MPI_Comm_rank(comm,&rank);
134:   if (rank == 0) {
135:     PetscStrcpy(head,"Authorization: Bearer ");
136:     PetscStrcat(head,access_token);
137:     PetscStrcat(head,"\r\n");
138:     PetscStrcat(head,"uploadType: multipart\r\n");

140:     err = stat(filename,&sb);
142:     len = 1024 + sb.st_size;
143:     PetscMalloc1(len,&body);
144:     PetscStrcpy(body,"--foo_bar_baz\r\n"
145:                             "Content-Type: application/json\r\n\r\n"
146:                             "{");
147:     PetscPushJSONValue(body,"title",filename,len);
148:     PetscStrcat(body,",");
149:     PetscPushJSONValue(body,"mimeType","text.html",len);
150:     PetscStrcat(body,",");
151:     PetscPushJSONValue(body,"description","a file",len);
152:     PetscStrcat(body,"}\r\n\r\n"
153:                             "--foo_bar_baz\r\n"
154:                             "Content-Type: text/html\r\n\r\n");
155:     PetscStrlen(body,&blen);
156:     fd = fopen (filename, "r");
158:     rd = fread (body+blen, sizeof (unsigned char), sb.st_size, fd);
160:     fclose(fd);
161:     body[blen + rd] = 0;
162:     PetscStrcat(body,"\r\n\r\n"
163:                             "--foo_bar_baz\r\n");
164:     PetscSSLInitializeContext(&ctx);
165:     PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);
166:     PetscHTTPSRequest("POST","www.googleapis.com/upload/drive/v2/files/",head,"multipart/related; boundary=\"foo_bar_baz\"",body,ssl,buff,sizeof(buff));
167:     PetscFree(body);
168:     PetscSSLDestroyContext(ctx);
169:     close(sock);
170:     PetscStrstr(buff,"\"title\"",&title);
172:   }
173:   return 0;
174: }

176: #if defined(PETSC_HAVE_UNISTD_H)
177: #include <unistd.h>
178: #endif

180: /*@C
181:      PetscGoogleDriveAuthorize - Get authorization and refresh token for accessing Google drive from PETSc

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

185:    Input Parameters:
186: +  comm - the MPI communicator
187: -  tokensize - size of the token arrays

189:    Output Parameters:
190: +  access_token - can be used with PetscGoogleDriveUpload() for this one session
191: -  refresh_token - can be used for ever to obtain new access_tokens with PetscGoogleDriveRefresh(), guard this like a password
192:                    it gives access to your Google Drive

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

197:    You can run src/sys/webclient/tutorials/googleobtainrefreshtoken to get a refresh token and then in the future pass it to
198:    PETSc programs with -google_refresh_token XXX

200:    Level: intermediate

202: .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscURLShorten()

204: @*/
205: PetscErrorCode PetscGoogleDriveAuthorize(MPI_Comm comm,char access_token[],char refresh_token[],size_t tokensize)
206: {
207:   SSL_CTX        *ctx;
208:   SSL            *ssl;
209:   int            sock;
211:   char           buff[8*1024],*ptr,body[1024];
212:   PetscMPIInt    rank;
213:   size_t         len;
214:   PetscBool      found;

216:   MPI_Comm_rank(comm,&rank);
217:   if (rank == 0) {
219:     PetscPrintf(comm,"Cut and paste the following into your browser:\n\n"
220:                             "https://accounts.google.com/o/oauth2/auth?"
221:                             "scope=https%%3A%%2F%%2Fwww.googleapis.com%%2Fauth%%2Fdrive.file&"
222:                             "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
223:                             "response_type=code&"
224:                             "client_id="
225:                             PETSC_GOOGLE_CLIENT_ID
226:                             "\n\n");
227:     PetscPrintf(comm,"Paste the result here:");
228:     ptr  = fgets(buff, 1024, stdin);
230:     PetscStrlen(buff,&len);
231:     buff[len-1] = 0; /* remove carriage return at end of line */

233:     PetscSSLInitializeContext(&ctx);
234:     PetscHTTPSConnect("accounts.google.com",443,ctx,&sock,&ssl);
235:     PetscStrcpy(body,"code=");
236:     PetscStrcat(body,buff);
237:     PetscStrcat(body,"&client_id=");
238:     PetscStrcat(body,PETSC_GOOGLE_CLIENT_ID);
239:     PetscStrcat(body,"&client_secret=");
240:     PetscStrcat(body,PETSC_GOOGLE_CLIENT_ST);
241:     PetscStrcat(body,"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&");
242:     PetscStrcat(body,"grant_type=authorization_code");

244:     PetscHTTPSRequest("POST","accounts.google.com/o/oauth2/token",NULL,"application/x-www-form-urlencoded",body,ssl,buff,sizeof(buff));
245:     PetscSSLDestroyContext(ctx);
246:     close(sock);

248:     PetscPullJSONValue(buff,"access_token",access_token,tokensize,&found);
250:     PetscPullJSONValue(buff,"refresh_token",refresh_token,tokensize,&found);

253:     PetscPrintf(comm,"Here is your Google refresh token, save it in a save place, in the future you can run PETSc\n");
254:     PetscPrintf(comm,"programs with the option -google_refresh_token %s\n",refresh_token);
255:     PetscPrintf(comm,"to access Google Drive automatically\n");
256:   }
257:   return 0;
258: }

260: /*@C
261:      PetscURLShorten - Uses Google's service to get a short url for a long url

263:     Input Parameters:
264: +    url - long URL you want shortened
265: -    lenshorturl - length of buffer to contain short URL

267:     Output Parameter:
268: .    shorturl - the shortened URL

270:    Level: intermediate

272: .seealso: PetscGoogleDriveRefresh(), PetscGoogleDriveUpload(), PetscGoogleDriveAuthorize()
273: @*/
274: PetscErrorCode PetscURLShorten(const char url[],char shorturl[],size_t lenshorturl)
275: {
276:   SSL_CTX        *ctx;
277:   SSL            *ssl;
278:   int            sock;
279:   char           buff[1024],body[512],post[1024];
280:   PetscBool      found;

282:   PetscSSLInitializeContext(&ctx);
283:   PetscHTTPSConnect("www.googleapis.com",443,ctx,&sock,&ssl);
284:   PetscStrcpy(body,"{");
285:   PetscPushJSONValue(body,"longUrl",url,sizeof(body)-2);
286:   PetscStrcat(body,"}");
287:   PetscSNPrintf(post,sizeof(post),"www.googleapis.com/urlshortener/v1/url?key=%s",PETSC_GOOGLE_API_KEY);
288:   PetscHTTPSRequest("POST",post,NULL,"application/json",body,ssl,buff,sizeof(buff));
289:   PetscSSLDestroyContext(ctx);
290:   close(sock);

292:   PetscPullJSONValue(buff,"id",shorturl,lenshorturl,&found);
294:   return 0;
295: }