s3.c 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040
  1. /** **************************************************************************
  2. * s3.c
  3. *
  4. * Copyright 2008 Bryan Ischo <[email protected]>
  5. *
  6. * This file is part of libs3.
  7. *
  8. * libs3 is free software: you can redistribute it and/or modify it under the
  9. * terms of the GNU Lesser General Public License as published by the Free
  10. * Software Foundation, version 3 of the License.
  11. *
  12. * In addition, as a special exception, the copyright holders give
  13. * permission to link the code of this library and its programs with the
  14. * OpenSSL library, and distribute linked combinations including the two.
  15. *
  16. * libs3 is distributed in the hope that it will be useful, but WITHOUT ANY
  17. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  18. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  19. * details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public License
  22. * version 3 along with libs3, in a file named COPYING. If not, see
  23. * <https://www.gnu.org/licenses/>.
  24. *
  25. ************************************************************************** **/
  26. /**
  27. * This is a 'driver' program that simply converts command-line input into
  28. * calls to libs3 functions, and prints the results.
  29. **/
  30. #define _XOPEN_SOURCE 600
  31. #include <ctype.h>
  32. #include <getopt.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <strings.h>
  37. #include <sys/stat.h>
  38. #include <sys/types.h>
  39. #include <time.h>
  40. #include <unistd.h>
  41. #include "libs3.h"
  42. // Some Windows stuff
  43. #ifndef FOPEN_EXTRA_FLAGS
  44. #define FOPEN_EXTRA_FLAGS ""
  45. #endif
  46. // Some Unix stuff (to work around Windows issues)
  47. #ifndef SLEEP_UNITS_PER_SECOND
  48. #define SLEEP_UNITS_PER_SECOND 1
  49. #endif
  50. // Also needed for Windows, because somehow MinGW doesn't define this
  51. extern int putenv(char *);
  52. // Command-line options, saved as globals ------------------------------------
  53. static int forceG = 0;
  54. static int showResponsePropertiesG = 0;
  55. static S3Protocol protocolG = S3ProtocolHTTPS;
  56. static S3UriStyle uriStyleG = S3UriStylePath;
  57. static int retriesG = 5;
  58. static int timeoutMsG = 0;
  59. static int verifyPeerG = 0;
  60. static const char *awsRegionG = NULL;
  61. // Environment variables, saved as globals ----------------------------------
  62. static const char *accessKeyIdG = 0;
  63. static const char *secretAccessKeyG = 0;
  64. // Request results, saved as globals -----------------------------------------
  65. static int statusG = 0;
  66. static char errorDetailsG[4096] = { 0 };
  67. // Other globals -------------------------------------------------------------
  68. static char putenvBufG[256];
  69. // Option prefixes -----------------------------------------------------------
  70. #define LOCATION_PREFIX "location="
  71. #define LOCATION_PREFIX_LEN (sizeof(LOCATION_PREFIX) - 1)
  72. #define CANNED_ACL_PREFIX "cannedAcl="
  73. #define CANNED_ACL_PREFIX_LEN (sizeof(CANNED_ACL_PREFIX) - 1)
  74. #define PREFIX_PREFIX "prefix="
  75. #define PREFIX_PREFIX_LEN (sizeof(PREFIX_PREFIX) - 1)
  76. #define MARKER_PREFIX "marker="
  77. #define MARKER_PREFIX_LEN (sizeof(MARKER_PREFIX) - 1)
  78. #define DELIMITER_PREFIX "delimiter="
  79. #define DELIMITER_PREFIX_LEN (sizeof(DELIMITER_PREFIX) - 1)
  80. #define ENCODING_TYPE_PREFIX "encoding-type="
  81. #define ENCODING_TYPE_PREFIX_LEN (sizeof(ENCODING_TYPE_PREFIX) - 1)
  82. #define MAX_UPLOADS_PREFIX "max-uploads="
  83. #define MAX_UPLOADS_PREFIX_LEN (sizeof(MAX_UPLOADS_PREFIX) - 1)
  84. #define KEY_MARKER_PREFIX "key-marker="
  85. #define KEY_MARKER_PREFIX_LEN (sizeof(KEY_MARKER_PREFIX) - 1)
  86. #define UPLOAD_ID_PREFIX "upload-id="
  87. #define UPLOAD_ID_PREFIX_LEN (sizeof(UPLOAD_ID_PREFIX) - 1)
  88. #define MAX_PARTS_PREFIX "max-parts="
  89. #define MAX_PARTS_PREFIX_LEN (sizeof(MAX_PARTS_PREFIX) - 1)
  90. #define PART_NUMBER_MARKER_PREFIX "part-number-marker="
  91. #define PART_NUMBER_MARKER_PREFIX_LEN (sizeof(PART_NUMBER_MARKER_PREFIX) - 1)
  92. #define UPLOAD_ID_MARKER_PREFIX "upload-id-marker="
  93. #define UPLOAD_ID_MARKER_PREFIX_LEN (sizeof(UPLOAD_ID_MARKER_PREFIX) - 1)
  94. #define MAXKEYS_PREFIX "maxkeys="
  95. #define MAXKEYS_PREFIX_LEN (sizeof(MAXKEYS_PREFIX) - 1)
  96. #define FILENAME_PREFIX "filename="
  97. #define FILENAME_PREFIX_LEN (sizeof(FILENAME_PREFIX) - 1)
  98. #define CONTENT_LENGTH_PREFIX "contentLength="
  99. #define CONTENT_LENGTH_PREFIX_LEN (sizeof(CONTENT_LENGTH_PREFIX) - 1)
  100. #define CACHE_CONTROL_PREFIX "cacheControl="
  101. #define CACHE_CONTROL_PREFIX_LEN (sizeof(CACHE_CONTROL_PREFIX) - 1)
  102. #define CONTENT_TYPE_PREFIX "contentType="
  103. #define CONTENT_TYPE_PREFIX_LEN (sizeof(CONTENT_TYPE_PREFIX) - 1)
  104. #define MD5_PREFIX "md5="
  105. #define MD5_PREFIX_LEN (sizeof(MD5_PREFIX) - 1)
  106. #define CONTENT_DISPOSITION_FILENAME_PREFIX "contentDispositionFilename="
  107. #define CONTENT_DISPOSITION_FILENAME_PREFIX_LEN \
  108. (sizeof(CONTENT_DISPOSITION_FILENAME_PREFIX) - 1)
  109. #define CONTENT_ENCODING_PREFIX "contentEncoding="
  110. #define CONTENT_ENCODING_PREFIX_LEN (sizeof(CONTENT_ENCODING_PREFIX) - 1)
  111. #define EXPIRES_PREFIX "expires="
  112. #define EXPIRES_PREFIX_LEN (sizeof(EXPIRES_PREFIX) - 1)
  113. #define X_AMZ_META_PREFIX "x-amz-meta-"
  114. #define X_AMZ_META_PREFIX_LEN (sizeof(X_AMZ_META_PREFIX) - 1)
  115. #define USE_SERVER_SIDE_ENCRYPTION_PREFIX "useServerSideEncryption="
  116. #define USE_SERVER_SIDE_ENCRYPTION_PREFIX_LEN \
  117. (sizeof(USE_SERVER_SIDE_ENCRYPTION_PREFIX) - 1)
  118. #define IF_MODIFIED_SINCE_PREFIX "ifModifiedSince="
  119. #define IF_MODIFIED_SINCE_PREFIX_LEN (sizeof(IF_MODIFIED_SINCE_PREFIX) - 1)
  120. #define IF_NOT_MODIFIED_SINCE_PREFIX "ifNotmodifiedSince="
  121. #define IF_NOT_MODIFIED_SINCE_PREFIX_LEN \
  122. (sizeof(IF_NOT_MODIFIED_SINCE_PREFIX) - 1)
  123. #define IF_MATCH_PREFIX "ifMatch="
  124. #define IF_MATCH_PREFIX_LEN (sizeof(IF_MATCH_PREFIX) - 1)
  125. #define IF_NOT_MATCH_PREFIX "ifNotMatch="
  126. #define IF_NOT_MATCH_PREFIX_LEN (sizeof(IF_NOT_MATCH_PREFIX) - 1)
  127. #define START_BYTE_PREFIX "startByte="
  128. #define START_BYTE_PREFIX_LEN (sizeof(START_BYTE_PREFIX) - 1)
  129. #define BYTE_COUNT_PREFIX "byteCount="
  130. #define BYTE_COUNT_PREFIX_LEN (sizeof(BYTE_COUNT_PREFIX) - 1)
  131. #define ALL_DETAILS_PREFIX "allDetails="
  132. #define ALL_DETAILS_PREFIX_LEN (sizeof(ALL_DETAILS_PREFIX) - 1)
  133. #define NO_STATUS_PREFIX "noStatus="
  134. #define NO_STATUS_PREFIX_LEN (sizeof(NO_STATUS_PREFIX) - 1)
  135. #define RESOURCE_PREFIX "resource="
  136. #define RESOURCE_PREFIX_LEN (sizeof(RESOURCE_PREFIX) - 1)
  137. #define TARGET_BUCKET_PREFIX "targetBucket="
  138. #define TARGET_BUCKET_PREFIX_LEN (sizeof(TARGET_BUCKET_PREFIX) - 1)
  139. #define TARGET_PREFIX_PREFIX "targetPrefix="
  140. #define TARGET_PREFIX_PREFIX_LEN (sizeof(TARGET_PREFIX_PREFIX) - 1)
  141. #define HTTP_METHOD_PREFIX "method="
  142. #define HTTP_METHOD_PREFIX_LEN (sizeof(HTTP_METHOD_PREFIX) - 1)
  143. // util ----------------------------------------------------------------------
  144. static void S3_init()
  145. {
  146. S3Status status;
  147. const char *hostname = getenv("S3_HOSTNAME");
  148. if ((status = S3_initialize("s3", verifyPeerG|S3_INIT_ALL, hostname))
  149. != S3StatusOK) {
  150. fprintf(stderr, "Failed to initialize libs3: %s\n",
  151. S3_get_status_name(status));
  152. exit(-1);
  153. }
  154. }
  155. static void printError()
  156. {
  157. if (statusG < S3StatusErrorAccessDenied) {
  158. fprintf(stderr, "\nERROR: %s\n", S3_get_status_name(statusG));
  159. }
  160. else {
  161. fprintf(stderr, "\nERROR: %s\n", S3_get_status_name(statusG));
  162. fprintf(stderr, "%s\n", errorDetailsG);
  163. }
  164. }
  165. static void usageExit(FILE *out)
  166. {
  167. fprintf(out,
  168. "\n Options:\n"
  169. "\n"
  170. " Command Line:\n"
  171. "\n"
  172. " -f/--force : force operation despite warnings\n"
  173. " -h/--vhost-style : use virtual-host-style URIs (default is "
  174. "path-style)\n"
  175. " -u/--unencrypted : unencrypted (use HTTP instead of HTTPS)\n"
  176. " -s/--show-properties : show response properties on stdout\n"
  177. " -r/--retries : retry retryable failures this number of times\n"
  178. " (default is 5)\n"
  179. " -t/--timeout : request timeout, milliseconds. 0 if waiting forever\n"
  180. " (default is 0)\n"
  181. " -v/--verify-peer : verify peer SSL certificate (default is no)\n"
  182. " -g/--region <REGION> : use <REGION> for request authorization\n"
  183. "\n"
  184. " Environment:\n"
  185. "\n"
  186. " S3_ACCESS_KEY_ID : S3 access key ID (required)\n"
  187. " S3_SECRET_ACCESS_KEY : S3 secret access key (required)\n"
  188. " S3_HOSTNAME : specify alternative S3 host (optional)\n"
  189. "\n"
  190. " Commands (with <required parameters> and [optional parameters]) :\n"
  191. "\n"
  192. " (NOTE: all command parameters take a value and are specified using the\n"
  193. " pattern parameter=value)\n"
  194. "\n"
  195. " help : Prints this help text\n"
  196. "\n"
  197. " list : Lists owned buckets\n"
  198. " [allDetails] : Show full details\n"
  199. "\n"
  200. " test : Tests a bucket for existence and accessibility\n"
  201. " <bucket> : Bucket to test\n"
  202. "\n"
  203. " create : Create a new bucket\n"
  204. " <bucket> : Bucket to create\n"
  205. " [cannedAcl] : Canned ACL for the bucket (see Canned ACLs)\n"
  206. " [location] : Location for bucket (for example, EU)\n"
  207. "\n"
  208. " delete : Delete a bucket or key\n"
  209. " <bucket>[/<key>] : Bucket or bucket/key to delete\n"
  210. "\n"
  211. " list : List bucket contents\n"
  212. " <bucket> : Bucket to list\n"
  213. " [prefix] : Prefix for results set\n"
  214. " [marker] : Where in results set to start listing\n"
  215. " [delimiter] : Delimiter for rolling up results set\n"
  216. " [maxkeys] : Maximum number of keys to return in results set\n"
  217. " [allDetails] : Show full details for each key\n"
  218. "\n"
  219. " getacl : Get the ACL of a bucket or key\n"
  220. " <bucket>[/<key>] : Bucket or bucket/key to get the ACL of\n"
  221. " [filename] : Output filename for ACL (default is stdout)\n"
  222. "\n"
  223. " setacl : Set the ACL of a bucket or key\n"
  224. " <bucket>[/<key>] : Bucket or bucket/key to set the ACL of\n"
  225. " [filename] : Input filename for ACL (default is stdin)\n"
  226. " getlifecycle : Get the lifecycle of a bucket\n"
  227. " <bucket> : Bucket or bucket to get the lifecycle of\n"
  228. " [filename] : Output filename for lifecycle (default is stdout)\n"
  229. "\n"
  230. " setlifecycle : Set the lifecycle of a bucket or key\n"
  231. " <bucket> : Bucket or bucket to set the lifecycle of\n"
  232. " [filename] : Input filename for lifecycle (default is stdin)\n"
  233. "\n"
  234. " getlogging : Get the logging status of a bucket\n"
  235. " <bucket> : Bucket to get the logging status of\n"
  236. " [filename] : Output filename for logging (default is stdout)\n"
  237. "\n"
  238. " setlogging : Set the logging status of a bucket\n"
  239. " <bucket> : Bucket to set the logging status of\n"
  240. " [targetBucket] : Target bucket to log to; if not present, disables\n"
  241. " logging\n"
  242. " [targetPrefix] : Key prefix to use for logs\n"
  243. " [filename] : Input filename for logging (default is stdin)\n"
  244. "\n"
  245. " put : Puts an object\n"
  246. " <bucket>/<key> : Bucket/key to put object to\n"
  247. " [filename] : Filename to read source data from "
  248. "(default is stdin)\n"
  249. " [contentLength] : How many bytes of source data to put (required if\n"
  250. " source file is stdin)\n"
  251. " [cacheControl] : Cache-Control HTTP header string to associate with\n"
  252. " object\n"
  253. " [contentType] : Content-Type HTTP header string to associate with\n"
  254. " object\n"
  255. " [md5] : MD5 for validating source data\n"
  256. " [contentDispositionFilename] : Content-Disposition filename string to\n"
  257. " associate with object\n"
  258. " [contentEncoding] : Content-Encoding HTTP header string to associate\n"
  259. " with object\n"
  260. " [expires] : Expiration date to associate with object\n"
  261. " [cannedAcl] : Canned ACL for the object (see Canned ACLs)\n"
  262. " [x-amz-meta-...]] : Metadata headers to associate with the object\n"
  263. " [useServerSideEncryption] : Whether or not to use server-side\n"
  264. " encryption for the object\n"
  265. " [upload-id] : Upload-id of a uncomplete multipart upload, if you \n"
  266. " want to continue to put the object, you must specifil\n"
  267. "\n"
  268. " copy : Copies an object; if any options are set, the "
  269. "entire\n"
  270. " metadata of the object is replaced\n"
  271. " <sourcebucket>/<sourcekey> : Source bucket/key\n"
  272. " <destbucket>/<destkey> : Destination bucket/key\n"
  273. " [cacheControl] : Cache-Control HTTP header string to associate with\n"
  274. " object\n"
  275. " [contentType] : Content-Type HTTP header string to associate with\n"
  276. " object\n"
  277. " [contentDispositionFilename] : Content-Disposition filename string to\n"
  278. " associate with object\n"
  279. " [contentEncoding] : Content-Encoding HTTP header string to associate\n"
  280. " with object\n"
  281. " [expires] : Expiration date to associate with object\n"
  282. " [cannedAcl] : Canned ACL for the object (see Canned ACLs)\n"
  283. " [x-amz-meta-...]] : Metadata headers to associate with the object\n"
  284. "\n"
  285. " get : Gets an object\n"
  286. " <buckey>/<key> : Bucket/key of object to get\n"
  287. " [filename] : Filename to write object data to (required if -s\n"
  288. " command line parameter was used)\n"
  289. " [ifModifiedSince] : Only return the object if it has been modified "
  290. "since\n"
  291. " this date\n"
  292. " [ifNotmodifiedSince] : Only return the object if it has not been "
  293. "modified\n"
  294. " since this date\n"
  295. " [ifMatch] : Only return the object if its ETag header matches\n"
  296. " this string\n"
  297. " [ifNotMatch] : Only return the object if its ETag header does "
  298. "not\n"
  299. " match this string\n"
  300. " [startByte] : First byte of byte range to return\n"
  301. " [byteCount] : Number of bytes of byte range to return\n"
  302. "\n"
  303. " head : Gets only the headers of an object, implies -s\n"
  304. " <bucket>/<key> : Bucket/key of object to get headers of\n"
  305. "\n"
  306. " gqs : Generates an authenticated query string\n"
  307. " <bucket>[/<key>] : Bucket or bucket/key to generate query string for\n"
  308. " [expires] : Expiration date for query string\n"
  309. " [resource] : Sub-resource of key for query string, without a\n"
  310. " leading '?', for example, \"torrent\"\n"
  311. " [method] : HTTP method for use with the query string\n"
  312. " : (default is \"GET\")"
  313. "\n"
  314. " listmultiparts : Show multipart uploads\n"
  315. " <bucket> : Bucket multipart uploads belongs to\n"
  316. " [key-marker] : this parameter specifies the multipart upload after which listing should begin.\n"
  317. " [upload-id-marker] : Together with key-marker, specifies the multipart upload after which listing should begin\n"
  318. " [delimiter] : Character you use to group keys.\n"
  319. " [max-uploads] : Sets the maximum number of multipart uploads, from 1 to 1,000\n"
  320. " [encoding-type] : Requests Amazon S3 to encode the response and specifies the encoding method to use.\n"
  321. "\n"
  322. " abortmp : aborts a multipart upload.\n"
  323. " <bucket>/<key> : Bucket/key of upload belongs to.\n"
  324. " [upload-id] : upload-id of this upload\n"
  325. "\n"
  326. " listparts : lists the parts that have been uploaded for a specific multipart upload.\n"
  327. " <bucket>/<key> : Bucket/key of upload belongs to\n"
  328. " [upload-id] : upload-id of this upload\n"
  329. " [max-parts] : Sets the maximum number of parts to return in the response body.\n"
  330. " [encoding-type] : Requests Amazon S3 to encode the response and specifies the encoding method to use.\n"
  331. " [part-number-marker] : Specifies the part after which listing should begin.\n"
  332. "\n"
  333. " Canned ACLs:\n"
  334. "\n"
  335. " The following canned ACLs are supported:\n"
  336. " private (default), public-read, public-read-write, authenticated-read\n"
  337. "\n"
  338. " ACL Format:\n"
  339. "\n"
  340. " For the getacl and setacl commands, the format of the ACL list is:\n"
  341. " 1) An initial line giving the owner id in this format:\n"
  342. " OwnerID <Owner ID> <Owner Display Name>\n"
  343. " 2) Optional header lines, giving column headers, starting with the\n"
  344. " word \"Type\", or with some number of dashes\n"
  345. " 3) Grant lines, of the form:\n"
  346. " <Grant Type> (whitespace) <Grantee> (whitespace) <Permission>\n"
  347. " where Grant Type is one of: Email, UserID, or Group, and\n"
  348. " Grantee is the identification of the grantee based on this type,\n"
  349. " and Permission is one of: READ, WRITE, READ_ACP, or FULL_CONTROL.\n"
  350. "\n"
  351. " Note that the easiest way to modify an ACL is to first get it, saving it\n"
  352. " into a file, then modifying the file, and then setting the modified file\n"
  353. " back as the new ACL for the bucket/object.\n"
  354. "\n"
  355. " Date Format:\n"
  356. "\n"
  357. " The format for dates used in parameters is as ISO 8601 dates, i.e.\n"
  358. " YYYY-MM-DDTHH:MM:SS[+/-dd:dd]. Examples:\n"
  359. " 2008-07-29T20:36:14\n"
  360. " 2008-07-29T20:36:14-06:00\n"
  361. " 2008-07-29T20:36:14+11:30\n"
  362. "\n");
  363. exit(-1);
  364. }
  365. static uint64_t convertInt(const char *str, const char *paramName)
  366. {
  367. uint64_t ret = 0;
  368. while (*str) {
  369. if (!isdigit(*str)) {
  370. fprintf(stderr, "\nERROR: Nondigit in %s parameter: %c\n",
  371. paramName, *str);
  372. usageExit(stderr);
  373. }
  374. ret *= 10;
  375. ret += (*str++ - '0');
  376. }
  377. return ret;
  378. }
  379. typedef struct growbuffer
  380. {
  381. // The total number of bytes, and the start byte
  382. int size;
  383. // The start byte
  384. int start;
  385. // The blocks
  386. char data[64 * 1024];
  387. struct growbuffer *prev, *next;
  388. } growbuffer;
  389. // returns nonzero on success, zero on out of memory
  390. static int growbuffer_append(growbuffer **gb, const char *data, int dataLen)
  391. {
  392. int toCopy = 0 ;
  393. while (dataLen) {
  394. growbuffer *buf = *gb ? (*gb)->prev : 0;
  395. if (!buf || (buf->size == sizeof(buf->data))) {
  396. buf = (growbuffer *) malloc(sizeof(growbuffer));
  397. if (!buf) {
  398. return 0;
  399. }
  400. buf->size = 0;
  401. buf->start = 0;
  402. if (*gb && (*gb)->prev) {
  403. buf->prev = (*gb)->prev;
  404. buf->next = *gb;
  405. (*gb)->prev->next = buf;
  406. (*gb)->prev = buf;
  407. }
  408. else {
  409. buf->prev = buf->next = buf;
  410. *gb = buf;
  411. }
  412. }
  413. toCopy = (sizeof(buf->data) - buf->size);
  414. if (toCopy > dataLen) {
  415. toCopy = dataLen;
  416. }
  417. memcpy(&(buf->data[buf->size]), data, toCopy);
  418. buf->size += toCopy, data += toCopy, dataLen -= toCopy;
  419. }
  420. return toCopy;
  421. }
  422. static void growbuffer_read(growbuffer **gb, int amt, int *amtReturn,
  423. char *buffer)
  424. {
  425. *amtReturn = 0;
  426. growbuffer *buf = *gb;
  427. if (!buf) {
  428. return;
  429. }
  430. *amtReturn = (buf->size > amt) ? amt : buf->size;
  431. memcpy(buffer, &(buf->data[buf->start]), *amtReturn);
  432. buf->start += *amtReturn, buf->size -= *amtReturn;
  433. if (buf->size == 0) {
  434. if (buf->next == buf) {
  435. *gb = 0;
  436. }
  437. else {
  438. *gb = buf->next;
  439. buf->prev->next = buf->next;
  440. buf->next->prev = buf->prev;
  441. }
  442. free(buf);
  443. }
  444. }
  445. static void growbuffer_destroy(growbuffer *gb)
  446. {
  447. growbuffer *start = gb;
  448. while (gb) {
  449. growbuffer *next = gb->next;
  450. free(gb);
  451. gb = (next == start) ? 0 : next;
  452. }
  453. }
  454. // Convenience utility for making the code look nicer. Tests a string
  455. // against a format; only the characters specified in the format are
  456. // checked (i.e. if the string is longer than the format, the string still
  457. // checks out ok). Format characters are:
  458. // d - is a digit
  459. // anything else - is that character
  460. // Returns nonzero the string checks out, zero if it does not.
  461. static int checkString(const char *str, const char *format)
  462. {
  463. while (*format) {
  464. if (*format == 'd') {
  465. if (!isdigit(*str)) {
  466. return 0;
  467. }
  468. }
  469. else if (*str != *format) {
  470. return 0;
  471. }
  472. str++, format++;
  473. }
  474. return 1;
  475. }
  476. static int64_t parseIso8601Time(const char *str)
  477. {
  478. // Check to make sure that it has a valid format
  479. if (!checkString(str, "dddd-dd-ddTdd:dd:dd")) {
  480. return -1;
  481. }
  482. #define nextnum() (((*str - '0') * 10) + (*(str + 1) - '0'))
  483. // Convert it
  484. struct tm stm;
  485. memset(&stm, 0, sizeof(stm));
  486. stm.tm_year = (nextnum() - 19) * 100;
  487. str += 2;
  488. stm.tm_year += nextnum();
  489. str += 3;
  490. stm.tm_mon = nextnum() - 1;
  491. str += 3;
  492. stm.tm_mday = nextnum();
  493. str += 3;
  494. stm.tm_hour = nextnum();
  495. str += 3;
  496. stm.tm_min = nextnum();
  497. str += 3;
  498. stm.tm_sec = nextnum();
  499. str += 2;
  500. stm.tm_isdst = -1;
  501. // This is hokey but it's the recommended way ...
  502. char *tz = getenv("TZ");
  503. snprintf(putenvBufG, sizeof(putenvBufG), "TZ=UTC");
  504. putenv(putenvBufG);
  505. int64_t ret = mktime(&stm);
  506. snprintf(putenvBufG, sizeof(putenvBufG), "TZ=%s", tz ? tz : "");
  507. putenv(putenvBufG);
  508. // Skip the millis
  509. if (*str == '.') {
  510. str++;
  511. while (isdigit(*str)) {
  512. str++;
  513. }
  514. }
  515. if (checkString(str, "-dd:dd") || checkString(str, "+dd:dd")) {
  516. int sign = (*str++ == '-') ? -1 : 1;
  517. int hours = nextnum();
  518. str += 3;
  519. int minutes = nextnum();
  520. ret += (-sign * (((hours * 60) + minutes) * 60));
  521. }
  522. // Else it should be Z to be a conformant time string, but we just assume
  523. // that it is rather than enforcing that
  524. return ret;
  525. }
  526. // Simple ACL format: Lines of this format:
  527. // Type - ignored
  528. // Starting with a dash - ignored
  529. // Email email_address permission
  530. // UserID user_id (display_name) permission
  531. // Group Authenticated AWS Users permission
  532. // Group All Users permission
  533. // permission is one of READ, WRITE, READ_ACP, WRITE_ACP, FULL_CONTROL
  534. static int convert_simple_acl(char *aclXml, char *ownerId,
  535. char *ownerDisplayName,
  536. int *aclGrantCountReturn,
  537. S3AclGrant *aclGrants)
  538. {
  539. *aclGrantCountReturn = 0;
  540. *ownerId = 0;
  541. *ownerDisplayName = 0;
  542. #define SKIP_SPACE(require_more) \
  543. do { \
  544. while (isspace(*aclXml)) { \
  545. aclXml++; \
  546. } \
  547. if (require_more && !*aclXml) { \
  548. return 0; \
  549. } \
  550. } while (0)
  551. #define COPY_STRING_MAXLEN(field, maxlen) \
  552. do { \
  553. SKIP_SPACE(1); \
  554. int len = 0; \
  555. while ((len < maxlen) && !isspace(*aclXml)) { \
  556. field[len++] = *aclXml++; \
  557. } \
  558. field[len] = 0; \
  559. } while (0)
  560. #define COPY_STRING(field) \
  561. COPY_STRING_MAXLEN(field, (int) (sizeof(field) - 1))
  562. while (1) {
  563. SKIP_SPACE(0);
  564. if (!*aclXml) {
  565. break;
  566. }
  567. // Skip Type lines and dash lines
  568. if (!strncmp(aclXml, "Type", sizeof("Type") - 1) ||
  569. (*aclXml == '-')) {
  570. while (*aclXml && ((*aclXml != '\n') && (*aclXml != '\r'))) {
  571. aclXml++;
  572. }
  573. continue;
  574. }
  575. if (!strncmp(aclXml, "OwnerID", sizeof("OwnerID") - 1)) {
  576. aclXml += sizeof("OwnerID") - 1;
  577. COPY_STRING_MAXLEN(ownerId, S3_MAX_GRANTEE_USER_ID_SIZE);
  578. SKIP_SPACE(1);
  579. COPY_STRING_MAXLEN(ownerDisplayName,
  580. S3_MAX_GRANTEE_DISPLAY_NAME_SIZE);
  581. continue;
  582. }
  583. if (*aclGrantCountReturn == S3_MAX_ACL_GRANT_COUNT) {
  584. return 0;
  585. }
  586. S3AclGrant *grant = &(aclGrants[(*aclGrantCountReturn)++]);
  587. if (!strncmp(aclXml, "Email", sizeof("Email") - 1)) {
  588. grant->granteeType = S3GranteeTypeAmazonCustomerByEmail;
  589. aclXml += sizeof("Email") - 1;
  590. COPY_STRING(grant->grantee.amazonCustomerByEmail.emailAddress);
  591. }
  592. else if (!strncmp(aclXml, "UserID", sizeof("UserID") - 1)) {
  593. grant->granteeType = S3GranteeTypeCanonicalUser;
  594. aclXml += sizeof("UserID") - 1;
  595. COPY_STRING(grant->grantee.canonicalUser.id);
  596. SKIP_SPACE(1);
  597. // Now do display name
  598. COPY_STRING(grant->grantee.canonicalUser.displayName);
  599. }
  600. else if (!strncmp(aclXml, "Group", sizeof("Group") - 1)) {
  601. aclXml += sizeof("Group") - 1;
  602. SKIP_SPACE(1);
  603. if (!strncmp(aclXml, "Authenticated AWS Users",
  604. sizeof("Authenticated AWS Users") - 1)) {
  605. grant->granteeType = S3GranteeTypeAllAwsUsers;
  606. aclXml += (sizeof("Authenticated AWS Users") - 1);
  607. }
  608. else if (!strncmp(aclXml, "All Users", sizeof("All Users") - 1)) {
  609. grant->granteeType = S3GranteeTypeAllUsers;
  610. aclXml += (sizeof("All Users") - 1);
  611. }
  612. else if (!strncmp(aclXml, "Log Delivery",
  613. sizeof("Log Delivery") - 1)) {
  614. grant->granteeType = S3GranteeTypeLogDelivery;
  615. aclXml += (sizeof("Log Delivery") - 1);
  616. }
  617. else {
  618. return 0;
  619. }
  620. }
  621. else {
  622. return 0;
  623. }
  624. SKIP_SPACE(1);
  625. if (!strncmp(aclXml, "READ_ACP", sizeof("READ_ACP") - 1)) {
  626. grant->permission = S3PermissionReadACP;
  627. aclXml += (sizeof("READ_ACP") - 1);
  628. }
  629. else if (!strncmp(aclXml, "READ", sizeof("READ") - 1)) {
  630. grant->permission = S3PermissionRead;
  631. aclXml += (sizeof("READ") - 1);
  632. }
  633. else if (!strncmp(aclXml, "WRITE_ACP", sizeof("WRITE_ACP") - 1)) {
  634. grant->permission = S3PermissionWriteACP;
  635. aclXml += (sizeof("WRITE_ACP") - 1);
  636. }
  637. else if (!strncmp(aclXml, "WRITE", sizeof("WRITE") - 1)) {
  638. grant->permission = S3PermissionWrite;
  639. aclXml += (sizeof("WRITE") - 1);
  640. }
  641. else if (!strncmp(aclXml, "FULL_CONTROL",
  642. sizeof("FULL_CONTROL") - 1)) {
  643. grant->permission = S3PermissionFullControl;
  644. aclXml += (sizeof("FULL_CONTROL") - 1);
  645. }
  646. }
  647. return 1;
  648. }
  649. static int should_retry()
  650. {
  651. if (retriesG--) {
  652. // Sleep before next retry; start out with a 1 second sleep
  653. static int retrySleepInterval = 1 * SLEEP_UNITS_PER_SECOND;
  654. sleep(retrySleepInterval);
  655. // Next sleep 1 second longer
  656. retrySleepInterval++;
  657. return 1;
  658. }
  659. return 0;
  660. }
  661. static struct option longOptionsG[] =
  662. {
  663. { "force", no_argument, 0, 'f' },
  664. { "vhost-style", no_argument, 0, 'h' },
  665. { "unencrypted", no_argument, 0, 'u' },
  666. { "show-properties", no_argument, 0, 's' },
  667. { "retries", required_argument, 0, 'r' },
  668. { "timeout", required_argument, 0, 't' },
  669. { "verify-peer", no_argument, 0, 'v' },
  670. { "region", required_argument, 0, 'g' },
  671. { 0, 0, 0, 0 }
  672. };
  673. // response properties callback ----------------------------------------------
  674. // This callback does the same thing for every request type: prints out the
  675. // properties if the user has requested them to be so
  676. static S3Status responsePropertiesCallback
  677. (const S3ResponseProperties *properties, void *callbackData)
  678. {
  679. (void) callbackData;
  680. if (!showResponsePropertiesG) {
  681. return S3StatusOK;
  682. }
  683. #define print_nonnull(name, field) \
  684. do { \
  685. if (properties-> field) { \
  686. printf("%s: %s\n", name, properties-> field); \
  687. } \
  688. } while (0)
  689. print_nonnull("Content-Type", contentType);
  690. print_nonnull("Request-Id", requestId);
  691. print_nonnull("Request-Id-2", requestId2);
  692. if (properties->contentLength > 0) {
  693. printf("Content-Length: %llu\n",
  694. (unsigned long long) properties->contentLength);
  695. }
  696. print_nonnull("Server", server);
  697. print_nonnull("ETag", eTag);
  698. if (properties->lastModified > 0) {
  699. char timebuf[256];
  700. time_t t = (time_t) properties->lastModified;
  701. // gmtime is not thread-safe but we don't care here.
  702. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&t));
  703. printf("Last-Modified: %s\n", timebuf);
  704. }
  705. int i;
  706. for (i = 0; i < properties->metaDataCount; i++) {
  707. printf("x-amz-meta-%s: %s\n", properties->metaData[i].name,
  708. properties->metaData[i].value);
  709. }
  710. if (properties->usesServerSideEncryption) {
  711. printf("UsesServerSideEncryption: true\n");
  712. }
  713. return S3StatusOK;
  714. }
  715. // response complete callback ------------------------------------------------
  716. // This callback does the same thing for every request type: saves the status
  717. // and error stuff in global variables
  718. static void responseCompleteCallback(S3Status status,
  719. const S3ErrorDetails *error,
  720. void *callbackData)
  721. {
  722. (void) callbackData;
  723. statusG = status;
  724. // Compose the error details message now, although we might not use it.
  725. // Can't just save a pointer to [error] since it's not guaranteed to last
  726. // beyond this callback
  727. int len = 0;
  728. if (error && error->message) {
  729. len += snprintf(&(errorDetailsG[len]), sizeof(errorDetailsG) - len,
  730. " Message: %s\n", error->message);
  731. }
  732. if (error && error->resource) {
  733. len += snprintf(&(errorDetailsG[len]), sizeof(errorDetailsG) - len,
  734. " Resource: %s\n", error->resource);
  735. }
  736. if (error && error->furtherDetails) {
  737. len += snprintf(&(errorDetailsG[len]), sizeof(errorDetailsG) - len,
  738. " Further Details: %s\n", error->furtherDetails);
  739. }
  740. if (error && error->extraDetailsCount) {
  741. len += snprintf(&(errorDetailsG[len]), sizeof(errorDetailsG) - len,
  742. "%s", " Extra Details:\n");
  743. int i;
  744. for (i = 0; i < error->extraDetailsCount; i++) {
  745. len += snprintf(&(errorDetailsG[len]),
  746. sizeof(errorDetailsG) - len, " %s: %s\n",
  747. error->extraDetails[i].name,
  748. error->extraDetails[i].value);
  749. }
  750. }
  751. }
  752. // list service --------------------------------------------------------------
  753. typedef struct list_service_data
  754. {
  755. int headerPrinted;
  756. int allDetails;
  757. } list_service_data;
  758. static void printListServiceHeader(int allDetails)
  759. {
  760. printf("%-56s %-20s", " Bucket",
  761. " Created");
  762. if (allDetails) {
  763. printf(" %-64s %-12s",
  764. " Owner ID",
  765. "Display Name");
  766. }
  767. printf("\n");
  768. printf("-------------------------------------------------------- "
  769. "--------------------");
  770. if (allDetails) {
  771. printf(" -------------------------------------------------"
  772. "--------------- ------------");
  773. }
  774. printf("\n");
  775. }
  776. static S3Status listServiceCallback(const char *ownerId,
  777. const char *ownerDisplayName,
  778. const char *bucketName,
  779. int64_t creationDate, void *callbackData)
  780. {
  781. list_service_data *data = (list_service_data *) callbackData;
  782. if (!data->headerPrinted) {
  783. data->headerPrinted = 1;
  784. printListServiceHeader(data->allDetails);
  785. }
  786. char timebuf[256];
  787. if (creationDate >= 0) {
  788. time_t t = (time_t) creationDate;
  789. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&t));
  790. }
  791. else {
  792. timebuf[0] = 0;
  793. }
  794. printf("%-56s %-20s", bucketName, timebuf);
  795. if (data->allDetails) {
  796. printf(" %-64s %-12s", ownerId ? ownerId : "",
  797. ownerDisplayName ? ownerDisplayName : "");
  798. }
  799. printf("\n");
  800. return S3StatusOK;
  801. }
  802. static void list_service(int allDetails)
  803. {
  804. list_service_data data;
  805. data.headerPrinted = 0;
  806. data.allDetails = allDetails;
  807. S3_init();
  808. S3ListServiceHandler listServiceHandler =
  809. {
  810. { &responsePropertiesCallback, &responseCompleteCallback },
  811. &listServiceCallback
  812. };
  813. do {
  814. S3_list_service(protocolG, accessKeyIdG, secretAccessKeyG, 0, 0,
  815. awsRegionG, 0, timeoutMsG, &listServiceHandler, &data);
  816. } while (S3_status_is_retryable(statusG) && should_retry());
  817. if (statusG == S3StatusOK) {
  818. if (!data.headerPrinted) {
  819. printListServiceHeader(allDetails);
  820. }
  821. }
  822. else {
  823. printError();
  824. }
  825. S3_deinitialize();
  826. }
  827. // test bucket ---------------------------------------------------------------
  828. static void test_bucket(int argc, char **argv, int optindex)
  829. {
  830. // test bucket
  831. if (optindex == argc) {
  832. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  833. usageExit(stderr);
  834. }
  835. const char *bucketName = argv[optindex++];
  836. if (optindex != argc) {
  837. fprintf(stderr, "\nERROR: Extraneous parameter: %s\n", argv[optindex]);
  838. usageExit(stderr);
  839. }
  840. S3_init();
  841. S3ResponseHandler responseHandler =
  842. {
  843. &responsePropertiesCallback, &responseCompleteCallback
  844. };
  845. char locationConstraint[64];
  846. do {
  847. S3_test_bucket(protocolG, uriStyleG, accessKeyIdG, secretAccessKeyG, 0,
  848. 0, bucketName, awsRegionG, sizeof(locationConstraint),
  849. locationConstraint, 0, timeoutMsG, &responseHandler, 0);
  850. } while (S3_status_is_retryable(statusG) && should_retry());
  851. const char *result;
  852. switch (statusG) {
  853. case S3StatusOK:
  854. // bucket exists
  855. result = locationConstraint[0] ? locationConstraint : "USA";
  856. break;
  857. case S3StatusErrorNoSuchBucket:
  858. result = "Does Not Exist";
  859. break;
  860. case S3StatusErrorAccessDenied:
  861. result = "Access Denied";
  862. break;
  863. default:
  864. result = 0;
  865. break;
  866. }
  867. if (result) {
  868. printf("%-56s %-20s\n", " Bucket",
  869. " Status");
  870. printf("-------------------------------------------------------- "
  871. "--------------------\n");
  872. printf("%-56s %-20s\n", bucketName, result);
  873. }
  874. else {
  875. printError();
  876. }
  877. S3_deinitialize();
  878. }
  879. // create bucket -------------------------------------------------------------
  880. static void create_bucket(int argc, char **argv, int optindex)
  881. {
  882. if (optindex == argc) {
  883. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  884. usageExit(stderr);
  885. }
  886. const char *bucketName = argv[optindex++];
  887. if (!forceG && (S3_validate_bucket_name
  888. (bucketName, S3UriStyleVirtualHost) != S3StatusOK)) {
  889. fprintf(stderr, "\nWARNING: Bucket name is not valid for "
  890. "virtual-host style URI access.\n");
  891. fprintf(stderr, "Bucket not created. Use -f option to force the "
  892. "bucket to be created despite\n");
  893. fprintf(stderr, "this warning.\n\n");
  894. exit(-1);
  895. }
  896. const char *locationConstraint = 0;
  897. S3CannedAcl cannedAcl = S3CannedAclPrivate;
  898. while (optindex < argc) {
  899. char *param = argv[optindex++];
  900. if (!strncmp(param, LOCATION_PREFIX, LOCATION_PREFIX_LEN)) {
  901. locationConstraint = &(param[LOCATION_PREFIX_LEN]);
  902. }
  903. else if (!strncmp(param, CANNED_ACL_PREFIX, CANNED_ACL_PREFIX_LEN)) {
  904. char *val = &(param[CANNED_ACL_PREFIX_LEN]);
  905. if (!strcmp(val, "private")) {
  906. cannedAcl = S3CannedAclPrivate;
  907. }
  908. else if (!strcmp(val, "public-read")) {
  909. cannedAcl = S3CannedAclPublicRead;
  910. }
  911. else if (!strcmp(val, "public-read-write")) {
  912. cannedAcl = S3CannedAclPublicReadWrite;
  913. }
  914. else if (!strcmp(val, "authenticated-read")) {
  915. cannedAcl = S3CannedAclAuthenticatedRead;
  916. }
  917. else {
  918. fprintf(stderr, "\nERROR: Unknown canned ACL: %s\n", val);
  919. usageExit(stderr);
  920. }
  921. }
  922. else {
  923. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  924. usageExit(stderr);
  925. }
  926. }
  927. S3_init();
  928. S3ResponseHandler responseHandler =
  929. {
  930. &responsePropertiesCallback, &responseCompleteCallback
  931. };
  932. do {
  933. S3_create_bucket(protocolG, accessKeyIdG, secretAccessKeyG, 0, 0,
  934. bucketName, awsRegionG, cannedAcl, locationConstraint,
  935. 0, 0, &responseHandler, 0);
  936. } while (S3_status_is_retryable(statusG) && should_retry());
  937. if (statusG == S3StatusOK) {
  938. printf("Bucket successfully created.\n");
  939. }
  940. else {
  941. printError();
  942. }
  943. S3_deinitialize();
  944. }
  945. // delete bucket -------------------------------------------------------------
  946. static void delete_bucket(int argc, char **argv, int optindex)
  947. {
  948. if (optindex == argc) {
  949. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  950. usageExit(stderr);
  951. }
  952. const char *bucketName = argv[optindex++];
  953. if (optindex != argc) {
  954. fprintf(stderr, "\nERROR: Extraneous parameter: %s\n", argv[optindex]);
  955. usageExit(stderr);
  956. }
  957. S3_init();
  958. S3ResponseHandler responseHandler =
  959. {
  960. &responsePropertiesCallback, &responseCompleteCallback
  961. };
  962. do {
  963. S3_delete_bucket(protocolG, uriStyleG, accessKeyIdG, secretAccessKeyG,
  964. 0, 0, bucketName, awsRegionG, 0, timeoutMsG, &responseHandler, 0);
  965. } while (S3_status_is_retryable(statusG) && should_retry());
  966. if (statusG != S3StatusOK) {
  967. printError();
  968. }
  969. S3_deinitialize();
  970. }
  971. // list bucket ---------------------------------------------------------------
  972. typedef struct list_bucket_callback_data
  973. {
  974. int isTruncated;
  975. char nextMarker[1024];
  976. int keyCount;
  977. int allDetails;
  978. } list_bucket_callback_data;
  979. static void printListBucketHeader(int allDetails)
  980. {
  981. printf("%-50s %-20s %-5s",
  982. " Key",
  983. " Last Modified", "Size");
  984. if (allDetails) {
  985. printf(" %-34s %-64s %-12s",
  986. " ETag",
  987. " Owner ID",
  988. "Display Name");
  989. }
  990. printf("\n");
  991. printf("-------------------------------------------------- "
  992. "-------------------- -----");
  993. if (allDetails) {
  994. printf(" ---------------------------------- "
  995. "-------------------------------------------------"
  996. "--------------- ------------");
  997. }
  998. printf("\n");
  999. }
  1000. static S3Status listBucketCallback(int isTruncated, const char *nextMarker,
  1001. int contentsCount,
  1002. const S3ListBucketContent *contents,
  1003. int commonPrefixesCount,
  1004. const char **commonPrefixes,
  1005. void *callbackData)
  1006. {
  1007. list_bucket_callback_data *data =
  1008. (list_bucket_callback_data *) callbackData;
  1009. data->isTruncated = isTruncated;
  1010. // This is tricky. S3 doesn't return the NextMarker if there is no
  1011. // delimiter. Why, I don't know, since it's still useful for paging
  1012. // through results. We want NextMarker to be the last content in the
  1013. // list, so set it to that if necessary.
  1014. if ((!nextMarker || !nextMarker[0]) && contentsCount) {
  1015. nextMarker = contents[contentsCount - 1].key;
  1016. }
  1017. if (nextMarker) {
  1018. snprintf(data->nextMarker, sizeof(data->nextMarker), "%s",
  1019. nextMarker);
  1020. }
  1021. else {
  1022. data->nextMarker[0] = 0;
  1023. }
  1024. if (contentsCount && !data->keyCount) {
  1025. printListBucketHeader(data->allDetails);
  1026. }
  1027. int i;
  1028. for (i = 0; i < contentsCount; i++) {
  1029. const S3ListBucketContent *content = &(contents[i]);
  1030. char timebuf[256];
  1031. if (0) {
  1032. time_t t = (time_t) content->lastModified;
  1033. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
  1034. gmtime(&t));
  1035. printf("\nKey: %s\n", content->key);
  1036. printf("Last Modified: %s\n", timebuf);
  1037. printf("ETag: %s\n", content->eTag);
  1038. printf("Size: %llu\n", (unsigned long long) content->size);
  1039. if (content->ownerId) {
  1040. printf("Owner ID: %s\n", content->ownerId);
  1041. }
  1042. if (content->ownerDisplayName) {
  1043. printf("Owner Display Name: %s\n", content->ownerDisplayName);
  1044. }
  1045. }
  1046. else {
  1047. time_t t = (time_t) content->lastModified;
  1048. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
  1049. gmtime(&t));
  1050. char sizebuf[16];
  1051. if (content->size < 100000) {
  1052. sprintf(sizebuf, "%5llu", (unsigned long long) content->size);
  1053. }
  1054. else if (content->size < (1024 * 1024)) {
  1055. sprintf(sizebuf, "%4lluK",
  1056. ((unsigned long long) content->size) / 1024ULL);
  1057. }
  1058. else if (content->size < (10 * 1024 * 1024)) {
  1059. float f = content->size;
  1060. f /= (1024 * 1024);
  1061. sprintf(sizebuf, "%1.2fM", f);
  1062. }
  1063. else if (content->size < (1024 * 1024 * 1024)) {
  1064. sprintf(sizebuf, "%4lluM",
  1065. ((unsigned long long) content->size) /
  1066. (1024ULL * 1024ULL));
  1067. }
  1068. else {
  1069. float f = (content->size / 1024);
  1070. f /= (1024 * 1024);
  1071. sprintf(sizebuf, "%1.2fG", f);
  1072. }
  1073. printf("%-50s %s %s", content->key, timebuf, sizebuf);
  1074. if (data->allDetails) {
  1075. printf(" %-34s %-64s %-12s",
  1076. content->eTag,
  1077. content->ownerId ? content->ownerId : "",
  1078. content->ownerDisplayName ?
  1079. content->ownerDisplayName : "");
  1080. }
  1081. printf("\n");
  1082. }
  1083. }
  1084. data->keyCount += contentsCount;
  1085. for (i = 0; i < commonPrefixesCount; i++) {
  1086. printf("\nCommon Prefix: %s\n", commonPrefixes[i]);
  1087. }
  1088. return S3StatusOK;
  1089. }
  1090. static void list_bucket(const char *bucketName, const char *prefix,
  1091. const char *marker, const char *delimiter,
  1092. int maxkeys, int allDetails)
  1093. {
  1094. S3_init();
  1095. S3BucketContext bucketContext =
  1096. {
  1097. 0,
  1098. bucketName,
  1099. protocolG,
  1100. uriStyleG,
  1101. accessKeyIdG,
  1102. secretAccessKeyG,
  1103. 0,
  1104. awsRegionG
  1105. };
  1106. S3ListBucketHandler listBucketHandler =
  1107. {
  1108. { &responsePropertiesCallback, &responseCompleteCallback },
  1109. &listBucketCallback
  1110. };
  1111. list_bucket_callback_data data;
  1112. if (marker) {
  1113. snprintf(data.nextMarker, sizeof(data.nextMarker), "%s", marker);
  1114. } else {
  1115. data.nextMarker[0] = 0;
  1116. }
  1117. data.keyCount = 0;
  1118. data.allDetails = allDetails;
  1119. do {
  1120. data.isTruncated = 0;
  1121. do {
  1122. S3_list_bucket(&bucketContext, prefix, data.nextMarker,
  1123. delimiter, maxkeys, 0, timeoutMsG, &listBucketHandler, &data);
  1124. } while (S3_status_is_retryable(statusG) && should_retry());
  1125. if (statusG != S3StatusOK) {
  1126. break;
  1127. }
  1128. } while (data.isTruncated && (!maxkeys || (data.keyCount < maxkeys)));
  1129. if (statusG == S3StatusOK) {
  1130. if (!data.keyCount) {
  1131. printListBucketHeader(allDetails);
  1132. }
  1133. }
  1134. else {
  1135. printError();
  1136. }
  1137. S3_deinitialize();
  1138. }
  1139. static void list(int argc, char **argv, int optindex)
  1140. {
  1141. if (optindex == argc) {
  1142. list_service(0);
  1143. return;
  1144. }
  1145. const char *bucketName = 0;
  1146. const char *prefix = 0, *marker = 0, *delimiter = 0;
  1147. int maxkeys = 0, allDetails = 0;
  1148. while (optindex < argc) {
  1149. char *param = argv[optindex++];
  1150. if (!strncmp(param, PREFIX_PREFIX, PREFIX_PREFIX_LEN)) {
  1151. prefix = &(param[PREFIX_PREFIX_LEN]);
  1152. }
  1153. else if (!strncmp(param, MARKER_PREFIX, MARKER_PREFIX_LEN)) {
  1154. marker = &(param[MARKER_PREFIX_LEN]);
  1155. }
  1156. else if (!strncmp(param, DELIMITER_PREFIX, DELIMITER_PREFIX_LEN)) {
  1157. delimiter = &(param[DELIMITER_PREFIX_LEN]);
  1158. }
  1159. else if (!strncmp(param, MAXKEYS_PREFIX, MAXKEYS_PREFIX_LEN)) {
  1160. maxkeys = convertInt(&(param[MAXKEYS_PREFIX_LEN]), "maxkeys");
  1161. }
  1162. else if (!strncmp(param, ALL_DETAILS_PREFIX,
  1163. ALL_DETAILS_PREFIX_LEN)) {
  1164. const char *ad = &(param[ALL_DETAILS_PREFIX_LEN]);
  1165. if (!strcmp(ad, "true") || !strcmp(ad, "TRUE") ||
  1166. !strcmp(ad, "yes") || !strcmp(ad, "YES") ||
  1167. !strcmp(ad, "1")) {
  1168. allDetails = 1;
  1169. }
  1170. }
  1171. else if (!bucketName) {
  1172. bucketName = param;
  1173. }
  1174. else {
  1175. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  1176. usageExit(stderr);
  1177. }
  1178. }
  1179. if (bucketName) {
  1180. list_bucket(bucketName, prefix, marker, delimiter, maxkeys,
  1181. allDetails);
  1182. }
  1183. else {
  1184. list_service(allDetails);
  1185. }
  1186. }
  1187. typedef struct list_multiparts_callback_data
  1188. {
  1189. int isTruncated;
  1190. char nextKeyMarker[1024];
  1191. char nextUploadIdMarker[1024];
  1192. int uploadCount;
  1193. int allDetails;
  1194. } list_multiparts_callback_data;
  1195. typedef struct UploadManager{
  1196. //used for initial multipart
  1197. char * upload_id;
  1198. //used for upload part object
  1199. char **etags;
  1200. int next_etags_pos;
  1201. //used for commit Upload
  1202. growbuffer *gb;
  1203. int remaining;
  1204. } UploadManager;
  1205. typedef struct list_parts_callback_data
  1206. {
  1207. int isTruncated;
  1208. char nextPartNumberMarker[24];
  1209. char initiatorId[256];
  1210. char initiatorDisplayName[256];
  1211. char ownerId[256];
  1212. char ownerDisplayName[256];
  1213. char storageClass[256];
  1214. int partsCount;
  1215. int handlePartsStart;
  1216. int allDetails;
  1217. int noPrint;
  1218. UploadManager *manager;
  1219. } list_parts_callback_data;
  1220. typedef struct list_upload_callback_data
  1221. {
  1222. char uploadId[1024];
  1223. } abort_upload_callback_data;
  1224. static void printListMultipartHeader(int allDetails)
  1225. {
  1226. (void)allDetails;
  1227. }
  1228. static void printListPartsHeader()
  1229. {
  1230. printf("%-25s %-30s %-30s %-15s",
  1231. "LastModified",
  1232. "PartNumber", "ETag", "SIZE");
  1233. printf("\n");
  1234. printf("--------------------- "
  1235. " ------------- "
  1236. "------------------------------- "
  1237. " -----");
  1238. printf("\n");
  1239. }
  1240. static S3Status listMultipartCallback(int isTruncated, const char *nextKeyMarker,
  1241. const char *nextUploadIdMarker,
  1242. int uploadsCount,
  1243. const S3ListMultipartUpload *uploads,
  1244. int commonPrefixesCount,
  1245. const char **commonPrefixes,
  1246. void *callbackData)
  1247. {
  1248. list_multiparts_callback_data *data =
  1249. (list_multiparts_callback_data *) callbackData;
  1250. data->isTruncated = isTruncated;
  1251. /*
  1252. // This is tricky. S3 doesn't return the NextMarker if there is no
  1253. // delimiter. Why, I don't know, since it's still useful for paging
  1254. // through results. We want NextMarker to be the last content in the
  1255. // list, so set it to that if necessary.
  1256. if ((!nextKeyMarker || !nextKeyMarker[0]) && uploadsCount) {
  1257. nextKeyMarker = uploads[uploadsCount - 1].key;
  1258. }*/
  1259. if (nextKeyMarker) {
  1260. snprintf(data->nextKeyMarker, sizeof(data->nextKeyMarker), "%s",
  1261. nextKeyMarker);
  1262. }
  1263. else {
  1264. data->nextKeyMarker[0] = 0;
  1265. }
  1266. if (nextUploadIdMarker) {
  1267. snprintf(data->nextUploadIdMarker, sizeof(data->nextUploadIdMarker), "%s",
  1268. nextUploadIdMarker);
  1269. }
  1270. else {
  1271. data->nextUploadIdMarker[0] = 0;
  1272. }
  1273. if (uploadsCount && !data->uploadCount) {
  1274. printListMultipartHeader(data->allDetails);
  1275. }
  1276. int i;
  1277. for (i = 0; i < uploadsCount; i++) {
  1278. const S3ListMultipartUpload *upload = &(uploads[i]);
  1279. char timebuf[256];
  1280. if (1) {
  1281. time_t t = (time_t) upload->initiated;
  1282. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
  1283. gmtime(&t));
  1284. printf("\nKey: %s\n", upload->key);
  1285. printf("Initiated: %s\n", timebuf);
  1286. printf("UploadId: %s\n", upload->uploadId);
  1287. if (upload->initiatorId) {
  1288. printf("Initiator ID: %s\n", upload->initiatorId);
  1289. }
  1290. if (upload->initiatorDisplayName) {
  1291. printf("Initiator Display Name: %s\n", upload->initiatorDisplayName);
  1292. }
  1293. if (upload->ownerId) {
  1294. printf("Owner ID: %s\n", upload->ownerId);
  1295. }
  1296. if (upload->ownerDisplayName) {
  1297. printf("Owner Display Name: %s\n", upload->ownerDisplayName);
  1298. }
  1299. printf("StorageClass: %s\n", upload->storageClass);
  1300. }
  1301. else {
  1302. time_t t = (time_t) upload->initiated;
  1303. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
  1304. gmtime(&t));
  1305. printf("%-50s %s %-50s", upload->key, timebuf, upload->uploadId);
  1306. if (data->allDetails) {
  1307. printf(" %-34s %-64s %-12s %-64s %-12s",
  1308. upload->storageClass,
  1309. upload->ownerId ? upload->ownerId : "",
  1310. upload->ownerDisplayName ?
  1311. upload->ownerDisplayName : "",
  1312. upload->initiatorId ? upload->initiatorId : "",
  1313. upload->initiatorDisplayName ?
  1314. upload->initiatorDisplayName : "");
  1315. }
  1316. printf("\n");
  1317. }
  1318. }
  1319. data->uploadCount += uploadsCount;
  1320. for (i = 0; i < commonPrefixesCount; i++) {
  1321. printf("\nCommon Prefix: %s\n", commonPrefixes[i]);
  1322. }
  1323. return S3StatusOK;
  1324. }
  1325. static S3Status listPartsCallback(int isTruncated,
  1326. const char *nextPartNumberMarker,
  1327. const char *initiatorId,
  1328. const char *initiatorDisplayName,
  1329. const char *ownerId,
  1330. const char *ownerDisplayName,
  1331. const char *storageClass,
  1332. int partsCount,
  1333. int handlePartsStart,
  1334. const S3ListPart *parts,
  1335. void *callbackData)
  1336. {
  1337. list_parts_callback_data *data =
  1338. (list_parts_callback_data *) callbackData;
  1339. data->isTruncated = isTruncated;
  1340. data->handlePartsStart = handlePartsStart;
  1341. UploadManager *manager = data->manager;
  1342. /*
  1343. // This is tricky. S3 doesn't return the NextMarker if there is no
  1344. // delimiter. Why, I don't know, since it's still useful for paging
  1345. // through results. We want NextMarker to be the last content in the
  1346. // list, so set it to that if necessary.
  1347. if ((!nextKeyMarker || !nextKeyMarker[0]) && uploadsCount) {
  1348. nextKeyMarker = uploads[uploadsCount - 1].key;
  1349. }*/
  1350. if (nextPartNumberMarker) {
  1351. snprintf(data->nextPartNumberMarker,
  1352. sizeof(data->nextPartNumberMarker), "%s",
  1353. nextPartNumberMarker);
  1354. }
  1355. else {
  1356. data->nextPartNumberMarker[0] = 0;
  1357. }
  1358. if (initiatorId) {
  1359. snprintf(data->initiatorId, sizeof(data->initiatorId), "%s",
  1360. initiatorId);
  1361. }
  1362. else {
  1363. data->initiatorId[0] = 0;
  1364. }
  1365. if (initiatorDisplayName) {
  1366. snprintf(data->initiatorDisplayName,
  1367. sizeof(data->initiatorDisplayName), "%s",
  1368. initiatorDisplayName);
  1369. }
  1370. else {
  1371. data->initiatorDisplayName[0] = 0;
  1372. }
  1373. if (ownerId) {
  1374. snprintf(data->ownerId, sizeof(data->ownerId), "%s",
  1375. ownerId);
  1376. }
  1377. else {
  1378. data->ownerId[0] = 0;
  1379. }
  1380. if (ownerDisplayName) {
  1381. snprintf(data->ownerDisplayName, sizeof(data->ownerDisplayName), "%s",
  1382. ownerDisplayName);
  1383. }
  1384. else {
  1385. data->ownerDisplayName[0] = 0;
  1386. }
  1387. if (storageClass) {
  1388. snprintf(data->storageClass, sizeof(data->storageClass), "%s",
  1389. storageClass);
  1390. }
  1391. else {
  1392. data->storageClass[0] = 0;
  1393. }
  1394. if (partsCount && !data->partsCount && !data->noPrint) {
  1395. printListPartsHeader();
  1396. }
  1397. int i;
  1398. for (i = 0; i < partsCount; i++) {
  1399. const S3ListPart *part = &(parts[i]);
  1400. char timebuf[256];
  1401. if (data->noPrint) {
  1402. manager->etags[handlePartsStart+i] = strdup(part->eTag);
  1403. manager->next_etags_pos++;
  1404. manager->remaining = manager->remaining - part->size;
  1405. } else {
  1406. time_t t = (time_t) part->lastModified;
  1407. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
  1408. gmtime(&t));
  1409. printf("%-30s", timebuf);
  1410. printf("%-15llu", (unsigned long long) part->partNumber);
  1411. printf("%-45s", part->eTag);
  1412. printf("%-15llu\n", (unsigned long long) part->size);
  1413. }
  1414. }
  1415. data->partsCount += partsCount;
  1416. return S3StatusOK;
  1417. }
  1418. static void list_multipart_uploads(int argc, char **argv, int optindex)
  1419. {
  1420. if (optindex == argc) {
  1421. fprintf(stderr, "\nERROR: Usage: listmultiparts <bucket name>\n");
  1422. return;
  1423. }
  1424. const char *bucketName = 0;
  1425. const char *prefix = 0, *keymarker = 0, *delimiter = 0;
  1426. const char *encodingtype = 0, *uploadidmarker = 0;
  1427. int maxuploads = 0, allDetails = 0;
  1428. while (optindex < argc) {
  1429. char *param = argv[optindex++];
  1430. if (!strncmp(param, PREFIX_PREFIX, PREFIX_PREFIX_LEN)) {
  1431. prefix = &(param[PREFIX_PREFIX_LEN]);
  1432. }
  1433. else if (!strncmp(param, KEY_MARKER_PREFIX, KEY_MARKER_PREFIX_LEN)) {
  1434. keymarker = &(param[KEY_MARKER_PREFIX_LEN]);
  1435. }
  1436. else if (!strncmp(param, DELIMITER_PREFIX, DELIMITER_PREFIX_LEN)) {
  1437. delimiter = &(param[DELIMITER_PREFIX_LEN]);
  1438. }
  1439. else if (!strncmp(param, ENCODING_TYPE_PREFIX,
  1440. ENCODING_TYPE_PREFIX_LEN)) {
  1441. encodingtype = &(param[ENCODING_TYPE_PREFIX_LEN]);
  1442. }
  1443. else if (!strncmp(param, UPLOAD_ID_MARKER_PREFIX,
  1444. UPLOAD_ID_MARKER_PREFIX_LEN)) {
  1445. uploadidmarker = &(param[UPLOAD_ID_MARKER_PREFIX_LEN]);
  1446. }
  1447. else if (!strncmp(param, MAX_UPLOADS_PREFIX, MAX_UPLOADS_PREFIX_LEN)) {
  1448. maxuploads = convertInt(&(param[MAX_UPLOADS_PREFIX_LEN]),
  1449. "maxuploads");
  1450. }
  1451. else if (!strncmp(param, ALL_DETAILS_PREFIX, ALL_DETAILS_PREFIX_LEN)) {
  1452. const char *ad = &(param[ALL_DETAILS_PREFIX_LEN]);
  1453. if (!strcmp(ad, "true") || !strcmp(ad, "TRUE") ||
  1454. !strcmp(ad, "yes") || !strcmp(ad, "YES") ||
  1455. !strcmp(ad, "1")) {
  1456. allDetails = 1;
  1457. }
  1458. }
  1459. else if (!bucketName) {
  1460. bucketName = param;
  1461. }
  1462. else {
  1463. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  1464. usageExit(stderr);
  1465. }
  1466. }
  1467. if (bucketName) {
  1468. S3_init();
  1469. S3BucketContext bucketContext =
  1470. {
  1471. 0,
  1472. bucketName,
  1473. protocolG,
  1474. uriStyleG,
  1475. accessKeyIdG,
  1476. secretAccessKeyG,
  1477. 0,
  1478. awsRegionG
  1479. };
  1480. S3ListMultipartUploadsHandler listMultipartUploadsHandler =
  1481. {
  1482. { &responsePropertiesCallback, &responseCompleteCallback },
  1483. &listMultipartCallback
  1484. };
  1485. list_multiparts_callback_data data;
  1486. memset(&data, 0, sizeof(list_multiparts_callback_data));
  1487. if (keymarker != 0) {
  1488. snprintf(data.nextKeyMarker, sizeof(data.nextKeyMarker), "%s",
  1489. keymarker);
  1490. }
  1491. if (uploadidmarker != 0) {
  1492. snprintf(data.nextUploadIdMarker, sizeof(data.nextUploadIdMarker),
  1493. "%s", uploadidmarker);
  1494. }
  1495. data.uploadCount = 0;
  1496. data.allDetails = allDetails;
  1497. do {
  1498. data.isTruncated = 0;
  1499. do {
  1500. S3_list_multipart_uploads(&bucketContext, prefix,
  1501. data.nextKeyMarker,
  1502. data.nextUploadIdMarker, encodingtype,
  1503. delimiter, maxuploads, 0,
  1504. timeoutMsG,
  1505. &listMultipartUploadsHandler, &data);
  1506. } while (S3_status_is_retryable(statusG) && should_retry());
  1507. if (statusG != S3StatusOK) {
  1508. break;
  1509. }
  1510. } while (data.isTruncated &&
  1511. (!maxuploads || (data.uploadCount < maxuploads)));
  1512. if (statusG == S3StatusOK) {
  1513. if (!data.uploadCount) {
  1514. printListMultipartHeader(data.allDetails);
  1515. }
  1516. }
  1517. else {
  1518. printError();
  1519. }
  1520. S3_deinitialize();
  1521. }
  1522. }
  1523. static void list_parts(int argc, char **argv, int optindex)
  1524. {
  1525. if (optindex == argc) {
  1526. fprintf(stderr, "\nERROR: Usage: listparts <bucket name> <filename> "
  1527. "<upload-id>\n");
  1528. return;
  1529. }
  1530. // Split bucket/key
  1531. char *slash = argv[optindex];
  1532. while (*slash && (*slash != '/')) {
  1533. slash++;
  1534. }
  1535. if (!*slash || !*(slash + 1)) {
  1536. fprintf(stderr, "\nERROR: Invalid bucket/key name: %s\n",
  1537. argv[optindex]);
  1538. usageExit(stderr);
  1539. }
  1540. *slash++ = 0;
  1541. const char *bucketName = argv[optindex++];
  1542. const char *key = slash;
  1543. const char *uploadid = 0, *partnumbermarker = 0;
  1544. const char *encodingtype = 0;
  1545. int allDetails = 0, maxparts = 0;
  1546. while (optindex < argc) {
  1547. char *param = argv[optindex++];
  1548. if (!strncmp(param, UPLOAD_ID_PREFIX, UPLOAD_ID_PREFIX_LEN)) {
  1549. uploadid = &(param[UPLOAD_ID_PREFIX_LEN]);
  1550. }
  1551. else if (!strncmp(param, PART_NUMBER_MARKER_PREFIX,
  1552. PART_NUMBER_MARKER_PREFIX_LEN)) {
  1553. partnumbermarker = &(param[PART_NUMBER_MARKER_PREFIX_LEN]);
  1554. }
  1555. else if (!strncmp(param, ENCODING_TYPE_PREFIX,
  1556. ENCODING_TYPE_PREFIX_LEN)) {
  1557. encodingtype = &(param[ENCODING_TYPE_PREFIX_LEN]);
  1558. }
  1559. else if (!strncmp(param, MAX_PARTS_PREFIX, MAX_PARTS_PREFIX_LEN)) {
  1560. maxparts = convertInt(&(param[MAX_PARTS_PREFIX_LEN]), "max-parts");
  1561. }
  1562. else if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  1563. key = &(param[FILENAME_PREFIX_LEN]);
  1564. }
  1565. else if (!strncmp(param, ALL_DETAILS_PREFIX,
  1566. ALL_DETAILS_PREFIX_LEN)) {
  1567. const char *ad = &(param[ALL_DETAILS_PREFIX_LEN]);
  1568. if (!strcmp(ad, "true") || !strcmp(ad, "TRUE") ||
  1569. !strcmp(ad, "yes") || !strcmp(ad, "YES") ||
  1570. !strcmp(ad, "1")) {
  1571. allDetails = 1;
  1572. }
  1573. }
  1574. else {
  1575. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  1576. usageExit(stderr);
  1577. }
  1578. }
  1579. if (bucketName) {
  1580. S3_init();
  1581. S3BucketContext bucketContext =
  1582. {
  1583. 0,
  1584. bucketName,
  1585. protocolG,
  1586. uriStyleG,
  1587. accessKeyIdG,
  1588. secretAccessKeyG,
  1589. 0,
  1590. awsRegionG
  1591. };
  1592. S3ListPartsHandler listPartsHandler =
  1593. {
  1594. { &responsePropertiesCallback, &responseCompleteCallback },
  1595. &listPartsCallback
  1596. };
  1597. list_parts_callback_data data;
  1598. memset(&data, 0, sizeof(list_parts_callback_data));
  1599. if (partnumbermarker != 0) {
  1600. snprintf(data.nextPartNumberMarker,
  1601. sizeof(data.nextPartNumberMarker), "%s", partnumbermarker);
  1602. }
  1603. data.partsCount = 0;
  1604. data.allDetails = allDetails;
  1605. data.noPrint = 0;
  1606. do {
  1607. data.isTruncated = 0;
  1608. do {
  1609. S3_list_parts(&bucketContext, key, data.nextPartNumberMarker,
  1610. uploadid, encodingtype,
  1611. maxparts,
  1612. 0, timeoutMsG,
  1613. &listPartsHandler, &data);
  1614. } while (S3_status_is_retryable(statusG) && should_retry());
  1615. if (statusG != S3StatusOK) {
  1616. break;
  1617. }
  1618. } while (data.isTruncated &&
  1619. (!maxparts || (data.partsCount < maxparts)));
  1620. if (statusG == S3StatusOK) {
  1621. if (!data.partsCount) {
  1622. printListMultipartHeader(data.allDetails);
  1623. }
  1624. }
  1625. else {
  1626. printError();
  1627. }
  1628. S3_deinitialize();
  1629. }
  1630. }
  1631. static void abort_multipart_upload(int argc, char **argv, int optindex)
  1632. {
  1633. if (optindex == argc) {
  1634. fprintf(stderr, "\nERROR: Usage: abortmultipartupload <bucket name> "
  1635. "<upload-id>\n");
  1636. return;
  1637. }
  1638. // Split bucket/key
  1639. char *slash = argv[optindex];
  1640. while (*slash && (*slash != '/')) {
  1641. slash++;
  1642. }
  1643. if (!*slash || !*(slash + 1)) {
  1644. fprintf(stderr, "\nERROR: Invalid bucket/key name: %s\n",
  1645. argv[optindex]);
  1646. usageExit(stderr);
  1647. }
  1648. *slash++ = 0;
  1649. const char *bucketName = argv[optindex++];
  1650. const char *key = slash;
  1651. const char *uploadid = 0;
  1652. while (optindex < argc) {
  1653. char *param = argv[optindex++];
  1654. if (!strncmp(param, UPLOAD_ID_PREFIX, UPLOAD_ID_PREFIX_LEN)) {
  1655. uploadid = &(param[UPLOAD_ID_PREFIX_LEN]);
  1656. }
  1657. else if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  1658. key = &(param[FILENAME_PREFIX_LEN]);
  1659. }
  1660. else {
  1661. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  1662. usageExit(stderr);
  1663. }
  1664. }
  1665. if (bucketName) {
  1666. S3_init();
  1667. S3BucketContext bucketContext =
  1668. {
  1669. 0,
  1670. bucketName,
  1671. protocolG,
  1672. uriStyleG,
  1673. accessKeyIdG,
  1674. secretAccessKeyG,
  1675. 0,
  1676. awsRegionG
  1677. };
  1678. S3AbortMultipartUploadHandler abortMultipartUploadHandler =
  1679. {
  1680. { &responsePropertiesCallback, &responseCompleteCallback },
  1681. };
  1682. /*
  1683. list_multiparts_callback_data data;
  1684. memset(&data, 0, sizeof(list_multiparts_callback_data));
  1685. if (keymarker != 0) {
  1686. snprintf(data.nextKeyMarker, sizeof(data.nextKeyMarker), "%s",
  1687. keymarker);
  1688. }
  1689. if (uploadidmarker != 0) {
  1690. snprintf(data.nextUploadIdMarker, sizeof(data.nextUploadIdMarker),
  1691. "%s", uploadidmarker);
  1692. }
  1693. data.uploadCount = 0;
  1694. data.allDetails = allDetails;
  1695. */
  1696. do {
  1697. S3_abort_multipart_upload(&bucketContext, key, uploadid,
  1698. timeoutMsG, &abortMultipartUploadHandler);
  1699. } while (S3_status_is_retryable(statusG) && should_retry());
  1700. S3_deinitialize();
  1701. }
  1702. }
  1703. // delete object -------------------------------------------------------------
  1704. static void delete_object(int argc, char **argv, int optindex)
  1705. {
  1706. (void) argc;
  1707. // Split bucket/key
  1708. char *slash = argv[optindex];
  1709. // We know there is a slash in there, put_object is only called if so
  1710. while (*slash && (*slash != '/')) {
  1711. slash++;
  1712. }
  1713. *slash++ = 0;
  1714. const char *bucketName = argv[optindex++];
  1715. const char *key = slash;
  1716. S3_init();
  1717. S3BucketContext bucketContext =
  1718. {
  1719. 0,
  1720. bucketName,
  1721. protocolG,
  1722. uriStyleG,
  1723. accessKeyIdG,
  1724. secretAccessKeyG,
  1725. 0,
  1726. awsRegionG
  1727. };
  1728. S3ResponseHandler responseHandler =
  1729. {
  1730. 0,
  1731. &responseCompleteCallback
  1732. };
  1733. do {
  1734. S3_delete_object(&bucketContext, key, 0, timeoutMsG, &responseHandler, 0);
  1735. } while (S3_status_is_retryable(statusG) && should_retry());
  1736. if ((statusG != S3StatusOK) &&
  1737. (statusG != S3StatusErrorPreconditionFailed)) {
  1738. printError();
  1739. }
  1740. S3_deinitialize();
  1741. }
  1742. // put object ----------------------------------------------------------------
  1743. typedef struct put_object_callback_data
  1744. {
  1745. FILE *infile;
  1746. growbuffer *gb;
  1747. uint64_t contentLength, originalContentLength;
  1748. uint64_t totalContentLength, totalOriginalContentLength;
  1749. int noStatus;
  1750. } put_object_callback_data;
  1751. static int putObjectDataCallback(int bufferSize, char *buffer,
  1752. void *callbackData)
  1753. {
  1754. put_object_callback_data *data =
  1755. (put_object_callback_data *) callbackData;
  1756. int ret = 0;
  1757. if (data->contentLength) {
  1758. int toRead = ((data->contentLength > (unsigned) bufferSize) ?
  1759. (unsigned) bufferSize : data->contentLength);
  1760. if (data->gb) {
  1761. growbuffer_read(&(data->gb), toRead, &ret, buffer);
  1762. }
  1763. else if (data->infile) {
  1764. ret = fread(buffer, 1, toRead, data->infile);
  1765. }
  1766. }
  1767. data->contentLength -= ret;
  1768. data->totalContentLength -= ret;
  1769. if (data->contentLength && !data->noStatus) {
  1770. // Avoid a weird bug in MingW, which won't print the second integer
  1771. // value properly when it's in the same call, so print separately
  1772. printf("%llu bytes remaining ",
  1773. (unsigned long long) data->totalContentLength);
  1774. printf("(%d%% complete) ...\n",
  1775. (int) (((data->totalOriginalContentLength -
  1776. data->totalContentLength) * 100) /
  1777. data->totalOriginalContentLength));
  1778. }
  1779. return ret;
  1780. }
  1781. #define MULTIPART_CHUNK_SIZE (15 << 20) // multipart is 15M
  1782. typedef struct MultipartPartData {
  1783. put_object_callback_data put_object_data;
  1784. int seq;
  1785. UploadManager *manager;
  1786. } MultipartPartData;
  1787. S3Status initial_multipart_callback(const char * upload_id,
  1788. void * callbackData)
  1789. {
  1790. UploadManager *manager = (UploadManager *) callbackData;
  1791. manager->upload_id = strdup(upload_id);
  1792. return S3StatusOK;
  1793. }
  1794. S3Status MultipartResponseProperiesCallback
  1795. (const S3ResponseProperties *properties, void *callbackData)
  1796. {
  1797. responsePropertiesCallback(properties, callbackData);
  1798. MultipartPartData *data = (MultipartPartData *) callbackData;
  1799. int seq = data->seq;
  1800. const char *etag = properties->eTag;
  1801. data->manager->etags[seq - 1] = strdup(etag);
  1802. data->manager->next_etags_pos = seq;
  1803. return S3StatusOK;
  1804. }
  1805. static int multipartPutXmlCallback(int bufferSize, char *buffer,
  1806. void *callbackData)
  1807. {
  1808. UploadManager *manager = (UploadManager*)callbackData;
  1809. int ret = 0;
  1810. if (manager->remaining) {
  1811. int toRead = ((manager->remaining > bufferSize) ?
  1812. bufferSize : manager->remaining);
  1813. growbuffer_read(&(manager->gb), toRead, &ret, buffer);
  1814. }
  1815. manager->remaining -= ret;
  1816. return ret;
  1817. }
  1818. static int try_get_parts_info(const char *bucketName, const char *key,
  1819. UploadManager *manager)
  1820. {
  1821. S3BucketContext bucketContext =
  1822. {
  1823. 0,
  1824. bucketName,
  1825. protocolG,
  1826. uriStyleG,
  1827. accessKeyIdG,
  1828. secretAccessKeyG,
  1829. 0,
  1830. awsRegionG
  1831. };
  1832. S3ListPartsHandler listPartsHandler =
  1833. {
  1834. { &responsePropertiesCallback, &responseCompleteCallback },
  1835. &listPartsCallback
  1836. };
  1837. list_parts_callback_data data;
  1838. memset(&data, 0, sizeof(list_parts_callback_data));
  1839. data.partsCount = 0;
  1840. data.allDetails = 0;
  1841. data.manager = manager;
  1842. data.noPrint = 1;
  1843. do {
  1844. data.isTruncated = 0;
  1845. do {
  1846. S3_list_parts(&bucketContext, key, data.nextPartNumberMarker,
  1847. manager->upload_id, 0, 0, 0, timeoutMsG, &listPartsHandler,
  1848. &data);
  1849. } while (S3_status_is_retryable(statusG) && should_retry());
  1850. if (statusG != S3StatusOK) {
  1851. break;
  1852. }
  1853. } while (data.isTruncated);
  1854. if (statusG == S3StatusOK) {
  1855. if (!data.partsCount) {
  1856. printListMultipartHeader(data.allDetails);
  1857. }
  1858. }
  1859. else {
  1860. printError();
  1861. return -1;
  1862. }
  1863. return 0;
  1864. }
  1865. static void put_object(int argc, char **argv, int optindex,
  1866. const char *srcBucketName, const char *srcKey, unsigned long long srcSize)
  1867. {
  1868. if (optindex == argc) {
  1869. fprintf(stderr, "\nERROR: Missing parameter: bucket/key\n");
  1870. usageExit(stderr);
  1871. }
  1872. // Split bucket/key
  1873. char *slash = argv[optindex];
  1874. while (*slash && (*slash != '/')) {
  1875. slash++;
  1876. }
  1877. if (!*slash || !*(slash + 1)) {
  1878. fprintf(stderr, "\nERROR: Invalid bucket/key name: %s\n",
  1879. argv[optindex]);
  1880. usageExit(stderr);
  1881. }
  1882. *slash++ = 0;
  1883. const char *bucketName = argv[optindex++];
  1884. const char *key = slash;
  1885. const char *uploadId = 0;
  1886. const char *filename = 0;
  1887. uint64_t contentLength = 0;
  1888. const char *cacheControl = 0, *contentType = 0, *md5 = 0;
  1889. const char *contentDispositionFilename = 0, *contentEncoding = 0;
  1890. int64_t expires = -1;
  1891. S3CannedAcl cannedAcl = S3CannedAclPrivate;
  1892. int metaPropertiesCount = 0;
  1893. S3NameValue metaProperties[S3_MAX_METADATA_COUNT];
  1894. char useServerSideEncryption = 0;
  1895. int noStatus = 0;
  1896. while (optindex < argc) {
  1897. char *param = argv[optindex++];
  1898. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  1899. filename = &(param[FILENAME_PREFIX_LEN]);
  1900. }
  1901. else if (!strncmp(param, CONTENT_LENGTH_PREFIX,
  1902. CONTENT_LENGTH_PREFIX_LEN)) {
  1903. contentLength = convertInt(&(param[CONTENT_LENGTH_PREFIX_LEN]),
  1904. "contentLength");
  1905. if (contentLength > (5LL * 1024 * 1024 * 1024)) {
  1906. fprintf(stderr, "\nERROR: contentLength must be no greater "
  1907. "than 5 GB\n");
  1908. usageExit(stderr);
  1909. }
  1910. }
  1911. else if (!strncmp(param, CACHE_CONTROL_PREFIX,
  1912. CACHE_CONTROL_PREFIX_LEN)) {
  1913. cacheControl = &(param[CACHE_CONTROL_PREFIX_LEN]);
  1914. }
  1915. else if (!strncmp(param, CONTENT_TYPE_PREFIX,
  1916. CONTENT_TYPE_PREFIX_LEN)) {
  1917. contentType = &(param[CONTENT_TYPE_PREFIX_LEN]);
  1918. }
  1919. else if (!strncmp(param, MD5_PREFIX, MD5_PREFIX_LEN)) {
  1920. md5 = &(param[MD5_PREFIX_LEN]);
  1921. }
  1922. else if (!strncmp(param, CONTENT_DISPOSITION_FILENAME_PREFIX,
  1923. CONTENT_DISPOSITION_FILENAME_PREFIX_LEN)) {
  1924. contentDispositionFilename =
  1925. &(param[CONTENT_DISPOSITION_FILENAME_PREFIX_LEN]);
  1926. }
  1927. else if (!strncmp(param, CONTENT_ENCODING_PREFIX,
  1928. CONTENT_ENCODING_PREFIX_LEN)) {
  1929. contentEncoding = &(param[CONTENT_ENCODING_PREFIX_LEN]);
  1930. }
  1931. else if (!strncmp(param, UPLOAD_ID_PREFIX,
  1932. UPLOAD_ID_PREFIX_LEN)) {
  1933. uploadId = &(param[UPLOAD_ID_PREFIX_LEN]);
  1934. }
  1935. else if (!strncmp(param, EXPIRES_PREFIX, EXPIRES_PREFIX_LEN)) {
  1936. expires = parseIso8601Time(&(param[EXPIRES_PREFIX_LEN]));
  1937. if (expires < 0) {
  1938. fprintf(stderr, "\nERROR: Invalid expires time "
  1939. "value; ISO 8601 time format required\n");
  1940. usageExit(stderr);
  1941. }
  1942. }
  1943. else if (!strncmp(param, X_AMZ_META_PREFIX, X_AMZ_META_PREFIX_LEN)) {
  1944. if (metaPropertiesCount == S3_MAX_METADATA_COUNT) {
  1945. fprintf(stderr, "\nERROR: Too many x-amz-meta- properties, "
  1946. "limit %lu: %s\n",
  1947. (unsigned long) S3_MAX_METADATA_COUNT, param);
  1948. usageExit(stderr);
  1949. }
  1950. char *name = &(param[X_AMZ_META_PREFIX_LEN]);
  1951. char *value = name;
  1952. while (*value && (*value != '=')) {
  1953. value++;
  1954. }
  1955. if (!*value || !*(value + 1)) {
  1956. fprintf(stderr, "\nERROR: Invalid parameter: %s\n", param);
  1957. usageExit(stderr);
  1958. }
  1959. *value++ = 0;
  1960. metaProperties[metaPropertiesCount].name = name;
  1961. metaProperties[metaPropertiesCount++].value = value;
  1962. }
  1963. else if (!strncmp(param, USE_SERVER_SIDE_ENCRYPTION_PREFIX,
  1964. USE_SERVER_SIDE_ENCRYPTION_PREFIX_LEN)) {
  1965. const char *val = &(param[USE_SERVER_SIDE_ENCRYPTION_PREFIX_LEN]);
  1966. if (!strcmp(val, "true") || !strcmp(val, "TRUE") ||
  1967. !strcmp(val, "yes") || !strcmp(val, "YES") ||
  1968. !strcmp(val, "1")) {
  1969. useServerSideEncryption = 1;
  1970. }
  1971. else {
  1972. useServerSideEncryption = 0;
  1973. }
  1974. }
  1975. else if (!strncmp(param, CANNED_ACL_PREFIX, CANNED_ACL_PREFIX_LEN)) {
  1976. char *val = &(param[CANNED_ACL_PREFIX_LEN]);
  1977. if (!strcmp(val, "private")) {
  1978. cannedAcl = S3CannedAclPrivate;
  1979. }
  1980. else if (!strcmp(val, "public-read")) {
  1981. cannedAcl = S3CannedAclPublicRead;
  1982. }
  1983. else if (!strcmp(val, "public-read-write")) {
  1984. cannedAcl = S3CannedAclPublicReadWrite;
  1985. }
  1986. else if (!strcmp(val, "authenticated-read")) {
  1987. cannedAcl = S3CannedAclAuthenticatedRead;
  1988. }
  1989. else {
  1990. fprintf(stderr, "\nERROR: Unknown canned ACL: %s\n", val);
  1991. usageExit(stderr);
  1992. }
  1993. }
  1994. else if (!strncmp(param, NO_STATUS_PREFIX, NO_STATUS_PREFIX_LEN)) {
  1995. const char *ns = &(param[NO_STATUS_PREFIX_LEN]);
  1996. if (!strcmp(ns, "true") || !strcmp(ns, "TRUE") ||
  1997. !strcmp(ns, "yes") || !strcmp(ns, "YES") ||
  1998. !strcmp(ns, "1")) {
  1999. noStatus = 1;
  2000. }
  2001. }
  2002. else {
  2003. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  2004. usageExit(stderr);
  2005. }
  2006. }
  2007. put_object_callback_data data;
  2008. data.infile = 0;
  2009. data.gb = 0;
  2010. data.noStatus = noStatus;
  2011. if (srcSize) {
  2012. // This is really a COPY multipart, not a put, so take from source object
  2013. contentLength = srcSize;
  2014. data.infile = NULL;
  2015. }
  2016. else if (filename) {
  2017. if (!contentLength) {
  2018. struct stat statbuf;
  2019. // Stat the file to get its length
  2020. if (stat(filename, &statbuf) == -1) {
  2021. fprintf(stderr, "\nERROR: Failed to stat file %s: ",
  2022. filename);
  2023. perror(0);
  2024. exit(-1);
  2025. }
  2026. contentLength = statbuf.st_size;
  2027. }
  2028. // Open the file
  2029. if (!(data.infile = fopen(filename, "r" FOPEN_EXTRA_FLAGS))) {
  2030. fprintf(stderr, "\nERROR: Failed to open input file %s: ",
  2031. filename);
  2032. perror(0);
  2033. exit(-1);
  2034. }
  2035. }
  2036. else {
  2037. // Read from stdin. If contentLength is not provided, we have
  2038. // to read it all in to get contentLength.
  2039. if (!contentLength) {
  2040. // Read all if stdin to get the data
  2041. char buffer[64 * 1024];
  2042. while (1) {
  2043. int amtRead = fread(buffer, 1, sizeof(buffer), stdin);
  2044. if (amtRead == 0) {
  2045. break;
  2046. }
  2047. if (!growbuffer_append(&(data.gb), buffer, amtRead)) {
  2048. fprintf(stderr, "\nERROR: Out of memory while reading "
  2049. "stdin\n");
  2050. exit(-1);
  2051. }
  2052. contentLength += amtRead;
  2053. if (amtRead < (int) sizeof(buffer)) {
  2054. break;
  2055. }
  2056. }
  2057. }
  2058. else {
  2059. data.infile = stdin;
  2060. }
  2061. }
  2062. data.totalContentLength =
  2063. data.totalOriginalContentLength =
  2064. data.contentLength =
  2065. data.originalContentLength =
  2066. contentLength;
  2067. S3_init();
  2068. S3BucketContext bucketContext =
  2069. {
  2070. 0,
  2071. bucketName,
  2072. protocolG,
  2073. uriStyleG,
  2074. accessKeyIdG,
  2075. secretAccessKeyG,
  2076. 0,
  2077. awsRegionG
  2078. };
  2079. S3PutProperties putProperties =
  2080. {
  2081. contentType,
  2082. md5,
  2083. cacheControl,
  2084. contentDispositionFilename,
  2085. contentEncoding,
  2086. expires,
  2087. cannedAcl,
  2088. metaPropertiesCount,
  2089. metaProperties,
  2090. useServerSideEncryption
  2091. };
  2092. if (contentLength <= MULTIPART_CHUNK_SIZE) {
  2093. S3PutObjectHandler putObjectHandler =
  2094. {
  2095. { &responsePropertiesCallback, &responseCompleteCallback },
  2096. &putObjectDataCallback
  2097. };
  2098. do {
  2099. S3_put_object(&bucketContext, key, contentLength, &putProperties, 0,
  2100. 0, &putObjectHandler, &data);
  2101. } while (S3_status_is_retryable(statusG) && should_retry());
  2102. if (data.infile) {
  2103. fclose(data.infile);
  2104. }
  2105. else if (data.gb) {
  2106. growbuffer_destroy(data.gb);
  2107. }
  2108. if (statusG != S3StatusOK) {
  2109. printError();
  2110. }
  2111. else if (data.contentLength) {
  2112. fprintf(stderr, "\nERROR: Failed to read remaining %llu bytes from "
  2113. "input\n", (unsigned long long) data.contentLength);
  2114. }
  2115. }
  2116. else {
  2117. uint64_t totalContentLength = contentLength;
  2118. uint64_t todoContentLength = contentLength;
  2119. UploadManager manager;
  2120. manager.upload_id = 0;
  2121. manager.gb = 0;
  2122. //div round up
  2123. int seq;
  2124. int totalSeq = ((contentLength + MULTIPART_CHUNK_SIZE- 1) /
  2125. MULTIPART_CHUNK_SIZE);
  2126. MultipartPartData partData;
  2127. int partContentLength = 0;
  2128. S3MultipartInitialHandler handler = {
  2129. {
  2130. &responsePropertiesCallback,
  2131. &responseCompleteCallback
  2132. },
  2133. &initial_multipart_callback
  2134. };
  2135. S3PutObjectHandler putObjectHandler = {
  2136. {&MultipartResponseProperiesCallback, &responseCompleteCallback },
  2137. &putObjectDataCallback
  2138. };
  2139. S3MultipartCommitHandler commit_handler = {
  2140. {
  2141. &responsePropertiesCallback,&responseCompleteCallback
  2142. },
  2143. &multipartPutXmlCallback,
  2144. 0
  2145. };
  2146. manager.etags = (char **) malloc(sizeof(char *) * totalSeq);
  2147. manager.next_etags_pos = 0;
  2148. if (uploadId) {
  2149. manager.upload_id = strdup(uploadId);
  2150. manager.remaining = contentLength;
  2151. if (!try_get_parts_info(bucketName, key, &manager)) {
  2152. fseek(data.infile, -(manager.remaining), 2);
  2153. contentLength = manager.remaining;
  2154. goto upload;
  2155. } else {
  2156. goto clean;
  2157. }
  2158. }
  2159. do {
  2160. S3_initiate_multipart(&bucketContext, key,0, &handler,0, timeoutMsG, &manager);
  2161. } while (S3_status_is_retryable(statusG) && should_retry());
  2162. if (manager.upload_id == 0 || statusG != S3StatusOK) {
  2163. printError();
  2164. goto clean;
  2165. }
  2166. upload:
  2167. todoContentLength -= MULTIPART_CHUNK_SIZE * manager.next_etags_pos;
  2168. for (seq = manager.next_etags_pos + 1; seq <= totalSeq; seq++) {
  2169. memset(&partData, 0, sizeof(MultipartPartData));
  2170. partData.manager = &manager;
  2171. partData.seq = seq;
  2172. partData.put_object_data = data;
  2173. partContentLength = ((contentLength > MULTIPART_CHUNK_SIZE) ?
  2174. MULTIPART_CHUNK_SIZE : contentLength);
  2175. printf("%s Part Seq %d, length=%d\n", srcSize ? "Copying" : "Sending", seq, partContentLength);
  2176. partData.put_object_data.contentLength = partContentLength;
  2177. partData.put_object_data.originalContentLength = partContentLength;
  2178. partData.put_object_data.totalContentLength = todoContentLength;
  2179. partData.put_object_data.totalOriginalContentLength = totalContentLength;
  2180. putProperties.md5 = 0;
  2181. do {
  2182. if (srcSize) {
  2183. S3BucketContext srcBucketContext =
  2184. {
  2185. 0,
  2186. srcBucketName,
  2187. protocolG,
  2188. uriStyleG,
  2189. accessKeyIdG,
  2190. secretAccessKeyG,
  2191. 0,
  2192. awsRegionG
  2193. };
  2194. S3ResponseHandler copyResponseHandler = { &responsePropertiesCallback, &responseCompleteCallback };
  2195. int64_t lastModified;
  2196. unsigned long long startOffset = (unsigned long long)MULTIPART_CHUNK_SIZE * (unsigned long long)(seq-1);
  2197. unsigned long long count = partContentLength - 1; // Inclusive for copies
  2198. // The default copy callback tries to set this for us, need to allocate here
  2199. manager.etags[seq-1] = malloc(512); // TBD - magic #! Isa there a max etag defined?
  2200. S3_copy_object_range(&srcBucketContext, srcKey,
  2201. bucketName, key,
  2202. seq, manager.upload_id,
  2203. startOffset, count,
  2204. &putProperties,
  2205. &lastModified, 512 /*TBD - magic # */,
  2206. manager.etags[seq-1], 0,
  2207. timeoutMsG,
  2208. &copyResponseHandler, 0);
  2209. } else {
  2210. S3_upload_part(&bucketContext, key, &putProperties,
  2211. &putObjectHandler, seq, manager.upload_id,
  2212. partContentLength,
  2213. 0, timeoutMsG,
  2214. &partData);
  2215. }
  2216. } while (S3_status_is_retryable(statusG) && should_retry());
  2217. if (statusG != S3StatusOK) {
  2218. printError();
  2219. goto clean;
  2220. }
  2221. contentLength -= MULTIPART_CHUNK_SIZE;
  2222. todoContentLength -= MULTIPART_CHUNK_SIZE;
  2223. }
  2224. int i;
  2225. int size = 0;
  2226. size += growbuffer_append(&(manager.gb), "<CompleteMultipartUpload>",
  2227. strlen("<CompleteMultipartUpload>"));
  2228. char buf[256];
  2229. int n;
  2230. for (i = 0; i < totalSeq; i++) {
  2231. n = snprintf(buf, sizeof(buf), "<Part><PartNumber>%d</PartNumber>"
  2232. "<ETag>%s</ETag></Part>", i + 1, manager.etags[i]);
  2233. size += growbuffer_append(&(manager.gb), buf, n);
  2234. }
  2235. size += growbuffer_append(&(manager.gb), "</CompleteMultipartUpload>",
  2236. strlen("</CompleteMultipartUpload>"));
  2237. manager.remaining = size;
  2238. do {
  2239. S3_complete_multipart_upload(&bucketContext, key, &commit_handler,
  2240. manager.upload_id, manager.remaining,
  2241. 0, timeoutMsG, &manager);
  2242. } while (S3_status_is_retryable(statusG) && should_retry());
  2243. if (statusG != S3StatusOK) {
  2244. printError();
  2245. goto clean;
  2246. }
  2247. clean:
  2248. if(manager.upload_id) {
  2249. free(manager.upload_id);
  2250. }
  2251. for (i = 0; i < manager.next_etags_pos; i++) {
  2252. free(manager.etags[i]);
  2253. }
  2254. growbuffer_destroy(manager.gb);
  2255. free(manager.etags);
  2256. }
  2257. S3_deinitialize();
  2258. }
  2259. // copy object ---------------------------------------------------------------
  2260. static S3Status copyListKeyCallback(int isTruncated, const char *nextMarker,
  2261. int contentsCount,
  2262. const S3ListBucketContent *contents,
  2263. int commonPrefixesCount,
  2264. const char **commonPrefixes,
  2265. void *callbackData)
  2266. {
  2267. unsigned long long *size = (unsigned long long *)callbackData;
  2268. // These are unused, avoid warnings in a hopefully portable way
  2269. (void)(nextMarker);
  2270. (void)(commonPrefixesCount);
  2271. (void)(commonPrefixes);
  2272. (void)(isTruncated);
  2273. if (contentsCount != 1) {
  2274. // We either have no matched or multiples...can't perform the operation
  2275. return S3StatusErrorUnexpectedContent;
  2276. }
  2277. *size = (unsigned long long) contents->size;
  2278. return S3StatusOK;
  2279. }
  2280. static void copy_object(int argc, char **argv, int optindex)
  2281. {
  2282. if (optindex == argc) {
  2283. fprintf(stderr, "\nERROR: Missing parameter: source bucket/key\n");
  2284. usageExit(stderr);
  2285. }
  2286. // Split bucket/key
  2287. char *slash = argv[optindex];
  2288. while (*slash && (*slash != '/')) {
  2289. slash++;
  2290. }
  2291. if (!*slash || !*(slash + 1)) {
  2292. fprintf(stderr, "\nERROR: Invalid source bucket/key name: %s\n",
  2293. argv[optindex]);
  2294. usageExit(stderr);
  2295. }
  2296. *slash++ = 0;
  2297. const char *sourceBucketName = argv[optindex++];
  2298. const char *sourceKey = slash;
  2299. unsigned long long sourceSize = 0;
  2300. if (optindex == argc) {
  2301. fprintf(stderr, "\nERROR: Missing parameter: "
  2302. "destination bucket/key\n");
  2303. usageExit(stderr);
  2304. }
  2305. S3_init();
  2306. S3BucketContext listBucketContext =
  2307. {
  2308. 0,
  2309. sourceBucketName,
  2310. protocolG,
  2311. uriStyleG,
  2312. accessKeyIdG,
  2313. secretAccessKeyG,
  2314. 0,
  2315. awsRegionG
  2316. };
  2317. S3ListBucketHandler listBucketHandler =
  2318. {
  2319. { &responsePropertiesCallback, &responseCompleteCallback },
  2320. &copyListKeyCallback
  2321. };
  2322. // Find size of existing key to determine if MP required
  2323. do {
  2324. S3_list_bucket(&listBucketContext, sourceKey, NULL,
  2325. ".", 1, 0,
  2326. timeoutMsG, &listBucketHandler, &sourceSize);
  2327. } while (S3_status_is_retryable(statusG) && should_retry());
  2328. if (statusG != S3StatusOK) {
  2329. fprintf(stderr, "\nERROR: Unable to get source object size (%s)\n",
  2330. S3_get_status_name(statusG));
  2331. fprintf(stderr, "%s\n", errorDetailsG);
  2332. exit(1);
  2333. }
  2334. if (sourceSize > MULTIPART_CHUNK_SIZE) {
  2335. printf("\nUsing multipart copy because object size %llu is above %d.\n", sourceSize, MULTIPART_CHUNK_SIZE);
  2336. put_object(argc, argv, optindex, sourceBucketName, sourceKey, sourceSize);
  2337. return;
  2338. }
  2339. // Split bucket/key
  2340. slash = argv[optindex];
  2341. while (*slash && (*slash != '/')) {
  2342. slash++;
  2343. }
  2344. if (!*slash || !*(slash + 1)) {
  2345. fprintf(stderr, "\nERROR: Invalid destination bucket/key name: %s\n",
  2346. argv[optindex]);
  2347. usageExit(stderr);
  2348. }
  2349. *slash++ = 0;
  2350. const char *destinationBucketName = argv[optindex++];
  2351. const char *destinationKey = slash;
  2352. const char *cacheControl = 0, *contentType = 0;
  2353. const char *contentDispositionFilename = 0, *contentEncoding = 0;
  2354. int64_t expires = -1;
  2355. S3CannedAcl cannedAcl = S3CannedAclPrivate;
  2356. int metaPropertiesCount = 0;
  2357. S3NameValue metaProperties[S3_MAX_METADATA_COUNT];
  2358. char useServerSideEncryption = 0;
  2359. int anyPropertiesSet = 0;
  2360. while (optindex < argc) {
  2361. char *param = argv[optindex++];
  2362. if (!strncmp(param, CACHE_CONTROL_PREFIX,
  2363. CACHE_CONTROL_PREFIX_LEN)) {
  2364. cacheControl = &(param[CACHE_CONTROL_PREFIX_LEN]);
  2365. anyPropertiesSet = 1;
  2366. }
  2367. else if (!strncmp(param, CONTENT_TYPE_PREFIX,
  2368. CONTENT_TYPE_PREFIX_LEN)) {
  2369. contentType = &(param[CONTENT_TYPE_PREFIX_LEN]);
  2370. anyPropertiesSet = 1;
  2371. }
  2372. else if (!strncmp(param, CONTENT_DISPOSITION_FILENAME_PREFIX,
  2373. CONTENT_DISPOSITION_FILENAME_PREFIX_LEN)) {
  2374. contentDispositionFilename =
  2375. &(param[CONTENT_DISPOSITION_FILENAME_PREFIX_LEN]);
  2376. anyPropertiesSet = 1;
  2377. }
  2378. else if (!strncmp(param, CONTENT_ENCODING_PREFIX,
  2379. CONTENT_ENCODING_PREFIX_LEN)) {
  2380. contentEncoding = &(param[CONTENT_ENCODING_PREFIX_LEN]);
  2381. anyPropertiesSet = 1;
  2382. }
  2383. else if (!strncmp(param, EXPIRES_PREFIX, EXPIRES_PREFIX_LEN)) {
  2384. expires = parseIso8601Time(&(param[EXPIRES_PREFIX_LEN]));
  2385. if (expires < 0) {
  2386. fprintf(stderr, "\nERROR: Invalid expires time "
  2387. "value; ISO 8601 time format required\n");
  2388. usageExit(stderr);
  2389. }
  2390. anyPropertiesSet = 1;
  2391. }
  2392. else if (!strncmp(param, X_AMZ_META_PREFIX, X_AMZ_META_PREFIX_LEN)) {
  2393. if (metaPropertiesCount == S3_MAX_METADATA_COUNT) {
  2394. fprintf(stderr, "\nERROR: Too many x-amz-meta- properties, "
  2395. "limit %lu: %s\n",
  2396. (unsigned long) S3_MAX_METADATA_COUNT, param);
  2397. usageExit(stderr);
  2398. }
  2399. char *name = &(param[X_AMZ_META_PREFIX_LEN]);
  2400. char *value = name;
  2401. while (*value && (*value != '=')) {
  2402. value++;
  2403. }
  2404. if (!*value || !*(value + 1)) {
  2405. fprintf(stderr, "\nERROR: Invalid parameter: %s\n", param);
  2406. usageExit(stderr);
  2407. }
  2408. *value++ = 0;
  2409. metaProperties[metaPropertiesCount].name = name;
  2410. metaProperties[metaPropertiesCount++].value = value;
  2411. anyPropertiesSet = 1;
  2412. }
  2413. else if (!strncmp(param, USE_SERVER_SIDE_ENCRYPTION_PREFIX,
  2414. USE_SERVER_SIDE_ENCRYPTION_PREFIX_LEN)) {
  2415. if (!strcmp(param, "true") || !strcmp(param, "TRUE") ||
  2416. !strcmp(param, "yes") || !strcmp(param, "YES") ||
  2417. !strcmp(param, "1")) {
  2418. useServerSideEncryption = 1;
  2419. anyPropertiesSet = 1;
  2420. }
  2421. else {
  2422. useServerSideEncryption = 0;
  2423. }
  2424. }
  2425. else if (!strncmp(param, CANNED_ACL_PREFIX, CANNED_ACL_PREFIX_LEN)) {
  2426. char *val = &(param[CANNED_ACL_PREFIX_LEN]);
  2427. if (!strcmp(val, "private")) {
  2428. cannedAcl = S3CannedAclPrivate;
  2429. }
  2430. else if (!strcmp(val, "public-read")) {
  2431. cannedAcl = S3CannedAclPublicRead;
  2432. }
  2433. else if (!strcmp(val, "public-read-write")) {
  2434. cannedAcl = S3CannedAclPublicReadWrite;
  2435. }
  2436. else if (!strcmp(val, "authenticated-read")) {
  2437. cannedAcl = S3CannedAclAuthenticatedRead;
  2438. }
  2439. else {
  2440. fprintf(stderr, "\nERROR: Unknown canned ACL: %s\n", val);
  2441. usageExit(stderr);
  2442. }
  2443. anyPropertiesSet = 1;
  2444. }
  2445. else {
  2446. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  2447. usageExit(stderr);
  2448. }
  2449. }
  2450. S3BucketContext bucketContext =
  2451. {
  2452. 0,
  2453. sourceBucketName,
  2454. protocolG,
  2455. uriStyleG,
  2456. accessKeyIdG,
  2457. secretAccessKeyG,
  2458. 0,
  2459. awsRegionG
  2460. };
  2461. S3PutProperties putProperties =
  2462. {
  2463. contentType,
  2464. 0,
  2465. cacheControl,
  2466. contentDispositionFilename,
  2467. contentEncoding,
  2468. expires,
  2469. cannedAcl,
  2470. metaPropertiesCount,
  2471. metaProperties,
  2472. useServerSideEncryption
  2473. };
  2474. S3ResponseHandler responseHandler =
  2475. {
  2476. &responsePropertiesCallback,
  2477. &responseCompleteCallback
  2478. };
  2479. int64_t lastModified;
  2480. char eTag[256];
  2481. do {
  2482. S3_copy_object(&bucketContext, sourceKey, destinationBucketName,
  2483. destinationKey, anyPropertiesSet ? &putProperties : 0,
  2484. &lastModified, sizeof(eTag), eTag, 0,
  2485. timeoutMsG,
  2486. &responseHandler, 0);
  2487. } while (S3_status_is_retryable(statusG) && should_retry());
  2488. if (statusG == S3StatusOK) {
  2489. if (lastModified >= 0) {
  2490. char timebuf[256];
  2491. time_t t = (time_t) lastModified;
  2492. strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%SZ",
  2493. gmtime(&t));
  2494. printf("Last-Modified: %s\n", timebuf);
  2495. }
  2496. if (eTag[0]) {
  2497. printf("ETag: %s\n", eTag);
  2498. }
  2499. }
  2500. else {
  2501. printError();
  2502. }
  2503. S3_deinitialize();
  2504. }
  2505. // get object ----------------------------------------------------------------
  2506. static S3Status getObjectDataCallback(int bufferSize, const char *buffer,
  2507. void *callbackData)
  2508. {
  2509. FILE *outfile = (FILE *) callbackData;
  2510. size_t wrote = fwrite(buffer, 1, bufferSize, outfile);
  2511. return ((wrote < (size_t) bufferSize) ?
  2512. S3StatusAbortedByCallback : S3StatusOK);
  2513. }
  2514. static void get_object(int argc, char **argv, int optindex)
  2515. {
  2516. if (optindex == argc) {
  2517. fprintf(stderr, "\nERROR: Missing parameter: bucket/key\n");
  2518. usageExit(stderr);
  2519. }
  2520. // Split bucket/key
  2521. char *slash = argv[optindex];
  2522. while (*slash && (*slash != '/')) {
  2523. slash++;
  2524. }
  2525. if (!*slash || !*(slash + 1)) {
  2526. fprintf(stderr, "\nERROR: Invalid bucket/key name: %s\n",
  2527. argv[optindex]);
  2528. usageExit(stderr);
  2529. }
  2530. *slash++ = 0;
  2531. const char *bucketName = argv[optindex++];
  2532. const char *key = slash;
  2533. const char *filename = 0;
  2534. int64_t ifModifiedSince = -1, ifNotModifiedSince = -1;
  2535. const char *ifMatch = 0, *ifNotMatch = 0;
  2536. uint64_t startByte = 0, byteCount = 0;
  2537. while (optindex < argc) {
  2538. char *param = argv[optindex++];
  2539. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  2540. filename = &(param[FILENAME_PREFIX_LEN]);
  2541. }
  2542. else if (!strncmp(param, IF_MODIFIED_SINCE_PREFIX,
  2543. IF_MODIFIED_SINCE_PREFIX_LEN)) {
  2544. // Parse ifModifiedSince
  2545. ifModifiedSince = parseIso8601Time
  2546. (&(param[IF_MODIFIED_SINCE_PREFIX_LEN]));
  2547. if (ifModifiedSince < 0) {
  2548. fprintf(stderr, "\nERROR: Invalid ifModifiedSince time "
  2549. "value; ISO 8601 time format required\n");
  2550. usageExit(stderr);
  2551. }
  2552. }
  2553. else if (!strncmp(param, IF_NOT_MODIFIED_SINCE_PREFIX,
  2554. IF_NOT_MODIFIED_SINCE_PREFIX_LEN)) {
  2555. // Parse ifModifiedSince
  2556. ifNotModifiedSince = parseIso8601Time
  2557. (&(param[IF_NOT_MODIFIED_SINCE_PREFIX_LEN]));
  2558. if (ifNotModifiedSince < 0) {
  2559. fprintf(stderr, "\nERROR: Invalid ifNotModifiedSince time "
  2560. "value; ISO 8601 time format required\n");
  2561. usageExit(stderr);
  2562. }
  2563. }
  2564. else if (!strncmp(param, IF_MATCH_PREFIX, IF_MATCH_PREFIX_LEN)) {
  2565. ifMatch = &(param[IF_MATCH_PREFIX_LEN]);
  2566. }
  2567. else if (!strncmp(param, IF_NOT_MATCH_PREFIX,
  2568. IF_NOT_MATCH_PREFIX_LEN)) {
  2569. ifNotMatch = &(param[IF_NOT_MATCH_PREFIX_LEN]);
  2570. }
  2571. else if (!strncmp(param, START_BYTE_PREFIX, START_BYTE_PREFIX_LEN)) {
  2572. startByte = convertInt
  2573. (&(param[START_BYTE_PREFIX_LEN]), "startByte");
  2574. }
  2575. else if (!strncmp(param, BYTE_COUNT_PREFIX, BYTE_COUNT_PREFIX_LEN)) {
  2576. byteCount = convertInt
  2577. (&(param[BYTE_COUNT_PREFIX_LEN]), "byteCount");
  2578. }
  2579. else {
  2580. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  2581. usageExit(stderr);
  2582. }
  2583. }
  2584. FILE *outfile = 0;
  2585. if (filename) {
  2586. // Stat the file, and if it doesn't exist, open it in w mode
  2587. struct stat buf;
  2588. if (stat(filename, &buf) == -1) {
  2589. outfile = fopen(filename, "w" FOPEN_EXTRA_FLAGS);
  2590. }
  2591. else {
  2592. // Open in r+ so that we don't truncate the file, just in case
  2593. // there is an error and we write no bytes, we leave the file
  2594. // unmodified
  2595. outfile = fopen(filename, "r+" FOPEN_EXTRA_FLAGS);
  2596. }
  2597. if (!outfile) {
  2598. fprintf(stderr, "\nERROR: Failed to open output file %s: ",
  2599. filename);
  2600. perror(0);
  2601. exit(-1);
  2602. }
  2603. }
  2604. else if (showResponsePropertiesG) {
  2605. fprintf(stderr, "\nERROR: get -s requires a filename parameter\n");
  2606. usageExit(stderr);
  2607. }
  2608. else {
  2609. outfile = stdout;
  2610. }
  2611. S3_init();
  2612. S3BucketContext bucketContext =
  2613. {
  2614. 0,
  2615. bucketName,
  2616. protocolG,
  2617. uriStyleG,
  2618. accessKeyIdG,
  2619. secretAccessKeyG,
  2620. 0,
  2621. awsRegionG
  2622. };
  2623. S3GetConditions getConditions =
  2624. {
  2625. ifModifiedSince,
  2626. ifNotModifiedSince,
  2627. ifMatch,
  2628. ifNotMatch
  2629. };
  2630. S3GetObjectHandler getObjectHandler =
  2631. {
  2632. { &responsePropertiesCallback, &responseCompleteCallback },
  2633. &getObjectDataCallback
  2634. };
  2635. do {
  2636. S3_get_object(&bucketContext, key, &getConditions, startByte,
  2637. byteCount, 0, 0, &getObjectHandler, outfile);
  2638. } while (S3_status_is_retryable(statusG) && should_retry());
  2639. if (statusG != S3StatusOK) {
  2640. printError();
  2641. }
  2642. fclose(outfile);
  2643. S3_deinitialize();
  2644. }
  2645. // head object ---------------------------------------------------------------
  2646. static void head_object(int argc, char **argv, int optindex)
  2647. {
  2648. if (optindex == argc) {
  2649. fprintf(stderr, "\nERROR: Missing parameter: bucket/key\n");
  2650. usageExit(stderr);
  2651. }
  2652. // Head implies showing response properties
  2653. showResponsePropertiesG = 1;
  2654. // Split bucket/key
  2655. char *slash = argv[optindex];
  2656. while (*slash && (*slash != '/')) {
  2657. slash++;
  2658. }
  2659. if (!*slash || !*(slash + 1)) {
  2660. fprintf(stderr, "\nERROR: Invalid bucket/key name: %s\n",
  2661. argv[optindex]);
  2662. usageExit(stderr);
  2663. }
  2664. *slash++ = 0;
  2665. const char *bucketName = argv[optindex++];
  2666. const char *key = slash;
  2667. if (optindex != argc) {
  2668. fprintf(stderr, "\nERROR: Extraneous parameter: %s\n", argv[optindex]);
  2669. usageExit(stderr);
  2670. }
  2671. S3_init();
  2672. S3BucketContext bucketContext =
  2673. {
  2674. 0,
  2675. bucketName,
  2676. protocolG,
  2677. uriStyleG,
  2678. accessKeyIdG,
  2679. secretAccessKeyG,
  2680. 0,
  2681. awsRegionG
  2682. };
  2683. S3ResponseHandler responseHandler =
  2684. {
  2685. &responsePropertiesCallback,
  2686. &responseCompleteCallback
  2687. };
  2688. do {
  2689. S3_head_object(&bucketContext, key, 0, 0, &responseHandler, 0);
  2690. } while (S3_status_is_retryable(statusG) && should_retry());
  2691. if ((statusG != S3StatusOK) &&
  2692. (statusG != S3StatusErrorPreconditionFailed)) {
  2693. printError();
  2694. }
  2695. S3_deinitialize();
  2696. }
  2697. // generate query string ------------------------------------------------------
  2698. static void generate_query_string(int argc, char **argv, int optindex)
  2699. {
  2700. if (optindex == argc) {
  2701. fprintf(stderr, "\nERROR: Missing parameter: bucket[/key]\n");
  2702. usageExit(stderr);
  2703. }
  2704. const char *bucketName = argv[optindex];
  2705. const char *key = 0;
  2706. // Split bucket/key
  2707. char *slash = argv[optindex++];
  2708. while (*slash && (*slash != '/')) {
  2709. slash++;
  2710. }
  2711. if (*slash) {
  2712. *slash++ = 0;
  2713. key = slash;
  2714. }
  2715. else {
  2716. key = 0;
  2717. }
  2718. int expires = -1;
  2719. const char *resource = 0;
  2720. const char *httpMethod = "GET";
  2721. while (optindex < argc) {
  2722. char *param = argv[optindex++];
  2723. if (!strncmp(param, EXPIRES_PREFIX, EXPIRES_PREFIX_LEN)) {
  2724. expires = parseIso8601Time(&(param[EXPIRES_PREFIX_LEN]));
  2725. if (expires < 0) {
  2726. fprintf(stderr, "\nERROR: Invalid expires time "
  2727. "value; ISO 8601 time format required\n");
  2728. usageExit(stderr);
  2729. }
  2730. }
  2731. else if (!strncmp(param, RESOURCE_PREFIX, RESOURCE_PREFIX_LEN)) {
  2732. resource = &(param[RESOURCE_PREFIX_LEN]);
  2733. }
  2734. else if (!strncmp(param, HTTP_METHOD_PREFIX, HTTP_METHOD_PREFIX_LEN)) {
  2735. httpMethod = &(param[HTTP_METHOD_PREFIX_LEN]);
  2736. }
  2737. else {
  2738. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  2739. usageExit(stderr);
  2740. }
  2741. }
  2742. S3_init();
  2743. S3BucketContext bucketContext =
  2744. {
  2745. 0,
  2746. bucketName,
  2747. protocolG,
  2748. uriStyleG,
  2749. accessKeyIdG,
  2750. secretAccessKeyG,
  2751. 0,
  2752. awsRegionG
  2753. };
  2754. char buffer[S3_MAX_AUTHENTICATED_QUERY_STRING_SIZE];
  2755. S3Status status = S3_generate_authenticated_query_string
  2756. (buffer, &bucketContext, key, expires, resource, httpMethod);
  2757. if (status != S3StatusOK) {
  2758. printf("Failed to generate authenticated query string: %s\n",
  2759. S3_get_status_name(status));
  2760. }
  2761. else {
  2762. printf("%s\n", buffer);
  2763. }
  2764. S3_deinitialize();
  2765. }
  2766. // get acl -------------------------------------------------------------------
  2767. void get_acl(int argc, char **argv, int optindex)
  2768. {
  2769. if (optindex == argc) {
  2770. fprintf(stderr, "\nERROR: Missing parameter: bucket[/key]\n");
  2771. usageExit(stderr);
  2772. }
  2773. const char *bucketName = argv[optindex];
  2774. const char *key = 0;
  2775. // Split bucket/key
  2776. char *slash = argv[optindex++];
  2777. while (*slash && (*slash != '/')) {
  2778. slash++;
  2779. }
  2780. if (*slash) {
  2781. *slash++ = 0;
  2782. key = slash;
  2783. }
  2784. else {
  2785. key = 0;
  2786. }
  2787. const char *filename = 0;
  2788. while (optindex < argc) {
  2789. char *param = argv[optindex++];
  2790. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  2791. filename = &(param[FILENAME_PREFIX_LEN]);
  2792. }
  2793. else {
  2794. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  2795. usageExit(stderr);
  2796. }
  2797. }
  2798. FILE *outfile = 0;
  2799. if (filename) {
  2800. // Stat the file, and if it doesn't exist, open it in w mode
  2801. struct stat buf;
  2802. if (stat(filename, &buf) == -1) {
  2803. outfile = fopen(filename, "w" FOPEN_EXTRA_FLAGS);
  2804. }
  2805. else {
  2806. // Open in r+ so that we don't truncate the file, just in case
  2807. // there is an error and we write no bytes, we leave the file
  2808. // unmodified
  2809. outfile = fopen(filename, "r+" FOPEN_EXTRA_FLAGS);
  2810. }
  2811. if (!outfile) {
  2812. fprintf(stderr, "\nERROR: Failed to open output file %s: ",
  2813. filename);
  2814. perror(0);
  2815. exit(-1);
  2816. }
  2817. }
  2818. else if (showResponsePropertiesG) {
  2819. fprintf(stderr, "\nERROR: getacl -s requires a filename parameter\n");
  2820. usageExit(stderr);
  2821. }
  2822. else {
  2823. outfile = stdout;
  2824. }
  2825. int aclGrantCount;
  2826. S3AclGrant aclGrants[S3_MAX_ACL_GRANT_COUNT];
  2827. char ownerId[S3_MAX_GRANTEE_USER_ID_SIZE];
  2828. char ownerDisplayName[S3_MAX_GRANTEE_DISPLAY_NAME_SIZE];
  2829. S3_init();
  2830. S3BucketContext bucketContext =
  2831. {
  2832. 0,
  2833. bucketName,
  2834. protocolG,
  2835. uriStyleG,
  2836. accessKeyIdG,
  2837. secretAccessKeyG,
  2838. 0,
  2839. awsRegionG
  2840. };
  2841. S3ResponseHandler responseHandler =
  2842. {
  2843. &responsePropertiesCallback,
  2844. &responseCompleteCallback
  2845. };
  2846. do {
  2847. S3_get_acl(&bucketContext, key, ownerId, ownerDisplayName,
  2848. &aclGrantCount, aclGrants, 0,
  2849. timeoutMsG, &responseHandler, 0);
  2850. } while (S3_status_is_retryable(statusG) && should_retry());
  2851. if (statusG == S3StatusOK) {
  2852. fprintf(outfile, "OwnerID %s %s\n", ownerId, ownerDisplayName);
  2853. fprintf(outfile, "%-6s %-90s %-12s\n", " Type",
  2854. " User Identifier",
  2855. " Permission");
  2856. fprintf(outfile, "------ "
  2857. "------------------------------------------------------------"
  2858. "------------------------------ ------------\n");
  2859. int i;
  2860. for (i = 0; i < aclGrantCount; i++) {
  2861. S3AclGrant *grant = &(aclGrants[i]);
  2862. const char *type;
  2863. char composedId[S3_MAX_GRANTEE_USER_ID_SIZE +
  2864. S3_MAX_GRANTEE_DISPLAY_NAME_SIZE + 16];
  2865. const char *id;
  2866. switch (grant->granteeType) {
  2867. case S3GranteeTypeAmazonCustomerByEmail:
  2868. type = "Email";
  2869. id = grant->grantee.amazonCustomerByEmail.emailAddress;
  2870. break;
  2871. case S3GranteeTypeCanonicalUser:
  2872. type = "UserID";
  2873. snprintf(composedId, sizeof(composedId),
  2874. "%s (%s)", grant->grantee.canonicalUser.id,
  2875. grant->grantee.canonicalUser.displayName);
  2876. id = composedId;
  2877. break;
  2878. case S3GranteeTypeAllAwsUsers:
  2879. type = "Group";
  2880. id = "Authenticated AWS Users";
  2881. break;
  2882. case S3GranteeTypeAllUsers:
  2883. type = "Group";
  2884. id = "All Users";
  2885. break;
  2886. default:
  2887. type = "Group";
  2888. id = "Log Delivery";
  2889. break;
  2890. }
  2891. const char *perm;
  2892. switch (grant->permission) {
  2893. case S3PermissionRead:
  2894. perm = "READ";
  2895. break;
  2896. case S3PermissionWrite:
  2897. perm = "WRITE";
  2898. break;
  2899. case S3PermissionReadACP:
  2900. perm = "READ_ACP";
  2901. break;
  2902. case S3PermissionWriteACP:
  2903. perm = "WRITE_ACP";
  2904. break;
  2905. default:
  2906. perm = "FULL_CONTROL";
  2907. break;
  2908. }
  2909. fprintf(outfile, "%-6s %-90s %-12s\n", type, id, perm);
  2910. }
  2911. }
  2912. else {
  2913. printError();
  2914. }
  2915. fclose(outfile);
  2916. S3_deinitialize();
  2917. }
  2918. // set acl -------------------------------------------------------------------
  2919. void set_acl(int argc, char **argv, int optindex)
  2920. {
  2921. if (optindex == argc) {
  2922. fprintf(stderr, "\nERROR: Missing parameter: bucket[/key]\n");
  2923. usageExit(stderr);
  2924. }
  2925. const char *bucketName = argv[optindex];
  2926. const char *key = 0;
  2927. // Split bucket/key
  2928. char *slash = argv[optindex++];
  2929. while (*slash && (*slash != '/')) {
  2930. slash++;
  2931. }
  2932. if (*slash) {
  2933. *slash++ = 0;
  2934. key = slash;
  2935. }
  2936. else {
  2937. key = 0;
  2938. }
  2939. const char *filename = 0;
  2940. while (optindex < argc) {
  2941. char *param = argv[optindex++];
  2942. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  2943. filename = &(param[FILENAME_PREFIX_LEN]);
  2944. }
  2945. else {
  2946. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  2947. usageExit(stderr);
  2948. }
  2949. }
  2950. FILE *infile;
  2951. if (filename) {
  2952. if (!(infile = fopen(filename, "r" FOPEN_EXTRA_FLAGS))) {
  2953. fprintf(stderr, "\nERROR: Failed to open input file %s: ",
  2954. filename);
  2955. perror(0);
  2956. exit(-1);
  2957. }
  2958. }
  2959. else {
  2960. infile = stdin;
  2961. }
  2962. // Read in the complete ACL
  2963. char aclBuf[65536];
  2964. aclBuf[fread(aclBuf, 1, sizeof(aclBuf) - 1, infile)] = 0;
  2965. char ownerId[S3_MAX_GRANTEE_USER_ID_SIZE];
  2966. char ownerDisplayName[S3_MAX_GRANTEE_DISPLAY_NAME_SIZE];
  2967. // Parse it
  2968. int aclGrantCount;
  2969. S3AclGrant aclGrants[S3_MAX_ACL_GRANT_COUNT];
  2970. if (!convert_simple_acl(aclBuf, ownerId, ownerDisplayName,
  2971. &aclGrantCount, aclGrants)) {
  2972. fprintf(stderr, "\nERROR: Failed to parse ACLs\n");
  2973. fclose(infile);
  2974. exit(-1);
  2975. }
  2976. S3_init();
  2977. S3BucketContext bucketContext =
  2978. {
  2979. 0,
  2980. bucketName,
  2981. protocolG,
  2982. uriStyleG,
  2983. accessKeyIdG,
  2984. secretAccessKeyG,
  2985. 0,
  2986. awsRegionG
  2987. };
  2988. S3ResponseHandler responseHandler =
  2989. {
  2990. &responsePropertiesCallback,
  2991. &responseCompleteCallback
  2992. };
  2993. do {
  2994. S3_set_acl(&bucketContext, key, ownerId, ownerDisplayName,
  2995. aclGrantCount, aclGrants, 0,
  2996. timeoutMsG, &responseHandler, 0);
  2997. } while (S3_status_is_retryable(statusG) && should_retry());
  2998. if (statusG != S3StatusOK) {
  2999. printError();
  3000. }
  3001. fclose(infile);
  3002. S3_deinitialize();
  3003. }
  3004. // get lifecycle -------------------------------------------------------------------
  3005. void get_lifecycle(int argc, char **argv, int optindex)
  3006. {
  3007. if (optindex == argc) {
  3008. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  3009. usageExit(stderr);
  3010. }
  3011. const char *bucketName = argv[optindex++];
  3012. const char *filename = 0;
  3013. while (optindex < argc) {
  3014. char *param = argv[optindex++];
  3015. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  3016. filename = &(param[FILENAME_PREFIX_LEN]);
  3017. }
  3018. else {
  3019. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  3020. usageExit(stderr);
  3021. }
  3022. }
  3023. FILE *outfile = 0;
  3024. if (filename) {
  3025. // Stat the file, and if it doesn't exist, open it in w mode
  3026. struct stat buf;
  3027. if (stat(filename, &buf) == -1) {
  3028. outfile = fopen(filename, "w" FOPEN_EXTRA_FLAGS);
  3029. }
  3030. else {
  3031. // Open in r+ so that we don't truncate the file, just in case
  3032. // there is an error and we write no bytes, we leave the file
  3033. // unmodified
  3034. outfile = fopen(filename, "r+" FOPEN_EXTRA_FLAGS);
  3035. }
  3036. if (!outfile) {
  3037. fprintf(stderr, "\nERROR: Failed to open output file %s: ",
  3038. filename);
  3039. perror(0);
  3040. exit(-1);
  3041. }
  3042. }
  3043. else if (showResponsePropertiesG) {
  3044. fprintf(stderr, "\nERROR: getlifecycle -s requires a filename parameter\n");
  3045. usageExit(stderr);
  3046. }
  3047. else {
  3048. outfile = stdout;
  3049. }
  3050. char lifecycleBuffer[64 * 1024];
  3051. S3_init();
  3052. S3BucketContext bucketContext =
  3053. {
  3054. 0,
  3055. bucketName,
  3056. protocolG,
  3057. uriStyleG,
  3058. accessKeyIdG,
  3059. secretAccessKeyG,
  3060. 0,
  3061. awsRegionG
  3062. };
  3063. S3ResponseHandler responseHandler =
  3064. {
  3065. &responsePropertiesCallback,
  3066. &responseCompleteCallback
  3067. };
  3068. do {
  3069. S3_get_lifecycle(&bucketContext,
  3070. lifecycleBuffer, sizeof(lifecycleBuffer),
  3071. 0, timeoutMsG, &responseHandler, 0);
  3072. } while (S3_status_is_retryable(statusG) && should_retry());
  3073. if (statusG == S3StatusOK) {
  3074. fprintf(outfile, "%s", lifecycleBuffer);
  3075. }
  3076. else {
  3077. printError();
  3078. }
  3079. fclose(outfile);
  3080. S3_deinitialize();
  3081. }
  3082. // set lifecycle -------------------------------------------------------------------
  3083. void set_lifecycle(int argc, char **argv, int optindex)
  3084. {
  3085. if (optindex == argc) {
  3086. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  3087. usageExit(stderr);
  3088. }
  3089. const char *bucketName = argv[optindex++];
  3090. const char *filename = 0;
  3091. while (optindex < argc) {
  3092. char *param = argv[optindex++];
  3093. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  3094. filename = &(param[FILENAME_PREFIX_LEN]);
  3095. }
  3096. else {
  3097. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  3098. usageExit(stderr);
  3099. }
  3100. }
  3101. FILE *infile;
  3102. if (filename) {
  3103. if (!(infile = fopen(filename, "r" FOPEN_EXTRA_FLAGS))) {
  3104. fprintf(stderr, "\nERROR: Failed to open input file %s: ",
  3105. filename);
  3106. perror(0);
  3107. exit(-1);
  3108. }
  3109. }
  3110. else {
  3111. infile = stdin;
  3112. }
  3113. // Read in the complete ACL
  3114. char lifecycleBuf[65536];
  3115. lifecycleBuf[fread(lifecycleBuf, 1, sizeof(lifecycleBuf) - 1, infile)] = 0;
  3116. S3_init();
  3117. S3BucketContext bucketContext =
  3118. {
  3119. 0,
  3120. bucketName,
  3121. protocolG,
  3122. uriStyleG,
  3123. accessKeyIdG,
  3124. secretAccessKeyG,
  3125. 0,
  3126. awsRegionG
  3127. };
  3128. S3ResponseHandler responseHandler =
  3129. {
  3130. &responsePropertiesCallback,
  3131. &responseCompleteCallback
  3132. };
  3133. do {
  3134. S3_set_lifecycle(&bucketContext,
  3135. lifecycleBuf,
  3136. 0, timeoutMsG, &responseHandler, 0);
  3137. } while (S3_status_is_retryable(statusG) && should_retry());
  3138. if (statusG != S3StatusOK) {
  3139. printError();
  3140. }
  3141. fclose(infile);
  3142. S3_deinitialize();
  3143. }
  3144. // get logging ----------------------------------------------------------------
  3145. void get_logging(int argc, char **argv, int optindex)
  3146. {
  3147. if (optindex == argc) {
  3148. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  3149. usageExit(stderr);
  3150. }
  3151. const char *bucketName = argv[optindex++];
  3152. const char *filename = 0;
  3153. while (optindex < argc) {
  3154. char *param = argv[optindex++];
  3155. if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  3156. filename = &(param[FILENAME_PREFIX_LEN]);
  3157. }
  3158. else {
  3159. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  3160. usageExit(stderr);
  3161. }
  3162. }
  3163. FILE *outfile = 0;
  3164. if (filename) {
  3165. // Stat the file, and if it doesn't exist, open it in w mode
  3166. struct stat buf;
  3167. if (stat(filename, &buf) == -1) {
  3168. outfile = fopen(filename, "w" FOPEN_EXTRA_FLAGS);
  3169. }
  3170. else {
  3171. // Open in r+ so that we don't truncate the file, just in case
  3172. // there is an error and we write no bytes, we leave the file
  3173. // unmodified
  3174. outfile = fopen(filename, "r+" FOPEN_EXTRA_FLAGS);
  3175. }
  3176. if (!outfile) {
  3177. fprintf(stderr, "\nERROR: Failed to open output file %s: ",
  3178. filename);
  3179. perror(0);
  3180. exit(-1);
  3181. }
  3182. }
  3183. else if (showResponsePropertiesG) {
  3184. fprintf(stderr, "\nERROR: getlogging -s requires a filename "
  3185. "parameter\n");
  3186. usageExit(stderr);
  3187. }
  3188. else {
  3189. outfile = stdout;
  3190. }
  3191. int aclGrantCount;
  3192. S3AclGrant aclGrants[S3_MAX_ACL_GRANT_COUNT];
  3193. char targetBucket[S3_MAX_BUCKET_NAME_SIZE];
  3194. char targetPrefix[S3_MAX_KEY_SIZE];
  3195. S3_init();
  3196. S3BucketContext bucketContext =
  3197. {
  3198. 0,
  3199. bucketName,
  3200. protocolG,
  3201. uriStyleG,
  3202. accessKeyIdG,
  3203. secretAccessKeyG,
  3204. 0,
  3205. awsRegionG
  3206. };
  3207. S3ResponseHandler responseHandler =
  3208. {
  3209. &responsePropertiesCallback,
  3210. &responseCompleteCallback
  3211. };
  3212. do {
  3213. S3_get_server_access_logging(&bucketContext, targetBucket, targetPrefix,
  3214. &aclGrantCount, aclGrants, 0,
  3215. timeoutMsG,
  3216. &responseHandler, 0);
  3217. } while (S3_status_is_retryable(statusG) && should_retry());
  3218. if (statusG == S3StatusOK) {
  3219. if (targetBucket[0]) {
  3220. printf("Target Bucket: %s\n", targetBucket);
  3221. if (targetPrefix[0]) {
  3222. printf("Target Prefix: %s\n", targetPrefix);
  3223. }
  3224. fprintf(outfile, "%-6s %-90s %-12s\n", " Type",
  3225. " User Identifier",
  3226. " Permission");
  3227. fprintf(outfile, "------ "
  3228. "---------------------------------------------------------"
  3229. "--------------------------------- ------------\n");
  3230. int i;
  3231. for (i = 0; i < aclGrantCount; i++) {
  3232. S3AclGrant *grant = &(aclGrants[i]);
  3233. const char *type;
  3234. char composedId[S3_MAX_GRANTEE_USER_ID_SIZE +
  3235. S3_MAX_GRANTEE_DISPLAY_NAME_SIZE + 16];
  3236. const char *id;
  3237. switch (grant->granteeType) {
  3238. case S3GranteeTypeAmazonCustomerByEmail:
  3239. type = "Email";
  3240. id = grant->grantee.amazonCustomerByEmail.emailAddress;
  3241. break;
  3242. case S3GranteeTypeCanonicalUser:
  3243. type = "UserID";
  3244. snprintf(composedId, sizeof(composedId),
  3245. "%s (%s)", grant->grantee.canonicalUser.id,
  3246. grant->grantee.canonicalUser.displayName);
  3247. id = composedId;
  3248. break;
  3249. case S3GranteeTypeAllAwsUsers:
  3250. type = "Group";
  3251. id = "Authenticated AWS Users";
  3252. break;
  3253. default:
  3254. type = "Group";
  3255. id = "All Users";
  3256. break;
  3257. }
  3258. const char *perm;
  3259. switch (grant->permission) {
  3260. case S3PermissionRead:
  3261. perm = "READ";
  3262. break;
  3263. case S3PermissionWrite:
  3264. perm = "WRITE";
  3265. break;
  3266. case S3PermissionReadACP:
  3267. perm = "READ_ACP";
  3268. break;
  3269. case S3PermissionWriteACP:
  3270. perm = "WRITE_ACP";
  3271. break;
  3272. default:
  3273. perm = "FULL_CONTROL";
  3274. break;
  3275. }
  3276. fprintf(outfile, "%-6s %-90s %-12s\n", type, id, perm);
  3277. }
  3278. }
  3279. else {
  3280. printf("Service logging is not enabled for this bucket.\n");
  3281. }
  3282. }
  3283. else {
  3284. printError();
  3285. }
  3286. fclose(outfile);
  3287. S3_deinitialize();
  3288. }
  3289. // set logging ----------------------------------------------------------------
  3290. void set_logging(int argc, char **argv, int optindex)
  3291. {
  3292. if (optindex == argc) {
  3293. fprintf(stderr, "\nERROR: Missing parameter: bucket\n");
  3294. usageExit(stderr);
  3295. }
  3296. const char *bucketName = argv[optindex++];
  3297. const char *targetBucket = 0, *targetPrefix = 0, *filename = 0;
  3298. while (optindex < argc) {
  3299. char *param = argv[optindex++];
  3300. if (!strncmp(param, TARGET_BUCKET_PREFIX, TARGET_BUCKET_PREFIX_LEN)) {
  3301. targetBucket = &(param[TARGET_BUCKET_PREFIX_LEN]);
  3302. }
  3303. else if (!strncmp(param, TARGET_PREFIX_PREFIX,
  3304. TARGET_PREFIX_PREFIX_LEN)) {
  3305. targetPrefix = &(param[TARGET_PREFIX_PREFIX_LEN]);
  3306. }
  3307. else if (!strncmp(param, FILENAME_PREFIX, FILENAME_PREFIX_LEN)) {
  3308. filename = &(param[FILENAME_PREFIX_LEN]);
  3309. }
  3310. else {
  3311. fprintf(stderr, "\nERROR: Unknown param: %s\n", param);
  3312. usageExit(stderr);
  3313. }
  3314. }
  3315. int aclGrantCount = 0;
  3316. S3AclGrant aclGrants[S3_MAX_ACL_GRANT_COUNT];
  3317. if (targetBucket) {
  3318. FILE *infile;
  3319. if (filename) {
  3320. if (!(infile = fopen(filename, "r" FOPEN_EXTRA_FLAGS))) {
  3321. fprintf(stderr, "\nERROR: Failed to open input file %s: ",
  3322. filename);
  3323. perror(0);
  3324. exit(-1);
  3325. }
  3326. }
  3327. else {
  3328. infile = stdin;
  3329. }
  3330. // Read in the complete ACL
  3331. char aclBuf[65536];
  3332. aclBuf[fread(aclBuf, 1, sizeof(aclBuf), infile)] = 0;
  3333. char ownerId[S3_MAX_GRANTEE_USER_ID_SIZE];
  3334. char ownerDisplayName[S3_MAX_GRANTEE_DISPLAY_NAME_SIZE];
  3335. // Parse it
  3336. if (!convert_simple_acl(aclBuf, ownerId, ownerDisplayName,
  3337. &aclGrantCount, aclGrants)) {
  3338. fprintf(stderr, "\nERROR: Failed to parse ACLs\n");
  3339. fclose(infile);
  3340. exit(-1);
  3341. }
  3342. fclose(infile);
  3343. }
  3344. S3_init();
  3345. S3BucketContext bucketContext =
  3346. {
  3347. 0,
  3348. bucketName,
  3349. protocolG,
  3350. uriStyleG,
  3351. accessKeyIdG,
  3352. secretAccessKeyG,
  3353. 0,
  3354. awsRegionG
  3355. };
  3356. S3ResponseHandler responseHandler =
  3357. {
  3358. &responsePropertiesCallback,
  3359. &responseCompleteCallback
  3360. };
  3361. do {
  3362. S3_set_server_access_logging(&bucketContext, targetBucket,
  3363. targetPrefix, aclGrantCount, aclGrants,
  3364. 0,
  3365. timeoutMsG, &responseHandler, 0);
  3366. } while (S3_status_is_retryable(statusG) && should_retry());
  3367. if (statusG != S3StatusOK) {
  3368. printError();
  3369. }
  3370. S3_deinitialize();
  3371. }
  3372. // main ----------------------------------------------------------------------
  3373. int main(int argc, char **argv)
  3374. {
  3375. // Parse args
  3376. while (1) {
  3377. int idx = 0;
  3378. int c = getopt_long(argc, argv, "vfhusr:t:g:", longOptionsG, &idx);
  3379. if (c == -1) {
  3380. // End of options
  3381. break;
  3382. }
  3383. switch (c) {
  3384. case 'f':
  3385. forceG = 1;
  3386. break;
  3387. case 'h':
  3388. uriStyleG = S3UriStyleVirtualHost;
  3389. break;
  3390. case 'u':
  3391. protocolG = S3ProtocolHTTP;
  3392. break;
  3393. case 's':
  3394. showResponsePropertiesG = 1;
  3395. break;
  3396. case 'r': {
  3397. const char *v = optarg;
  3398. retriesG = 0;
  3399. while (*v) {
  3400. retriesG *= 10;
  3401. retriesG += *v - '0';
  3402. v++;
  3403. }
  3404. }
  3405. break;
  3406. case 't': {
  3407. const char *v = optarg;
  3408. timeoutMsG = 0;
  3409. while (*v) {
  3410. timeoutMsG *= 10;
  3411. timeoutMsG += *v - '0';
  3412. v++;
  3413. }
  3414. }
  3415. break;
  3416. case 'v':
  3417. verifyPeerG = S3_INIT_VERIFY_PEER;
  3418. break;
  3419. case 'g':
  3420. awsRegionG = strdup(optarg);
  3421. break;
  3422. default:
  3423. fprintf(stderr, "\nERROR: Unknown option: -%c\n", c);
  3424. // Usage exit
  3425. usageExit(stderr);
  3426. }
  3427. }
  3428. // The first non-option argument gives the operation to perform
  3429. if (optind == argc) {
  3430. fprintf(stderr, "\n\nERROR: Missing argument: command\n\n");
  3431. usageExit(stderr);
  3432. }
  3433. const char *command = argv[optind++];
  3434. if (!strcmp(command, "help")) {
  3435. fprintf(stdout, "\ns3 is a program for performing single requests "
  3436. "to Amazon S3.\n");
  3437. usageExit(stdout);
  3438. }
  3439. accessKeyIdG = getenv("S3_ACCESS_KEY_ID");
  3440. if (!accessKeyIdG) {
  3441. fprintf(stderr, "Missing environment variable: S3_ACCESS_KEY_ID\n");
  3442. return -1;
  3443. }
  3444. secretAccessKeyG = getenv("S3_SECRET_ACCESS_KEY");
  3445. if (!secretAccessKeyG) {
  3446. fprintf(stderr,
  3447. "Missing environment variable: S3_SECRET_ACCESS_KEY\n");
  3448. return -1;
  3449. }
  3450. if (!strcmp(command, "list")) {
  3451. list(argc, argv, optind);
  3452. }
  3453. else if (!strcmp(command, "test")) {
  3454. test_bucket(argc, argv, optind);
  3455. }
  3456. else if (!strcmp(command, "create")) {
  3457. create_bucket(argc, argv, optind);
  3458. }
  3459. else if (!strcmp(command, "delete")) {
  3460. if (optind == argc) {
  3461. fprintf(stderr,
  3462. "\nERROR: Missing parameter: bucket or bucket/key\n");
  3463. usageExit(stderr);
  3464. }
  3465. char *val = argv[optind];
  3466. int hasSlash = 0;
  3467. while (*val) {
  3468. if (*val++ == '/') {
  3469. hasSlash = 1;
  3470. break;
  3471. }
  3472. }
  3473. if (hasSlash) {
  3474. delete_object(argc, argv, optind);
  3475. }
  3476. else {
  3477. delete_bucket(argc, argv, optind);
  3478. }
  3479. }
  3480. else if (!strcmp(command, "put")) {
  3481. put_object(argc, argv, optind, NULL, NULL, 0);
  3482. }
  3483. else if (!strcmp(command, "copy")) {
  3484. copy_object(argc, argv, optind);
  3485. }
  3486. else if (!strcmp(command, "get")) {
  3487. get_object(argc, argv, optind);
  3488. }
  3489. else if (!strcmp(command, "head")) {
  3490. head_object(argc, argv, optind);
  3491. }
  3492. else if (!strcmp(command, "gqs")) {
  3493. generate_query_string(argc, argv, optind);
  3494. }
  3495. else if (!strcmp(command, "getacl")) {
  3496. get_acl(argc, argv, optind);
  3497. }
  3498. else if (!strcmp(command, "setacl")) {
  3499. set_acl(argc, argv, optind);
  3500. }
  3501. else if (!strcmp(command, "getlifecycle")) {
  3502. get_lifecycle(argc, argv, optind);
  3503. }
  3504. else if (!strcmp(command, "setlifecycle")) {
  3505. set_lifecycle(argc, argv, optind);
  3506. }
  3507. else if (!strcmp(command, "getlogging")) {
  3508. get_logging(argc, argv, optind);
  3509. }
  3510. else if (!strcmp(command, "setlogging")) {
  3511. set_logging(argc, argv, optind);
  3512. }
  3513. else if (!strcmp(command, "listmultiparts")) {
  3514. list_multipart_uploads(argc, argv, optind);
  3515. }
  3516. else if (!strcmp(command, "abortmp")) {
  3517. abort_multipart_upload(argc, argv, optind);
  3518. }
  3519. else if (!strcmp(command, "listparts")) {
  3520. list_parts(argc, argv, optind);
  3521. }
  3522. else {
  3523. fprintf(stderr, "Unknown command: %s\n", command);
  3524. return -1;
  3525. }
  3526. return 0;
  3527. }