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 rank 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()`
104: @*/
105: PetscErrorCode PetscBoxAuthorize(MPI_Comm comm, char access_token[], char refresh_token[], size_t tokensize)
106: {
107: SSL_CTX *ctx;
108: SSL *ssl;
109: int sock;
110: char buff[8 * 1024], body[1024];
111: PetscMPIInt rank;
112: PetscBool flg, found;
114: MPI_Comm_rank(comm, &rank);
115: if (rank == 0) {
117: PetscCall(PetscPrintf(comm, "Cut and paste the following into your browser:\n\n"
118: "https://www.box.com/api/oauth2/authorize?"
119: "response_type=code&"
120: "client_id=" PETSC_BOX_CLIENT_ID "&state=PETScState"
121: "\n\n"));
122: PetscBoxStartWebServer_Private();
123: PetscStrbeginswith((const char *)result, "state=PETScState&code=", &flg);
125: PetscStrncpy(buff, (const char *)result + 22, sizeof(buff));
127: PetscSSLInitializeContext(&ctx);
128: PetscHTTPSConnect("www.box.com", 443, ctx, &sock, &ssl);
129: PetscStrcpy(body, "code=");
130: PetscStrcat(body, buff);
131: PetscStrcat(body, "&client_id=");
132: PetscStrcat(body, PETSC_BOX_CLIENT_ID);
133: PetscStrcat(body, "&client_secret=");
134: PetscStrcat(body, PETSC_BOX_CLIENT_ST);
135: PetscStrcat(body, "&grant_type=authorization_code");
137: PetscHTTPSRequest("POST", "www.box.com/api/oauth2/token", NULL, "application/x-www-form-urlencoded", body, ssl, buff, sizeof(buff));
138: PetscSSLDestroyContext(ctx);
139: close(sock);
141: PetscPullJSONValue(buff, "access_token", access_token, tokensize, &found);
143: PetscPullJSONValue(buff, "refresh_token", refresh_token, tokensize, &found);
146: PetscPrintf(comm, "Here is your Box refresh token, save it in a save place, in the future you can run PETSc\n");
147: PetscPrintf(comm, "programs with the option -box_refresh_token %s\n", refresh_token);
148: PetscPrintf(comm, "to access Box Drive automatically\n");
149: }
150: return 0;
151: }
152: #endif
154: /*@C
155: PetscBoxRefresh - Get a new authorization token for accessing Box drive from PETSc from a refresh token
157: Not collective, only the first process in the `MPI_Comm` does anything
159: Input Parameters:
160: + comm - MPI communicator
161: . refresh token - obtained with `PetscBoxAuthorize()`, if NULL PETSc will first look for one in the options data
162: if not found it will call `PetscBoxAuthorize()`
163: - tokensize - size of the output string access_token
165: Output Parameters:
166: + access_token - token that can be passed to `PetscBoxUpload()`
167: - 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
169: Level: intermediate
171: .seealso: `PetscURLShorten()`, `PetscBoxAuthorize()`, `PetscBoxUpload()`
172: @*/
173: PetscErrorCode PetscBoxRefresh(MPI_Comm comm, const char refresh_token[], char access_token[], char new_refresh_token[], size_t tokensize)
174: {
175: SSL_CTX *ctx;
176: SSL *ssl;
177: int sock;
178: char buff[8 * 1024], body[1024];
179: PetscMPIInt rank;
180: char *refreshtoken = (char *)refresh_token;
181: PetscBool found;
183: MPI_Comm_rank(comm, &rank);
184: if (rank == 0) {
185: if (!refresh_token) {
186: PetscBool set;
187: PetscMalloc1(512, &refreshtoken);
188: PetscOptionsGetString(NULL, NULL, "-box_refresh_token", refreshtoken, sizeof(refreshtoken), &set);
189: #if defined(PETSC_HAVE_SAWS)
190: if (!set) {
191: PetscBoxAuthorize(comm, access_token, new_refresh_token, 512 * sizeof(char));
192: PetscFree(refreshtoken);
193: return 0;
194: }
195: #else
197: #endif
198: }
199: PetscSSLInitializeContext(&ctx);
200: PetscHTTPSConnect("www.box.com", 443, ctx, &sock, &ssl);
201: PetscStrcpy(body, "client_id=");
202: PetscStrcat(body, PETSC_BOX_CLIENT_ID);
203: PetscStrcat(body, "&client_secret=");
204: PetscStrcat(body, PETSC_BOX_CLIENT_ST);
205: PetscStrcat(body, "&refresh_token=");
206: PetscStrcat(body, refreshtoken);
207: if (!refresh_token) PetscFree(refreshtoken);
208: PetscStrcat(body, "&grant_type=refresh_token");
210: PetscHTTPSRequest("POST", "www.box.com/api/oauth2/token", NULL, "application/x-www-form-urlencoded", body, ssl, buff, sizeof(buff));
211: PetscSSLDestroyContext(ctx);
212: close(sock);
214: PetscPullJSONValue(buff, "access_token", access_token, tokensize, &found);
216: PetscPullJSONValue(buff, "refresh_token", new_refresh_token, tokensize, &found);
219: PetscPrintf(comm, "Here is your new Box refresh token, save it in a save place, in the future you can run PETSc\n");
220: PetscPrintf(comm, "programs with the option -box_refresh_token %s\n", new_refresh_token);
221: PetscPrintf(comm, "to access Box Drive automatically\n");
222: }
223: return 0;
224: }
226: #include <sys/stat.h>
228: /*@C
229: PetscBoxUpload - Loads a file to the Box Drive
231: This routine has not yet been written; it is just copied from Google Drive
233: Not collective, only the first process in the `MPI_Comm` uploads the file
235: Input Parameters:
236: + comm - MPI communicator
237: . access_token - obtained with `PetscBoxRefresh()`, pass NULL to have PETSc generate one
238: - filename - file to upload; if you upload multiple times it will have different names each time on Box Drive
240: Options Database Key:
241: . -box_refresh_token XXX - the token value
243: Usage Patterns:
244: .vb
245: With PETSc option -box_refresh_token XXX given
246: PetscBoxUpload(comm,NULL,filename); will upload file with no user interaction
248: Without PETSc option -box_refresh_token XXX given
249: PetscBoxUpload(comm,NULL,filename); for first use will prompt user to authorize access to Box Drive with their processor
251: With PETSc option -box_refresh_token XXX given
252: PetscBoxRefresh(comm,NULL,access_token,sizeof(access_token));
253: PetscBoxUpload(comm,access_token,filename);
255: With refresh token entered in some way by the user
256: PetscBoxRefresh(comm,refresh_token,access_token,sizeof(access_token));
257: PetscBoxUpload(comm,access_token,filename);
259: PetscBoxAuthorize(comm,access_token,refresh_token,sizeof(access_token));
260: PetscBoxUpload(comm,access_token,filename);
261: .ve
263: Level: intermediate
265: .seealso: `PetscURLShorten()`, `PetscBoxAuthorize()`, `PetscBoxRefresh()`
266: @*/
267: PetscErrorCode PetscBoxUpload(MPI_Comm comm, const char access_token[], const char filename[])
268: {
269: SSL_CTX *ctx;
270: SSL *ssl;
271: int sock;
272: char head[1024], buff[8 * 1024], *body, *title;
273: PetscMPIInt rank;
274: struct stat sb;
275: size_t len, blen, rd;
276: FILE *fd;
277: int err;
279: MPI_Comm_rank(comm, &rank);
280: if (rank == 0) {
281: PetscStrcpy(head, "Authorization: Bearer ");
282: PetscStrcat(head, access_token);
283: PetscStrcat(head, "\r\n");
284: PetscStrcat(head, "uploadType: multipart\r\n");
286: err = stat(filename, &sb);
288: len = 1024 + sb.st_size;
289: PetscMalloc1(len, &body);
290: PetscCall(PetscStrcpy(body, "--foo_bar_baz\r\n"
291: "Content-Type: application/json\r\n\r\n"
292: "{"));
293: PetscPushJSONValue(body, "title", filename, len);
294: PetscStrcat(body, ",");
295: PetscPushJSONValue(body, "mimeType", "text.html", len);
296: PetscStrcat(body, ",");
297: PetscPushJSONValue(body, "description", "a file", len);
298: PetscCall(PetscStrcat(body, "}\r\n\r\n"
299: "--foo_bar_baz\r\n"
300: "Content-Type: text/html\r\n\r\n"));
301: PetscStrlen(body, &blen);
302: fd = fopen(filename, "r");
304: rd = fread(body + blen, sizeof(unsigned char), sb.st_size, fd);
306: fclose(fd);
307: body[blen + rd] = 0;
308: PetscCall(PetscStrcat(body, "\r\n\r\n"
309: "--foo_bar_baz\r\n"));
310: PetscSSLInitializeContext(&ctx);
311: PetscHTTPSConnect("www.boxapis.com", 443, ctx, &sock, &ssl);
312: PetscHTTPSRequest("POST", "www.boxapis.com/upload/drive/v2/files/", head, "multipart/related; boundary=\"foo_bar_baz\"", body, ssl, buff, sizeof(buff));
313: PetscFree(body);
314: PetscSSLDestroyContext(ctx);
315: close(sock);
316: PetscStrstr(buff, "\"title\"", &title);
318: }
319: return 0;
320: }