synology dsm 3rd party apps developer guide

Post on 01-Jan-2017

299 Views

Category:

Documents

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

0

1

1.1

2

2.1

2.1.1

2.1.2

2.1.3

2.2

2.2.1

2.2.2

2.2.3

2.2.4

2.2.5

2.3

2.4

2.5

2.6

3

3.1

3.2

3.2.1

3.2.2

3.3

3.4

3.4.1

3.5

3.6

4

4.1

4.2

4.2.1

4.2.2

4.2.3

4.2.4

4.3

4.4

4.5

4.6

TableofContentsPackageDeveloperGuide

GettingStarted

SystemRequirements

CreatePackage

Preparation

InstallToolkit

PrepareBuildEnvironment

PrepareGPGKey

HelloWorldPackage

BuildStage

PackStage

SignPackage

EssentialRunTimeFiles

Summary

CompileOpenSourceProject:tmux

CompileOpenSourceProject:nmap

CompileKernelModules

Advanced

SynologyPackage

PackageStructure

INFO

NecessaryFields

OptionalFields

package.tgz

scripts

ScriptEnvironmentVariables

conf

WIZARD_UIFILES

IntegrateYourPackageintoDSM

ManageStorageforApplicationFiles

IntegrateYourPackageintoDSMWebGUI

Startup

Config

IntegrateHelpDocumentintoDSMHelp

IntegratewithDSMWebAuthentication

DSMBackwardCompatibility

ShowMessagestoUsers

CreatePHPApplication

RunScriptsWhentheSystemBoots

SynologyDSM6.0DeveloperGuide

2

4.7

4.8

4.9

4.9.1

4.9.2

4.9.3

4.9.3.1

4.10

4.10.1

4.10.2

4.10.3

4.10.4

4.10.4.1

4.10.4.2

4.10.4.3

4.10.4.4

4.10.4.5

4.10.4.6

4.10.4.7

4.10.4.8

5

5.1

5.2

5.3

6

6.1

7

7.1

7.2

7.3

7.4

LocaleSupport

InstallPackageRelatedPortsInformationintoDSM

LowerPrivilege

PackageUser&Group

Mechanism

PrivilegeSpecification

Categories

ResourceAcquisition

ResourceSpecification

Timing

ConfigUpdate

AvailableWorkers

/usr/locallinker

Apache2.2Config

DataShare

IndexDB

MariaDB

PHPINI

PortConfig

SyslogConfig

PublishSynologyPackages

GetStartedwithPublishing

SubmittingthePackageforApproval

RespondingtoUserIssues

AppendixA:PlatformandArchValueMappingTable

RevisionHistory

AppendixB:CompileApplicationsManually

DownloadDSMToolChain

Compile

CompileOpenSourceProjects

CompileKernelModules

SynologyDSM6.0DeveloperGuide

3

SynologyDSM6.0DeveloperGuideTHISDOCUMENTCONTAINSPROPRIETARYTECHNICALINFORMATIONWHICHISTHEPROPERTYOFSYNOLOGYINCORPORATEDANDSHALLNOTBEREPRODUCED,COPIED,ORUSEDASTHEBASISFORDESIGN,MANUFACTURING,ORSALEOFAPPARATUSWITHOUTWRITTENPERMISSIONOFSYNOLOGYINCORPORATED

Copyright

SynologyInc.®2016SynologyInc.Allrightsreserved.

Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmitted,inanyformorbyanymeans,mechanical,electronic,photocopying,recording,orotherwise,withoutpriorwrittenpermissionofSynologyInc.,withthefollowingexceptions:AnypersonisherebyauthorizedtostoredocumentationonasinglecomputerforpersonaluseonlyandtoprintcopiesofdocumentationforpersonaluseprovidedthatthedocumentationcontainsSynology’scopyrightnotice.

TheSynologylogoisatrademarkofSynologyInc.

Nolicenses,expressorimplied,aregrantedwithrespecttoanyofthetechnologydescribedinthisdocument.Synologyretainsallintellectualpropertyrightsassociatedwiththetechnologydescribedinthisdocument.ThisdocumentisintendedtoassistapplicationdeveloperstodevelopapplicationsonlyforSynology-labeledcomputers.

Everyefforthasbeenmadetoensurethattheinformationinthisdocumentisaccurate.Synologyisnotresponsiblefortypographicalerrors.

SynologyInc.3F-3,No.106,Chang-AnW.Rd.Taipei103,Taiwan

SynologyandtheSynologylogoaretrademarksofSynologyInc.,registeredintheUnitedStatesandothercountries.

MarvellisregisteredtrademarksofMarvellSemiconductor,Inc.oritssubsidiariesintheUnitedStatesandothercountries.

FreescaleisregisteredtrademarksofFreescale.IntelandAtomisregisteredtrademarksofIntel.

Semiconductor,Inc.oritssubsidiariesintheUnitedStatesandothercountries.

Otherproductsandcompanynamesmentionedhereinaretrademarksoftheirrespectiveholders.

EventhoughSynologyhasreviewedthisdocument,SYNOLOGYMAKESNOWARRANTYORREPRESENTATION,EITHEREXPRESSORIMPLIED,WITHRESPECTTOTHISDOCUMENT,ITSQUALITY,ACCURACY,MERCHANTABILITY,ORFITNESSFORAPARTICULARPURPOSE.ASARESULT,THISDOCUMENTISPROVIDED“ASIS,”ANDYOU,THEREADER,AREASSUMINGTHEENTIRERISKASTOITSQUALITYANDACCURACY.INNOEVENTWILLSYNOLOGYBELIABLEFORDIRECT,INDIRECT,SPECIAL,INCIDENTAL,ORCONSEQUENTIALDAMAGESRESULTINGFROMANYDEFECTORINACCURACYINTHISDOCUMENT,evenifadvisedofthepossibilityofsuchdamages.

THEWARRANTYANDREMEDIESSETFORTHABOVEAREEXCLUSIVEANDINLIEUOFALLOTHERS,ORALORWRITTEN,EXPRESSORIMPLIED.NoSynologydealer,agent,oremployeeisauthorizedtomakeanymodification,extension,oradditiontothiswarranty.

Somestatesdonotallowtheexclusionorlimitationofimpliedwarrantiesorliabilityforincidentalorconsequentialdamages,sotheabovelimitationorexclusionmaynotapplytoyou.Thiswarrantygivesyouspecificlegalrights,andyoumayalsohaveotherrightswhichvaryfromstatetostate.

SynologyDSM6.0DeveloperGuide

4PackageDeveloperGuide

GettingStartedSynologyoffersthisdeveloperguidewithinstructionsonhowtodevelopandinstall3rd-partyapplicationsonSynologyNASproductsoralineofnetworkattachedstoragedevicesdevelopedontheLinuxkernel.Withthisguide,youcanfamiliarizeyourselfwiththefollowingprocedures:

CompileprogramstorunonaSynologyNAS.IntegrateapplicationswithSynologyDiskStationManager(DSM).InstallapplicationfilestotherecommendedpathtokeepthemintactwhenDSMisupgraded.IntegrateapplicationswiththeSynologywebauthenticationinterface.Createapackagefileformanualorone-clickinstallationinSynologyPackageCenter.

ThisdocumentiswrittenforSynologyusersandsystemintegratorswhoareinterestedinaddingtheirapplicationstotheirSynologyNAS.ThosewhoreadthisdocumentareassumedtohavesomebasicunderstandingofLinuxprogramming.

SynologyDSM6.0DeveloperGuide

5GettingStarted

SystemRequirements

ToolkitRequirements

InordertocompileprogramstorunontheSynologyNAS,thesystemmustmeetthefollowingrequirements.

64bitgenericlinuxenvironment.(Forexample,Ubuntu16.04LTS)bash(>=4.1.5)Python(>=2.7.3)Requirerootpermission.(Ourtoolkitwillusechrootcommand)

PleasedoNOTuseSynologyNASbasesystemtoinstalltoolkitasyourdevelopmentenvironment.NASsystemisspecializedforstorage,notforgenericdevelopingpurpose.

Instead,youcaninstallSynologyDockerpackageonNASandsetupagenericlinuxcontainertoinstallthetoolkit.

PackageRuntimeOSSuggestions

Theresultingpackage(.spk)willhavebestcompatibilityrunningon

SynologyNASversionDSM6.0+

SynologyDSM6.0DeveloperGuide

6SystemRequirements

CreatePackageInthissection,wewillexplainhowtocreateaSynologyPackageusingPackageToolkit.

IfyouwanttobuildaSynologyPackagewithoutusingPackageToolkit,youmust:

PrepareacrosscompiletoolchainPrepareabuildenvironmentPreparemetadataCompilesourcecodeCreateandsignthepackage

Creatingapackagemanuallycanbeverycomplexformostdevelopers,sowerecommendedusingthePackageToolkittomakethepackagecreationprocesseasier.Tomakethepackagecreationprocessgosmoothly,youwillstillneedtowritesomescriptsdescribinghowyouwanttobuildandcreateyourpackages.

Inthefollowingsub-sections,thenecessaryscriptswillbestatedindetail.

Youcandownloadtheexamplesourcefromgithub:SynologyOpenSource

SynologyDSM6.0DeveloperGuide

7CreatePackage

Preparation:Inthissection,wewillguideyouthroughhowtosetupanenvironmentforbuildingaSynologyPackage.Detailedstepsinclude:

InstallToolkitPrepareBuildEnvironmentPrepareGPGKey

SynologyDSM6.0DeveloperGuide

8Preparation

InstallToolkitThistutorialconsistsoftwoparts:

Pre-builtenvironmentFront-endscripts

ToolkitInstallation:

Toinstallthetookit,simplyrefertothefollowingsteps.First,youneedtoclonethefront-endscriptsfromthislinktoyourtoolkitbase.(ForDSM5.x,usethislinkinstead.)

Wewilluse/toolkitastoolkitbaseinthisdocumentfromnowon.

mkdir-p/toolkit

gitclone{{book.externalLinks.pkgscripts}}pkgscripts

Pre-buildEnvironment:Forfasterdevelopment,wehavepreparedseveralbuildenvironmentsthatdependondifferentarchitecturesforpackagedevelopers.Youdon'thavetoworryaboutthenecessarybuilt-timelibraries(.aand.so)andheaderfiles(.hand.hpp)whenyouaredevelopingyourpackage.Thisisbecausethebuildenvironmentsalreadycontainsomepre-builtprojectswhoseexecutablebinariesorsharedlibrariesarebuiltonDSM,forexample,zlib,libxml2,andsoon.

Frond-endScripts:Wehavealsoprovidedfront-endscriptsinafoldernamed“pkgscripts”tomaketheenvironmentdeployment,packagecompilation,andcreationofthefinalpackageSPKfileeasier.Inmostcases,youonlyneedtousethesethreescriptswhiledevelopingapackage:

EnvDeployPkgCreate.pyinclude/pkg_utils.sh

ThenextsectionwillguideyouthroughhowtoestablishabuildenvironmentandcreateaSynologyPackagebyusingPackageToolkit.

SynologyDSM6.0DeveloperGuide

9InstallToolkit

PrepareBuildEnvironmentYoucandownloadandsetuppre-builtenvironmentsbyusingEnvDeploywiththefollowingcommands.Use-vtospecifyDSMversion,-ptospecifydesiredplatform,and-ttospecifythefilelocationwhenyoustoredthetoolkitlocallyonyourdevelopmentmachine.If-pisnotgiven,allavailableplatformsforgivenversionswillbesetup.

cd/toolkit/pkgscripts/

./EnvDeploy-v6.0-px64#forexample

Theworkingdirectorywilllooklikethefollowingfigure.Thechrootenvironmenttobuildyourownprojectswillbeds.${platform}-${version}.Asmentionedbefore,thistoolkitcontainssomepre-builtlibrariesandheaderswhichcanbefoundundercrossgccsysroot.Sysrootisdefaultsearchpathofcompiler.Ifgcccannotfindheaderorlibraryfrompathusergiven,gccwillsearchsysroot/usr/{lib,include}.

AvailablePlatformsYoucanuseoneofthefollowingcommandstoshowavailableplatforms.If-visnotgiven,availableplatformsforallversionswillbelisted.

./EnvDeploy-v6.0--list

./EnvDeploy-v6.0--infoplatform

UpdateEnvironmentUseEnvDeployagaintoupdateyourenvironments.Forexample,youcanupdatex64forDSM6.0byusingthefollowingcommand.

./EnvDeploy-v6.0-px64

RemoveEnvironmentToremoveabuildenvironment,youneedtoapplychroottothebuildenvironment.Unmountthe/procfolderandexitchroot.Afterthat,removethebuildenvironmentfolder.Thefollowingcommandsillustratehowtoremoveabuildenvironmentwithversion6.0andplatformx64.

chroot/toolkit/build_env/ds.x64-6.0umount/proc

rm-rf/toolkit/build_env/ds.x64-6.0

SynologyDSM6.0DeveloperGuide

10PrepareBuildEnvironment

PrepareGPGKeyIfthebuildenvironmentis5.0orabove,thePackageToolkitwilluseagpgkeytosignthepackagewhencreatingthespkfile.PleaserefertoPackageSignatureformoredetailsaboutpackagesignatures.

IfyouhaveyourownGPGkey(withoutapassphrase)already,youwillneedtoputtheprivatekeyin/root/.gnupgundereachplatform(/toolkit/build_env/ds.${platform}-6.0/root/.gnupg/).

GeneratetheGPGkey

Requirement:gpg,gpg-agent

gpg--gen-key

>Pleaseselectwhatkindofkeyyouwant:

(1)RSAandRSA(default)

>choosekeysizeandenteryourname,email

>enterapassphrase:justpressEnterwithouttypinganycharacter

WARNING:Pleasemakesurethatyoudonottypeanycharactersinthepassphrasefield,otherwisethebuildprocesswillFAIL.

Aftercompletingthestepsabove,thekeywillbegeneratedunder~/.gnupg.Movethemwiththechrootenvironment.

cp~/.gnupg/*/toolkit/build_env/ds.${platform}-6.0/root/.gnupg/

Youcanalsousethefollowingcommandstoverifywhetherthekeywassuccessfullyimportedornot.

cd/toolkit/build_env/ds.${platform}-6.0/

chroot.

gpg-K

Theoutputmayproducethefollowingmessage.

/root/.gnupg/secring.gpg

------------------------

sec2048R/145E0AFD2015-12-21

uidSynologyInc.<synology_inc@synology.com>

ssb2048R/E0C20F112015-12-21

SynologyDSM6.0DeveloperGuide

11PrepareGPGKey

HelloWorldPackageWeusethefront-endscriptPkgCreate.pytohelpuscompilesourcecodeandpackaSynologyPackageoraSPKfile.SPKisthefileformatusedbySynologyPackageCentertoproperlyinstallyourapplication.FormoredetailsaboutthestructuralformatofanSPKfile,youmayrefertoSynologyPackage.

Inthefollowingsections,wewillguideyouonhowtocreateasimpleutilityprogramthatcanprintoutsystemmemory,andpackitintoanSPKfilebyusingPkgCreate.py.

Formorecomplicatedcases,youcanrefertothefollowingexamplesprovided:

CompileOpenSourceProject:tmux:IfyouareinterestedinportinganopensourceprojecttoDSMsystemusingtmuxorsettingupanyadvancedconfigurations,youmayrefertothissection.CompileOpenSourceProject:nmap:IfyouareinterestedinportinganopensourceprojecttoDSMsystemusingnmaporsettingupanyadvancedconfigurations,youmayrefertothissection.CompileKernelModule:IfyouareinterestedininstallingmorekernelmodulestoyourDSMsystem,youmayrefertothissection.

CreatePackageWorkflow:

TherearetwostagesinthePkgCreate.pypackagecreationprocess,theBuildStageandthePackStage.

IntheBuildStage,PkgCreate.pywillcompileyourprojectandalldependentprojectsinthecorrectorder.InthePackStage,PkgCreate.pywillpackyourprojectintoanSPKfile.

TocreateyourSPKfilewithPkgCreate.pyproperly,youwillneedtoprovideadditionalconfigurationfilesandbuildscriptstodescribehowtobuildyourproject.Thesefilesareputinafoldernamed“SynoBuildConf”underyourproject.Thesefilesandtheirpurposearelistedinbelow.

SynoBuildConf/depends:definesthedependencyofyourproject.Forfurtherdetails,pleaserefertoBuildStageSynoBuildConf/build:specifiesPkgCreate.pyonhowtocompileyourproject.Forfurtherdetails,pleaserefertoBuildStageSynoBuildConf/install:specifiesPkgCreate.pyonhowtopackyourSPKfile.Forfurtherdetails,pleaserefertoPackStageSynoBuildConf/install-dev:similartoSynoBuildConf/install,butthiswillpackyourSPKfileinchrootenvironmentratherthangeneralDSMsystem.Forfurtherdetails,pleaserefertoCompileOpenSourceProject:nmap.

Formoredetailsabouttheseconfigurationfiles,pleaserefertoBuildStageandPackStage.Thefollowingfigureshowstheworkflowofthesetwostages.

SynologyDSM6.0DeveloperGuide

12HelloWorldPackage

YoucanusethefollowingcommandstotellPkgCreate.pyhowtorunthroughbothstages.

cd/toolkit

pkgscripts/PkgCreate.py-x0-c${project}

The-coptiontellsPkgCreate.pytobuild,pack,andsignyourproject.The-x0optionismeanttotraverseandbuildalldependentprojectsinthecorrectorder.EachprojectisbuiltaccordingtotheirownSynoBuildConf/build.

Note:PkgCreate.pycompilessourcecodeandpacksyourpackageunderchrootenvironment.Therefore,youmustrunallcommandswithrootpermissionorwithsudo.

PkgCreate.pyhasmanyotheroptionstocontrolthebuildflow.ThefollowingsubsectionswillexploredeeperintothoseoptionsoryoumaydirectlyrefertotheAdvancedsectionformoredetails.

SourceCodeLayout:InBuildStage,PkgCreate.pywilltrytolinkalltheprojectstothebuildenvironment.Asaresult,yourprojectsourcecodemustbeputinafolder(wecallita“project”)under/toolkit/source.Thefollowingfigureshowsthewholeworkingdirectoryasanexample.

SynologyDSM6.0DeveloperGuide

13HelloWorldPackage

toolkit/

├──build_env/

│└──ds.${platform}-${version}/

│└──/usr/syno/

│├──bin

│├──include

│└──lib

├──pkgscripts/

└──source/

└──minimalPkg/

├──minimalPkg.c

├──INFO.sh

├──Makefile

├──PACKAGE_ICON.PNG

├──PACKAGE_ICON_256.PNG

├──scripts/

│├──postinst

│├──postuninst

│├──postupgrade

│├──preinst

│├──preuninst

│├──preupgrade

│└──start-stop-status

└──SynoBuildConf/

├──build

├──depends

└──install

Note:YoumayorganizethesourcecodeinanystructureyoulikeaslongasSynoBuildConfiseditedcorrectly.Thefollowingsectionswillexplainthisindetail.

Belowissomesamplecodethatwewilluseasanexample.

//Copyright(c)2000-2016SynologyInc.Allrightsreserved.

#include<sys/sysinfo.h>

#include<syslog.h>

#include<stdio.h>

intmain(intargc,char**argv){

structsysinfoinfo;

intret;

if(ret!=0){

syslog(LOG_SYSLOG,"Failedtogetinfo\n");

return-1;

}

syslog(LOG_SYSLOG,"[MinimalPkg]%ssamplepackage...",argv[1]);

syslog(LOG_SYSLOG,"[MinimalPkg]TotalRam:%u\n",(unsignedint)info.totalram);

syslog(LOG_SYSLOG,"[MinimalPkg]FreeRAM:%u\n",(unsignedint)info.freeram);

return0;

}

EnvironmentVariablesinBuildandInstallScriptFront-endscriptswillpasssomeenvironmentvariablestoSynoBuildConf/buildandSynoBuildConf/install.Youcanutilizethemtobuildandinstallyourprojects.Youcanalsofindmostofthemin/toolkit/build_env/ds.${platform}-${version}/{env.mak,env32/64.mak}.Someoftheenvironmentvariablesarelistedinbelow.

CC:pathofgcccrosscompiler.CXX:pathofg++crosscompiler.LD:pathofcrosscompilerlinker.

SynologyDSM6.0DeveloperGuide

14HelloWorldPackage

CFLAGS:globalcflagsincludes.AR:pathofcrosscompilerar.NM:pathofcrosscompilernm.STRIP:pathofcrosscompilerstrip.RANLIB:pathofcrosscompilerranlib.OBJDUMP:pathofcrosscompilerobjdump.LDFLAGS:globalldflagsincludes.ConfigOpt:optionsforconfigure.ARCH:processorarchitecture.SYNO_PLATFORM:Synologyplatform.DSM_SHLIB_MAJOR:majornumberofDSM(integer).DSM_SHLIB_MINOR:minornumberofDSM(integer).DSM_SHLIB_NUM:buildnumberofDSM(integer).ToolChainSysRoot:crosscompilersysrootpath.SysRootPrefix:crosscompilersysrootconcatwithprefix/usr.SysRootInclude:crosscompilersysrootconcatwithinclude_dir/usr/include.SysRootLib:crosscompilersysrootconcatwithlib_dir/usr/lib.

SynologyDSM6.0DeveloperGuide

15HelloWorldPackage

BuildStage:IntheBuildStage,PkgCreate.pywillcompiletheprojectanditsdependentprojects.Pleasenotethatinthisstage,PkgCreate.pydependsontwobuildscripts(SynoBuildConf/buildandSynoBuildConf/depend)togetthenecessaryinformation.

PkgCreate.py${project}#buildproject

BuildStageWorkflow:

TheworkflowoftheBuildStageisasfollows.

1. BasedonyourSynoBuildConf/depend,PkgCreate.pywilllocatethetargetDSMversionfrom[default]section.2. PkgCreate.pywillresolvetheprojectsyoudependon.3. Yourprojectandthedependentprojectswhichareplacedunder/toolkit/sourcewillbehard-linkedto

/toolkit/build_env/ds.${platform}/source.4. TheirSynoBuildConf/buildwillbeexecutedinorderaccordingtotheirdependencybasedoneachSynoBuildConf/depend.5. Ifyourprojectisneededbyotherprojectforcrosscompiling,youmayaddSynoBuildConf/install-devscript.install-devscript

willinstallcrosscompiledproductintoplatformchroot.

Note:SynoBuildConf/buildisexecutedunderchrootenvironment/toolkit/build_env/ds.${platform}.

SynoBuildConf/depends

PkgCreate.pywillresolveyourdependencyaccordingtothisconfigurationfile.Youneedtospecifyyourprojectdependencyandthebuildenvironmentofyourprojectinthisfile.Forexample:

SynologyDSM6.0DeveloperGuide

16BuildStage

[BuildDependent]

#eachlinehereisadependentproject

[ReferenceOnly]

#eachlinehereisaprojectforreferenceonlybutnoneedtobebuilt

[default]

all="6.0"#toolkitenvironmentversionofspecificplatform.(allplatformuse6.0toolkitenvironment)

TherearethreefieldsinSynoBuildConf/depends.

BuildDependent:Describesotherprojectswhicharedependentonthisproject.Forfurtherdetailsaboutthisfield,pleaserefertoCompileOpenSourceProject:nmap.ReferenceOnly:Describesotherprojectswhicharereferredbythisproject,withoutthebuildprocess.default:Describesthetoolkitenvironment.Thissectionisanecessaryfield.ItindicateseachplatformtobuildagainstsomeDSMversionandthekey"all"meansallplatformusethisversionbydefault.

YoucanuseProjDepends.pyfront-endscriptstoseewhetherthedependencyorderofyourprojectsiscorrect.Option-x0willtraversealldependentprojectsof${project}.

cd/toolkit/pkgscripts

./ProjDepends.py-x0${project}

Ifyourapplicationcontainsmorethanoneproject,putthemin/toolkit/sourceandeditSynoBuildConfaccordinglyforeachofthem.

Formoreadvancedusageofthisfile,youmayrefertoCompileOpenSourceProjectandAdvanced.

SynoBuildConf/build

SynoBuildConf/buildisashellscriptthattellsPkgCreate.pyhowtocompileyourproject.Thecurrentworkingdirectoryofthisshellscriptislocatedin/source/${project}underchrootenvironment.

Allpre-builtbinaries,headers,andlibrariesareundercrosscompilersysrootinchrootenvironment.Sincesysrootisthedefaultsearchpathofcrosscompiler,youdonotneedtoprovide-Ior-LtoCFLAGSorLDFLAGS.

Variables:

AllvariableyoucanuseinSynoBuildConf/build:

CC:pathofgcccrosscompiler.CXX:pathofg++crosscompiler.LD:pathofcrosscompilerlinker.CFLAGS:globalcflagsincludes.AR:pathofcrosscompilerar.NM:pathofcrosscompilernm.STRIP:pathofcrosscompilerstrip.RANLIB:pathofcrosscompilerranlib.OBJDUMP:pathofcrosscompilerobjdump.LDFLAGS:globalldflagsincludes.ConfigOpt:optionsforconfigure.ARCH:processorarchitecture.SYNO_PLATFORM:Synologyplatform.DSM_SHLIB_MAJOR:majornumberofDSM(integer).DSM_SHLIB_MINOR:minornumberofDSM(integer).DSM_SHLIB_NUM:buildnumberofDSM(integer).ToolChainSysRoot:crosscompilersysrootpath.

SynologyDSM6.0DeveloperGuide

17BuildStage

SysRootPrefix:crosscompilersysrootconcatwithprefix/usr.SysRootInclude:crosscompilersysrootconcatwithinclude_dir/usr/include.SysRootLib:crosscompilersysrootconcatwithlib_dir/usr/lib.

Theexamplebuildscriptsislike:

#SynoBuildConf/build

case${MakeClean}in

[Yy][Ee][Ss])

makedistclean

;;

esac

make${MAKE_FLAGS}

TheaboveexamplecallsthemakecommandandcompilesyourprojectaccordingtoyourMakefilelocatedin/source/${project}.

Synologytoolkitenvironmenthasincludedselectedprebuildprojects.Youcanenterthechrootandusefollowingcommandtocheckifneededheaderorprojectisprovidedbytoolkit.

##innerchroot

dpkg-l#listalldpkgprojects.

dpkg-L{projectdev}#listprojectinstallfiles

dpkg-S{header/librarypattern}#searchheader/librarypattern.

Forexample,theprojectneedszlib.handlibz.sointhebuildstage.Usefollowingcommandtocheckifzlibanditscomponentareinstalledinchroot.

chroot/tookit/build_env/ds.x64-6.0/

##innerchroot

>>dpkg-l|grepzlib

iizlib-1.x-x64-dev6.0-7274allSynologybuild-timelibrary

>>dpkg-Lzlib-1.x-x64-dev

/.

/usr

/usr/local

/usr/local/x86_64-pc-linux-gnu

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.so

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.a

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/pkgconfig

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/pkgconfig/zlib.pc

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.so.1

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.so.1.2.8

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/include

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/include/zconf.h

/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/include/zlib.h

>>dpkg-Szlib.so

zlib-1.x-x64-dev:/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.so

zlib-1.x-x64-dev:/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.so.1.2.8

zlib-1.x-x64-dev:/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/libz.so.1

Allfilehasbeeninstalledintosysroot,crossgcccanfindzlib.handlibz.sodirectly.

Someopensourcerequiretouseotherprojects'crosscompiledproductwhilebuildingtheirown.Forexample,pythonneedslibffiandzlibwhileconfigure,weneedtoprovidethosetwoprojectbeforebuildpython.Youcaninstallthecrosscompiledproductintothedestinationyouwantinbuildscript.PleaserefertoCompileOpenSourceProject:nmapformoreinformation.

SynologyDSM6.0DeveloperGuide

18BuildStage

Makefile

ThefollowingexampleshowsaMakefile.Mostofthecontentcontainstypicalmakefilerules.NotethatwhenwritingyourprojectMakefile,youcanutilizepre-definedvariablesin/env.mak.

#Copyright(c)2000-2016SynologyInc.Allrightsreserved.

##YoucanuseCCCFALGSLDLDFLAGSCXXCXXFLAGSARRANLIBREADELFSTRIPafterincludeenv.mak

include/env.mak

EXEC=minimalPkg

OBJS=minimalPkg.o

all:$(EXEC)

$(EXEC):$(OBJS)

$(CC)$(CFLAGS)$<-o$@$(LDFLAGS)

install:$(EXEC)

mkdir-p$(DESTDIR)/usr/bin/

install$<$(DESTDIR)/usr/bin/

clean:

rm-rf*.o$(EXEC)

Formoredetaileddescriptionsaboutmakefile,pleaserefertohere.Forafulllistofenvironmentvariablesthatareprovidedby/env.mak,pleaserefertoCreatePackage.

SynologyDSM6.0DeveloperGuide

19BuildStage

PackStage:InthePackStage,PkgCreate.pypacksallthenecessaryfilesaccordingtoyourmetadataandcreatesafinalSynologyPackageintheresult_spkfolder.IfyouwantPkgCreate.pytoenterthePackStagewithouttheBuildStage,simplyrunPkgCreate.pywiththe-ioption.

Forexample,thefollowingcommandwillexecute${project}/SynoBuildConf/installwithoutsigningandputtingthefinalpackageSPKfile(ifany)to/toolkit/result_spk.

cd/toolkit

pkgscripts/PkgCreate.py-i--no-sign${project}

PackStageWorkFlow:

TheworkflowofthePackStageisasfollows.

1. PkgCreate.pywillexecutethebuildscriptSynoBuildConf/install.i. CreateINFOfilebyusingINFO.sh.ii. Movenecessaryfilestoatemporaryfolder,/tmp/_install,forinstance,andcreatepackagetgz.iii. Movenecessarymetadataandresourcestothetemporaryfolder,/tmp/_pkg,forinstance,andcreatethefinalSynology

Package.2. PkgCreate.pywillsignthenewlycreatedSynologyPackagefilewithagpgkeywhichisplacedunder/root/.

ThefollowingfigureshowstheworkflowofthePackStage.

SynoBuildConf/install

SynologyDSM6.0DeveloperGuide

20PackStage

Thisfilemustbewritteninbashandindicatesthefront-endscriptonhowtopackyourproject.Thecurrentworkingdirectoryis/source/${project}underchrootenvironment.Ifthisisthetopprojectofyourpackage,thisfilewilldefinehowtocreatethefinalpackageSPKfile,includingdirectorystructureandtheINFOfileinyourSPK.(PleaserefertoINFOchapter)

DefineSynoBuildConf/installforinstallationmetadata,resourcefilesandpackingyourpackage.

#!/bin/bash

#Copyright(C)2000-2016SynologyInc.Allrightsreserved.

###UsePKG_DIRasworkingdirectory.

PKG_DIR=/tmp/_test_spk

rm-rf$PKG_DIR

mkdir-p$PKG_DIR

###getspkpackingfunctions

source/pkgscripts/include/pkg_util.sh

create_inner_tarball(){

localinner_tarball_dir=/tmp/_inner_tarball

###cleardestinationdirectory

rm-rf$inner_tarball_dir&&mkdir-p$inner_tarball_dir

###installneededfileintoPKG_DIR

makeinstallDESTDIR="$inner_tarball_dir"

###createpackage.txz:$1=source_dir,$2=dest_dir

pkg_make_inner_tarball$inner_tarball_dir"${PKG_DIR}"

}

create_spk(){

localscripts_dir=$PKG_DIR/scripts

###CopyPackageCenterscriptstoPKG_DIR

mkdir-p$scripts_dir

cp-avscripts/*$scripts_dir

###Copypackageicon

cp-avPACKAGE_ICON*.PNG$PKG_DIR

###GenerateINFOfile

./INFO.sh>INFO

cpINFO$PKG_DIR/INFO

###Createthefinalspk.

#pkg_make_spk<sourcepath><destpath><spkfilename>

#Pleaseputtheresultspkinto/image/packages

#spknamefunctions:pkg_get_spk_namepkg_get_spk_unified_namepkg_get_spk_family_name

mkdir-p/image/packages

pkg_make_spk${PKG_DIR}"/image/packages"$(pkg_get_spk_family_name)

}

create_inner_tarball

create_spk

Wewillbrieflyexplainthescriptsabove.

Inthebeginning,thescriptwillcallthePrepareDirsfunctionwhichwillpreparethenecessaryfolderfortheproject.

Aftercreatingthefolder,thescriptcalledSetupPackageFileswillmovethenecessaryresourcefilesto$INST_DIRand$PKG_DIR.Inthisstep,wehavecalledtheINFO.shfiletocreatetheINFOfile.AlthoughyoumayputthecodesthatwillgeneratetheINFOfileintheSynoBuildConf/installscript,wehighlyrecommendthatyoucreatetheINFOseperately.Generally,wenameitINFO.sh.YoucanseehowtowriteINFO.shinthefollowingsubsections.

INFOscriptsbinary

SynologyDSM6.0DeveloperGuide

21PackStage

Aftermovingtheresourcefiletotheproperlocation,wewillcalltheMakePackagefunctiontocreatethepackageforus.Wehaveincluded/sourcedahelperscriptcalledpkg_util.shwhichislocatedin/pkgscripts/include.ThisscriptcreatesthefinalpackageSPKfileinthecorrectformat.Thepkg_make_packageandpkg_make_spk,whicharedefinedin*pkg_util.sh,createtheSynologyPackage.Youcanseehowtousethishelperfunctionbelow.

pkg_make_inner_tarball$1$2:Create$2/packages.tgzfromfilesin$1.pkg_make_spk$1$2:Create$2/spkfromfilesin$1.

INFO.sh

Asmentionedearlier,INFO.shisjustanoptionalscript.YoucancreatetheINFOfilebyhandormovethecodetoSynoBuildConf/install.However,westronglyrecommendthatyouutilizeINFO.shsothatyoucancreatetheINFOfileseparatelyfromSynoBuildConf/install.

#!/bin/bash

#Copyright(c)2000-2016SynologyInc.Allrightsreserved.

source/pkgscripts/include/pkg_util.sh

package="minimalPkg"

version="1.0.0000"

displayname="MinimalPackage"

maintainer="SynologyInc."

arch="$(pkg_get_unified_platform)"

description="thisisaminimalpackage"

["$(caller)"!="0NULL"]&&return0

pkg_dump_info

Note:Theabovecodeisjustanexampletoshowsomeimportantvariablesforpkg_dump_info.IfyouwanttoknowmoredetailsabouttheINFOfileandeachofthefields,pleaserefertoINFO.

SimilartoSynoBuildConf/install,wemustfirstincludepkg_util.sh.Afterthat,wecansetupthepropervariablesandcallthepkg_dump_infotocreatetheINFOfilecorrectly.

Asyoumayhavenoticed,weusedanotherhelperfunctioncalledpkg_get_platformtosetthearchvariable.Thisvariableindicatesthecurrentplatformwearebuilding.

Thefollowingstatementsindicatehowtousethehelperfunctions.

pkg_get_spk_platform:Returnplatformfor“arch”inINFO.pkg_dump_info:DumpINFOaccordingtogivenvariables.

AftercreatingtheINFO.shfile,remembertoaddexecutablebitinINFO.sh.

chmod+xINFO.sh

Packutilfunctions

Synologypackageframeworkprovidesseveralfunctionsandandincreasesefficiencyofpackingpackages.ThefunctionssuchasgeneratingarchinformationintheINFOfile,separatingspknameandcreatingspkwillbeenableafterexecuting/pkgscripts/include/pkg_util.shundefined.

Platformfunctions

Aspkcanbeinstalledononeormoreplatforms.YoucandecidewhichplatformscaninstallthisspkviaspkINFOfile.

SynologyDSM6.0DeveloperGuide

22PackStage

functionname Values Description

(Nofunction) noarch Packageonlycontainscripts.spkcanberunonallsynologymodels.

pkg_get_platform_family(DSM6.0only)

x86_64i686armv7armv5ppc...

Unifyplatformswithsamekernelintoaplatformfamily.spkcanrunonsamefamilysynologymodels.

pkg_get_spk_platform bromolowcedarviewqoriqarmadaxp...

Directlyoutputtheplatformwherethetoolkitenvironmentisused.spkonlycanberunonthespecificplatform.

First,ifyourpackagedoesn'thaveanybinary,youcanusenoarchastheplatfromandwritethescriptsforyourpackage.Packagewitharch=noarchcanbeinstalledontoanysynologymodel.Second,ifyourpackagedoesn’thaveanykernelrelatedfunctions,thepackagecanrunonthesamearchitectureplatforms.Usefunctionpkg_get_platform_familytogetplatformfamily.Packagecanbeinstalledonthemodelswhichareincludedinthesameplatformfamily.Forexample,packagewitharch=x86_64canbeinstallontobromolowx64cedarviewdockerx64broadwellmodels.Pleaserefertotheplatformfamilymapatgithub.(Note:PlatformfamilyonlysupportDSM6.0orupperversion)Third,ifyourpackagecontainkernelrelatedfunctions,everyplatformswillneedaspecificspk.Pleaseusefunctionpkg_get_spk_platformtogettheplatform(s)whichbecompatiablewithyourtoolkitenvironment.

spknamefunctions

Afterspkgenerated,weneedtodistinguishspknamefromplatform.Wecanusespknamefunctions:

Functionname Correspondingplatformfunction Example Description

pkg_get_spk_name pkg_get_spk_platform

minimalPkg-bromolow-1.0.0000.spk/minimalPkg-cedarview-1.0.0000.spk...

spknamedependonwhichtoolkitenvironmentisusing.

pkg_get_spk_name noarch minimalPkg-1.0.0000.spk

Ifpackageplatform="noarch",thisfunctionwilloutputspknamewithoutplatforninfo.

pkg_get_spk_family_name pkg_get_platform_familyminimalPkg-x86_64-1.0.0000.spk

spknamewillbeunifiedintoplatformfamily.Thesameplatformfamilywillgeneatesamespkname.i.ebromolowandx64willhassamespkname.

YouneedtoinputINFOpathasargument.Ifnopathinput,thefunctionwillgetINFOfilefrom$PKG_DIR/INFOautomaticallywithoutinputtingINFOpath.

Createspkfunction

Developercanusepkg_make_spktocreatespk.

Usage:

pkg_make_spk$source_path$dest_path$spk_name

source_pathisspksourcedirectory.Allspkfilesmustcopyintothisdirecotrybeforerunpkg_make_spk.

dest_pathistargetspkpath.

spk_nameisspknamewith/withoutplatforminfo.

Example:

pkg_make_spk/tmp/_test_spk"/image/packages"$(pkg_get_spk_family_name)

SynologyDSM6.0DeveloperGuide

23PackStage

SynologyDSM6.0DeveloperGuide

24PackStage

SignPackageInDSM5.1andonward,thePackageCenterhasabuilt-incodesignmechanismtoensurethepackage'spublisherintegrity.ThetoolkitbasedonDSM5.0andonwardhastheCodeSign.phpscripttosignthepackagewithGnuPGkeys.IfyoudonothaveaGPGkey,youwillneedtogenerateone.PleaserefertoPrepareGPGKeyformoreinformation.

IfyouwantPkgCreate.pytosignthepackageautomatically,youcanusethePkgCreate.pywithoutthe--no-signoption.Forexample,thefollowingcommandindicatesPkgCreate.pytobuildandinstallyourprojectwithoutasignature.

PkgCreate.py-i${project}

Inaddition,ifyouwanttosignthepackageonyourown,youcanusethefollowingcommandtosignyourpackagemanually.

chroot/toolkit/build_env/ds.${platform}-${version}

php/pkgscripts/CodeSign.php[option]--sign=package-path

Options:

--keydir=keyringsdirectory(defaultis/root/.gnupg)

--keyfpr=key'sfingerprint(defaultis"".Underthiscircumstances,wewillusingthefirstkeyinthekeydirectorytosignthepackage)

Examples:

php/pkgscripts/CodeSign.php--sign=phpBB-3.0.12-0031.spk

php/pkgscripts/CodeSign.php--keydir=/root/.gpg--keyfpr=C1BF63CD--sign=phpBB-3.0.12-0031.spk

SynologyDSM6.0DeveloperGuide

25SignPackage

EssentialRunTimeFiles

Scripts:

The“scripts”foldercontainsshellscriptswhichareexecutedduringtheinstallation,uninstallation,upgrading,starting,andstoppingofpackages.Therearesevenscriptfilesstoredinthe“scripts”folder:

postinstpostuninstpostupgradepreinstpreuninstpreupgradestart-stop-status

Note:Evenifyoudonotprovideanyofthesescriptfiles,thepackagewillbecreatedwithoutanyerrors.However,whenyoutrytoinstallyourpackageonyourDSMsystem,PackageCenterwillnotbeabletoinstallyourpackage.

Forsimplicity,thescriptswilllooklikethefollowingexample.

#!/bin/sh

exit0

Moredetailsaboutthesescriptswillbeexplainedinthescriptssection.

Icon:

YoucanaddanicontoyourpackagesothatwhenPackageCentershowstheinformationofyourpackage,itwillusetheiconyouhaveprovidedinsteadofthedefaultone.

Toaddanicontoyourpackage,puttheimageyourwantintoyourprojectsourcefolder,thenslightlymodifyyourSynoBuildConf/installscript.ThefollowingisanexampleofamodifiedSynoBuildConf/installfromthepreviousexample.Forfurtherdetailsregardingpackageicons,pleaserefertothePackageStructuresection.

Theonlydifferencefromthepreviousexampleisthatwecopiedourimagefilesintothe$PKG_DIRandrenamedittoPACKAGE_ICON.PNGandPACKAGE_ICON_256.PNG.insidetheSetupPackageFilesfunction.

Note:RemembertorenameyourimagetoPACKAGE_ICON.PNGandPACKAGE_ICON_256.PNGinallCAPS;otherwise,PackageCenterwillnotrendertheiconproperly.

SynologyDSM6.0DeveloperGuide

26EssentialRunTimeFiles

#!/bin/bash

#Copyright(C)2000-2016SynologyInc.Allrightsreserved.

###UsePKG_DIRasworkingdirectory.

PKG_DIR=/tmp/_test_spk

rm-rf$PKG_DIR

mkdir-p$PKG_DIR

###getspkpackingfunctions

source/pkgscripts/include/pkg_util.sh

create_inner_tarball(){

localinner_tarball_dir=/tmp/_inner_tarball

###cleardestinationdirectory

rm-rf$inner_tarball_dir&&mkdir-p$inner_tarball_dir

###installneededfileintoPKG_DIR

makeinstallDESTDIR="$inner_tarball_dir"

###createpackage.txz:$1=source_dir,$2=dest_dir

pkg_make_inner_tarball$inner_tarball_dir"${PKG_DIR}"

}

create_spk(){

localscripts_dir=$PKG_DIR/scripts

###CopyPackageCenterscriptstoPKG_DIR

mkdir-p$scripts_dir

cp-avscripts/*$scripts_dir

###Copypackageicon

cp-avPACKAGE_ICON*.PNG$PKG_DIR

###GenerateINFOfile

./INFO.sh>INFO

cpINFO$PKG_DIR/INFO

###Createthefinalspk.

#pkg_make_spk<sourcepath><destpath><spkfilename>

#Pleaseputtheresultspkinto/image/packages

#spknamefunctions:pkg_get_spk_namepkg_get_spk_unified_namepkg_get_spk_family_name

mkdir-p/image/packages

pkg_make_spk${PKG_DIR}"/image/packages"$(pkg_get_spk_family_name)

}

create_inner_tarball

create_spk

SynologyDSM6.0DeveloperGuide

27EssentialRunTimeFiles

SummaryInprevioussections,welearnedhowtousePackageTooltocompileandpackyourproject.Wewilllistsomeimportantnoteshere.

SourceCodeLayout:

toolkit/

├──pkgscripts/

├──build_env/

│└──ds.${platform}-${version}

│└──/usr/syno

│├──lib

│├──bin

│└──include

├──result_spk/

│└──${package}-${version}/

│└──*.spk

└──source/

└──${project}/

├──sourcecode,Makefile...

├──INFO.sh

├──PACKAGE_ICON.PNG

├──PACKAGE_ICON_256.PNG

├──scripts/

│├──postinst

│├──postuninst

│├──postupgrade

│├──preinst

│├──preuninst

│├──preupgrade

│└──start-stop-status

└──SynoBuildConf/

├──build

├──depends

└──install

ThenecessaryfilesrequiredbyPkgCreate.pyarelistedbelow.

INFOSynoBuildConf/buildSynoBuildConf/installSynoBuildConf/dependsscripts/postinstscripts/postuninstscripts/postupgradescripts/preinstscripts/preuninstscripts/preupgradescripts/start-stop-status

Walk-ThroughofCreatePackage1. InstallPackageToolkit2. ListAvailableEnvironments3. CreateBuildingEnvironmentusingEnvDeploy4. CreateGPGkey5. CreateSynoBuildConf/buildSynoBuildConf/installSynoBuildConf/depends

SynologyDSM6.0DeveloperGuide

28Summary

6. Createscriptsfolderandscripts7. BuildpackagewithPkgCreate.py

CommandWalk-Through

#InstallPackageToolkit

mkdir-p/toolkit

cd/toolkit

gitclonehttps://github.com/SynologyOpenSource/pkgscripts-ngpkgscripts

#MakeBuildEnvironment

./pkgscripts/EnvDeploy-v6.0--list

./pkgscripts/EnvDeploy-v6.0--infoplatform

./pkgscripts/EnvDeploy-v6.0-px64#forexample

#PrepareGPGkey

gpg--gen-key

>Pleaseselectwhatkindofkeyyouwant:

(1)RSAandRSA(default)

>choosekeysizeandenteryourname,email

>enterapassphrase:justpressEnterwithouttypinganycharacter

cp~/.gnupg/*/toolkit/build_env/ds.x64-6.0/root/.gnupg/

#PrepareProjectfolder

mkdir-p./source/${project}

#addsourcecode,Makefile,SynoBuildConfandscripts

...

#CompileandBuildSynologyPackage

./pkgscripts/PkgCreate.py-x0-c${project}

SynologyDSM6.0DeveloperGuide

29Summary

CompileOpenSourceProjectThischapterwillshowyouhowtobuildanopensourceprojectforyourDSMsystemusingPackageToolkit.Ifyouwishtocompiletheopensourceprojectmanually,pleaserefertoAppendixB:CompileOpenSourceProjectManually.

AsmentionedinCreatePackage,youhavetocreateSynoBuildConf/build,SynoBuildConf/install,andSynoBuildConf/dependsbeforeusingPackageToolkit.

Unlikethepreviousexample,compilinganapplicationonmostopensourceprojectsmayrequireexecutingthefollowingthreesteps:

1. configure2. make3. makeinstall

Theconfigurescriptconsistsofmanylineswhichareusedtochecksomedetailsaboutthemachinewherethesoftwareisgoingtobeinstalled.Thisscriptwillalsocheckalotofdependenciesonyoursystem.Whenyouruntheconfigurescript,youwillseealotofoutputonthescreen,eachbeingsomesortofquestionwitharespectiveyes/noasareply.Ifanyofthemajorrequirementsaremissingonyoursystem,theconfigurescriptwillexitandyouwillnotbeabletoproceedwiththeinstallationuntilyoumeettherequiredconditions.Inmostcases,compileapplicationsonsomeparticulartargetmachineswillrequireyoutomodifytheconfigurescriptmanuallytoprovidethecorrectvalues.

Whenrunningtheconfigurescripttoconfiguresoftwarepackagesforcross-compiling,youwillneedtospecifytheCC,LD,RANLIB,CFLAGS,LDFLAGS,host,target,andbuild.

Inthischapter,wewilluseplatformx64asourexample.

Preparation:

Firstdownloadthetmuxsourcecodefromtheofficialgithubsiteoryoucandownloadtmuxfromthislink.

Note:Thearchivefileyou'vedownloadedfromtheabovelinksisdifferentfromtheofficialtmuxsourcecode.Wehaveaddedthenecessarybuildscripts.

ProjectLayout:

tmux/

├──tmuxrelatedsourcecode

├──INFO.sh

├──scripts/

└──SynoBuildConf/

├──build

├──depends

└──install

SynoBuildConf/depends:Thefollowingisthedependsfileforthisexample.Thereisnothingspecialaboutthedependsfile.

[default]

all="6.0"

SynoBuildConf/build:

SynologyDSM6.0DeveloperGuide

30CompileOpenSourceProject:tmux

Thebuildscriptisslightlydifferentfromthepreviousone.Hereyouwillhavetopassthefollowingenvironmentvariablestoconfigure:

CCARCFLAGSLDFLAGS

Inaddition,sincetmuxisdependentonncurses,youwillneedtousepkg-configtoresolvethenecessaryheaderfilesandlibrariesfortmux.

ThefollowingisanexampleofSynoBuildConf/build:

#!/bin/sh

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

include/env.mak

case${MakeClean}in

[Yy][Ee][Ss])

makedistclean

;;

esac

NCURSES_INCS="`pkg-configncurses--cflags`"

NCURSES_LIBS="`pkg-configncurses--libs`"

CFLAGS+="${CFLAGS}${NCURSES_INCS}"

LDFLAGS+="${LDFLAGS}${NCURSES_LIBS}"

envCC="${CC}"AR=${AR}CFLAGS="${CFLAGS}"LDFLAGS="${LDFLAGS}"\

./configure${ConfigOpt}

make${MAKE_FLAGS}

SynoBuildConf/install

Insteadofcopyingthebinarytothedestinationfolder,mostbigprojectswillusemakeinstalltoinstallthebinariesandlibraries.YoucanpasstheDESTDIRenvironmentvariabletospecifywhereyouwanttoinstallthebinariesandlibraries.

SynologyDSM6.0DeveloperGuide

31CompileOpenSourceProject:tmux

#!/bin/bash

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

PKG_NAME="tmux"

INST_DIR="/tmp/_${PKG_NAME}"

PKG_DIR="/tmp/_${PKG_NAME}_pkg"

PKG_DEST="/image/packages"

PrepareDirs(){

fordirin$INST_DIR$PKG_DIR;do

rm-rf"$dir"

done

fordirin$INST_DIR$PKG_DIR$PKG_DEST;do

mkdir-p"$dir"

done

}

SetupPackageFiles(){

DESTDIR="${INST_DIR}"makeinstall

./INFO.sh>INFO

cpINFO"${PKG_DIR}"

cp-rscripts/"${PKG_DIR}"

}

MakePackage(){

source/pkgscripts/include/pkg_util.sh

pkg_make_package$INST_DIR$PKG_DIR

pkg_make_spk$PKG_DIR$PKG_DEST

}

main(){

PrepareDirs

SetupPackageFiles

MakePackage

}

main"$@"

INFO.shAsmentionedbefore,wewilluseINFO.shtogeneratetheINFOfile.

#!/bin/sh

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

./pkgscripts/include/pkg_util.sh

package="tmux"

version="1.9-a"

displayname="tmux"

arch="$(pkg_get_platform)"

maintainer="SynologyInc."

description="ThispackagewillinstalltmuxinyourDSMsystem."

["$(caller)"!="0NULL"]&&return0

pkg_dump_info

Note:RemembertosettheexecutablebitofINFO.shfile.

BuildandCreatePackage:

Runthefollowingcommandstocompilethesourcecodeandbuildthepackage.

/toolkit/pkgscripts/PkgCreate.py-px64-ctmux

SynologyDSM6.0DeveloperGuide

32CompileOpenSourceProject:tmux

Afterthebuildprocess,youcanchecktheresultin/toolkit/result_spk.

VerifytheResult

Ifthebuildingprocesswassuccessful,youwillseethatthe.spkfilehasbeenplacedunderresult_spkfolder.Totestthespkfile,YoucanusemanualinstallinPackageCentertoinstallyourpackage.

Warning:RemembertoimportyourkeystotheDSMsystemorselectAnypublisherinPackageCenter->Settings->General->TrustLevel.Otherwise,theinstallationwillfail.

YoucanthentrytoconnecttotheDSMusingsshandtypethefollowingcommandtofullyscanyourDSMmachine.

cd/var/packages/"${PKG_NAME}"/target/usr/local/bin

./tmux

SynologyDSM6.0DeveloperGuide

33CompileOpenSourceProject:tmux

CompileOpenSourceProject:nmapThischapterwillshowyouhowtobuildanopensourceprojectforyourDSMsystemusingPackageToolkit.Theopensourceprojectthatwearegoingtobuildinthisexampleisnmap,anetworkscanningprogram.Wewillusex64asourbuildenvironmentplatform.

Ifyouwishtocompileanopensourceprojectmanually,pleaserefertoAppendixB:CompileOpenSourceProjectManually.

AswehavementionedinHelloWorldPackage,youhavetocreatetheSynoBuildConf/build,SynoBuildConf/install,andSynoBuildConf/dependsbeforeusingPackageToolkit.

Unlikethepreviousexample,compilinganapplicationonmostopensourceprojectsmayrequireexecutingthefollowingthreesteps:

1. configure2. make3. makeinstall

Theconfigurescriptconsistsofmanylineswhichareusedtochecksomedetailsaboutthemachinewherethesoftwareisgoingtobeinstalled.Thisscriptwillalsocheckalotofdependenciesonyoursystem.Whenyouruntheconfigurescript,youwillseealotofoutputonthescreen,eachbeingsomesortofquestionwitharespectiveyes/noasareply.Ifanyofthemajorrequirementsaremissingonyoursystem,theconfigurescriptwillexitandyouwillnotbeabletoproceedwiththeinstallationuntilyoumeettherequiredconditions.Inmostcases,compileapplicationsonsomeparticulartargetmachineswillrequireyoutomodifytheconfigurescriptmanuallytoprovidethecorrectvalues.

Whenrunningtheconfigurescripttoconfiguresoftwarepackagesforcross-compiling,youwillneedtospecifytheCC,LD,RANLIB,CFLAGS,LDFLAGS,host,target,andbuild.

Preparation:

First,youwillneedtodownloadthenmapsourcecodefromtheofficialgithubsite.Youwillalsoneedtodownloadthelibpcapsourcecodesincenmapdependsonlibpcap.Thelibpcapsourcecodecanbefoundhere.

Thefollowingcommandswilldownloadthesourcecodeforlibpacpandnmap.

wgethttps://nmap.org/dist/nmap-7.01.tar.bz2

tarxvfnmap-7.01.tar.bz2-C/toolkit/source

mv/toolkit/source/nmap-7.01/toolkit/source/nmap

wgethttp://www.tcpdump.org/release/libpcap-1.6.2.tar.gz

tarxvflibpcap-1.6.2.tar.gz-C/toolkit/source

mv/toolkit/source/libpcap-1.6.2/toolkit/source/libpcap

Orusegittodownloadsourcecode

cd/toolkit/source

gitclonehttps://github.com/nmap/nmap

gitclonehttps://github.com/the-tcpdump-group/libpcap

cdlibpcap

gitcheckoutorigin/libpcap-1.6

Pleaseremembertoupgradethelibpacptoversion1.6orthebuildpackageprocesswillfail.

ProjectLayout:

Afteryoudownloadthesourcecode,yourtoolkitlayoutshouldlooklikethefollowingfigure.

SynologyDSM6.0DeveloperGuide

34CompileOpenSourceProject:nmap

toolkit/

├──build_env/

│└──ds.${platform}-${version}/

│└──/usr/syno/

│├──bin

│├──include

│└──lib

├──pkgscripts/

└──source/

├──nmap/

│├──nmaprelatedsourcecode

│├──INFO.sh

│├──Makefile

│├──Synoscripts/#nmaphasit'sownscriptsfolder

│└──SynoBuildConf/

│├──build

│├──depends

│└──install

└──libpcap/

├──libpcaprelatedsourcecode

├──Makefile

└──SynoBuildConf/

├──build

├──depends

├──install-dev

└──install

Thefile,install-dev,isaspecialfilewhichwewillbecoveredinthefollowingsection.

SynoBuildConf/depends:

TheSynoBuildConf/dependsfornmapisslightlydifferentfromthepreviousexample.Sincenmapdependsonlibpcap,wehavetoaddthevaluetotheBuildDependentfield,sothatthePkgCreate.pycanresolvethedependencyandcompiletheprojectinthecorrectorder.

Thedependsfilefornmapisasfollows.

[BuildDependent]

libpcap

[default]

all="6.0"

However,theSynoBuildConf/dependsforlibpcapisthesameastheHelloWorldExample.

[BuildDependent]

[default]

all="6.0"

SynoBuildConf/build:

TheSynoBuildConf/buildscriptisalsodifferentfromthepreviousone.

Hereyouwillhavetopassseveralenvironmentvariablestoconfigure,sothatnmapcanbecompiledproperly

CCCXXLDARSTRIPRANLIB

SynologyDSM6.0DeveloperGuide

35CompileOpenSourceProject:nmap

NMCFLAGSCXXFLAGSLDFLAGS

Sincenmapwillbecompiledwithmanyfeaturesbydefault,wewillneedtodisablesomeofthemtomakeitclean.Thefollowinglistcontainsthefeaturesthatwillbedisabled:

ndiffzenmapnpingncatnmap-updateliblua

Note:Ifyouareinterestedinsomeoftheabovefeaturesandyouwanttoenablethem,justchangethe--without-${feature}into--with-${feature}.

ThefollowingistheSynoBuildConf/buildfornmap

#!/bin/sh

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

include/env.mak

PKG_NAME=nmap

INST_DIR=/tmp/_${PKG_NAME}

case${MakeClean}in

[Yy][Ee][Ss])

makedistclean

;;

esac

envCC="${CC}"CXX="${CXX}"LD="${LD}"AR=${AR}STRIP=${STRIP}RANLIB=${RANLIB}NM=${NM}\

CFLAGS="${CFLAGS}"CXXFLAGS="$CXXFLAGS$CFLAGS"\

LDFLAGS="${LDFLAGS}-lnl-lnl-genl-ldbus-1"\

./configure${ConfigOpt}\

--prefix=${INST_DIR}\

--without-ndiff\

--without-zenmap\

--without-nping\

--without-ncat\

--without-nmap-update\

--without-liblua\

--with-libpcap=/usr/local

make${MAKE_FLAGS}

Inthisexample,--with-libpcapisassignedwithvalue/usr/local.Weneedtoinstalllibpcap'scrosscompiledproductinto"/usr/local"sothatnmap'sconfigurecanretrievelibpcapcorrectly.

ThefollowingistheSynoBuildConf/buildforlibpcap.

SynologyDSM6.0DeveloperGuide

36CompileOpenSourceProject:nmap

#!/bin/bash

#Copyright(c)2000-2012SynologyInc.Allrightsreserved.

case${MakeClean}in

[Yy][Ee][Ss])

makedistclean

;;

esac

case${CleanOnly}in

[Yy][Ee][Ss])

return

;;

esac

#prefixwith/usr/local,allfileswillbeinstalledinto/usr/local

envCC="${CC}"CXX="${CXX}"LD="${LD}"AR=${AR}STRIP=${STRIP}RANLIB=${RANLIB}NM=${NM}\

CFLAGS="${CFLAGS}-Os"CXXFLAGS="${CXXFLAGS}"LDFLAGS="${LDFLAGS}"\

./configure${ConfigOpt}\

--with-pcap=linux--prefix=/usr/local

make${MAKE_FLAGS}

makeinstall

Theabovescriptwillinstalllibpcaprelatedfilesinto/usr/local/inchrootenvironment.Afterinstallinglibpcap,nmapcanfindlibpcap'scrosscompiledproductsin/usr/local.

Synologytoolkitprovideslibpcapinchroot.

>dpkg-l|greplibpcap

iilibpcap-x64-dev6.0-7274allSynologybuild-timelibrary

nmapcanusechroot'slibpcapbyusing${SysRootPrefix}variable.

--with-libpcap=${SysRootPrefix}

SynoBuildConf/install

Insteadofcopyingthebinarytothedestinationfolder,mostbigprojectswillusemakeinstalltoinstallthebinariesandlibraries.Sincewehaveusedthe--prefixflagwhenconfiguringthenmapproject,wecanjustexecutemakeinstallanditwillinstallthenmaprelatedfilestothefolderspecifiedby--prefix.

SynologyDSM6.0DeveloperGuide

37CompileOpenSourceProject:nmap

#!/bin/bash

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

PKG_NAME="nmap"

INST_DIR="/tmp/_${PKG_NAME}"

PKG_DIR="/tmp/_${PKG_NAME}_pkg"

PKG_DEST="/image/packages"

PrepareDirs(){

fordirin$INST_DIR$PKG_DIR;do

rm-rf"$dir"

done

fordirin$INST_DIR$PKG_DIR$PKG_DEST;do

mkdir-p"$dir"

done

}

SetupPackageFiles(){

makeinstall

./INFO.sh>INFO

cpINFO"${PKG_DIR}"

cp-rscripts/"${PKG_DIR}"

}

MakePackage(){

source/pkgscripts/include/pkg_util.sh

pkg_make_package$INST_DIR$PKG_DIR

pkg_make_spk$PKG_DIR$PKG_DEST

}

main(){

PrepareDirs

SetupPackageFiles

MakePackage

}

main"$@"

INFO.shAsmentionedbefore,wewilluseINFO.shtogeneratetheINFOfile.

#!/bin/sh

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

./pkgscripts/include/pkg_util.sh

package="nmap"

version="7.01"

displayname="nmap"

arch="$(pkg_get_platform)"

maintainer="SynologyInc."

description="ThispackagewillinstallnmapinyourDSMsystem."

["$(caller)"!="0NULL"]&&return0

pkg_dump_info

Note:RemembertosettheexecutablebitofINFO.shfile.

BuildandCreatePackage:

Lastly,runthefollowingcommandstocompilethesourcecodeandbuildthepackage.

/toolkit/pkgscripts/PkgCreate.py-px64-x0-cnmap

SynologyDSM6.0DeveloperGuide

38CompileOpenSourceProject:nmap

Afterthebuildprocess,youcanchecktheresultin/toolkit/result_spk.

VerifytheResult

Ifthepackingprocesswassuccessful,youwillseeanspkfileplacedintheresult_spkfolder.Totestthespkfile,youcanusemanualinstallinDSMPackageCentertoinstallyourpackage.

Warning:RemembertoimportyourkeystotheDSMsystemorselectAnypublisherinPackageCenter->Settings->General->TrustLevel.Otherwise,theinstallationwillfail.

YoucanthentrytoconnecttotheDSMusingsshandtypethefollowingcommandtofullyscanyourDSMmachine.

cd/var/packages/nmap/target/usr/local/bin

./nmap-v-Alocalhost

SynologyDSM6.0DeveloperGuide

39CompileOpenSourceProject:nmap

CompileKernelModulesInthischapter,wewillprovidethetutorialofbuildingLinuxkernelmodulesfortheDSMsystemwithPackageToolkit.

Ifyouhavetherequirementofcompilingkernelmodulesmanually,pleaserefertoAppendixB:CompileKernelModulesManually.

Usetoolkittobuildkernelmodules

Synologytoolkitcontainkernel-devwhichpackallkerneldevelopercomponentsin.Youcanfollowthedirectionsinpkgscripts-ngtosettheenvironmentup.

Kernelrelatedvariables

pkgscripts-ngbuildframeworkprovidesseveralvariableswhicharedifferentbetweenplatforms.

CROSS_COMPILE:Cross-compilertoolchainprefix.ARCH:Targetarchitecture.KSRC:Thepathofthestorekernelsourcecross-compiledproduct.Itcontainscomponentsforcompilingthekernelmodules.

Example:

Inbromolow:

ROSS_COMPILE=/usr/local/x86_64-pc-linux-gnu/bin/x86_64-pc-linux-gnu-

ARCH=x86_64

KSRC=/usr/local/x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root/usr/lib/modules/DSM-6.1/build

Incomcerto2k:

CROSS_COMPILE=/usr/local/arm-unknown-linux-gnueabi/bin/arm-unknown-linux-gnueabi-

ARCH=arm

KSRC=/usr/local/arm-unknown-linux-gnueabi/arm-unknown-linux-gnueabi/sysroot/usr/lib/modules/DSM-6.1/build

Usage

makeKSRC="$KSRC"CROSS_COMPILE="$CROSS_COMPILE"ARCH="$ARCH"

Samplepackage:HelloKernel

HelloKernelisasamplepackageforbuildingkernelmodule.YoucangetHelloKernelatgithub.

Beforestarting

Pleasesetupyourbuildenvironmentbyfollowingpkgscripts-ng.

Gettingstarted

First,preparingasimplekernelmodulewhichprintsmessageafterinsmod/rmmodthemodule.

SynologyDSM6.0DeveloperGuide

40CompileKernelModules

#include<linux/module.h>

#include<linux/kernel.h>

intinit_module(void){

printk(KERN_INFO"SynologyHelloKernelpackageisinstalled.\n");

return0;

}

voidcleanup_module(void){

printk(KERN_INFO"SynologyHelloKernelpackagehasbeenremoved.\n");

}

Then,creatingtheMakefileandusingKSRCvariabletoassignkernelsourcedirectory.

HELLO_KERNEL=hello_kernel.ko

all:$(HELLO_KERNEL)

obj-m:=hello_kernel.o

$(HELLO_KERNEL):

make-C$(KSRC)M=$(PWD)modules

install:$(HELLO_KERNEL)

mkdir-p$(DESTDIR)/hello_kernel/

install$<$(DESTDIR)/hello_kernel/

clean:

rm-rf*.o$(HELLO_KERNEL)*.cmd

InordertobecompatiblewiththeframeworkofSynologypackages,youneedtocreatethebuildscript(SynoBuildConf/build)andassignkernel-devvariablestoMakefileforcompilingkernelmodules.

#!/bin/bash

#Copyright(C)2000-2017SynologyInc.Allrightsreserved.

case${MakeClean}in

[Yy][Ee][Ss])

makeclean

;;

esac

make${MAKE_FLAGS}KSRC=$KSRCCROSS_COMPILE=$CROSS_COMPILEARCH=$ARCH

Inaddition,youcanusePkgCreate.pytoverifythebuildscript.Pleaserefertotheexampleofarmadaxpasfollows:

pkgscripts-ng/PkgCreate.py-parmadaxp-IHelloKernel

AfterrunningPkgCreate.py,hello_kernel.kowillgenaratedi(Filepath:build_env/ds.armadaxp-6.1/source/HelloKernel/hello_kernel.ko).Youcanruninsmodhello_kernel.koonarmadaxpseriesmodelsuchasds214+...etc.Ifkernelmoduleinsertsuccessfully,themessage"Hi~Synologykernelpackageinstalled."willshowindmesg.

Synologyprovidetheexampleprogramsongithub[https://github.com/SynologyOpenSource/HelloKernel].YoucanclonetheHelloKernelrepoandusePkgCreate.pytogeneratespk.

pkgscripts-ng/PkgCreate.py-cHelloKernel

SynologyDSM6.0DeveloperGuide

41CompileKernelModules

AdvancedThissectionillustratesadvancedtypesofusageforthePackageToolkit.

PkgCreate.pyCommandOptionList

ThefollowingtablelistssomeofthePkgCreate.pycommands.

OptionName OptionPurpose

(default) Runbuildstageonlywhichincludelinkandcompilesourcecode.It'sthesameas-Uoption.

-p Specifytheplatformyouwanttopackyourproject.

-x Builddependentprojectlevel.

-c Runbothbuildstageandpackstagewhichincludelinksourcecode,compilesourcecode,packpackageandsignthefinalspk.

-U Runbuildstageonlywhichincludeslinkandcompilesourcecode.

-l Runbuildstageonly,butwillonlylinkyoursourcecode.

-L Runbuildstageonly,butwillcompileyoursourcecodeonly.

-I Runpackstageonly,whichwillpackandsignyourspk.

--no-sign TellsPkgCreat.pynottosignyourspkfile.forexample,PkgCreat.py-I--no-sign${project}

-z Runallplatformsconcurrently.

-J Compileyourprojectwith-Jmakecommandoptions.

-S Disablesilentmake.

Thefollowingtableshowstherelationshipbetweencommandoptionsindifferentstages.Youcanchoosetheproperoptionsbasedonyourneeds.Option-cisenoughformostcases.

Stage Action (default) -l -L -U -I--no-sign -I -c

BuildStage LinkSourcecode Yes Yes No Yes No No Yes

BuildStage CompileSourcecode Yes No Yes Yes No No Yes

PackStage PackPackage No No No No Yes Yes Yes

PackStage SignPackage No No No No No Yes Yes

Platform-SpecificDependency

Platform-specificdependencymeansyoucanhaveseveraldependentprojectsfordifferentplatformsbyappending":${platform}"tothefollowingsections:BuildDependentandReferenceOnly.Thefollowingexampleshows816xandaramda370projectsthatareonlibbar-1.0.

SynologyDSM6.0DeveloperGuide

42Advanced

#SynoBuildConf/depends

[BuildDependent]

libfoo-1.0

[BuildDependent:816x,armada370]

libfoo-1.0

libbar-1.0

[default]

all="6.0"

CollecttheSPKFileinYourOwnWayBydefault,PkgCreate.pywillmovetheSPKfileto/toolkit/result_spkaccordingto/toolkit/build_env/ds.${platform}-${version}/source/${project}/INFO.Youcanhaveyourowncollectoperationbyaddingahook,SynoBuildConf/collect.SynoBuildConf/collectcanbeanyexecutableshellscript(soremembertochmod+x)andPkgCreate.pywillpassthefollowingenvironmentvariablestoit:

SPK_SRC_DIR:SourcefolderoftargetSPKfile.SPK_DST_DIR:DefaultdestinationfoldertoputSPKfile.SPK_VERSION:Versionofpackage(accordingtoINFO).

ThecurrentworkingdirectoryofSynoBuildConf/collectis/source/${project}willbeunderchrootenvironment.

SynologyDSM6.0DeveloperGuide

43Advanced

PackageIntroductionInpackage,youdefinessomescriptsandmetadatatocontroltheinstallation,un-installation,upgrading,startingandstoppingprocessesaswellashowtocommunicatewithSynologyPackageCenterinDSM.SynologyPackageCenterprovidesuserinterfacetotheenduserandautomatestheprocessesandconfiguringpackagestomaketheenduserinstall,un-install,upgrade,startandstopyourpackageeasily.

SynologyDSM6.0DeveloperGuide

44SynologyPackage

PackageStructureASynologypackageisaSPKfileintarformat,containingmetadataandfilesasinthefollowing:

File/FolderName Description File/FolderType DSMRequirement

INFO

ThisfilecontainstheinformationdisplayedinPackageCenterortocontroltheflowofinstallation.(PleaserefertoINFOsectionformoreinformation)

File 2.0-0731

WIZARD_UIFILES

Optional.ThisfoldercontainsfileswheredescriptionsofUIcomponentsareshownduringtheinstallation,un-installation,andupgradingprocess.

(PleaserefertoWIZARD_UIFILESsectionformoreinformation)

Folder(Containsinstall_uifile,upgrade_uifile,uninstall_uifile,

...)

3.2-1922

package.tgz

Thisisacompressedfile,containingallthefilesthatarerequired,suchasexecutablebinary,library,orUIfiles.

(Pleaserefertopackage.tgzsectionformoreinformation)

.tgzFile 2.0-0731

scripts

Thisfoldercontainsshellscriptswhichareexecutedduringtheinstallation,uninstalling,upgrading,starting,andstoppingprocesses.

(Pleaseseethescriptssectionformoreinformation)

Folder(Containspreinst,postinst,

preuninst,postunist,preupgrade,postupgrade,

start-stop-status)

2.0-0731

conf

Optional.Thisfoldercontainsconfigurations.

Note:1.InDSM4.2~DSM5.2,ifyouwanttoconfigurefileswithinit,thesupport_conf_folderkeyintheINFOfilemustbesetto"yes".2.InDSM6.0,youdon'tneedtodefinethesupport_conf_folderkeyintheINFOfile.(Pleaserefertoconfsectionformoreinformation)

Folder(containsPKG_DEPS,

PKG_CONX,...)4.2-3160

LICENSE Optional.Thisfileisshownintheinstallationprocess,andmustbelessthan1MB. File 3.2-1922

PACKAGE_ICON.PNG 72x72.pngimageisshowninPackageCenter .pngfile 3.2-1922

PACKAGE_ICON_120.PNG

(Deprecated)

120x120.pngimageisshowninPackageCenter.

Note:ItisnotcompatiblewithallDSMversionsbecausetheiconwillnotbeinstalledinDSM4.1orolder.IfyourpackagecanbeinstalledinDSM4.1orolder,pleaserefertothenextsectiontodefinepackage_icon_120intheINFOfileinsteadoftakingPACKAGE_ICON_120.PNG.

.pngfile 4.2-3160~4.3-3810

PACKAGE_ICON_256.PNG

256x256.pngimageisshowninPackageCenter.

Note:ItisnotcompatiblewithallDSMversionsbecausetheiconwillnotbeinstalledinDSM4.3orolder.IfyourpackagecanbeinstalledinDSM4.3orolder,pleaserefernextsectiontodefinepackage_icon_256inINFOfiletoinsteadoftakingPACKAGE_ICON_256.PNG.

.pngfile 5.0-4400

SynologyDSM6.0DeveloperGuide

45PackageStructure

Note:

Allwordsarecasesensitive.YoucanusePkgCreate.pyandpkg_make_spktohelpyoucreatethepackage.Formoredetails,pleaserefertoBuildandCreatePackagePackStage:SynoBuildConf/install

SynologyDSM6.0DeveloperGuide

46PackageStructure

INFOThe“INFO”fileisusedtodescribetheinformationofthepackage.PackageCenterwillsearchforinformationonhowtocontroltheinstallation,un-installation,upgrading,startingandstoppingprocessesandlistingsinPackageCenter.Forexample,ifyouwouldlikethepackagetobedependentonsomeservices,youcandefinethekeyasinstall_dep_services.Ifyouwouldliketorestartsomeservicesaftertheinstallationprocess,youcandefinethekeyasinstuninst_restart_services.PackageCenterwillputthe“INFO”fileto/var/packages/[packageidentify]/INFOafterthepackageisinstalled.

INFOFieldFormat:

EachpieceofinformationintheINFOfileisdefinedbykey/valuepairsseparatedbyanequalssigne.g.key="value".

Note:Allwordsinkeyandvaluearecasesensitive.

INFOFieldList:

TherearemanyfieldsinanINFOfile.Wecandividethemintotwogroups:

Necessaryfields:NecessaryFieldsOptionalfields:OptionalFields

ThefollowingaresomeCodeWordsfortheINFOfieldlist:

apache-sys=apachedaemonlisteningonDSMports(e.g.5000or5001)apache-web=apachedaemonlisteningonWebStationports(e.g.80or443).mdns=MulticastDNSServiceDiscoverydb=MySQLandPostgreSQLapplenetwork=AppleNetworknfs=NFSssh=SSH,SecureShellpgsql=PostgreSQL

TheversionofDSMrequirementmeanskey/valuepairsinINFOworkscorrectlyintheminimumversionofDSM.

WritingINFOFile:

InsteadofwritingtheINFOfilebyyourself,wehaveprovidedusefulhelperfunctionsinPackageToolkitthatwillhelpyoucreatetheINFOfile.PleaserefertoPackStage:INFO.sh.

SynologyDSM6.0DeveloperGuide

47INFO

FieldName:package

Description:Packageidentity.Nomorethanoneversionofapackagecanexistatthesametimeintheenduser'sDSM;therefore,theidentificationisuniquetoidentifyyourpackage.Besides,PackageCenterwillcreatea/var/packages/[packageidentity]foldertoputpackagefiles.

Note:Thisvalueofthekeycannotcontainanyofthesespecialcharacters:,/,>,<,|or=.

Value:String

DefaultValue:(Empty)

Example:

package="DownloadStation"

DSMRequirement:2.0-0731

FieldName:displaynameDescription:PackageCentershowsthenameofthepackage.

Note:Ifdisplaynamekeyisempty,PackageCenterwilldisplaythevalueofpackagekey.

Value:StringDefaultValue:ThevalueofpackagekeyExample:NoneDSMRequirement:2.3-1118

FieldName:version

Description:Packageversion.Enduserscanidentifythepackageversion.

Note:

1. Eachversiondelimiterisonlyallowedtobe.-or_.2. Eachversionnumberwhichisdelimitedbydelimiterisonlyallowedtobenumber

Value:String

DefaultValue:(Empty)

Example:

version="3.6-3263"

DSMRequirement:2.0-0731

FieldName:firmwareDescription:EarliestversionofDSMfirmwarethatisrequiredtorunthepackage.

Note:Deprecatedafter6.1-14715,useos_min_verinstead.

Value:X.Y-ZDSMmajornumber,DSMminornumber,DSMbuildnumberDefaultValue:(Empty)Example:NoneDSMRequirement:2.3-1118

SynologyDSM6.0DeveloperGuide

48NecessaryFields

FieldName:os_min_ver

Description:EarliestversionofDSMthatisrequiredtorunthepackage.Value:X.Y-ZDSMmajornumber,DSMminornumber,DSMbuildnumberDefaultValue:NoneExample:

os_min_ver="6.1-14715"

DSMRequirement:6.1-14715

FieldName:description

Description:PackageCentershowsashortdescriptionofthepackage.

Value:String

DefaultValue:(Empty)

Example:

description="DownloadStationisaweb-baseddownloadapplicationwhichallowsyoutodownloadfilesfromtheInternetthroughBT,FTP,HTTP,NZB,Thunder,FlashGet,QQDL,andeMule,andsubscribetoRSSfeedstokeepyouupdatedonthehottestorlatestBT.ItofferstheautounzipservicetohelpyouextractcompressedfilestoyourSynologyNASwheneverfilesaredownloaded.WithDownloadStation,youcandownloadfilesfrommultiplefilehostingsites,andsearchfortorrentfilesviasystemdefaultsearchenginesaswellasself-addedengineswiththeBTsearchfunction."

DSMRequirement:2.3-1118

DSMRequirement:4.2-3160

FieldName:archDescription:ListtheCPUarchitectureswhichcanbeusedtoinstallthepackage.

Value:(archvaluesareseparatedwithaspace.PleasereferAppendixA:PlatformandArchValueMappingTabletomoreinformation)

DefaultValue:noarch

Note:

1. "noarch"meansthepackagecanbeinstalledandworkinanyplatform.Forexample,thepackageiswritteninPHPorshellscript.

2. Pleasenotpackallbinaryfileswithdifferentplatformstoonepackagespkfile.

Example:

arch="noarch"

or

arch="x86alpine".

DSMRequirement:2.0-0731

FieldName:maintainerDescription:PackageCentershowsthedeveloperofthepackage.

Value:String

SynologyDSM6.0DeveloperGuide

49NecessaryFields

DefaultValue:(Empty)

Example:

maintainer="SynologyInc."

DSMRequirement:2.0-0731

FieldName:package_icon

Description:72x72pngimagedataisencodedbyBase64.

Note:

1. ThisvaluewillbereplacedwhenaPACKAGE_ICON.PNGfileisstoredinthe[packagename].spk.2. IfthevalueisnotdefinedandnoPACKAGE_ICON.PNGfileisinthe[packagename].spk,thepackageiconwill

bethedefaultone.Value:Base64-encodedvalue

DefaultValue:adefaulticon

Example:None

DSMRequirement:3.2-1922

FieldName:package_icon_256

Description:256x256pngimagedataisencodedbyBase64.

Note:

1. ThisvaluewillbereplacedwhenaPACKAGE_ICON_256.PNGfileisstoredinthe[packagename].spk.2. IfthevalueisnotdefinedandnoPACKAGE_ICON_256.PNGfileisinthe[packagename].spk,a72x72iconwill

bethedefault,andtheresultswilllookmorepixelatedandblurryinDSM.Value:Base64-encodedvalue

DefaultValue:adefaulticon

Example:None

DSMRequirement:5.0-4458

SynologyDSM6.0DeveloperGuide

50NecessaryFields

FieldName:displayname_[DSMlanguage]

Description:PackageCentershowsthenameintheDSMlanguagesetbytheend-user.DSMsupportsthefollowinglanguages:enu(English)cht(TraditionalChinese)chs(SimplifiedChinese)krn(Korean)ger(German)fre(French)ita(Italian)spn(Spanish)jpn(Japanese)dan(Danish)nor(Norwegian)sve(Swedish)nld(Dutch)rus(Russian)plk(Polish)ptb(BrazilianPortuguese)ptg(EuropeanPortuguese)hun(Hungarian)trk(Turkish)csy(Czech)

Value:StringDefaultValue:packagenameExample:

displayname_enu="HelloWorld"

displayname_cht=""

DSMRequirement:2.3-1118

FieldName:description_[DSMlanguage]Description:PackageCentershowsashortdescriptionintheDSMlanguagesetbytheend-user.DSMsupportsthefollowinglanguages:

enu(English)cht(TraditionalChinese)chs(SimplifiedChinese)krn(Korean)ger(German)fre(French)ita(Italian)spn(Spanish)jpn(Japanese)dan(Danish)nor(Norwegian)sve(Swedish)nld(Dutch)rus(Russian)

SynologyDSM6.0DeveloperGuide

51OptionalFields

plk(Polish)ptb(BrazilianPortuguese)ptg(EuropeanPortuguese)hun(Hungarian)trk(Turkish)csy(Czech)

Value:String

DefaultValue:descriptionExample:

description_enu="HelloWorld"

description_cht=""

DSMRequirement:2.3-1118

FieldName:maintainer_urlDescription:Ifapackagehasadeveloperwebpage,PackageCenterwillshowalinktolettheuseropenit.Value:StringDefaultValue:(Empty)Example:

maintainer_url="http://www.synology.com"

DSMRequirement:4.2-3160

FieldName:distributorDescription:PackageCentershowsthepublisherofthepackage.Value:StringDefaultValue:(Empty)Example:

distributor="SynologyInc."

DSMRequirement:4.2-3160

FieldName:distributor_url

Description:Ifapackageisinstalledandhasadistributerwebpage,PackageCenterwillshowalinktolettheuseropenit.Value:StringDefaultValue:(Empty)Example:

distributor_url="http://www.synology.com/enu/apps/3rd-party_application_integration.php"

DSMRequirement:4.2-3160

FieldName:support_url

Description:PackageCentershowsasupportlinktoallowuserstoseektechnicalsupportwhenneeded.

SynologyDSM6.0DeveloperGuide

52OptionalFields

Value:String

DefaultValue:(Empty)

Example:

support_url="https://myds.synology.com/support/support_form.php".

FieldName:support_centerDescription:Ifsetto“yes,”PackageCenterdisplaysalinktomaketheenduserlaunchSynologySupportCenterApplicationwhenyourpackageisinstalled.

Note:Ifsetto“yes,”thereport_urllinkwon’tshowinPackageCenter.

Value:"yes"/"no"DefaultValue:"no"Example:NoneDSMRequirement:5.0-4458

FieldName:model

Description:Listofmodelsonwhichpackagescanbeinstalledinspesificmodels.ItisorganizedbySynologystring,architectureandmodelname.Value:(modelsareseparatedwithaspace,e.g.synology_88f6281_209,synology_cedarview_rs812rp+,synology_x86_411+II,synology_bromolow_3612xs,synology_cedarview_rs812rp+,…)DefaultValue:(Empty)Example:

model="synology_bromolow_3612xssynology_cedarview_rs812rp+".

DSMRequirement:4.0-2219

FieldName:exclude_archDescription:ListtheCPUarchitectureswherethepackagecan'tbeusedtoinstallthepackage.

Note:Becarefultousethisexclude_archfield.Ifthepackagehasdifferentexclude_archvalueinthedifferentversions,theendusercaninstallthepackageinthespecificversionwithoutsomearchvaluesofexclude_arch.

Value:(archvaluesareseparatedwithaspace.PleasereferAppendixA:PlatformandArchValueMappingTabletomoreinformation)DefaultValue:(Empty)Example:NoneDSMRequirement:6.0Example:

exclude_arch="bromolowcedarview".

FieldName:checksumDescription:ContainsMD5stringtoverifythepackage.tgz.Value:StringDefaultValue:(Empty)

SynologyDSM6.0DeveloperGuide

53OptionalFields

Example:NoneDSMRequirement:3.2-1922

FieldName:adminport

Description:ApackagelistenstoaspecificporttodisplayitsownUI.Ifthepackageisdefinedbyaport,alinkwillbeopenedwhenthepackageisstarted.

Note:adminprotocol,adminportandadminurlkeysarecombinedtoadminprotocol://ip:adminport/adminurllink

Value:0~65536DefaultValue:80Example:

adminport="9002"

DSMRequirement:2.0-0731

FieldName:adminurlDescription:Ifapackageisinstalledandhasawebpage,alinkwillbeopenedwhenthepackageisstarted.

Note:adminprotocol,adminportandadminurlkeysarecombinedtoadminprotocol://ip:adminport/adminurllink

Value:StringDefaultValue:(Empty)Example:

adminurl="web"

DSMRequirement:2.3-1118

FieldName:adminprotocol

Description:ApackageusesaspecificprotocoltodisplayitsownUI.Ifapackageisinstalledandhasawebpage,aprotocolwillbeopenedwhenthepackageisstarted.

Note:adminprotocol,adminportandadminurlkeysarecombinedtoadminprotocol://ip:adminport/adminurllink

Value:http/https(Separatedwithaspace)DefaultValue:httpExample:

adminprotocol="http"

DSMRequirement:3.2-1922

FieldName:dsmuidir

Description:DSMUIfoldernameinpackage.tgz.TheUIfolderofthepackagein/var/packges/[packgename]/target/[dsmuidir]willbeautomaticallylinkedtotheDSMUIfolderin/usr/syno/synoman/webman/3rdparty/[packagename]toshowyourpackage'sshortcutinDSMafterthepackageisstarted.Toremovethelink,afterthepackageisstopped.

SynologyDSM6.0DeveloperGuide

54OptionalFields

Note:

1. Thiskeycannotcontain:or/.2. PleasereferIntegrateYourpackageintoDSMformoreinformation.

Value:StringDefaultValue:(Empty)Example:NoneDSMRequirement:3.2-1922

FieldName:dsmappname

Description:ThevalueofeachindividualapplicationwillbeequaltotheuniquepropertynameinDSM’sconfigfilesoastobeintegratedintoSynologyDiskStation.

Note:PleasereferConfiginIntegrateYourpackageintoDSMchapterformoreinformation.

Value:(Separatedwithaspace)DefaultValue:(Empty)Example:

dsmappname="SYNO.SDS.PhotoStationSYNO.SDS.PersonalPhotoStation"

DSMRequirement:3.2-1922

FieldName:checkport

Description:CheckifthereisanyconflictbetweentheadminportandtheportswhicharereservedorarelisteningonDSMexceptweb-serviceports(e.g.80,443)andDSMports(e.g.5000,5001).Value:"yes"/"no"DefaultValue:"yes"Example:NoneDSMRequirement:3.2-1922

FieldName:startable

Description:Whennoprograminthepackageprovidestheend-userwiththeoptionstoenableordisableitsfunction.Thiskeyissetto"no"andtheend-usercannotstartorstopthepackageinPackageCenter.

Note:Deprecatedafter6.1-14907,usectl_stopinstead.If“startable”issetto“no”,start-stop-statusscriptwhichrunsinbootuporshotdownisstillrequired.

Value:"yes"/"no"DefaultValue:"yes"Example:NoneDSMRequirement:3.2-1922

FieldName:ctl_stopDescription:Whennoprograminthepackageprovidestheend-userwiththeoptionstoenableordisableitsfunction.Thiskeyissetto"no"andtheend-usercannotstartorstopthepackageinPackageCenter.

Note:If“ctl_stop”issetto“no”,start-stop-statusscriptwhichrunsinbootuporshotdownisstillrequired.

Value:"yes"/"no"DefaultValue:"yes"Example:None

SynologyDSM6.0DeveloperGuide

55OptionalFields

DSMRequirement:6.1-14907

FieldName:ctl_uninstall

Description:Ifthiskeyissetto"no",theend-usercannotuninstallthepackageinPackageCenter.Value:"yes"/"no"DefaultValue:"yes"Example:NoneDSMRequirement:6.1-14907

FieldName:precheckstartstop

Description:Ifsetto"yes",letstart-stop-statuswithprestartorprestopargumentrunbeforestartorstopthepackage.Pleaserefertostart-stop-statusinscriptsformoreinformation.Value:"yes"/"no"DefaultValue:"yes"Example:NoneDSMRequirement:6.0

FieldName:helpurl

Description:Ifapackageisinstalledandhasa"help"webpage,PackageCenterwilldisplayahyperlinktotheuser.Value:StringDefaultValue:(Empty)Example:

helpurl="https://www.synology.com/en-global/knowledgebase"

DSMRequirement:3.2-1922

FieldName:beta

Description:Ifthispackageisconsideredthebetaversion,thebetainformationwillbeshowninPackageCenter.Value:"yes"/"no"DefaultValue:"no"Example:NoneDSMRequirement:6.0

FieldName:report_url

Description:Ifapackageisabetaversionandhasa"report"webpage,PackageCenterwilldisplayahyperlink.Ifthispackageisconsideredthebetaversion,thebetainformationwillbealsobeshowninPackageCenter.Value:StringDefaultValue:(Empty)Example:NoneDSMRequirement:3.2-1922

FieldName:install_reboot

SynologyDSM6.0DeveloperGuide

56OptionalFields

Description:RebootDiskStationafterinstallingorupgradingthepackage.Value:"yes"/"no"DefaultValue:"no"Example:NoneDSMRequirement:3.2-1922

FieldName:install_dep_packages

Description:Beforeapackageisinstalledorupgraded,thesepackagesmustbeinstalledfirst.Inaddition,theorderofstartingorstoppingpackagesisalsodependentonit.Theformatconsistsofapackagename.Ifmorethanonedependentpackagesarerequired,thepackagenameofthepackage(s)willbeseparatedwithacolon,e.g.install_dep_packages="packageA".Ifaspecificversionrangeisrequired,packagenamewillbefollowedbyoneofthespecialcharacters=,<,>,>=,<=andpackageversionwhichiscomposedbynumberandperiods,e.g.install_dep_packages="packageA>2.2.2:packageB".

Note:>=and<=operatoronlysupportedinDSM4.2ornewer.Don’tuse<=and>=ifapackagecanbeinstalledinDSM4.1orolderbecauseitcannotbecomparedcorrectly.Instead,thepackageversionshouldbesetlowerorhigher.

Value:PackagenamesNote:Eachpackagenameisseparatedwithacolon.

DefaultValue:(Empty)Example:

install_dep_packages="packageA"

or

install_dep_packages="packageA>2.2.2:packageB"

DSMRequirement:3.2-1922

FieldName:install_conflict_packages

Description:Beforeyourpackageisinstalledorupgraded,theseconflictpackagescannotbeinstalled.Theformatconsistsofapackagename,e.g.install_conflict_packages="packageA".Ifmorethanoneconflictpackagesarerequiredwiththeformat,thenameofthepackage(s)willbeseparatedwithacolon,e.g.install_conflict_packages="packageA:packageB".Ifaspecificversionrangeisrequired,packagenamewillbefollowedbyoneofthespecialcharacters=,<,>,>=,<=andpackageversionwhichiscomposedbynumberandperiods,e.g.install_conflict_packages="packageA>2.2.2:packageB".

Note:>=and<=operatoronlysupportedinDSM4.2ornewer.Donotuse<=and>=ifapackagecanbeinstalledinDSM4.1becauseitcan’tbecomparedcorrectly.Instead,thepackageversionshouldbesetlowerorhigher.

Value:PackagenamesNote:Eachpackagenameisseparatedwithacolon.

DefaultValue:(Empty)Example:

install_conflict_packages="packageA:packageB"

or

install_conflict_packages="packageA>2.2.2:packageB"

DSMRequirement:4.1-2851

FieldName:install_break_packages

Description:Afteryourpackageisinstalledorupgraded,theseto-be-brokenpackageswillbestoppedandremainbrokenduringtheexistenceofyourpackage.Theformatconsistsofapackagename,e.g.install_break_packages="packageA".Ifmorethanoneto-be-brokenpackagesarerequiredwiththeformat,thenameofthepackage(s)willbeseparatedwithacolon,e.g.

SynologyDSM6.0DeveloperGuide

57OptionalFields

install_break_packages="packageA:packageB".Ifaspecificversionrangeisrequired,packagenamewillbefollowedbyoneofthespecialcharacters=,<,>,>=,<=andpackageversionwhichiscomposedbynumberandperiods,e.g.install_break_packages="packageA>2.2.2:packageB".Value:Packagenames

Note:Eachpackagenameisseparatedwithacolon.

DefaultValue:(Empty)Example:

install_break_packages="packageA:packageB"

or

install_break_packages="packageA>2.2.2:packageB"

DSMRequirement:6.1-15117

FieldName:install_replace_packagesDescription:Afteryourpackageisinstalledorupgraded,theseto-be-replacedpackageswillberemoved.Theformatconsistsofapackagename,e.g.install_replace_packages="packageA".Ifmorethanoneto-be-replacedpackagesarerequiredwiththeformat,thenameofthepackage(s)willbeseparatedwithacolon,e.g.install_replace_packages="packageA:packageB".Ifaspecificversionrangeisrequired,packagenamewillbefollowedbyoneofthespecialcharacters=,<,>,>=,<=andpackageversionwhichiscomposedbynumberandperiods,e.g.install_replace_packages="packageA>2.2.2:packageB".Value:Packagenames

Note:Eachpackagenameisseparatedwithacolon.

DefaultValue:(Empty)Example:

install_replace_packages="packageA:packageB"

or

install_replace_packages="packageA>2.2.2:packageB"

DSMRequirement:6.1-15117

FieldName:instuninst_restart_services

Description:Reloadservicesafterinstalling,upgradinganduninstallingthepackage.Note:

1. Iftheserviceisnotenabledorstartedbytheend-user,serviceswon'tbereloaded2. Iftheinstall_rebootissetto“yes”,thisvalueisignoredintheinstallationprocess.

Value:DSM4.3orolder:apache-sys,apache-web,mdns,samba,db,applenetwork,cron,nfs,firewallDSM5.0~DSM5.2:apache-sys,apache-web,mdns,samba,applenetwork,cron,nfs,firewallDSM6.0:nginx,mdns,samba,applenetwork,cron,nfs,firewall

Note:Eachserviceisseparatedwithaspace.

DefaultValue:(Empty)Example:

instuninst_restart_services="apache-sysapache-web"

DSMRequirement:3.2-1922

FieldName:startstop_restart_services

SynologyDSM6.0DeveloperGuide

58OptionalFields

Description:Reloadservicesafterstartingandstoppingthepackage.Note:

1. Iftheserviceisnotenabledorstartedbytheend-user,serviceswon'tbereloaded.2. Ifstartableissetto“no”,thevalueisignored.

Value:DSM4.3orolder:apache-sys,apache-web,mdns,samba,db,applenetwork,cron,nfs,firewallDSM5.0~DSM5.2:apache-sys,apache-web,mdns,samba,applenetwork,cron,nfs,firewallDSM6.0:nginx,mdns,samba,applenetwork,cron,nfs,firewall

Note:Eachserviceisseparatedwithaspace.

DefaultValue:(Empty)Example:

startstop_restart_services="apache-sysapache-web"

DSMRequirement:3.2-1922

FieldName:install_dep_services

Description:Beforethepackageisinstalledorupgraded,theseservicesmustbestartedorenabledbytheend-user.Value:DSM4.2orolder:apache-web,mysql,php_disable_safe_exec_dirDSM4.3:apache-web,mysql,php_disable_safe_exec_dir,sshDSM5.0~DSM5.2:apache-web,php_disable_safe_exec_dir,ssh,pgsqlDSM6.0:ssh,pgsql

Note:Eachserviceisseparatedwithaspace.

DefaultValue:(Empty)Example:

install_dep_services="apache-webssh"

DSMRequirement:3.2-1922

FieldName:start_dep_servicesDescription:Beforethepackageisstarted,theseservicesmustbestartedorenabledbytheend-user.Ifstartableissetto“no”,thisvalueisignored.Value:DSM4.2orolder:apache-web,mysql,php_disable_safe_exec_dirDSM4.3:apache-web,mysql,php_disable_safe_exec_dir,sshDSM5.0~DSM5.2:apache-web,php_disable_safe_exec_dir,ssh,pgsqlDSM6.0:ssh,pgsql

Note:Eachserviceisseparatedwithaspace.

DefaultValue:(Empty)Example:

install_dep_services="apache-webssh"

DSMRequirement:3.2-1922

FieldName:extractsize

SynologyDSM6.0DeveloperGuide

59OptionalFields

Description:Thisvalueindicatestheminimalspacetoinstallapackage.Itwillbeusedtoprompttheuserifthereisenoughfreespacetoinstallit.

Note:

1. InDSM5.2ororder,thesizebasedonbyteunit.2. InDSM6.0ornewer,thesizebasedonkilobyteunit.

Value:SizeunitDefaultValue:ThebytesizeofSPKfileofpackageExample:

extractsize="253796"

DSMRequirement:4.0-2166

FieldName:support_conf_folderDescription:InDSM5.2ororder,ifyouwanttousesomespecialconfigurationfileswithina"conf"folder,thisvaluemustbesetto"yes".Moredetailsaregiveninthe"conf"section.Howerver,inDSM6.0ornewer,youdon'tneedtodefineitanymore.

Note:DeprecatedinDSM6.0

Value:"yes"/"no"DefaultValue:"no"Example:

support_conf_folder="yes"

DSMRequirement:4.2-3160~5.2

FieldName:install_type

Description:Ifsetto“system”,yourpackagewillbeinstalledintherootfilesystem,/usr/local/packages/@appstore/,evenifthereisnovolume.

Note:Becarefulwhensettingthis,asitmayresultintheDiskStationcrashingifyourpackagerunsoutofthespaceintherootfilesystem.

Value:"system"DefaultValue:(Empty)Example:

install_type="system"

DSMRequirement:5.0-4458

FieldName:silent_install

Description:Ifsetto“yes”,yourpackageisallowedtobeinstalledwithoutthepackagewizardinthebackground.ThisallowsCMS(CentralManagementSystem)todistributepackageinstallationtootherNASconnected.Value:"yes"/"no"DefaultValue:"no"Example:

silent_install="yes"

DSMRequirement:5.0-4458

SynologyDSM6.0DeveloperGuide

60OptionalFields

FieldName:silent_upgrade

Description:Ifsetto“yes”,yourpackageisallowedtobeupgradedwithoutthepackagewizardinthebackground.Endusercannotmodifyanyinformationforupgrading.ThisallowsnotonlyyourpackagetobeupgradedautomaticallybutalsoforCMS(CentralManagementSystem)todistributepackageupgradestootherNASconnected.Value:"yes"/"no"DefaultValue:"no"Example:

silent_upgrade="yes"

DSMRequirement:5.0-4458

FieldName:silent_uninstallDescription:Ifsetto“yes”,yourpackageisallowedtobeuninstalledwithoutthepackagewizardinthebackground.ThisallowsCMS(CentralManagementSystem)todistributepackageuninstallationtootherNASconnected.Value:"yes"/"no"DefaultValue:"no"Example:

silent_uninstall="yes"

DSMRequirement:5.0-4458

FieldName:auto_upgrade_fromDescription:Itissettoaversionofyourpackage.Ifyourpackageissettosilent_upgrade="yes"andthevalueisset,PackageCenteronlyupgradesyourpackageautomaticallyfromtheinstalledpackagewiththeversionorthenewerversion.However,iftheenduserinstallaolderversionthanit,PackageCenterwon'tupgradeitautomaticallyandtheusermustupgradeitbythemself.Value:(apackageversion)DefaultValue:(Emptystring)Example:

auto_upgrade_from="2.0"

DSMRequirement:5.2-5565

FieldName:offline_install

Description:Ifsetto"yes",afterthepackageispublishedinsynologyserver,itwon'tbeshowninthepackagelistofPackageCenterfromSynologyserver.However,theusercaninstallthepackagemanually.Value:"yes"/"no"DefaultValue:"no"Example:

offline_install="yes"

DSMRequirement:DSM6.0

FieldName:thirdparty

SynologyDSM6.0DeveloperGuide

61OptionalFields

Description:Ifsetto“yes”,yourpackageisathird-partypackageandisn'tdevelopedbySynology.InPackageCenter,third-parypacakgeswillbeshowninanotherpart.

Note:It'snotusedinDSM5.0ornewer.

Value:"yes"/"no"DefaultValue:"no"Example:

thirdparty="yes"

DSMRequirement:4.0~4.3

FieldName:os_max_verDescription:MaximumversionofDSMthatiscapabletorunthepackage.Value:X.Y-ZDSMmajornumber,DSMminornumber,DSMbuildnumberDefaultValue:NoneExample:

os_max_ver="6.1-14715"

DSMRequirement:6.1-14715

SynologyDSM6.0DeveloperGuide

62OptionalFields

package.tgzThepackage.tgzisacompressedfilecontainingallthefilesyouwouldneedwhenbuildingupyourapplications.Forexample,

executablefileslibrariesUIfilesconfigurationfiles

Youcanusepkg_make_packagefunctiontocreatethepackage.tgz.Formoredetailsabouthowtocreatethepackage.tgz,pleaserefertoPackStage:SynoBuildConf/install.

Afteryouinstallyourpackage,PackageCenterwillextractpackage.tgzto@appstorefolder(/volume?/@appstore/withtheassignedvolumeor/usr/local/packages/@appstore/).Inaddition,PackageCenterwillalsocreateasoftlinkin/var/packages/[packageidentity]/targetandpointtotheassignedfolder.

Note:

1. InDSM5.2orolder,package.tgzmustbetgzformat.2. InDSM6.0ornewer,package.tgzcanbetgzorxzformat,butthefilenamemustbepackage.tgz.

SynologyDSM6.0DeveloperGuide

63package.tgz

scriptsThisfoldercontainsshellscriptswhichwillbeexecutedduringtheinstallation,un-installation,upgrading,starting,andstoppingofpackages.PackageCenterwillputthescriptsto/var/packages/[packageidentify]/scripts/afterthepackageisinstalled.Therearesevenbasicscriptfilesstoredinthescriptsfolder.

1. preinst:Thisscriptisrunbeforethepackagefilesaretransferredto@appstore.YoucancheckiftheinstallationrequirementsmeettheDSMorpackageversion,orifsomeservicesareenabledinthisscript.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Hello!!">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

2. postinst:Thisscriptisrunafterthepackagefilesaretransferredto@appstore.Youcanchangethefilepermissionandownershipinthisscript.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Hello!!">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

3. preuninst:Thisscriptisrunbeforethepackageisremoved.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Hello!!">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

4. postuninst:Thisscriptisrunafterthepackageisremovedfromthesystem.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Hello!!">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

5. preupgrade:PackageCenterwillcallthisscriptbeforeuninstallingtheoldversionofyourpackage.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Hello!!">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

6. postupgrade:PackageCenterwillcallthisscriptafterinstallingthenewversionofyourpackage.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Hello!!">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

7. start-stop-status:Thisscriptisusedtostartandstopapackage,detectrunningstatus,andgeneratethelogfile.Parametersusedbythescriptarelistedinbelow:

i. start:Whentheuserclicks"Run"torunthepackageortheNASisturnedon,thePackageCenterwillcallthisscriptwiththe"start"parameter.Areturnedvaluewillthenbeacquired.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Startfailed">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

ii. stop:Whentheuserclicks"Stop"tostoprunningthepackageortheNASisturnedoff,thePackageCenterwillcallthisscriptwiththe"stop"parameter.Areturnedvaluewillthenbeacquired.Fornon-zeroreturnedvalues,youcancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Stopfailed">$SYNOPKG_TEMP_LOGFILE).YoucanalsowritemessagesintheSYNOPKG_TEMP_LOGFILEfileforzeroreturnedvalueswhichrepresentthattheprocesswassuccessful.

iii. status:WhenPackageCenterisopenedtocheckpackagestatus,itwillsendarequesttoaskthestatusofthepackageusingthisparameter.Thefollowingexitstatuscodesshouldbereturned:

SynologyDSM6.0DeveloperGuide

64scripts

0:packageisrunning.

1:programofpackageisdeadand/var/runpidfileexists.

2:programofpackageisdeadand/var/locklockfileexists

3:packageisnotrunning

4:packagestatusisunknown

150:packageisbrokenandshouldbereinstalled.Pleasenote,brokenstatus(150)isonlysupportedbyDSM4.2andlater.

iv. log:WhenalogpageisopenedinPackageCenter,PackageCenterwillsendarequesttoaskthelogofthepackageusingthisparameter.WhenthelogfilenameissenttoSTDOUT,thecontentofthelogfilewillbedisplayed.

v. prestart:IfprecheckstartstopinINFOissetto"yes",itisrunforcheckingifit'sallowedtotheendusertostartyourpackageinsomesituationsornot.Forzeroreturnedvalue,theendusercanstartyourpackage.Fornon-zeroreturnedvalues,theenduserisn'tallowedtostartyourpackageandyoucancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Startfailed">$SYNOPKG_TEMP_LOGFILE)

Note:

i. ItonlyworksinDSM6.0ornewer.ii. Itwon'trunafterstartingapackageatbootingup.

vi. prestop:IfprecheckstartstopinINFOissetto"yes",itisrunforcheckingifit'sallowedtotheendusertostopyourpackageinsomesituationsornot.Forzeroreturnedvalue,theendusercanstopyourpackage.Fornon-zeroreturnedvalues,theenduserisn'tallowedtostopyourpackageandyoucancompileerrormessagesintheSYNOPKG_TEMP_LOGFILEfiletoprompttheuser(e.g.echo"Stopfailed">$SYNOPKG_TEMP_LOGFILE)

Note:

i. ItonlyworksinDSM6.0ornewer.ii. Itwon'trunbeforestoppingapackageatshuttingdown.

Toinstallapackage:

preinstpostinststart-stop-statuswithprestartargumentifenduserchoosestostartitimmediatelystart-stop-statuswithstartargumentifenduserchoosestostartitimmediately

Toupgradeapackage:

start-stop-statuswithprestopargumentifithasbeenstartedstart-stop-statuswithstopargumentifithasbeenstartedpreupgradepreuninstpostuninstpreinstpostinstpostupgradestart-stop-statuswithprestartargumentifitwasstartedbeforebeingupgradedstart-stop-statuswithstartargumentifitwasstartedbeforebeingupgraded

Touninstallapackage:

start-stop-statuswithprestopargumentifithasbeenstartedstart-stop-statuswithstopargumentifithasbeenstartedpreuninstpostuninst

Tostartapackage:

SynologyDSM6.0DeveloperGuide

65scripts

start-stop-statuswithprestartargumentstart-stop-statuswithstartargument

Tostopapackage:

start-stop-statuswithprestopargumentstart-stop-statuswithstopargument

Note:start-stop-statuswithprestartorprestopargumentisonlysupportedinDSM6.0ornewer.

SynologyDSM6.0DeveloperGuide

66scripts

ScriptEnvironmentVariablesSeveralvariablesareexportedbyPackageCenterandcanbeusedinthescripts.Descriptionsofthevariablesaregivenasbelow:

SYNOPKG_PKGNAME:PackageidentifywhichisdefinedinINFO.SYNOPKG_PKGVER:PackageversionwhichisdefinedinINFO.SYNOPKG_PKGDEST:Targetdirectorywherethepackageisstored.SYNOPKG_PKGDEST_VOL:Targetvolumewherethepackageisstored.

Note:It'sonlyavailableinDSM4.2orabove.

SYNOPKG_PKGPORT:adminportportwhichisdefinedinINFO.Thisportwillbeoccupiedbythispackagewithitsmanagementinterface.SYNOPKG_PKGINST_TEMP_DIR:Thetemporarydirectorywherethepackageareextractedwheninstallingorupgradingit.SYNOPKG_TEMP_LOGFILE:Atemporaryfilepathforascripttologinformationorerrormessages.SYNOPKG_TEMP_UPGRADE_FOLDER:Thetemporarydirectorywhenthepackageisupgrading.Youcanmovethefilesfromthepreviousversionofthepackagetoitinpreupgradescriptandmovethembackinpostupgrade.

Note:It'sonlyavailableinDSM6.0orabove.

SYNOPKG_DSM_LANGUAGE:Enduser'sDSMlanguage.SYNOPKG_DSM_VERSION_MAJOR:Enduser’smajornumberofDSMversionwhichisformattedas[DSMmajornumber].[DSMminornumber]-[DSMbuildnumber].SYNOPKG_DSM_VERSION_MINOR:Enduser’sminornumberofDSMversionwhichisformattedas[DSMmajornumber].[DSMminornumber]-[DSMbuildnumber].SYNOPKG_DSM_VERSION_BUILD:Enduser’sDSMbuildnumberofDSMversionwhichisformattedas[DSMmajornumber].[DSMminornumber]-[DSMbuildnumber].SYNOPKG_DSM_ARCH:Enduser’sDSMCPUarchitecture.PleasereferAppendixA:PlatformandArchValueMappingTabletomoreinformationSYNOPKG_PKG_STATUS:Packagestatuspresentedbythesevalues:INSTALL,UPGRADE,UNINSTALL,START,STOPorempty.1. INSTALLwillbesetasthestatusvalueinthepreinstandpostinstscriptswhilethepackageisinstalling.Iftheuserchooses

to“startafterinstallation”atthelaststepoftheinstallationwizard,thevaluewillbesettoINSTALLinthestart-stop-statusscriptwhenthepackageisstarted.

2. UPGRADEwillbesetasthestatusvalueinthepreupgrade,preuninst,postunist,preinst,postinstandpostupgradescriptssequentiallywhilethepackageisupgrading.Ifthepackagehasalreadystartedbeforeupgrade,thevaluewillbesettoUPGRADEinthestart-stop-statusscriptwhenthepackageisstartedorstopped.

3. UNINSTALLwillbesetasthestatusvalueinthepreuninstandpostunistscriptswhilethepackageisun-installing.Ifthepackagehasalreadystartedbeforeun-installation,thevaluewillbesettoUNINSTALLinthestart-stop-statusscriptwhenthepackageisstopped.

4. IftheuserstartsorstopsapackageinthePackageCenter,STARTorSTOPwillbesetasthestatusvalueinthestart-stop-statusscript.

5. WhentheNASisbootinguporshuttingdown,itsstatusvaluewillbeempty.Note:SYNOPKG_PKG_STATUSisonlyavailableforthestart-stop-statusscriptinDSM4.0orabove.

SYNOPKG_OLD_PKGVER:ExistingpackageversionwhichisdefinedinINFO(onlyinpreupgradescript).SYNOPKG_TEMP_SPKFILE:ThelocationofpackagespkfileistemporarilystoredinDSwhenthepackageisinstalling/upgrading.

Note:It'sonlyavailableinDSM4.2orabove.

SYNOPKG_USERNAME:Theusernamewhoinstalls,upgrades,uninstalls,startsorstopsthepackage.Ifthevalueisempty,theactionistriggeredbyDSM,notbytheenduser.

Note:It'sonlyavailableinDSM5.2orabove.

SYNOPKG_PKG_PROGRESS_PATH:Atemporaryfilepathforascripttoshowingtheprogressininstallingandupgradingapackage.

SynologyDSM6.0DeveloperGuide

67ScriptEnvironmentVariables

Note:

1. Theprogressvalueisbetween0and1.2. It'sonlyavailableinDSM5.2orabove.3. Example:

flock-x"$SYNOPKG_PKG_PROGRESS_PATH"-cecho0.80>"$SYNOPKG_PKG_PROGRESS_PATH"

OncetheenduserentersorselectssomevaluesoftheUIcomponentswhichareconfiguredininstall_uifile(.sh)/upgrade_uifile(.sh)/uninstall_uifile(.sh)(PleaserefertoWIZARD_UIFILESsectionformoreinformation),thenamesandvaluesofthecomponentswillbesetintheenvironmentvariables.Alsonotethatthenamesofthesecomponentscannotbethesameasthoseoftheenvironmentvariables.

SynologyDSM6.0DeveloperGuide

68ScriptEnvironmentVariables

confThe“conf”foldercontainsspecialconfigurationsincludingsomeinformationwhichcannotbedescribedintheINFOfilewithkey/pairformat.PackageCentercontrolstheflowofinstallation,upgrading,un-installation,starting,andstoppingprocessesaccordingtotheseconfigurations.

InDSM4.2,therearetwoconfigurations,PKG_DEPSandPKG_CONX,whicharestoredinthisfolder.Theyareusedtodefinedependencyorconflictbetweenthepackages.Thedependencyorconflictwillbecheckedaccordingtotheenduser’sDSMversion.Forexample,PerlwasbuiltonDSM4.1,butitdoesnotexistonDSM4.2.Therefore,ifyourpackagedependsonPerl,thePerlpackagemustbeinstalledonDSM4.2beforeyourpackagecanbeinstalled.YoucansetthePKG_DEPSconfigurationtoindicatethatthedependencyruleonlyworksonDSM4.2orlater.

Thedependencyorconflictissimilartoinstall_dep_packagesandinstall_conflict_packageskeysinINFOfile,buttheydonotdefinetherestrictionaccordingtospecificDSMversions.

PKG_DEPSandPKG_CONXalwayshavehigherprioritycomparedwiththekeysintheINFOfile.Thatis,ifyoudefinedependencyinthePKG_DEPSfile,thentheinstall_dep_packageskeyintheINFOfilewillbeignoredinDSM4.2orlater.IfyoudefinetheconflictinthePKG_CONXfile,thentheinstall_conflict_packageskeyintheINFOfilewillbeignoredinDSM4.2orlater.

Theconffoldercontainsthefollowingfiles:

File/FolderName Description File/Folder

TypeDSM

Requirement

PKG_DEPS

DefinedependencybetweenpackageswithrestrictionsofDSMversion.Beforeyourpackageisinstalledorupgraded,thesepackagesmustbeinstalledfirst.PackageCentercontrolstheorderofstartorstoppackagesaccordingtothedependency.

File 4.2-3160

PKG_CONXDefineconflictsbetweenpackageswithrestrictionsofDSMversion.Beforeyourpackageisinstalledorupgraded,theseconflictingpackagescannotbeinstalled.

File 4.2-3160

Note:Allwordsarecasesensitive.

Eachconfigurationfileisdefinedinstandard.inifileformatwithkey/valuepairsandsessions,forexample:

[session]

Asessiondescribesauniquenameofdependent/conflictingpackage.EachsessioncontainsinformationabouttherequirementsofpackageversionsandtherestrictionofDSMversions.

KeysconfiguredinPKG_DEPSfileeachdependentpackage(session)contains:

Key Description Value

pkg_min_ver Minimumversionofdependentpackage.Youmustinstallthisdependentpackagewiththisversionornewerbeforeinstallingyourpackage. Packageversion

pkg_max_ver Maximumversionofdependentpackage.Youmustinstallthisdependentpackagewiththeversionorolderbeforeinstallingyourpackage. Packageversion

dsm_min_verMinimumrequiredDSMversion.Ifyouhavethisversionornewerof

DSM,thisdependencywillbeconsidered,butitwillbeignoredinanolderDSM.

X.Y-ZDSMmajornumber,DSMminornumber,DSMbuild

number

dsm_max_verMaximumrequiredDSMversion.Ifyouhavethisversionorolderof

DSM,thisdependencywillbeconsidered,butitwillbeignoredinanewerDSM.

X.Y-ZDSMmajornumber,DSMminornumber,DSMbuild

number

SynologyDSM6.0DeveloperGuide

69conf

Example:

;YourpackagedependsonPackageAinanyversion

[PackageA]

;YourpackagedependsonPackageBversion2ornewer

pkg_min_ver=2

;YourpackagedependsonPackageCwithversion2orolder

[PackageC]

pkg_max_ver=2

;YourpackagedependsonPackageDwithversion2orolderbutitwillbeignoredwhenDSMversionisolderthan4.1-2668

[PackageD]

dsm_min_ver=4.1-2668

pkg_min_ver=2

;YourpackagedependsonPackageEwithversion2ornewerbutitwillbeignoredwhenDSMversionisnewerthan4.1-2668

[PackageE]

dsm_max_ver=4.1-2668

pkg_min_ver=2

KeysconfiguredinPKG_CONXfileeachconflictingpackage(session)contain:

Key Description Value

pkg_min_verMinimumversionofconflictingpackage.Ifenduserinstallsthisconflictingpackagewiththespecifiedversionornewer,hewillnotbeabletoinstallyour

package.PackageVersion

pkg_max_verMaximumversionofconflictingpackage.Ifenduserinstallsthisconflictingpackagewiththespecifiedversionorolder,hewillnotbeabletoinstallyour

package.PackageVersion

dsm_min_verMinimumrequriedDSMversion.Ifenduserhasthespecifiedversionor

newerofDSM,thisconflictwillbeconsidered,butitwillbeignoredinolderversionsofDSM.

X.Y-ZDSMmajornumber,DSMminornumber,DSMbuild

number

dsm_max_verMaximumrequriedDSMversion.IftheenduserhasthespecifiedversionorolderofDSM,thisconflictwillbeconsidered,butitwillbeignoredinnewer

DSM.

X.Y-ZDSMmajornumber,DSMminornumber,DSMbuild

number

Example:

;YourpackageconflictswithPackageAinanyversion

[PackageA]

;YourpackageconflictswithPackageBversion2ornewer

[PackageB]

pkg_min_ver=2

;YourpackageconflictswithPackageCversion2orolder

[PackageC]

pkg_max_ver=2

;YourpackageconflictswithPackageDversion2orolder,butitwillbeignoredwhenDSMversionisolderthan4.1-2668

[PackageD]

dsm_min_ver=4.1-2668

pkg_min_ver=2

;YourpackageconflictonPackageEwithversion2ornewerbutitwillbeignoredwhenDSMversionisnewerthan4.1-2668

[PackageE]

dsm_max_ver=4.1-2668

pkg_min_ver=2

SynologyDSM6.0DeveloperGuide

70conf

SynologyDSM6.0DeveloperGuide

71conf

WIZARD_UIFILESinstall_uifile,upgrade_uifile,anduninstall_uifilearefileswhichdescribeUIcomponentsinJSONformat.Theyarestoredinthe“WIZARD_UIFILES”folder.Duringtheinstallation,upgrading,andun-installationprocesses,theseUIcomponentswillappearinthewizard.Oncethesecomponentsareselected,theirkeyswillbesetinthescriptenvironmentvariableswithtrue,false,ortextvalues.

Thesefilescanberegardedasusersettingsorusedtocontroltheflowofscriptexecution.

install_uifile:DescribesUIcomponentsfortheinstallationprocess.Duringtheprocessofthepreinstandpostinstscripts,thesecomponentkeysandvaluescanbefoundintheenvironmentvariables.upgrade_uifile:DescribesUIcomponentsfortheupgradeprocess.Duringtheprocessofthepreupgrade,postupgrade,preuninst,postuninst,preinstandpostinstscripts,thesecomponentkeysandvaluescanbefoundintheenvironmentvariables.uninstall_uifile:DescribesUIcomponentsfortheun-installationprocess.Duringtheprocessofthepreuninstandpostuninstscripts,thesecomponentkeysandvaluescanbefoundintheenvironmentvariables.

Ifyouwouldliketorunascripttogeneratethewizarddynamically,youcanaddinstall_uifile.sh,upgrade_uifile.shanduninstall_uifile.shfiles,theyarerunbeforeinstalling,upgrading,anduninstallingapackagerespectivelytogenerateUIcomponentsinJSONformatandwritetoSYNOPKG_TEMP_LOGFILE.Scriptenvironmentvariablesinthesescriptscanbegotteninthesescripts.Pleasereferto"ScriptEnvironmentVariables"formoreinformation.

IfyouwouldliketolocalizethedescriptionsofUIcomponents,youcanaddalanguageabbreviationsuffixtothefile“install_uifile_[DSMlanguage],”“upgrade_uifile_[DSMlanguage]”,“uninstall_uifile_[DSMlanguage]”,“install_uifile_[DSMlanguage].sh,”“upgrade_uifile_[DSMlanguage].sh”or“uninstall_uifile_[DSMlanguage].sh”inthisfolder.Forexample,inordertoperforminstallationinTraditionalChinese,[DSMlanguage]shouldbereplacedwith“cht”asfollows:“install_uifile_cht”.

ExampleofthefileinJSONformat:

[{

"step_title":"Step1",

"items":[{

"type":"singleselect",

"desc":"aradiogroup",

"subitems":[{

"key":"radio1",

"desc":"Radiobutton1",

"defaultVaule":false

},{

"key":"radio2",

"desc":"Radiobutton2",

"defaultVaule":true

}]

}]

},{

"step_title":"Step2",

"items":[{

"type":"multiselect",

"desc":"acheckgroup",

"subitems":[{

"key":"check1",

"desc":"Checkbutton1"

},{

"key":"check2",

"desc":"Checkbutton2",

"defaultVaule":true,

"validator":{

"fn":"{varv=arguments[0];if(!v)return'Checkthis';returntrue;}"

}

}]

},{

"type":"textfield",

"desc":"textfield",

"subitems":[{

"key":"textfield1",

SynologyDSM6.0DeveloperGuide

72WIZARD_UIFILES

"desc":"textfield1",

"defaultVaule":"default",

"validator":{

"allowBlank":false,

"minLength":2,

"maxLength":10

}

},{

"key":"textfield2",

"desc":"textfield2",

"emptyText":"abc1@cde.com",

"validator":{

"vtype":"email",

"regex":{

"expr":"/[0-9]/i",

"errorText":"Error"

}

}

}]

}]

},{

"step_title":"Step3",

"invalid_next_disabled":true,

"activeate":"{console.log('activeate',arguments);}",

"deactivate":"{console.log('deactivate',arguments);}",

"items":[{

"type":"singleselect",

"desc":"Checkit",

"subitems":[{

"key":"id1",

"desc":"Notchooseit",

"defaultValue":true

},

{

"key":"id2",

"desc":"Chooseit",

"defaultValue":false,

"validator":{

"fn":"{returnarguments[0];}"

}

}]

}]

}]

ExampleofusingascripttogenerateafileinJSONformat:

SynologyDSM6.0DeveloperGuide

73WIZARD_UIFILES

#!/bin/sh

/bin/cat>/tmp/wizard.php<<'EOF'

<?php

$ini_array=parse_ini_file("/etc.defaults/synoinfo.conf");

$unique=$ini_array["unique"];

echo<<<EOF

[{

"step_title":"Step1",

"items":[{

"type":"textfield",

"desc":"modelname",

"subitems":[{

"key":"pkgwizard_db_name",

"desc":"name",

"defaultValue":"$unique"

}]

},{

"type":"combobox",

"desc":"Pleaseselectavolume",

"subitems":[{

"key":"volume",

"desc":"volumename",

"displayField":"display_name",

"valueField":"volume_path",

"editable":false,

"mode":"remote",

"api_store":{

"api":"SYNO.Core.Storage.Volume",

"method":"list",

"version":1,

"baseParams":{

"limit":-1,

"offset":0,

"location":"internal"

},

"root":"volumes",

"idProperty":"volume_path",

"fields":["display_name","volume_path"]

},

"validator":{

"fn":"{console.log(arguments);returntrue;}"

}

}]

}]

}];

EOF;

?>

EOF

/usr/bin/php-n/tmp/wizard.php>$SYNOPKG_TEMP_LOGFILE

rm/tmp/wizard.php

exit0

HerearethepropertiesforeachstepinthewizardinJSONformat:

SynologyDSM6.0DeveloperGuide

74WIZARD_UIFILES

Property Description DSMRequirement

step_title Optional.Describesthetitleofthecurrentstepperformedinthewizard. 3.2-1922

items Describesanarraycontainingthecomponentsof“singleselect”,“multiselect”,“textfield”,“password”,or“combobox”type. 3.2-1922

type

Mustbe“singleselect”,“multiselect”,“textfield”“password”or“combobox”.“singleselect”typerepresentsthecomponentsinthesub-itemswhichareallradiobuttons.Youcanselectonlyoneradioboxwithauniquekey.“multiselect”typerepresentsthecomponentsinthesub-itemswhichareallcheckboxes.Youcancheckmorethanonecheckbox.“textfield”typerepresentsthecomponentsinthesub-itemswhicharealltextfields.Youcantypetext.“password”typerepresentsthecomponentsinthesub-itemswhichareallpasswordfields.Youcantypepasswords.“combobox”typerepresentsthecomponentsinthesub-itemswhichareallcomboboxfields.Theusercanchooseaiteminthecomboboxfield.Note:“combobox”typeisonlyavailableinDSM5.2ornewer.

3.2-1922

desc Optional.Describeacomponentinthelabeltext. 3.2-1922

subitems Describeanarraycontainingradiobuttons,checkboxes,textfields,orpasswordcomponents. 3.2-1922

activeate JSON-stylestringtodescribeafunctionwhichisrunafterthestepofthewizardhasbeenvisuallyactivated. 5.2

deactivate JSON-stylestringtodescribeafunctionwhichisrunafterthestepofthewizardhasbeenvisuallydeactivated. 5.2

invalid_next_disabled Ifsettotrue,thenextbuttoninthestepofthewizardwillbedisabledbydefault.Itwillbeenabledifallitemsarevalidatedscucuessfullybyvalidatorinthisstep. 5.2

HerearethepropertiesforcomponentsinsubitemsinJSONformat:

Property Description DSMRequirement

key

AuniquecomponentkeyvaluerepresentsaUIcomponent.Ifyouselectacomponent,thiskeywillbesetinthescriptenvironmentvariablesofpreinst,postinst,preupgrade,postupgrade,preuninst,postuninst,start-stop-status(thestringvalueoftheselectedcheckboxorradiobuttonisalways“true”.).

3.2-1922

defaultVaule Optional.true/falsevaluetoinitialize“singleselect”or“multiselect”component,orastringvaluetoinitialize“textfield”or“password”component. 4.2-3160

emptyText Optional.Theprompttexttoplaceintoanempty“textfield”or“password”componenttoprompttheuserhowtofillinifdefaultVauleisnotset. 4.2-3160

validatorJSON-styleobjecttodescribevalidationfunctions.Ifthevalidationfailswiththeuser'svalue,theusercannotgotothenextstepofthewizard.Moredetailedpropertiesofvalidatoraregiveninthevalidatortable.

4.2-3160

disabled truetodisablethefield(defaultstofalse). 6.0

height Theheightofthiscomponentinpixels. 6.0

hidden truetohidethiscomponent. 6.0

invalidText Theerrortexttousewhenmarkingafieldinvalidandnomessageisprovided. 6.0

preventMark truetodisablemarkingthefieldinvalid.Defaultstofalse. 6.0

width Thewidthofthiscomponentinpixels. 6.0

Herearethepropertiesofvalidator:

SynologyDSM6.0DeveloperGuide

75WIZARD_UIFILES

Property Description Value

allowBlank Specifyfalsetovalidatethatthevalue'slengthof“textfield”or“password”componentis>0 true/false

minLength Minimumlengthof“textfield”or“password”component Number

maxLength Maximumlengthof“textfield”or“password”component Number

vtype

Specifypre-definedvalidationfunction,"alpha":validatealphavalue"alphanum":validatealphanumericvalue"email":validateemailaddress"url":validateURL

"alpha","alphanum","email","url"

regexDescribevalidationfunctioninregularexpressionandinvalidmessage.Propertiescontain:"expr":JavascriptRegularExpression"errorText":invalidstring

JSON-styleobject

fnDescribetheJavascriptfunctionwhichisencodedbyJSON-stylestringwithcurlybrackets.Inthisfunction,youcanusearguments[0]togetthevalueofthecomponent.Inaddition,thisfunctionwillreturntrueifthevalueisvalidorasaninvalidstringifthevalueisinvalid.

String

Herearetheotherpropertiesfortextfield,passwordorcomboboxcomponentinsubitemsinJSONformat:

Property Description DSMRequirement

blankText TheerrortexttodisplayiftheallowBlankvalidationfails 6.0

grow trueifthisfieldshouldautomaticallygrowandshrinktoitscontent 6.0

growMax Themaximumheighttoallowwhengrowistrue 6.0

growMin Theminimumheighttoallowwhengrowistrue 6.0

htmlEncode falsetoskipHTML-encodingthetextwhenrenderingit(defaultstofalse). 6.0

maxLengthText ErrortexttodisplayifthemaximumlengthvalidationusingmaxLengthfails. 6.0

minLengthText ErrortexttodisplayiftheminimumlengthvalidationusingminLengthfails. 6.0

HerearethepropertiesforcomboboxcomponentinsubitemsinJSONformat:

Property Description DSMRequirement

api_store

JSON-styleobjecttodescribetosendaWebAPIrequestandstoretheresponseinthedatastrustureforcomboboxuse.Moredetailedpropertiesofapi_storearegiveninthestoretable.Example:{

"api":"SYNO.Core.XXX","method":"list","version":1,"baseParams":{"offset":0,"limit":-1,},"root":"items","idProperty":"name","fields":["name"]}

6.0

autoSelect truetoselectthefirstresultgatheredbythedatastore(defaultstotrue).Afalsevaluewouldrequireamanualselectionfromthedropdownlisttosetthecomponentsvalue. 6.0

displayField Theunderlyingdatafieldnametobindtothiscombobox. 6.0

editable falsetopreventtheuserfromtypingtextdirectlyintothefield,thefieldwillonlyrespondtoaclickonthetriggertosetthevalue.(defaultstotrue). 6.0

forceSelection truetorestricttheselectedvaluetooneofthevaluesinthelist,falsetoallowtheusertosetarbitrarytextintothefield(defaultstofalse). 6.0

SynologyDSM6.0DeveloperGuide

76WIZARD_UIFILES

handleHeight Theheightinpixelsofthedropdownlistresizehandleifresizableistrue. 6.0

listAlign Avalidanchorpositionvalue. 6.0

listEmptyText Theemptytexttodisplayinthedataviewifnoitemsarefound. 6.0

listWidth Thewidthofthedropdownlist. 6.0

maxHeight Themaximumheightinpixelsofthedropdownlistbeforescrollbarsareshown. 6.0

minChars TheminimumnumberofcharacterstheusermusttypebeforeautocompleteandtypeAheadactivate 6.0

minHeight Theminimumheightinpixelsofthedropdownlistwhenthelistisconstrainedbyitsdistancetotheviewportedges. 6.0

minListWidth Theminimumwidthofthedropdownlistinpixels. 6.0

mode

Setto'loacl'toloadlocalstoretoloadlocalJSON-arraydata.Moredetailedpropertiesoflocalstorearegiveninthestoretable.Example:{

"mode":"local","valueField":"myId","displayField":"displayText","store":{"xtype":"arraystore","fields":["myId","displayText"],"data":[[1,"item1"],[2,"item2"]]}}

6.0

pageSizeIfgreaterthan0,apagingtoolbarisdisplayedinthefooterofthedropdownlistandthefilterquerieswillexecutewithpagestartandlimitparameters.Onlyapplieswhenusingapi_store(defaultsto0).

6.0

queryDelay Thelengthoftimeinmillisecondstodelaybetweenthestartoftypingandsendingthequerytofilterthedropdownlist. 6.0

resizable truetoaddaresizehandletothebottomofthedropdownlist(Defaultstofalse). 6.0

selectOnFocus truetoselectanyexistingtextinthefieldimmediatelyonfocus.Onlyapplieswheneditableistrue(defaultstofalse). 6.0

store

Adatastructuretostoredataincombobox(defaultstoundefined).Itcan'tbeusedwithapi_storeatthesametime.Acceptablevaluesforthispropertyare:1-dimensionalarray:e.g.,["Foo","Bar"]2-dimensionalarray:Fora2-dimensionalarray,thevalueinindex0ofeachitemwillbeassumedtobethevalueField,whilethevalueatindex1isassumedtobethedisplayField,e.g.,[["f","Foo"],["b","Bar"]].

6.0

title Ifsupplied,aheaderelementiscreatedcontainingthistextandaddedintothetopofthedropdownlist 6.0

typeAhead truetopopulateandautoselecttheremainderofthetextbeingtypedafteraconfigurabledelay(typeAheadDelay). 6.0

typeAheadDelay Thelengthoftimeinmillisecondstowaituntilthetypeaheadtextisdisplayed. 6.0

valueField Theunderlyingdatavaluenametobindtothiscombobox. 6.0

Herearethepropertiesforapi_storeorstoredatastructureinJSONformat:

SynologyDSM6.0DeveloperGuide

77WIZARD_UIFILES

Property Description DSMRequirement

baseParams AnobjectcontainingpropertieswhicharetobesentasparametersforeveryWebAPIrequestinapi_store. 6.0

data AninlinedataobjectreadablebythereaderinlocalstoretoloadlocalJSON-arraydata. 6.0

displayField Theunderlyingdatafieldnametobindtothiscombobox. 6.0

fields definedfieldsforthedatastoredinthisstoreorapi_store. 6.0

idProperty Identityofthepropertywithindatathatcontainsauniquevalue. 6.0

root Thenameofthepropertywhichcontainsthearrayofdata.Defaultstoundefined. 6.0

valueField Theunderlyingdatavaluenametobindtothiscombobox. 6.0

xtype OnlysupportarraystoretypeforlocalstoretoloadlocalJSON-arraydata. 6.0

Note:

1. Allwordsarecasesensitive.2. InDSM4.0orabove,ifboththetypeandsubitemspropertiesareempty,textinthedescpropertywillbedisplayedasone

ofthestepsofwizard.3. install_uifile.sh,upgrade_uifile.sh,uninstall_uifile.shand*.shscriptstogernatethewizarddynamicallyareonlysupported

inDSM5.2ornewer.

SynologyDSM6.0DeveloperGuide

78WIZARD_UIFILES

IntegrateYourPackageintoDSM

SynologyDSM6.0DeveloperGuide

79IntegrateYourPackageintoDSM

ManageStorageforApplicationFilesWhenapackageisinstalling,package.tgzwillbeextractedto/var/packages/[packageidentity]/target,whichisasymboliclinkpointingtoafolderinadatavolumeselectedbytheenduser./var/packages/[packageidentity]/targetisalsoavailableattheSYNOPKG_PKGDESTenvironmentvariable,oneofthesevenfilesinthescriptfolder.Pleaseseethe"scripts"formoreinformation.

Despitethefactthatthedirectory/var/packagesor/usr/localisreservedfor3rd-partyapplications,thestoragespaceofsystemvolumeislimited.Ifthesizeoffilestobeinstalledexceedsthecapacityofthesystemvolume,storagespacewillrunout.Hence,itisrecommendedthatyoudirectlyreadorwriteapplicationfilesin/var/packages/[packageidentity]/targetoranotherspaceofthedatavolume.Youcanalsomakeasymboliclinkin/usr/localtopointto/var/packages/[packageidentity]/targetoranotherspacewhenrunningthepostinstscript.Thepathcanbeaccessedeasierinalibraryoradaemon.Pleasenotethatyoumayneedtospecifythecorrectprefixwhenrunningaconfigurationscriptsothattheapplicationcanfindthecorrectpathinformationuponexecution.

SynologyreleasesDSMupdatesonaregularbasis.Giventhatapplicationfilesmightbeaffectedduringtheupdateprocedure,itisimportantthatyouinstallyourapplicationinthecorrectdirectorytopreventthemfrombeingdeletedwhenDSMisbeingupgradedinthesystempartition.

WhenDSMisbeingupgraded,thedirectory/var/packages/[packageidentity]and/usr/localwillbebackedupandrestoredautomatically.However,somelibraryfilesorbuilt-insoftwaremightbemodifiedduringtheupgradeprocedure.Inotherwords,ifyourapplicationdependsonthefileswhicharesubjecttochange,theapplicationmaynotworkafterward.Inthiscase,youshouldcheckthestatusofthesefilesorre-linktheminthestart-stop-statusscripttorepairthemifnecessary.Alternatively,youcaninstallthemdirectlyto/var/packages/[packageidentity]/target.

SynologyDSM6.0DeveloperGuide

80ManageStorageforApplicationFiles

IntegrateYourPackageintoDSMWebGUIWithSynologyDSM,integrating3rd-partyapplicationsintoyourNASiseasy.Whenanapplicationisintegrated,itsiconwillappearintheMainMenuofDSM.Userscanalsousetheirowncustomizediconsfortheseapplications.ToplaceanicononDSMdesktop,simplydraganddropitfromtheMainMenutotheDSMdesktop.

SynologyDSM6.0DeveloperGuide

81IntegrateYourPackageintoDSMWebGUI

StartupTointegrateanapplicationintoSynologyDSM3.0orlater,pleasefollowthestepsbelow:

1. Createafolderunderthedirectory/usr/syno/synoman/webman/3rdparty/.2. Createatextfilenamed"config"inyourfolder.3. Underthesamedirectory,createasub-foldernamedafteryourapplication,suchas

/usr/syno/synoman/webman/3rdpaty/[packagename]/.PutallUIrelatedcomponents,suchasimages,CSS,andCGIinthedirectory.

IntheINFOfile,youcandefinethekeydsmuidir,whosevalueisaDSMdirectorynameinthepackage.tgzfile.PackageCenterwillautomaticallylink/unlinkitto/usr/syno/synoman/webman/3rdparty/[packagename]basedonthekeywhenyoustart/stopthepackage.YoushouldalsodefinedsmappnameintheINFOfiletointegratethepackagewithDSMapplications.PleaserefertodsmuidiranddsmappnamekeyinOptionalFieldssectionformoreinformationtolinkthefolderautomatically.

NextwewilldiscussthedetailsofUIconfiguration.

SynologyDSM6.0DeveloperGuide

82Startup

ConfigThetextfile“config”isusedtoconfigureUIbehavior.ThecontentofconfigshouldbeinJSONformat.

Forexample:

{

".url":{

"com.company.App1":{

"type":"url",

"allUsers":true,

"title":"TestApp1",

"desc":"Description",

"icon":"images/app_{0}.png",

"url":"http://www.yahoo.com"

},

"com.company.App2":{

"type":"legacy",

"allUsers":true,

"title":"TestApp2",

"desc":"Description2",

"icon":"images/app2_{0}.png",

"url":"http://www.synology.com"

}

}

}

Detailsofapplication.cfgarestatedinbelow.

SynologyDSM6.0DeveloperGuide

83Config

Property Description

com.company.App1com.company.App2 In“.url”,eachobjectshouldhaveauniquepropertyname.

title(Required) “title”representstheapplicationnamethatwillbedisplayedinthemainmenu.

desc “desc”displaysmoredetailsaboutthisapplicationuponmouse-over.

icon(Required)

“icon”indicatestheiconfortheapplication.Itisatemplatestring.The“{0}”canbereplacedby“16”,“24”,“32”,“48”,“64”,“72”,“256”dependingontheresolutionoftheicon.Theiconmustbesavedunder/usr/syno/synoman/webman/3rdparty/xxx/wherexxxisthedirectorynameofyourpackage.Forexample,ifyoucreateadirectorynamed"images"andputtheiconimagefile“icon.png”init,thefullpathfortheiconwouldbe:/usr/syno/synoman/webman/3rdparty/xxx/images/icon_16.png/usr/syno/synoman/webman/3rdparty/xxx/images/icon_24.png/usr/syno/synoman/webman/3rdparty/xxx/images/icon_32.png/usr/syno/synoman/webman/3rdparty/xxx/images/icon_48.png/usr/syno/synoman/webman/3rdparty/xxx/images/icon_64.png/usr/syno/synoman/webman/3rdparty/xxx/images/icon_72.png/usr/syno/synoman/webman/3rdparty/xxx/images/icon_256.pngTheiconvalueshouldalsobesetas"images/icon_{0}.png"

type(Required)

Whenyouclickthemenuitem,theaddressyouusetoconnecttotheDSMmanagementUIwillbeshownintherightframeofthemanagementUI.However,youcancustomizetheaddressasyouwish.The“type”valuecanbe"url"or"legacy"."url"meanswhenyouclicktheapplicationicon,theURLwillbeopenedinapop-upwindow,while"legacy"impliesthattheURLwillbeopenedinaniframewindowapplication.YoucanfollowthedescriptionsbelowtosetupyourcustomizedURL.

url(Required)ThefollowingisanexampleofvaluesettingforyourURLoftheapplication:“url”:http://www.synology.com/“url”:“3rdparty/xxx/index.html”

allUsers

Thiskeydetermineswhetherornotthemenuitemscanbeseenbyuserswhentheyloginwithanadminaccount.Ifyouwouldliketohaveallusersseethemenuitems,pleasesetthekeyvalueasbelow:"allUsers":trueThedefaultsettingisthatonlytheadmincanfindtheapplication.

SynologyDSM6.0DeveloperGuide

84Config

IntegrateHelpDocumentintoDSMHelpTointegrateahelpdocumentofyourapplicationintoDSMHelp,pleasedothefollowingsteps:

Classifythehelpdocumentsaccordingtolanguage,andputtheminthehelpfolderofyourapplication.Tohaveconsistentstyle,andourcustomizedscrollbar,youshouldaddthefollowinghtmltag:

<!DOCTYPEhtml>

<head>

<metacharset="UTF-8"/>

<metahttp-equiv="X-UA-Compatible"content="IE=edge,chrome=1">

<linkhref="../../../../help/help.css"rel="stylesheet"type="text/css">

<linkhref="../../../../help/scrollbar/flexcroll.css"rel="stylesheet"type="text/css">

<scripttype="text/javascript"src="../../../../help/scrollbar/flexcroll.js"></script>

<scripttype="text/javascript"src="../../../../help/scrollbar/initFlexcroll.js"></script>

</head>

Note:Thejsfilesarerequiredbecausethenativebrowserscrollbarhasbeendisabled.

Youwillneedtoaddatextfile"helptoc.conf"intoyourapplication.Thistextfile"helptoc.conf"istoconfigurethestructureofyourhelpdocument.Thecontentofhelptoc.confshouldbeinJSONformat.Forexample:

{

"app":"SYNO.App.TestAppInstance",

"title":"app_tree:index_title"

"helpset":"help",

"stringset":"texts",

"content":"testapp_index.html",

"toc":[{

"title":"app_tree:node_1"

"content":"testapp_node1.html",

"nodes":[{

"title":"app_tree:node_1_child"

"content":"testapp_node1_child.html"

}]

},{

"title":"app_tree:node_2"

"content":"testapp_node2.html"

}]

}

Detailsofhelptoc.confarestatedinbelow.

Property Description

stringset(Required) "stringset"isthefolderthatstoresyourapplicationstrings.

app "app"representstheapplicationinstance.

helpset "helpset"displaysmoredetailsabouttheapplicationuponmouse-over.

title(Required) "title"isthetextthatwillbedisplayedintheDSMHelptree.Itconsistsoftwoparts-sectionandkey,andisseparatedbyacolon.

content(Required) "content"representstheurlofthenode.

toc "toc"arethechildnodesforyourapplication.(useemptyarrayifyourapplicationdoesn'thaveone)

nodes "nodes"arethechildnodesoftoc.(notnecessaryifthereisnochildnodes)

SynologyDSM6.0DeveloperGuide

85IntegrateHelpDocumentintoDSMHelp

Addthefollowingcontenttotheresourcespecificationfile.PleaserefertoIndexDBformoredetail.

"indexdb":{

"app-index":{

"conf-relpath":"ui/index.conf",

"db-relpath":"indexdb/appindexdb"

},

"help-index":{

"conf-relpath":"ui/helptoc.conf",

"db-relpath":"indexdb/helpindexdb"

}

}

SynologyDSM6.0DeveloperGuide

86IntegrateHelpDocumentintoDSMHelp

IntegratewithDSMWebAuthenticationAfterintegratingyourapplicationintoSynologyDSM,youmaywanttoperformanauthenticationchecktoensureonlylogged-inuserscanaccessthepage.

Tocheckwhetherauserhasloggedin,runtheCGIcommandinbelow.

/usr/syno/synoman/webman/modules/authenticate.cgi

The“authenticate.cgi”willoutputtheusernameiftheuserhasloggedin.Therewillbenooutputiftheuserhasnotbeenauthenticated.

Belowisanexample:

SynologyDSM6.0DeveloperGuide

87IntegratewithDSMWebAuthentication

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<strings.h>

/**

*Checkwhetheruserisloggedin.

*

*Ifuserhasloggedin,puttheusernameinto"user".

*

*@paramuserThebufferforgetusername

*@parambufsizeThebuffersizeofuser

*

*@return0:Usernotloggedinorerror

*1:Userloggedin.Theusernameiswrittentogiven"user"

*/

intIsUserLogin(char*user,intbufsize)

{

FILE*fp=NULL;

charbuf[1024];

intlogin=0;

bzero(user,bufsize);

fp=popen("/usr/syno/synoman/webman/modules/authenticate.cgi","r");

if(!fp){

return0;

}

bzero(buf,sizeof(buf));

fread(buf,1024,1,fp);

if(strlen(buf)>0){

snprintf(user,bufsize,"%s",buf);

login=1;

}

pclose(fp);

returnlogin;

}

intmain(intargc,char**argv)

{

charuser[256];

printf("Content-type:text/html\r\n\r\n");

if(IsUserLogin(user,sizeof(user))==1){

printf("Userisauthenticated.Name:%s\n",user);

}else{

printf("Userisnotauthenticated.\n");

}

return0;

}

DSMmightrequirearandomvaluecalledSynoTokentopreventaCSRF(cross-siterequestforgery)attackafter4.3.WhenCSRFprotectionisenabledinthecontrolpanel,youmustappendSynoTokentothequerystringorheaderoftheHTTPrequest.

Inthequerystring:

http://192.168.1.1:5000/webman/3rdparty/DownloadStation/webUI/downloadman.cgi?SynoToken=9WuK4Cf50Vw7Q

Intherequestheader:

X-SYNO-TOKEN:9WuK4Cf50Vw7Q

ThevalueofSynoTokencanbeobtainedfromlogin.cgiiftheuserisloggedin.

SynologyDSM6.0DeveloperGuide

88IntegratewithDSMWebAuthentication

Request:

http://192.168.1.1:5000/webman/login.cgi

Response:

{"SynoToken":"9WuK4Cf50Vw7Q","result":"success","success":true}

IfyourapplicationisbasedonExtJsofDSM,pleaseincludedsmtoken.cgiinyourheadersection.

<header>

<scriptsrc="/webman/dsmtoken.cgi"></script>

</header>

Oncethedsmtoken.cgiisincluded,Ext.Ajax.Request,Ext.data.Connection,Ext.form.basicFormandExt.urlAppendwillappendSynoTokentotheHTTPrequestautomatically.

<script>

Ext.Ajax.Request({…})//addSynoTokenatevent'beforerequest'

Ext.data.Connection({…})//addSynoTokenatevent'beforerequet'

newExt.form.basicForm({…})//addSynoTokenatevent'beforeaction'

//Ext.urlAppendwilladdSynoTokeninternally

url=Ext.urlAppend('http://192.168.1.1',Ext.urlEncode({…}));

</script>

SynologyDSM6.0DeveloperGuide

89IntegratewithDSMWebAuthentication

DSMBackwardCompatibilityWeaklinkisapropertyofApple’sdevelopmentframeworkwhichensuresbackwardcompatibility.GCChasasimilarpropertycalled“weaksymbol.”Weutilizethiscapabilitytoprovideaweaklinkframeworkinlibsynosdkforbackwardcompatibilityaswell.Youcanfindavailableheadersinusr/syno/include/libsynosdkunderchrootenvironment.Eachfunctionprototypeinsynosdk/*_p.hislabeledwithamacrotellingyouwhenthisfunctionisaddedintolibsynosdk.Therefore,youcaninputafunctioninDSM4.2asfollows:

/*DONOTinclude*_p.hdirectly*/

#include<synosdk/user.h>

#include<synosdk/service.h>

/*example,SYNOServiceHomePathCheckisavailablesinceDSM4.2*/

if(SYNOServiceHomePathCheck){

SYNOServiceHomePathCheck(szPath,TRUE,TRUE,&pResult);

}else{

/*implementalternativetoSYNOServiceHomePathCheckhere*/

}

Asaresult,whenyourapplicationrunsinDSM4.2andlater,functionSYNOServiceHomePathCheckinlibsynosdk.soisinvoked.InDSM4.2andolder,else-partwillbeexecutedasareplacementtoSYNOServiceHomePathCheck.

SynologyDSM6.0DeveloperGuide

90DSMBackwardCompatibility

ShowMessagestoUsersIfyouwanttopromptuserswithamessagebeforetheyinstall,upgrade,orun-installapackageinPackageCenter,youcanwritethesemessagesinthedesckeyininstall_uifile,upgrade_uifile,oruninstall_uifile.Pleasereferto"WIZARD_UIFILES"formoreinformation.

Ifyouwanttosendapromptmessagetousersaftertheyinstall,upgrade,un-install,start,orstopapackageinPackageCenter,youcanimplementthemintothe$SYNOPKG_TEMP_LOGFILEvariableintherelatedscripts.Forexample,

echo"HelloWorld!!">$SYNOPKG_TEMP_LOGFILE

IfyouwanttopromptusersinthelanguagespecifiedintheirDSMsettings,youcanrefertothe$SYNOPKG_DSM_LANGUAGEvariableforlanguageabbreviationasshowninthescriptsbelow:

SynologyDSM6.0DeveloperGuide

91ShowMessagestoUsers

case$SYNOPKG_DSM_LANGUAGEin

chs)

echo"" >$SYNOPKG_TEMP_LOGFILE

;;

cht)

echo"" >$SYNOPKG_TEMP_LOGFILE

;;

csy)

echo"Český">$SYNOPKG_TEMP_LOGFILE

;;

dan)

echo"Dansk">$SYNOPKG_TEMP_LOGFILE

;;

enu)

echo"English">$SYNOPKG_TEMP_LOGFILE

;;

fre)

echo"Français">$SYNOPKG_TEMP_LOGFILE

;;

ger)

echo"Deutsch">$SYNOPKG_TEMP_LOGFILE

;;

hun)

echo"Magyar">$SYNOPKG_TEMP_LOGFILE

;;

ita)

echo"Italiano">$SYNOPKG_TEMP_LOGFILE

;;

jpn)

echo"" >$SYNOPKG_TEMP_LOGFILE

;;

krn)

echo"" >$SYNOPKG_TEMP_LOGFILE

;;

nld)

echo"Nederlands">$SYNOPKG_TEMP_LOGFILE

;;

nor)

echo"Norsk">$SYNOPKG_TEMP_LOGFILE

;;

plk)

echo"Polski">$SYNOPKG_TEMP_LOGFILE

;;

ptb)

echo"PortuguêsdoBrasil">$SYNOPKG_TEMP_LOGFILE

;;

ptg)

echo"PortuguêsEuropeu">$SYNOPKG_TEMP_LOGFILE

;;

rus)

echo"Русский">$SYNOPKG_TEMP_LOGFILE

;;

spn)

echo"Español">$SYNOPKG_TEMP_LOGFILE

;;

sve)

echo"Svenska">$SYNOPKG_TEMP_LOGFILE

;;

trk)

echo"Türkçe">$SYNOPKG_TEMP_LOGFILE

;;

*)

echo"English">$SYNOPKG_TEMP_LOGFILE

;;

esac

Pleaseseethe"scripts"and"ScriptEnvironmentVariables"sectionsformoreinformation.

Otherwise,youcanuse/usr/syno/bin/synodsmnotifytosendmessagestoDSMusers.Forexample,thestrings“title”and“messages”aresenttothe“administrators”group.

SynologyDSM6.0DeveloperGuide

92ShowMessagestoUsers

synodsmnotify@administratorstitlemessages

SynologyDSM6.0DeveloperGuide

93ShowMessagestoUsers

CreatePHPApplicationApache/NginxandPHPengineswhichallowyoutodevelopwebapplicationsandstorefilesinthewebspacetobuildyourownwebsite.Hence,thesefilesshouldbecompressedintopackage.tgz.Inthestart-stop-statusscript,youshouldlinkorcopythemtothewebspacewhenstartingapackage.InDSM,thedefaultwebspaceisthewebsharedfolder.Youcangetthepathvia/var/services/webwhichisasymboliclinkpointingtotheactualpathinthevolume.

InDSM5.2orolder,thewebapplicationworksaftertheadministratorenablesWebStation.Youcanconfiguretheinstall_dep_servicesandstart_dep_serviceskeyswiththeapache-webvalueintheINFOfiletomakesureWebStationisenabledbeforethepackageinstallation.InDSM6.0ornewer,thewebapplicationworksaftertheadministratorinstallsandstartsWebStationandPHPpackage.Youcanconfiguretheinstall_dep_packageswith"WebStation:PHP5.6"valueintheINFOfiletomakesurethesepackagesinstalledandstartedbeforethepackageinstallation.

YoucanthenprovideaURLinordertoaccessyourpagetoadminurl(ex:"/myapp/index.html")inINFOwhichwillbedisplayedinPackageCentertotelltheclientwhichURLtoopen.Whenthepackagestops,thisURLshouldnotbeaccessible.Youcanremoveorunlinkthewebsitefolderinthewebspace,orletthewebpageredirecttoanerrorpage.

Inaddition,itisrecommendedtoaddanicontoDSM’smainmenusothatuserscanclicktheicontolaunchtheapplicationintuitively.

TocustomizetheconfigsettingsforApache,NginxorPHP,pleasedonotmodifyanyoftheconfigfilesbelongingtoDSM.Instead,youshouldcreatesymboliclinksforyourconfigfilesinthecorrespondinglocations.ForApache/Nginx,linkyourconfigtothefolder/etc/httpd/sites-enabled-user/your_package_name.conf.ForPHP,pleaserefertoPHPINIformoredetail.

Inaddition,addtheapache-webinDSM5.2ororder,ornginxinDSM6.0ornewertothestart_stop_restart_servicestomakeApache/Nginxreloadconfigfiles.Otherwise,thesesymboliclinksshouldberemovedalongwiththepackage.

Hereisanexampleofapacheconfig:

<Directory"/var/services/photo">

OptionsMultiViews

AllowOverrideNone

Orderallow,deny

Allowfromall

</Directory>

SynologyDSM6.0DeveloperGuide

94CreatePHPApplication

RunScriptsWhentheSystemBootsIfyouwouldliketorunscriptswhenthesystemisbootinguporshuttingdown,youcanwritescriptsinstart-stop-status.Thisscriptwillbeexecutedwiththe"start"or"stop"parameter,whenthepackageisenabled.Ifyouwanttoexecuteascriptduringtheboot-uporshut-downprocess,youcanputastart-upscriptin/usr/local/etc/rc.d/.Belowaretherulesforthestart-upscript:

1. Itmustcontainthesuffix".sh".Forexample,"myprog.sh".2. Thepermissionmustbe755.3. Itmustcontaintheoptionsof"start"and"stop".Whenthesystembootsup,itwillcallmyprog.shstart;whenitshutsdown,it

willcallmyprog.shstop.

SynologyDSM6.0DeveloperGuide

95RunScriptsWhentheSystemBoots

LocaleSupportDSMprovideslocalesupportafterversion4.3.YoudonotneedtoaddorremovelocalerelatedfilesontheNASafterthisversion.

SynologyDSM6.0DeveloperGuide

96LocaleSupport

InstallPackageRelatedPortsInformationintoDSMIfyourpackageserviceusesspecificportsforcommunication(e.g.SurveillanceStationusesports19997/udpforsourceportand19998/udpfordestinationport),youshouldprepareaserviceconfigurationfileforthispackagetodescribewhichportswillbeused.Afterthat,oncetheusercreatesfirewallrulesorportforwardingrulesfromthebuild-inapplication,yourpackageservicewillalsobelistedforselection.

ServiceConfigureFileName

ThefilenameshouldfollowthenamingconventionSYNOPKG.sc(ex:SurveillanceStation.sc).SYNOPKGshouldbethepackagenamethatisspecifiedbythekey"package"intheINFOfile,andscmeansServiceConfigurefile.

ConfigureFormatTemplate

Pleaseseethefollowingexample:

[service_name]

title="Englishtitle"

desc="Englishdescription"

port_forward="yes"or"no"

src.ports="ports/protocols"

dst.ports="ports/protocols"

[service_name2]

Section/KeyDescriptions

Pleaseseethefollowingstatementsforthestringsandkeys:

SynologyDSM6.0DeveloperGuide

97InstallPackageRelatedPortsInformationintoDSM

Section/Key Description Value DefaultValue

DSMRequirement

service_name

Required

Usuallyapackageonlyhasoneuniqueservicename.Ifyourpackageneedsmorethanoneportdescription,youcandefineservice_name2,service_name3,…

Note:service_namecannotbeemptyandcanonlyincludecharacters“a~z”,“A~Z”,“0~9”,“-”,“\”,“.”

Uniqueservicename N/A 4.0-2206

title

Required

EnglishtitlewhichwillbeshownonfieldProtocolatfirewallbuild-inselectionmenu.

Englishtitle N/A 4.0-2206

desc

Required

EnglishdescriptionwhichwillbeshownonfieldApplicationsatfirewallbuild-inselectionmenu.

Englishdescription N/A 4.0-2206

port_forward

Optional

Ifsetto“yes,”yourpackageservicerelatedportswillbelistedwhenuserssetportforwardingrulefrombuild-inapplications.Otherwisetheywillnotbelisted.

“yes”or“no” “no” 4.0-2206

src.ports

Optional

Ifyourpackageservicehasspecifiedsourceports,youcansettheminthiskey.Thevalueshouldcontainatleasttheportnumbers,andadefaultprotocolthatistcp+udp.

Ex:6000,7000:8000/tcp,udpmeanssourceportsare6000,7000to8000,allportsaretcp+udp.

ports/protocolsports:1~65535(separatedby‘,’anduse‘:’torepresentportrange)protocols:tcp,udp(separatedby‘,’)

ports:N/A

protocols:tcp,udp

4.0-2206

dst.ports

Required

Eachserviceshouldhavedestinationports.Thevalueshouldcontainatleasttheportnumbers,andadefaultprotocolthatistcp+udp.

Ex:6000,7000:8000/tcp,udpmeansdestinationportsare6000,7000to8000,allportsaretcp+udp.

ports/protocolsports:1~65535(separatedby‘,’anduse‘:’torepresentportrange)protocols:tcp,udp(separatedby‘,’)

ports:N/A

protocols:tcp,udp

4.0-2206

Pleaseseethefollowingexample(SurveillanceStation.sc):

[ss_findhostd_port]

title="SearchSurveillanceStation"

desc="SurveillanceStation"

port_forward="yes"

src.ports="19997/udp"

dst.ports="19998/udp"

Aftertheserviceconfigurationfileisready,addthefollowingcontenttotheresourcespecificationfile.PleaserefertoPortConfigformoredetail.

"port-config":{

"protocol-file":"port_conf/xxdns.sc"

}

SynologyDSM6.0DeveloperGuide

98InstallPackageRelatedPortsInformationintoDSM

SynologyDSM6.0DeveloperGuide

99InstallPackageRelatedPortsInformationintoDSM

LowerPrivilegeToreducesecurityrisks,wenowprovideaframeworktorunpackageswithalowerprivileged"packageuser"insteadofroot.Belowisasummaryofhowtojointheframeworkandwhatpackagecenterdoesforyou:

1. Packagedevelopersprovideprivilegespecificationtospecifywhatprivilegeisneededduringprogramexecution.2. Duringpackageinstallation,packagecentercreatescorrespondinguserandgroup.SeePackageUser&Groupformoredetail.3. Accordingtotheprivilegespecification,packagecenterchownfilesunder/var/packages/${package}/target.(Thesetuidand

setgidbitwillbecleared)4. Packageexecutablesarerunwithprivilege(packageuser,systemorroot)accordingtoitsfileownerandgroup.SeeMechanism

formoredetail.

Withthisframework,packagedeveloperiscapableof:

Configurewhichexecutableshouldberunwithwhatprivilegewithasimpleprivilegespecificationfile.ResourceAcquistioncanbeusedtohelpmaintainsomechoresthatrequiresrootprivilege.

Whethertolowerthepackage'sprivilegeandcreatecorrespondinguser/groupisoptional.Thepackagehastoprovideprivilegespecificationtojointhisframework,otherwisethepackagewillstillberunwithrootprivilege,andnouser/groupwillbecreated.

SynologyDSM6.0DeveloperGuide

100LowerPrivilege

PackageUser&Group

Duringpackageinstallation,packagecenterusesthepackagenametocreateauserandgroupforthepackage.Andtheiruid/gidwillbethesamenumber,whichliesbetween100000and300000.Failureonuser/groupcreationwillcausepackageinstallationtoabort.Ifacustomuserandgroupnameispreferred,seeprivilegespecification.

User&GroupCreation

Newlycreateduserandgroupwillhavethebelowconfiguration:

#/etc/passwd

${package}:x:${uid}:${gid}::/var/packages/${package}/target:/sbin/nologin

#/etc/shadow

${package}:*:10933:0:99999:7:::

#/etc/group

${package}:x:${gid}:

UIBehavior

PackageusersandgroupswillnotappearonmostUIsettings.Includingthefollowing:

Applicationprivilege'spermissionviewerFPT'schrootuserselectorFileStations's

ChangeownerSharedLinksManager->Enablesecuresharing

Theonlyexceptionsare:

ControlPanel>SharedFolder>Edit>Permission>SysteminternaluserACLeditor

CreationPolicy

Whenthepackageuser/groupnameconflictswithalocaluser/group,itwillberenamedbyaddinga$PKG${time}postfixattheend.Therenamingpolicyisshowedbelow:

SynologyDSM6.0DeveloperGuide

101PackageUser&Group

SynologyDSM6.0DeveloperGuide

102PackageUser&Group

Mechanism

Apackagemaycontainmultipleexecutables,eachofthemtriggeredindifferenttimesbytheDSM.Forexample,CGIswillbespawnbythecgidaemon,andcontrolscripts(preinst,start_stop_status...)willbecalledbypackagecenter.Ourframeworkusestheowneruserandgroupoftheexecutabletodecidewhatuserprivilegetogrant.

Supposetheowneruseris```${package}:

Iftheownergroupissystem,thenusesetresuid(-1,${package},-1),whichgivestheprocessabilitytochangebacktoroot```.Otherwise,usesetresuid(${package},${package},${package}),dropitsprivilege.

ASummoryoffileowneruser/groupandgrantedprivilegeisshownbelow:

run-as owner euid ruid

package ${package}:${package} ${package} ${package}

system ${package}:system ${package} 0

root root:root 0 0

SynologyDSM6.0DeveloperGuide

103Mechanism

PrivilegeSpecification

Duringpackageinstallation,packagefileswillbechownwith${package}:${package}.AsmentionedinMechanism,thisresultsinpackageexecutablestoberunas${package}.Butsomeexecutablesmightrequirehigherprivilege.HereweprovideaJsonconfigfilecalledprivilegespecification,locatedintheSPK'sconf/privilege.Thisprivilegespecificationspecifieswhatkindofprivilegetheexecutablesneed.

NOTEForpackagesthatdoesnotsupportrunningwithlowerprivileges,simplydonotsupplythisprevilegespecification.Thenpackagecenterwillnotapplychownonthefiles.

Thecontentofprivilegespecificationisshownbelow.defaultsspecifiesthedefaultprivilegeanddecideshowtoapplychownonfiles.."username"andgroupnameareoptional,usedforcustomuser/groupname.Therestofthekeyisusedtooverwritethedefaultsetting.

{

"defaults":{

"run-as":"<run-as>"

},

"username":"<username>",

"groupname":"<groupname>",

"ctrl-script":[{

"action":"<action>",

"run-as":"<run-as>"

},...],

"executable":[{

"relpath":"<relpath>",

"run-as":"<run-as>"

},...],

"tool":[{

"relpath":"<relpath>",

"user":"<user>",

"group":"<group>",

"permission":"<mode>"

},...]

}

<run-as>

Canbepackage,system,orroot,determineswhatprivilegewilltheexecutablebegranted:

run-as description

package Runas${package}anddropprivilege.

system Runas${package},butpreservetheabilitytograntprivilege.

root Runasroot.

defaults

Userun-astospecifywhatprivilegetobegranted,alsodecideshowtochown.

run-as description

package chown-hR"${package}:${package}"

system chown-hR"${package}:system"

root Donotchown.

SynologyDSM6.0DeveloperGuide

104PrivilegeSpecification

SynologyDSM6.0DeveloperGuide

105PrivilegeSpecification

Categories

Inhereweintroducewhatcategoriesprivilegespecificationsupportstooverwritethesettingofdefaults.Afterapplyingchownaccordingtodefaults'ssettings,chownagainwiththecaterogy'ssettings:

ctrl-scriptexecutabletool

Eachcategoryisakeyoftheprivilegespecificationjsonobject,andthecorrespondingvalueisajsonobjectarray.Anobjectinthearrayrepresentstheconfigurationofanexecutable.

ctrl-script

Controlscripts(preinst,post_inst,start_stop_status...)arespawnedbythePackageCenter:

"ctrl-script":[{

"action":"<action>",

"run-as":"<run-as>"

},...]

Member Since Description

action6.0-5891

String,canonlybeoneof"preinst","postinst","preuninst","postuninst","preupgrade","postupgrade","start","stop,"status","prestart,"prestop",or"log"

run-as6.0-5891 Seedefaults.

executable

ExecutablesdirectlyspawnedbytheDSMframeworkbelongstothiscategory:

"executable":[{

"relpath":"<relpath>",

"run-as":"<run-as>"

},...]

Member Since Description

relpath 6.0-5891 String,thefile'srelativepathunder/var/packages/${package}/target/.

run-as 6.0-5891 Seedefaults.

tool

ExecutablesindirectlycalledbytheDSMframeworkspawnbelongstothiscategory(Forexample,commandlinetoolcalledbyaCGI):

"tool":[{

"relpath":"<relpath>",

"user":"<user>",

"group":"<group>",

"permission":"<mode>"

},...]

SynologyDSM6.0DeveloperGuide

106PrivilegeSpecification

Member Since Description

relpath 6.0-5891 String,thefile'srelativepathunder/var/packages/${package}/target/.

user 6.0-5891 String,file'sowneruser,canonlybe"package"or"root".

group 6.0-5891 String,file'sownergroup,canonlybe"package"or"root".

permission 6.0-5891 4digitnumbertosetfilepermission,forexample:4750

SynologyDSM6.0DeveloperGuide

107PrivilegeSpecification

ResourceAcquisitionDuringpackageinstallationandstart-up,weoftenneedtoinstallconfigfiles(e.g.php.ini,apache.conf)orregisterservices(e.g.portconfig,datashare)ontotheDSM.Aftersettingpackagetorunwithlowerprivilege,youmightlosetheabilitytodothesejobinthecontrolscripts.Insteadofwritingthesejobsintheinstallationscripts(preinst,postinst...),weprovideaframeworktosimplifytheprocess.

Theconfigfilesandservicesthatneedstobeinstalledandregisteredarecalledresource.Eachresourcehasacorrespondingworker,whichisresponsibleforinstallingtheresourceontotheDSM.Packagedevelopersjustneedtofollowapredefinedsyntaxandprovidetheresourcespecification,PackageCenterwillthencallthecorrespodingworkertofinishthejob.

NOTEIfapackageisusingthisframework,pleaseremembertoadjusttheINFOfile'sfirmwaretomeettheworker'srequirement

SynologyDSM6.0DeveloperGuide

108ResourceAcquisition

ResourceSpecificationThejsonfileresourceisusedtospecifyapackage'srequiredresources,anditshouldbeplacedintheconffolder.Afterpackageinstallation,thisfilewillbelocatedat/var/packages/${package}/conf/resource.Thecontentofthefileshouldbesomethinglike:

{

"<resource-id>":<specification>,

...

}

<resource-id>

String,representstheresource'sID.<specification>

Jsonobject,describestheresourcerequirements.

Takethebelow/usr/locallinkerworkerforexample:

{

"usr-local-linker":{

"lib":["lib/foo"],

"bin":["bin/foo"],

"etc":["etc/foo"],

}

}

"usr-local-linker"istheresourceIDandthecorrepondingJsonobjectisthespecification,whichspecifieswhatfilesshouldbeinstalledintotheDSM.

DatafromWizard

AsmentionedinWIZARD_UIFILES,installationscriptscanoptainuser'sinputfromtheUIwizard,someworkersarealsocapableofdoingthis.Intheresourcefile,variablessurroundedby{{}}willbereplacedbytheuserinput.

TakethebelowDataShareworkerforexample:

"data-share":{

"name":"{{pkgwizard_share_name}}",

"permission":{

"ro":["admin"]

}

}

{{pkgwizard_share_name}}willbereplacedbyWIZARD_UIFILES/install_uifile'sorWIZARD_UIFILES/upgrade_uifiles'spkgwizard_share_name

SynologyDSM6.0DeveloperGuide

109ResourceSpecification

TimingEveryworkeracquiresresourcesatcertaintimingsandholdsitduringaninterval.Forexample,/usr/locallinkerholdstheresourceduringtheintervalFROM_ENABLE_TO_DISABLE,whichmeansitacquiresresourceatWHEN_ENABLEandreleasesitatWHEN_DISABLE.Thetimingsarelistedandexplainedbelow:

SynologyDSM6.0DeveloperGuide

110Timing

timing descrioption whenFailure

WHEN_PREINST beforepreinst abortinstallation,rollback,showalertmessageonUI

WHEN_POSTINST beforepostinst finishinstallation,showalertmessageonUI

WHEN_ENABLEbeforeWHEN_STARTUP,won'tprocessduringbootup abortstartup,rollback,showalertmessageonUI

WHEN_STARTUP beforestart abortstartup,rollback,showalertmessageonUI

WHEN_PREUNINST afterpreuninst finishuninstallation,showalertmessageonUI

WHEN_POSTUNINST beforepostuninst finishuninstallation,showalertmessageonUI

WHEN_DISABLEafterWHEN_HALT,won'tprocessduringshutdown ignore

WHEN_HALT afterstop ignore

NOTEToletthepackageitselfdecidewhetheruninstallationshouldcontinueornot,WHEN_PREUNINSTisprocessedafterthepreuninstscript.

SynologyDSM6.0DeveloperGuide

111Timing

ConfigUpdateSomeworkerssupportconfigupdateafterpackageinstallation./usr/syno/sbin/synopkghelershouldbeusedtoaccomplishthejob.Belowarethestepstoupdatetheconfig:

1. Updatethecontentofconfigfileunder/var/packages/${package}/target/.2. Executethecommand/usr/syno/sbin/synopkghelperupdate<package><resource-id>totriggerthecorrespondingworkerto

updatetheconfig.

Forexample,supposeapackageallowstheusertoedititslisteningportandneedstotriggerthePortconfigworkerforupdate:

1. ProvidetheusersomeUItoinputtheportnumber.2. Afterreceivingthenewportnumber,updatetheconfigfileunder/var/packages/${package/target/.3. Executethecommand/usr/syno/sbin/synopkghelperupdate${package}protocol_file,theworkerwillre-readtheconfigfile

andreloadfirewallandportforwarding.

NOTENotallworkersupportsconfigupdate,pleaserefertotheUpdatablesectionofeachworker.

SynologyDSM6.0DeveloperGuide

112ConfigUpdate

AvailableWorkersAsmentionedinthesectionResourceAcquisition,aworkerisneededforresourcemanagement.GivenaResourceSpecificationconfigurationfile,theworkerwillinstall\/uninstallthedescribedresourceatcertaintime.ThissectiondescribestheavailableworkersontheDSM.

SynologyDSM6.0DeveloperGuide

113AvailableWorkers

/usr/locallinker

Description

Package'sexecutablesandlibraryfilesshouldbeinstalledto/usr/local.Thisworkerlink/unlinkfilesto/usr/local/{bin,lib,etc}duringpackagestart/stop.

Acquire():Createsymboliclinksunder/usr/local/{bin,lib,etc}/thatpointstofilesin/var/packages/${package}/target/.Filesnotfoundunder/var/packages/${package}/target/willbeignored.Ifthetargetfilealreadyexistsin/usr/local/{bin,lib,etc},itwillbeunlink()first.Failureonanyfilelinkresultsinthisworkertoabortandtriggersrollback.

Release():Deletethelinksunder/usr/local/{bin,lib,etc}/.Ignorefilesthatarenotfound.Ignoreunlink()failure.

Provider

DSM

TimingFROM_ENABLE_TO_DISABLE

EnvironmentVariables

None

Updatable

No

Syntax

"usr-local-linker":{

"bin"["<relpath>",...],

"lib"["<relpath>",...],

"etc"["<relpath>",...]

}

Member Since Description

bin 6.0-5941 Stringarray,listoffilestobelinkedunder/usr/local/bin/.

lib 6.0-5941 Stringarray,listoffilestobelinkedunder/usr/local/lib/.

etc 6.0-5941 Stringarray,listoffilestobelinkedunder/usr/local/etc/.

relpath 6.0-5941 String,targetfile'srelativepathunder/var/packages/${package}/target/.

Example

"usr-local-linker":{

"bin":["usr/bin/a2p","usr/bin/perl"],

"lib":["lib/perl5"]

}

SynologyDSM6.0DeveloperGuide

114AvailableWorkers

TheabovespecificationsgeneratesthefollowingsymboliclinksforthePerlpackage:

root@DS$ls-l/usr/local/{bin,lib,etc}

/usr/local/bin/:

total0

lrwxrwxrwx1rootroot30Aug1306:32a2p->/var/packages/Perl/target/usr/bin/a2p

lrwxrwxrwx1rootroot31Aug1306:32perl->/var/packages/Perl/target/usr/bin/perl

/usr/local/lib/:

total0

lrwxrwxrwx1rootroot28Aug1306:32perl5->/var/packages/Perl/target/lib/perl5

/usr/local/etc/:

total0

SynologyDSM6.0DeveloperGuide

115AvailableWorkers

Apache2.2Config

Description

Packagescancarrysites-enabled/*.conffilesforApacheHTTPServer2.2.Thisworkerinstalls/uninstallstheseconfigfilesduringpackagestart/stop.

Acquire():Copytheconffilesto/usr/local/etc/httpd/sites-enabled/.ThenreloadApache2.2.Thefilesshouldhave.confextension,otherwiseitwillbeignoredFileswillbeprefixedby${package}.Existingfileswillbeunlink()first.Failureonanyfilecopyresultsinthisworkertoabortandtriggersrollback.

Release():DeletepreviouslycreatedlinksIgnorefilesthatarenotfound.Ignoreunlink()failure.

Provider

WebStation

TimingFROM_ENABLE_TO_DISABLE

EnvironmentVariables

None

Updatable

No

Syntax

"apache22":{

"sites-enabled":[{

"relpath":"<conf-relpath>",

},...]

}

Member Since Description

sites-enabled WebStation-1.0-0049 Objectarray,listofconffilestoinstall.

relpath WebStation-1.0-0049 Targetfile'srelativepathunder/var/packages/${package}/target/.

Example

SynologyDSM6.0DeveloperGuide

116AvailableWorkers

{

"apache22":{

"sites-enabled":[{

"relpath":"synology_added/test_1.conf"

},{

"relpath":"synology_added/test_2.conf"

},{

"relpath":"synology_added/test_3.conf"

}]

}

}

SynologyDSM6.0DeveloperGuide

117AvailableWorkers

DataShare

Description

Thisworkercreatessharedfolderandsetitspermissionduringpackagestartup.Thesharenamecanbehard-codedinthespecificationorgivenbyuserinputfromtheUIwizard.Thesharedfolderwillnotberemovedafterpackageuninstallation,sinceitmightdeletetheuser’spersonaldataaswell.

Acquire():Createsharedfolderandsetitspermission.Ifthesharedfolderalreadyexists,skipsharecreationandsetthepermission.

Release():Doesnothing.

Provider

DSM

TimingFROM_ENABLE_TO_POSTUNINST

EnvironmentVariables

None

Updatable

No

Syntax

"data-share":{

"shares":[{

"name":"<share-name>",

"permission":{

"ro":["<user-name>",...],

"rw":["<user-name>",...]

},

"once":"<once>"

},...]

}

Member Since Description

shares 6.0-5914 Objectarray,arrayofsharestocreate

name 6.0-5914 String,nameoftheshare,canbeobtainedfromtheUIwizard

permission 6.0-5914 Jsonobject,permissionoftheshare.(optional)

ro 6.0-5914 Stringarrayuserstobeassignedwithread-onlypermission.

rw 6.0-5914 Stringarrayuserstobeassignedwithread/writepermission.

once 6.0-5914 Boolean,onlytrytocreateshareonpackage'sfirststart.(optional,default=false)

Example

SynologyDSM6.0DeveloperGuide

118AvailableWorkers

Thefollowingspecificationcreatesasharemusic,andgivestheuserAudioStationread-onlypermission.Sinceoncedefaultstofalse,theaboveprocedureisraneverytimethepackagestarts.

"data-share":{

"shares":[{

"name":"music",

"permission":{

"ro":["AudioStation"]

}

}]

}

ThefollowingspecificationreadsthesharenamefromWIZARD_UIFILES/install_uifile'spkgwizard_share_name,andgivestheuseradminread-onlypermission.

"data-share":{

"shares":[{

"name":"{{pkgwizard_share_name}}",

"permission":{

"ro":["admin"]

}

}]

}

SynologyDSM6.0DeveloperGuide

119AvailableWorkers

IndexDB

Description

Index/unindexpackagehelpandappindexduringpackagestart/stop.

Fordetaileddescriptiononpackageappindexandhelpindex,pleaserefertoIntegegrateHelpDocumentintoDSMHelp.

Acquire():Indexpackagehelpandappcontent.Release():Un-indexpackagehelpandappcontent.

Provider

DSM

TimingFROM_ENABLE_TO_DISABLE

EnvironmentVariables

None

Updatable

No

Syntax

"indexdb":{

"app-index":{

"conf-relpath":"<confrelpath>",

"db-relpath":"<appdbrelpath>"

},

"help-index":{

"conf-relpath":"<confrelpath>",

"db-relpath":"<helpdbrelpath>"

}

}

Member Since Description

app-index 6.0-5924 Object,appindexinfo.

help-index 6.0-5924 Object,helpindexinfo.

conf-relpath 6.0-5924 String,configfile'srelativepathunder/var/packages/${package}/target/.

db-relpath 6.0-5924 String,dbfolder'srelativepathunder/var/packages/${package}/target/.

Example

SynologyDSM6.0DeveloperGuide

120AvailableWorkers

"indexdb":{

"app-index":{

"conf-relpath":"app/index.conf",

"db-relpath":"indexdb/appindexdb"

},

"help-index":{

"conf-relpath":"app/helptoc.conf",

"db-relpath":"indexdb/helpindexdb"

}

}

SynologyDSM6.0DeveloperGuide

121AvailableWorkers

MariaDB

Description

Create/deletedatabaseanddb-userduringpackageinstall/uninstall.Thedatabasenamecanbehard-coded,readfromconfigfileorgivenbytheuserfromUIwizard.Packagedevelopercandecideifcreatingacorrespondingdb-userisneededornot.

Acquire():Createdatabaseanddb-useraccrodingtoresourcespecification.database:resourcespecificationcanspecifywhatactiontotakeifadatabasewiththesamenamealreadyexists:1. drop:Deletetheexistingdatabase.2. skip:Ignoredatabasecreation,keeptheexistingdatabaseandconitinueinstallation.3. error:Returnerrorandrollback.(Default:error)

db-user:Createdb-userandgrantaccesstothedatabaseaccordingtotheresourcespecification.Thedefaultdb-usertocreateis'${package}'@'localhost'

Release():Deletedatabaseanddb-useraccrodingtotheresourcespecification.Defaultistokeepthedatabaseanddb-user.Duringpackageupgrade,MariaDBworkerprovidestheget_key_valuemethodtoobtainpreviouslycreatedatabase'sname,andtherewillbenocreate/deletefordatabaseanddb-user

Provider

MariaDB

TimingFROM_PREINST_TO_PREUNINST

EnvironmentVariables

Variable Since Description

SYNOPKG_DB_USER_RAND_PW 6.0-5920 Therandompasswordgeneratedduringdatebaseusercreation.

Updatable

No

Syntax

((*)required)

SynologyDSM6.0DeveloperGuide

122AvailableWorkers

"mysql-db":{

"info":{

"db-name":"<dbname>",(*)

"conf":"<conf>",

"key":"<key>"

},

"root-pw":"<dbpassword>",(*)

"create-db":{

"char-set":"<character-set>",

"collate":"<collate>",

"db-collision":"drop"|"skip"|"error"

},

"grant-user":{

"user-name":"<dbusername>",

"host":"<dbuserhost>",

"user-pw":"<userpassword>",

"rand-pw":true|false

},

"drop-db-uninst":true|false,

"drop-user-uninst":true|false

}

SynologyDSM6.0DeveloperGuide

123AvailableWorkers

Member Since Description

info5.5.47-0062

Object,infoofdb-name.Thepriorityofretrievingdatabase'snameisdb-name>conf.Whichmeans,ifdb-nameisgiven,confandkeywillbeignored.

db-name5.5.47-0062 String,databasename,canbegivenbyUIwizard.

conf5.5.47-0062 String,filecontainingthedatabasename'skey-value-pair.

key5.5.47-0062 String,thekeyinconffiletolookfordb-name.

root-pw5.5.47-0062 String,rootpasswordofMariaDB.

create-db5.5.47-0062 Object,infoofdatabase.Ifdoesnotexist,databasewillnotbecreatedduringAcquire().

character-

set

5.5.47-0062 String,database'sCHARACTERSET.(default=utf8)

collate5.5.47-0062 String,database'sCOLLATE.(default=utf8_unicode_ci)

db-

collision

5.5.47-0062 String,actiontotakeifthedatabaseexists.Canbedrop/skip/error.

grant-

user

5.5.47-0062 Object,infoofdb-user.Ifdoesnotexist,db-userwillnotbecreatedduringAcquire().

user-name5.5.47-0062 String,db-username.(default=${package})

host5.5.47-0062 String,db-user'shost.(defaults=localhost)

user-pw5.5.47-0062

String,db-user'spassword.Ifemptyornull,db-user'spasswordwillnotbeset.Overridesexistinguser'spassword.

rand-pw5.5.47-0062

Boolean,whethertogeneratearandompassword.Ifsettotrue,thedb-userwillbegivenarandompasswordandbepassedtoenvironmentvariableSYNOPKG_DB_USER_RAND_PW.Ifuser-pwexists,thisvaluewillbeignored.

drop-db-

uninst

5.5.47-0062

Boolean,whethertodeletedatabaseduringRelease().CanbegivenbyUIwizard.(defaults=false)

drop-user-

uninst

5.5.47-0062

Boolean,whethertodeletedb-userduringRelease().CanbegivenbyUIwizard.(defaults=false)

Example

"mysql-db":{

"info":{

"db-name":"wordpressblog"

},

"root-pw":"{{pkgwizard_mysql_password}}",

"create-db":{

"db-collision":"skip"

},

"grant-user":{

"user-name":"wordpress"

},

"drop-db-uninst":"{{pkgwizard_remove_mysql}}",

"drop-user-uninst":"{{pkgwizard_remove_mysql}}"

}

SynologyDSM6.0DeveloperGuide

124AvailableWorkers

SynologyDSM6.0DeveloperGuide

125AvailableWorkers

PHPINI

Description

Packagescancarrycustomphp.iniandfpm.conffiles.Thisworkerinstalls/uninstallstheseconfigfilesduringpackagestart/stop.

Acquire():Copythephp.iniandfpm.conffilesto/usr/local/etc/php56/conf.d/and/usr/local/etc/php56/fpm.d/.Thenreloadphp56-fpm.

php.ini/fpm.conffilesshouldhave.ini/.confextension,otherwiseitwillbeignoredFileswillbeprefixedby${package}.Existingfileswillbeunlink()first.Failureonanyfilecopyresultsinthisworkertoabortandtriggersrollback.

Release():DeletepreviouslycreatedlinksIgnorefilesthatarenotfound.Ignoreunlink()failure.

Provider

PHP5.6

TimingFROM_ENABLE_TO_DISABLE

EnvironmentVariables

None

Updatable

No

Syntax

"php":{

"php-ini":[{

"relpath":"<ini-relpath>",

},...],

"fpm-conf":[{

"relpath":"<conf-relpath>",

},...]

}

Member Since Description

php-ini PHP5.6-5.6.17-0020 Objectarray,listofphp.inifilestoinstall.

fpm-conf PHP5.6-5.6.17-0020 Objectarray,listoffpm.conffilestoinstall.

relpath PHP5.6-5.6.17-0020 Targetfile'srelativepathunder/var/packages/${package}/target/.

Example

SynologyDSM6.0DeveloperGuide

126AvailableWorkers

{

"php":{

"php-ini":[{

"relpath":"synology_added/etc/php/conf.d/test_1.ini"

},{

"relpath":"synology_added/etc/php/conf.d/test_2.ini"

},{

"relpath":"synology_added/etc/php/conf.d/test_3.ini"

}],

"fpm-conf":[{

"relpath":"synology_added/etc/php/fpm.d/test_1.conf"

},{

"relpath":"synology_added/etc/php/fpm.d/test_2.conf"

},{

"relpath":"synology_added/etc/php/fpm.d/test_3.conf"

}]

}

}

SynologyDSM6.0DeveloperGuide

127AvailableWorkers

PortConfig

Description

Install/uninstallserviceportconfigfileduringpackageinstall/uninstall.

Fordetaileddescriptiononwhatisandhowtowriteaportconfigfile,pleaserefertoInstallPackageRelatedPortsInformationintoDSM.

Acquire():copythe.scfileto/usr/local/etc/service.d/Ifthedestinationfileexists,skipfilecopy.

Release():removethe.scfileandreloadthefirewallandportforward.Update():updatethe.scfileandreloadfirewallandportforward.

TimingFROM_POSTINST_TO_POSTUNINST

EnvironmentVariables

None

Updatable

Yes,pleaserefertoConfigUpdateonhowtotriggerupdate.

Syntax

"port-config":{

"protocol-file":<protocol_file>

}

Member Since Description

protocol_file 6.0-5936 .scfile'srelativepathunder/var/package/{$package}/target/

Example

"port-config":{

"protocol-file":"port_conf/xxdns.sc"

}

SynologyDSM6.0DeveloperGuide

128AvailableWorkers

SyslogConfig

Description

Install/uninstallthesyslog-ngandlogrotateconfigfileduringpackagestart/stop.

Pleaserefertosyslog-ngonhowtowritethesyslog-ng'sconfigfile.

Acquire():Copypatterndb/logratoateto/usr/local/etc/syslog-ng/patterndb.d///usr/local/etc/logrotate.d/.Thenreloadsyslog-ng.

Iffileexists,unlink()itfirst.Failureonanyfilecopyresultsinthisworkertoabortandtriggersrollback.

Release():Deletetheconfigfilesandreloadsyslog-ng.Ignoreunlink()failure.

Provider

DSM

TimingFROM_ENABLE_TO_DISABLE

EnvironmentVariables

None

Updatable

No

Syntax

"syslog-config":{

"patterndb-relpath":"<relpath>",

"logrotate-relpath":"<relpath>"

}

Member Since Description

patterndb-

relpath

6.0-7145

String,syslog-ng'sconfigfile'srelativepathunder/var/packages/${package}/target/,ignorethisifthelogisnotgeneratedbysyslog-ng(optional)

logrotate-

relpath

6.0-5911

String,logrotate'sconfigfile'srelativepathunder/var/packages/${package}/target/,ignorethisiflogissavedtodatabase(optional)

Example

"syslog-config":{

"patterndb-relpath":"etc/syslog-ng.conf",

"logrotate-relpath":"etc/logrotate.conf"

}

SynologyDSM6.0DeveloperGuide

129AvailableWorkers

SynologyDSM6.0DeveloperGuide

130AvailableWorkers

PublishSynologyPackages

SynologyDSM6.0DeveloperGuide

131PublishSynologyPackages

GetStartedwithPublishingTopublishinSynologyPackageCenterrequiresafewsimplesteps.Hereishowtodoit:

1. AcquireaSynologyCheckoutMerchantAccountviaaSynologyspecialist(formoredetailspleasecontactpackage@synology.com).

2. ReadandaccepttheDeveloperDistributionAgreement.NotethatpackagesthatyoupublishonPackageCentermustcomplywiththeTermsofServiceinPackageCenter.

Pleasenotethatthepackagequalitydirectlyinfluencesthelong-termsuccessofyourpackageintermsofinstallation,onlinereviews,engagement,anduserretention.

SynologyDSM6.0DeveloperGuide

132GetStartedwithPublishing

SubmittingthePackageforApprovalBeforeyoupublishyourpackageinPackageCenteranddistributeittousers,youneedtogetthepackage(theSPKfile)ready,testit,andprepareyourpromotionmaterialsifneeded.Pleaseseethechecklistbelowbeforesubmittingyourpackagetous.

ConfirmPackageSize

TheoverallsizeofyourpackagecanaffectitsdesignandhowyoupublishitinPackageCenter.Currently,themaximumsizeforaSPKfilepublishedonPackageCenteris100MB.

FreeorPaidPackage

InPackageCenter,youcanpublishfreeorpaidpackages.FreepackagescanbedownloadedbyanyuserinPackageCenter.PaidappscanbedownloadedonlybyuserswhohavearegisteredSynologyAccount.

Decidingwhetheryourpackagewillbefreeorpaidisimportantbecausefreepackagesmustremainfree.

Onceyourpackageispublishedasafreeone,youcannotchangeittoapaidpackage.Ifyoupublishyourpackageasapaidone,youcanchangeittofreeatanytime(butcannotbechangedbacktopaid).Ifyourpackageispaid,youneedtosetupaSynologyCheckoutMerchantAccountbeforethepackagecanbepublished.ForqueriesabouttheSynologyCheckoutMerchantAccount,youcancontactpackage@synology.com.

SetaPriceforYourPackageIfyouhaveapaidpackage,SynologyletsyousetpricesforyourpackageonlyinUScurrencyforusersinmarketsaroundtheworld.Beforeyoupublish,considerhowyouwillpriceyourpackageandwhatyourpricewillbeinvariouscurrencies.

PrepareScreenshotsWhenyoupublishinPackageCenter,youmustsupplyavarietyofhigh-qualityscreen-shotstoshowcaseyourpackageorbrand.Afteryoupublish,theywillappearonyourpackagedetailspage,orelsewhere.Thesescreen-shotsareakeypartofasuccessfulpackagedetailspagethatwillattractandengageusers.Therefore,youmayalsoconsiderhiringaprofessionaltoproducethemforyou.

SubmitYourPackageWhenyouarereadytopublish,sendanemailtoaSynologyspecialistpackage@synology.comtomakeyoursubmission.

Makesurethat:

YouhaveappliedthroughSynologyDevCenterandbecomeanauthorizeddeveloper.Yourpackageistherightversion.Youprovideadownloadlinkforyourpackage.Youprovideapackagedescriptionwithwhatitdoes.Youprovideachangelogwithwhatwasupdatedinthisversion.Packagepricingissettobefreeorpaid(forthefirsttimesubmission).Thelinktoyourwebsiteandthesupportemailaddressiscorrect.YouhaveacknowledgedthatyourpackagemeetstheDeveloperDistributionAgreementandalsotheTermsofServicefromPackageCenter.

SynologyDSM6.0DeveloperGuide

133SubmittingthePackageforApproval

SynologyDSM6.0DeveloperGuide

134SubmittingthePackageforApproval

RespondingtoUserIssuesAfteryoupublishapackage,ititcrucialforyoutooffersupporttoyourcustomers.Promptandcourteoussupportcanprovideabetterexperienceforusers,whichcanresultinmoredownloadsandmorepositiveonlinereviewsforyourpackages.Usersaremorelikelytobemoreengagedwithyourpackageandrecommenditifyouareresponsivetotheirneedsandfeedback.

Therearemanywaysthatyoucankeepintouchwithusersandofferthemsupport.Themostcommonwayistoprovideasupportemailaddressinyourpackagedetailspage.Youcanalsoprovidesupportinotherways,suchasaforumoramailinglist.TheSynologytechnicalsupportteamprovidesusersupportfordownloading,installingandpaymentsissues,butissuesthatfalloutsideofthesetopicswillfallunderyourdomain.Examplesofissuesyoucansupportinclude:featurerequests,questionsaboutusingtheappandquestionsaboutcompatibilitysettings.

Afterpublishing,pleaseplanto:

Providealinktoyoursupportresourcesandsetupanyothersupportoutletssuchasaforum.Provideanappropriatesupportemailaddressonyourpackagedetailpageandrespondtouserswhentheyemailyou.Acknowledgeandfixissueswithyourpackage.Ithelpstobetransparentandlistknownissuesonyourpackagedetailspageregularly.Publishupdatesfrequently,withoutsacrificingqualityorannoyinguserswithtoo-frequentupdates.Witheachupdate,makesureyouprovideasummaryofwhatisnew.Userswillreaditandappreciatethatyouareseriousaboutimprovingthequalityofyourpackage.

SynologyDSM6.0DeveloperGuide

135RespondingtoUserIssues

AppendixA:PlatformandArchValueMappingTableThearchitectureoftheNASisdevelopeduponvariousplatformsonwhichyourpackageisdesignedandneedstobeaddressedintheINFOfileinthepackage.

Inthebelowtable,youwillfindthestringvaluecorrespondingtotheplatforminquestion.Forexample,iftheplatformofyourNASisMarvellKirkwood,88F6281,thevaluethatshouldtobeprovidedasapairofthearchkeyis88f6281.

PleasechecktheplatformsoftheNAStobesupportedandrefertothetablebelowfortheircorrespondingstringvalues:

PlatformName ArchValue

MarvellKirkwood,88F6281 88f6281

MarvellKirkwood,88F6282 88f6282

IntelAtomD410/D510(Pineview) x86

IntelAtomD2700(Cedarview) cedarview

IntelSandyBridge,IntelIvyBridge,IntelHaswell bromolow

MarvellArmada370 armada370

MarvellArmada375 armada375

MarvellArmadaXP armadaxp

Annapurnalabs,Alpine alpine/alpine4k

Mindspeed,Comcerto,C2000 comcerto2k

IntelAtomCESoC evansport

Noplatformdependency noarch

SynologyDSM6.0DeveloperGuide

136AppendixA:PlatformandArchValueMappingTable

RevisionHistoryThistabledescribesthechangestotheSynologyDSM3rdPartyAppsDeveloperGuide.

SynologyDSM6.0DeveloperGuide

137RevisionHistory

Date Note

2008/06/16 1.Originalreleasedateofdocument.

2009/02/09 1.AddedFreescale8533toolchaininformation.

2009/03/09 1.AddedMarvell6281toolchaininformation.2.AddedDesktopIconchapter.

2010/05/20

1.Addedrelatedinformationfor10models.2.ChangedallDSM2.0&2.1toDSM2.3.3.Newscreenshotsfordesktopicon&DSMapplication.4.Changedconfigurationfilesandtoolchains.5.DS1010+usesIntelAtomD510.

2010/05/281.RevisedToolChaindescription2.Revised88f5182-configto88f5281-configinKernelModule.3.Revisedpathdescriptionofapplication.cfg/desktop.cfg.

2010/11/29 1.Renamedthedocumentto“SynologyDiskStationManager3rd-PartyAppsDeveloperGuide”.2.AddedDSM3.0Integrationsection.

2011/10/31 1.AddedSynologypackagecreationsection.2.UpdatedDSMtoolchaininformation.

2012/03/20 Addedtheguidelinetoapplicationstorage,webapplicationrunningonApacheandcreatedasharedfolder.

2012/09/19 AddedFreescaleQorIQtoolchaininformation.

2013/03/111.GeneralupdateforDSM4.2release.2.Addedsectionregardingpaymentframework.3.Updatedformatting.

2013/05/06 AddedMarvellArmada370toolchaininformation.

2013/05/29 AddedMarvellArmadaXPandEvansporttoolchaininformation.

2013/06/05 UpdatedQorIQ,ArmadaXP,Armada370,Evansport$CCvariable.

2013/07/09 1.Updatedinstall_dep_servicesandstart_dep_servicesinINFOsection.2.AddedLocaleSupport.

2013/07/25 1.UpdatedLinuxkernelversion.2.AddedCSRFprotectioninDSMWebAuthenticationsection.

2013/08/29 Generalupdateontoolchain,toolkit,andGPLkernelsourceforDSM4.3release.

2014/02/25

1.UpdatedkeysinINFOsectionforDSM5.0.2.AddedDSM5.0supportinplatformchart.3.UpdatedCreatePHPApplicationwithDSM5.0change.4.AddedCreateUserAccountandSharePermission.5.Minorcorrections.

2014/03/26 1.AddedAppendixforPlatformandArchstringmappingtable.2.AddedcompilationinstructionforDSM5.0build.

2014/08/17 1.Addedcodesignmechanismforpackages.

2014/10/29 1.AddedChapter:QuickStartGuide.2.Removedtheduplicatedcontent.

2015/09/10 1.AdedMarvellArmada375ANNAPURNALABS,AlpineAL212/AL314/AL514andMINDSPEED,Comcerto,C2000toolchaininformation.

2016/01/14 1.Contentrevised.2.ChangedtoformattoGitbook.

SynologyDSM6.0DeveloperGuide

138RevisionHistory

CompileApplicationsTheSynologyNASemploysembeddedSoCorx86-basedCPUs,implementingseveralplatforms--suchasARMandPowerPC--onavarietyofSynologyNASmodels.Inordertorun3rd-partyapplicationsontheSynologyNAS,itisnecessarytocompileapplicationsintoanexecutableformatforthecorrespondingplatform.

ThetablebelowliststheCPU,architecture,Endianness,andLinuxkernelversionofeachSynologyNASmodel.ThisinformationwillhelpyoudeterminewhichDSMtoolchain(pleaserefertothe“DownloadDSMToolChain”section)todownloadforeachmodel.

PleaserefertoWhatkindofCPUdoesmyNAShaveNeedtoupdatethehyperlinkforacompletemodellist.

Model(Tonameafew) CPU Arch Endianness Linux

DS112j,DS112,DS112+,DS411slim,DS213,DS212j Marvell6281Marvell6282 ARM Little

Endian 2.6.32

DS213j MarvellArmada370 ARM LittleEndian 3.2.40

DS214,DS214+ MarvellArmadaXP ARM LittleEndian 3.2.40

DS215+,DS416 Annapurnalabs,AlpineAL212 ARM Little

Endian 3.2.40

DS715,DS1515 Annapurnalabs,AlpineAL314 ARM Little

Endian 3.2.40

DS2015xs Annapurnalabs,AlpineAL514 ARM Little

Endian 3.2.40

DS115,DS215j MarvellArmada375 ARM LittleEndian 3.2.40

DS414j Mindspeed,Comcerto,C2000 ARM Little

Endian 3.2.40

DS712+,DS2412+,RS2212+,DS1512+,DS1812+,DS412+,RS812+ IntelAtom Intelx86 Little

Endian 3.2.40

DS3612xs,RS3412xs,RS3412RPxs IntelCorei3 Intelx86 LittleEndian 3.2.40

DS214play IntelSoC Intelx86 LittleEndian 3.2.40

DS213+,DS413 FreescaleQorIQP1022 PowerPC BigEndian 2.6.32

TocompileanapplicationfortheSynologyNAS,acompilerthatrunsonLinuxPCisrequiredinordertogenerateanexecutablefilefortheSynologyNAS.Thiscompilingprocedureiscalledcross-compiling,andthesetofcompilingtools(compiler,linker,etc)usedtocompiletheapplicationiscalledatoolchain.

SynologyDSM6.0DeveloperGuide

139AppendixB:CompileApplicationsManually

DownloadDSMToolChainTodownloadtheDSMtoolchain,pleasegotoSourceForge.ThetablebelowshowsthefilenameoftoolchainsforNASwithdifferentCPUs:

CPU ToolChain Linux

Marvell6281 Marvell88F628xLinux2.6.32 2.6.32

MarvellArmada370 MarvellArmada370Linux3.2.403 3.2.40

MarvellArmadaXPMarv MarvellArmadaxpLinux3.2.40 3.2.40

MarvellArmada375 MarvellArmada370Linux3.2.40 3.2.40

Annapurnalabs,AlpineAL212/AL314/AL514 Annapurnalabs,AlpineLinux3.2.40 3.2.40

Mindspeed,Comcerto,C2000 Mindspeed,Comcerto,C2000Linux3.2.40 3.2.40

FreescaleQorIQ(P1022) PowerPCQorIQLinux2.6.32 2.6.32

IntelAtom Intelx86Linux3.2.40(Pineview)Intelx86Linux3.2.40(Cedarview) 3.2.40

IntelCorei3 Intelx86Linux3.2.40(Bromolow) 3.2.40

IntelSoC Intelx86Linux3.2.40(Evansport) 3.2.40

Ifyouarenotsureaboutwhichtoolchainyouneed,pleaseexecutethefollowingcommandonyourSynologyNAS.

#uname-a

Linuxmyds3.2.40#3503SMPThuMar2115:17:31CST2013x86_64

GNU/Linuxsynology_x86_712+

Thelast“synology_x64_712+”tellsyouwhichtoolchainisappropriate.Forexamples,x86meansyouneedthetoolchainforPineview.

AfteryoudownloadtheDSMtoolchain,extractittowhereyouwantitonyourcomputer.Forthefollowinginstructionswewillextractto/usr/local/asanexample.Youcanextractthetoolchainbyusingthefollowingcommand:

#tarzxpfgcc343_glibc232_88f5281.tgz–C/usr/local/

Pleasemakesurethetoolchainislocatedinthedirectory/usr/localonyourcomputertoensureproperintegration.

SynologyDSM6.0DeveloperGuide

140DownloadDSMToolChain

CompileYoucanstartcompilinganapplicationcalled“minimalPkg.c”,forexample,thatlookslikethis:

#include<sys/sysinfo.h>

intmain()

{

structsysinfoinfo;

intret;

ret=sysinfo(&info);

if(ret!=0){

printf("Failedtogetsysteminformation.\n");

return-1;

}

printf("TotalRAM:%u\n",info.totalram);

printf("FreeRAM:%u\n",info.freeram);

return0;

}

Tocompiletheapplication,runthefollowingcommand:

/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linux-gnueabigccminimalPkg.c–osysinfo

YoucanalsowriteaMakefileforit:

EXEC=sysinfo

OBJS=sysinfo.o

CC=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-gcc

LD=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ld

CFLAGS+=-I/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/include

LDFLAGS+=-L/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/lib

all:$(EXEC)

$(EXEC):$(OBJS)

$(CC)$(CFLAGS)$(OBJS)-o$@$(LDFLAGS)

clean:

rm-rf*.o$(PROG)*.core

SynologyDSM6.0DeveloperGuide

141Compile

CompileOpenSourceProjectsTocompileanapplicationonmostopensourceprojects,youwillbeaskedtoexecutethefollowingthreesteps:

1. configure2. make3. makeinstall

Theconfigurescriptbasicallyconsistsofmanylineswhichareusedtocheckdetailsaboutthemachineonwherethesoftwareisgoingtobeinstalled.Thescriptwillcheckforalotofdependenciesonyoursystem.Whenyouruntheconfigurescript,youwillseealotofoutputonthescreen,eachbeingsomesortofquestionwitharespectiveyes/noreply.Ifthereareanymajorrequirementsmissingonyoursystem,theconfigurescriptwillexitandyouwillnotbeabletoproceedwiththeinstallationuntilyoumeetalltherequirements.Inmostcases,compileapplicationsonsomeparticulartargetmachineswillrequireyoutomodifytheconfigurescriptmanuallytoprovidethecorrectvalues.

Whenrunningtheconfigurescripttoconfiguresoftwarepackagesforcross-compiling,youwillneedtospecifytheCC,LD,RANLIB,CFLAGS,LDFLAGS,host,target,andbuild,etc.Someexamplesaregivenbelow.

ForPowerPCQorIQplatforminDSM5.0:

envCC=/usr/local/powerpc-none-linux-gnuspe/bin/powerpc-none-linuxgnuspe-gcc\

LD=/usr/local/powerpc-none-linux-gnuspe/bin/powerpc-none-linuxgnuspe-ld\

RANLIB=/usr/local/powerpc-none-linux-gnuspe/bin/powerpc-none-linuxgnuspe-ranlib\

CFLAGS="-I/usr/local/powerpc-none-linux-gnuspe/include-mcpu=8548-mhard-float-mfloat-gprs=double"\

LDFLAGS="-L/usr/local/powerpc-none-linux-gnuspe/lib"\

./configure\

--host=powerpc-unknown-linux\

--target=powerpc-unknown-linux\

--build=i686-pc-linux\

--prefix=/usr/local

ForMarvell6281platforminDSM5.0:

envCC=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-gcc\

LD=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ld\

RANLIB=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ranlib\

CFLAGS="-I/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/include"\

LDFLAGS="-L/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/lib"\

./configure\

--host=armle-unknown-linux\

--target=armle-unknown-linux\

--build=i686-pc-linux\

--prefix=/usr/local

ForMarvellArmada370platforminDSM5.0:

envCC=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-gcc\

LD=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ld\

RANLIB=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ranlib\

CFLAGS="-I/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/include-mhard-float-mfpu=vfpv3-d16"\

LDFLAGS="-L/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/lib"\

./configure\

--host=armle-unknown-linux\

--target=armle-unknown-linux\

--build=i686-pc-linux"\

--prefix=/usr/local

ForMarvellArmada375platforminDSM5.1:

SynologyDSM6.0DeveloperGuide

142CompileOpenSourceProjects

envCC=/usr/local/armv7-marvell-linux-gnueabi-hard/bin/arm-marvelllinux-gnueabi-ccache-gcc\

LD=/usr/local/armv7-marvell-linux-gnueabi-hard/bin/arm-marvell-linuxgnueabi-ld\

RANLIB=/usr/local/armv7-marvell-linux-gnueabi-hard/bin/arm-marvelllinux-gnueabi-ranlib\

CFLAGS="-I/usr/local/armv7-marvell-linux-gnueabi-hard/arm-marvelllinux-gnueabi/libc/usr/include-mhard-float-mfpu=vfpv3"

LDFLAGS="-L/usr/local/armv7-marvell-linux-gnueabi-hard/arm-marvelllinux-gnueabi/libc/lib"\

./configure\

--host=armle-unknown-linux\

--target=armle-unknown-linux\

--build=i686-pc-linux"\

--prefix=/usr/local

ForMarvellArmadaXPplatforminDSM5.0:

envCC=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-gcc\

LD=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ld\

RANLIB=/usr/local/arm-marvell-linux-gnueabi/bin/arm-marvell-linuxgnueabi-ranlib\

CFLAGS="-I/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/include-mhard-float-mfpu=vfpv3-d16"\

LDFLAGS="-L/usr/local/arm-marvell-linux-gnueabi/arm-marvell-linuxgnueabi/libc/lib"\

./configure\

--host=armle-unknown-linux\

--target=armle-unknown-linux\

--build=i686-pc-linux"\

--prefix=/usr/local

ForAnnapurnalabs,AlpineplatforminDSM5.1:

envCC=/usr/local/arm-cortex_a15-linux-gnueabi/bin/arm-cortex_a15-linux-gnueabi-ccache-gcc\

LD=/usr/local/arm-cortex_a15-linux-gnueabi/bin/arm-cortex_a15-linuxgnueabi-ld\

RANLIB=/usr/local/arm-cortex_a15-linux-gnueabi/bin/arm-cortex_a15-linux-gnueabi-ranlib\

CFLAGS="-I/usr/local/arm-cortex_a15-linux-gnueabi/arm-cortex_a15-linux-gnueabi/sysroot/usr/include-mfloat-abi=hard-mtune=cortex-a15-mfpu=neon-vfpv4-mthumb"

LDFLAGS="-L/usr/local/arm-cortex_a15-linux-gnueabi/arm-cortex_a15-linux-gnueabi/sysroot/lib"\

./configure\

--host=arm-cortex_a15-linux-gnueabi\

--target=arm-cortex_a15-linux-gnueabi\

--build=i686-pc-linux"\

--prefix=/usr/local

ForMindspeed,Comcerto,C2000platforminDSM5.0:

envCC=/usr/local/arm-cortexa9-linux-gnueabi/bin/arm-cortexa9-linuxgnueabi-ccache-gcc\

LD=/usr/local/arm-cortexa9-linux-gnueabi/bin/arm-cortexa9-linuxgnueabi-ld\

RANLIB=/usr/local/arm-cortexa9-linux-gnueabi/bin/arm-cortexa9-linuxgnueabi-ranlib\

CFLAGS="-I/usr/local/arm-cortexa9-linux-gnueabi/arm-cortexa9-linuxgnueabi/sysroot/include-mcpu=cortex-a9-march=armv7-a-mfpu=neon-mfloat-abi=hard-mthumb"

LDFLAGS="-L/usr/local/arm-cortexa9-linux-gnueabi/arm-cortexa9-linuxgnueabi/sysroot/lib"\

./configure\

--host=armle-unknown-linux\

--target=armle-unknown-linux\

--build=i686-pc-linux"\

--prefix=/usr/local

ForIntelX86platforminDSM5.0:

SynologyDSM6.0DeveloperGuide

143CompileOpenSourceProjects

envCC=/usr/local/i686-pc-linux-gnu/bin/i686-pc-linux-gnu-gcc\

LD=/usr/local/i686-pc-linux-gnu/bin/i686-pc-linux-gnu-ld\

RANLIB=/usr/local/i686-pc-linux-gnu/bin/i686-pc-linux-gnu-ranlib\

CFLAGS="-I/usr/local/i686-pc-linux-gnu/i686-pc-linux-gnu/sysroot/usr/include"\

LDFLAGS="-L/usr/local/i686-pc-linux-gnu/i686-pc-linux-gnu/sysroot/lib"\

./configure\

--host=i686-pc-linux-gnu\

--target=i686-pc-linux-gnu\

--build=i686-pc-linux\

--prefix=/usr/local

ForIntelAtomEvansportplatforminDSM5.0:

envCC=/usr/local/i686-pc-linux-gnu/bin/i686-pc-linux-gnu-gcc\

LD=/usr/local/i686-pc-linux-gnu/bin/i686-pc-linux-gnu-ld\

RANLIB=/usr/local/i686-pc-linux-gnu/bin/i686-pc-linux-gnu-ranlib\

CFLAGS="-I/usr/local/i686-pc-linux-gnu/i686-pc-linux-gnu/sysroot/usr/include"\

LDFLAGS="-L/usr/local/i686-pc-linux-gnu/i686-pc-linux-gnu/sysroot/lib"\

./configure\

--host=i686-pc-linux-gnu\

--target=i686-pc-linux-gnu\

--build=i686-pc-linux\

--prefix=/usr/local

SynologyDSM6.0DeveloperGuide

144CompileOpenSourceProjects

CompileKernelModulesAsmentionedbefore,youhavetocreatetheSynoBuildConf/build,SynoBuildConf/install,andSynoBuildConf/dependsbeforeusingPackageToolkit.

Inthischapter,wewilluseplatform6281asourexample.

Preparation:

First,youwillneedtodownloadtheGPLsourcecodeofyourplatform.Youcandownloadthesourcecodefromthislink.

AfterdownloadingtheSynologyGPLkernelsourcecode,movethefiletoyourtoolkitfolder.

SynoBuildConf/depends:Thereisnothingspecialaboutthedependsfile.Thefollowingisthedependsfileforthe6281platform.

[default]

all="6.0"

SynoBuildConf/build:Beforecompilingthekernelmodules,youwillneedtosetuptheconfigfilefirst.

Inthekernelsourcecode,thereareconfigurationfilesfordifferentplatforms.Theconfigurationfilesarelistedbelow:

CPU ConfigurationFile Arch Linux

Marvell6281Marvell6282 synoconfigs/88f6281 ARM 2.6.32

MarvellArmada370 synoconfigs/armada370 ARM 3.2.40

MarvellArmada375 synoconfigs/armada375 ARM 3.2.40

MarvellArmadaXP synoconfigs/armadaxp ARM 3.2.40

Annapurnalabs,AlpineAL212/AL314/AL514 synoconfigs/alpine(DS715,DS1515,DS2015xs)synoconfigs/alpine4k(DS215+,DS416) ARM 3.2.40

Mindspeed,Comcerto,C2000 synoconfigs/comcerto2k ARM 3.2.40

FreescaleQorIQ(P1022) synoconfigs/ppcQorIQ PowerPC 2.6.32

IntelAtomD525,D510,D410,D425 synoconfigs/x86_64 x86 3.2.40

IntelAtomD2700 synoconfigs/cedarview x86 3.2.40

IntelSoCCE5335 synoconfigs/evansport x86 3.2.40

IntelCorei3 synoconfigs/bromolow x86 3.2.40

Pleasecopytheproperconfigurationfileto.config,andrunmakeoldconfigandmakemenuconfigtoselectyourkernelmodules.Accordingtotheplatformsyouwouldliketocompile,youwillhavetosettheproperARCHandCROSS_COMPILEintoenvironmentvariables.

Thefollowingisasamplescriptthatwillcompilethelinuxkernelmodulesforthe6281platform.

SynologyDSM6.0DeveloperGuide

145CompileKernelModules

#!/bin/bash

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

#SynoBuildConf/build

case${MakeClean}in

[Yy][Ee][Ss])

[-fMakefile]&&makedistclean

;;

esac

case${CleanOnly}in

[Yy][Ee][Ss])

return

;;

esac

#prepareconfigfiles

cp-fsynoconfigs/88f6281.config

makeARCH=${ARCH}CC=${CC}oldconfig

#startcompilekernelmodules

echo"=====BuildSynologyLinuxkernel2.6Modules====="

makeARCH=${ARCH}CC=${CC}LD="${LD}"${MAKE_FLAGS}modules

#createtable

./scripts/syno_gen_usbmodem_table.shcreate-table

SynoBuildConf/installUnlikethepreviousexample,thisexamplewillnotpackthewholekernelmoduleintoonesinglespkfile.Instead,itwillinstallthekernelmodulesin/images/modulesunderthechrootenvironment.Asaresult,theinstallationscriptbelowisslightlydifferentfromthepreviousexample.

#!/bin/bash

#Copyright(c)2000-2015SynologyInc.Allrightsreserved.

#SynoBuildConf/install

MODULES_DIR="${ImageDir}/modules"

PrepareDirs(){

[-d"${MODULES_DIR}"]||mkdir-p${MODULES_DIR}

rm-f${ImageDir}/modules/*

}

InstallModules(){

makeARCH=${ARCH}CC=${CC}LD="${LD}"INSTALL_MOD_PATH=$MODULES_DIRmodules_install

}

main(){

PrepareDirs

InstallModules

}

main"$@"

CompileKernelModules:Lastly,runthefollowingcommandstocompileandinstallthekernelmodulestothedestinationfolder.

/toolkit/pkgscripts/PkgCreate.py-p6281-clinux-2.6.32

Afterthebuildprocess,youcanchecktheresultin/toolkit/ds.6281-6.0/image/modules.

SynologyDSM6.0DeveloperGuide

146CompileKernelModules

VerifytheResult:

YoucancopythekernelmoduleyouneedforyourDSMsystemandrunthefollowingcommandtoinstallthemodule.

insmod${module_name}

Usethefollowingcommandtoverifythatyourmodulehasbeeninstalledproperly.

lsmod|grep${module_name}

SynologyDSM6.0DeveloperGuide

147CompileKernelModules

top related